Spaces:
Running

File size: 31,236 Bytes
64378fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30247fe
 
64378fa
 
 
 
 
 
cecfe55
 
64378fa
 
 
 
 
 
 
 
 
 
30247fe
64378fa
30247fe
 
64378fa
 
 
 
 
 
cecfe55
 
64378fa
 
 
 
 
 
 
 
 
 
 
 
30247fe
64378fa
 
 
 
 
 
cecfe55
 
64378fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cecfe55
 
64378fa
 
 
 
 
 
 
 
 
 
30247fe
64378fa
 
30247fe
64378fa
 
 
 
 
cecfe55
 
64378fa
 
 
 
 
 
 
 
 
 
30247fe
64378fa
 
30247fe
64378fa
 
 
 
 
cecfe55
 
64378fa
 
 
 
 
 
 
 
 
 
 
 
 
30247fe
64378fa
 
 
 
 
cecfe55
 
64378fa
 
 
 
 
30247fe
 
 
64378fa
 
30247fe
64378fa
30247fe
64378fa
30247fe
 
 
 
 
 
 
64378fa
 
 
30247fe
 
64378fa
 
 
 
30247fe
 
 
64378fa
30247fe
 
 
 
 
 
 
64378fa
 
 
30247fe
 
64378fa
 
 
 
30247fe
 
 
64378fa
30247fe
 
 
 
 
 
 
64378fa
 
 
30247fe
 
64378fa
 
 
 
30247fe
 
 
64378fa
30247fe
 
 
 
 
 
 
64378fa
 
 
30247fe
 
64378fa
 
 
 
 
 
cecfe55
 
 
 
64378fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30247fe
64378fa
30247fe
64378fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cecfe55
 
 
 
 
64378fa
 
cecfe55
 
64378fa
 
 
cecfe55
 
 
 
 
 
 
 
 
 
 
 
64378fa
 
 
 
cecfe55
 
64378fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
import { createContext, html, useCallback, useContext, useEffect, useMemo, useRef, useState } from "./runtime.js";

// ---------------------------------------------------------------------------
// Account, shared content, plans, models and money.
//
// Everything shared between visitors lives in Supabase. If no project is
// connected yet the app runs in "preview" mode: the developer screens still
// work, but changes stay in this browser. That lets you set the site up,
// try it, then connect Supabase and publish the same edits to everyone.
// ---------------------------------------------------------------------------

export const DEVELOPER_EMAIL = "lucas.owen13@icloud.com";

const CONFIG_KEY = "explication.cloud.config.v1";
const PREVIEW_KEY = "explication.cloud.preview.v1";
const SDK_URL = "https://esm.sh/@supabase/supabase-js@2.45.4";

const T = {
  settings: "explication_settings",
  plans: "explication_plans",
  models: "explication_models",
  secrets: "explication_model_secrets",
  content: "explication_content",
  entitlements: "explication_entitlements",
  usage: "explication_usage"
};

// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------

export function readConfig() {
  let saved = {};
  try {
    saved = JSON.parse(localStorage.getItem(CONFIG_KEY) || "null") || {};
  } catch {
    saved = {};
  }
  const fromFile = (typeof window !== "undefined" && window.EXPLICATION_CONFIG) || {};
  const url = String(saved.url || fromFile.supabaseUrl || "").trim().replace(/\/+$/, "");
  const anonKey = String(saved.anonKey || fromFile.supabaseAnonKey || "").trim();
  return { url, anonKey, developerEmail: DEVELOPER_EMAIL, ready: !!url && !!anonKey };
}

export function saveConfig({ url, anonKey }) {
  const clean = { url: String(url || "").trim().replace(/\/+$/, ""), anonKey: String(anonKey || "").trim() };
  localStorage.setItem(CONFIG_KEY, JSON.stringify(clean));
  return clean;
}

export function forgetConfig() {
  localStorage.removeItem(CONFIG_KEY);
}

// Where Supabase sends people back to after an email link. It must not include
// the app's #/route: Supabase appends the session to this address itself, and
// a second # would bury the tokens inside the route.
function appRedirect() {
  if (typeof window === "undefined") return undefined;
  return window.location.origin + window.location.pathname.replace(/\/+$/, "");
}

let sdkPromise = null;
let sdkKey = "";
async function loadSdk(config) {
  const key = config.url + "|" + config.anonKey;
  if (sdkPromise && sdkKey === key) return sdkPromise;
  sdkKey = key;
  sdkPromise = import(SDK_URL).then((mod) => mod.createClient(config.url, config.anonKey, {
    auth: { persistSession: true, autoRefreshToken: true }
  }));
  return sdkPromise;
}

// ---------------------------------------------------------------------------
// Preview data (used until Supabase is connected)
// ---------------------------------------------------------------------------

export const DEFAULT_PLANS = [
  {
    id: "paragraph-lite",
    name: "Paragraph Lite",
    kind: "one_time",
    price_cents: 400,
    currency: "GBP",
    interval: null,
    blurb: "The little model that started it all, yours to keep. Download it once and mark paragraphs on the bus, on the train, anywhere.",
    features: [
      "Paragraph Lite — 2.5 GB, trained on 300 essays",
      "Qwen3-4B base, runs offline after one download",
      "Every marking tool, forever",
      "Use your own AI key if you have one"
    ],
    cost_limit_cents: 0,
    download_tier: 1,
    byok: true,
    paypal_plan_id: "",
    paypal_payment_link: "",
    active: true,
    sort: 1
  },
  {
    id: "model-library",
    name: "Model Library",
    kind: "one_time",
    price_cents: 1400,
    currency: "GBP",
    interval: null,
    blurb: "All four Paragraph models in one go: Lite, Turbo, Novel and Ace. Nothing else to buy.",
    features: [
      "Paragraph Lite (2.5 GB) and Turbo (5.8 GB)",
      "Paragraph Novel (7.4 GB) and Ace (61 GB)",
      "Download on every device you own",
      "Free updates when new models arrive"
    ],
    cost_limit_cents: 0,
    download_tier: 4,
    byok: true,
    paypal_plan_id: "",
    paypal_payment_link: "",
    active: true,
    sort: 2
  },
  {
    id: "exam-season",
    name: "Exam Season",
    kind: "one_time",
    price_cents: 2400,
    currency: "GBP",
    interval: null,
    blurb: "Everything unlocked for the run-up to the exams, including a pot of hosted AI for the nights you want the big models.",
    features: [
      "All four Paragraph models",
      "Priority access to the hosted models",
      "One payment, nothing renews"
    ],
    cost_limit_cents: 600,
    download_tier: 4,
    byok: true,
    paypal_plan_id: "",
    paypal_payment_link: "",
    active: true,
    sort: 3
  },
  {
    id: "ai-booster",
    name: "AI Booster",
    kind: "one_time",
    price_cents: 600,
    currency: "GBP",
    interval: null,
    blurb: "Already have a membership? Drop another pot of hosted AI into your account and keep the big models coming.",
    features: [
      "Stacks with any plan you already have",
      "Never expires",
      "No subscription, no renewal"
    ],
    cost_limit_cents: 500,
    download_tier: 0,
    byok: true,
    paypal_plan_id: "",
    paypal_payment_link: "",
    active: true,
    sort: 4
  },
  {
    id: "student",
    name: "Student",
    kind: "subscription",
    price_cents: 400,
    currency: "GBP",
    interval: "month",
    blurb: "The whole shelf of hosted models, plus two Paragraph downloads. About the price of a coffee a month.",
    features: [
      "Every hosted model, including the big ones",
      "Paragraph Lite (2.5 GB) and Turbo (5.8 GB) offline",
      "Use your own key and keep it free of limits"
    ],
    cost_limit_cents: 120,
    download_tier: 2,
    byok: true,
    paypal_plan_id: "",
    paypal_payment_link: "",
    active: true,
    sort: 5
  },
  {
    id: "scholar",
    name: "Scholar",
    kind: "subscription",
    price_cents: 900,
    currency: "GBP",
    interval: "month",
    blurb: "For long essays and heavy revision weeks: more AI, more downloads, and Novel offline.",
    features: [
      "Everything in Student",
      "Adds Paragraph Novel (7.4 GB)",
      "Priority when the hosted models are busy"
    ],
    cost_limit_cents: 400,
    download_tier: 3,
    byok: true,
    paypal_plan_id: "",
    paypal_payment_link: "",
    active: true,
    sort: 6
  },
  {
    id: "examiner",
    name: "Examiner",
    kind: "subscription",
    price_cents: 1900,
    currency: "GBP",
    interval: "month",
    blurb: "The full shelf, the biggest budget and every model offline. For the year it really matters.",
    features: [
      "Everything in Scholar",
      "All four Paragraph models, including Ace (61 GB)",
      "Early access to new models and marking prompts"
    ],
    cost_limit_cents: 1000,
    download_tier: 4,
    byok: true,
    paypal_plan_id: "",
    paypal_payment_link: "",
    active: true,
    sort: 7
  }
];

// The Paragraph family, exactly as published by quantilimited on Hugging Face.
// Sizes are the real file sizes. Ace is safetensors-only, so it has no GGUF
// download, but it is still the fourth and largest tier.
export const DEFAULT_MODELS = [
  {
    id: "paragraph-lite",
    name: "Paragraph Lite",
    host: "GGUF · Q4_K_M",
    endpoint_url: "",
    model_name: "Qwen3-4B-Instruct-2507",
    base_model: "Qwen3-4B-Instruct-2507",
    params: "4B",
    essays: 300,
    format: "GGUF · Q4_K_M",
    download_url: "https://huggingface.co/quantilimited/Paragraph-Lite/resolve/main/Qwen3-4B-Instruct-2507.Q4_K_M.gguf",
    card_url: "https://huggingface.co/quantilimited/Paragraph-Lite",
    cost_in_per_million: 0,
    cost_out_per_million: 0,
    min_tier: 1,
    download_size: "2.5 GB",
    note: "The fast tier. Small enough for an 8 GB iPhone, iPad or Mac.",
    enabled: true,
    sort: 1
  },
  {
    id: "paragraph-turbo",
    name: "Paragraph Turbo",
    host: "GGUF · Q4_K_M",
    endpoint_url: "",
    model_name: "Qwen3.5-9B",
    base_model: "Qwen3.5-9B",
    params: "9B",
    essays: 500,
    format: "GGUF · Q4_K_M",
    download_url: "https://huggingface.co/quantilimited/Paragraph-Turbo-gguf/resolve/main/Qwen3.5-9B.Q4_K_M.gguf",
    card_url: "https://huggingface.co/quantilimited/Paragraph-Turbo",
    cost_in_per_million: 0,
    cost_out_per_million: 0,
    min_tier: 2,
    download_size: "5.8 GB",
    note: "Sharper method and effect analysis. Needs about 16 GB of memory.",
    enabled: true,
    sort: 2
  },
  {
    id: "paragraph-novel",
    name: "Paragraph Novel",
    host: "GGUF · Q4_K_M",
    endpoint_url: "",
    model_name: "Gemma 4 12B",
    base_model: "Gemma 4 12B",
    params: "12B",
    essays: 750,
    format: "GGUF · Q4_K_M",
    download_url: "https://huggingface.co/quantilimited/Paragraph-Novel/resolve/main/gemma-4-12b-it.Q4_K_M.gguf",
    card_url: "https://huggingface.co/quantilimited/Paragraph-Novel",
    cost_in_per_million: 0,
    cost_out_per_million: 0,
    min_tier: 3,
    download_size: "7.4 GB",
    note: "12B Gemma 4 for voice, structure and whole-text argument. Needs about 16 GB.",
    enabled: true,
    sort: 3
  },
  {
    id: "paragraph-ace",
    name: "Paragraph Ace",
    host: "Safetensors · 16 shards",
    endpoint_url: "",
    model_name: "Qwen3-30B-A3B-Instruct-2507",
    base_model: "Qwen3-30B-A3B-Instruct-2507",
    params: "30B MoE · 3B active",
    essays: 1000,
    format: "Safetensors · 16 shards",
    download_url: "",
    card_url: "https://huggingface.co/quantilimited/Paragraph-Ace",
    cost_in_per_million: 0,
    cost_out_per_million: 0,
    min_tier: 4,
    download_size: "61 GB",
    note: "The full 30B mixture-of-experts checkpoint. Published as safetensors; there is no GGUF build yet.",
    enabled: true,
    sort: 4
  }
];

export const DEFAULT_SETTINGS = {
  paypal_client_id: "",
  paypal_mode: "live",
  checkout_mode: "function",
  checkout_function: "paypal-checkout",
  currency: "GBP",
  support_email: DEVELOPER_EMAIL
};

function previewDefaults() {
  return { plans: DEFAULT_PLANS, models: DEFAULT_MODELS, content: {}, settings: DEFAULT_SETTINGS, entitlements: [], usage: [] };
}

function readPreview() {
  try {
    const raw = JSON.parse(localStorage.getItem(PREVIEW_KEY) || "null");
    if (!raw) return previewDefaults();
    return { ...previewDefaults(), ...raw };
  } catch {
    return previewDefaults();
  }
}

function writePreview(next) {
  try {
    localStorage.setItem(PREVIEW_KEY, JSON.stringify(next));
  } catch {
    // ignore quota
  }
}

// ---------------------------------------------------------------------------
// Money helpers
// ---------------------------------------------------------------------------

export function money(cents, currency = "GBP") {
  try {
    return new Intl.NumberFormat("en-GB", { style: "currency", currency: currency || "GBP" }).format((Number(cents) || 0) / 100);
  } catch {
    return `£${((Number(cents) || 0) / 100).toFixed(2)}`;
  }
}

export function planPeriod(plan) {
  if (!plan) return "";
  if (plan.kind === "one_time") return "one-off";
  return `per ${plan.interval || "month"}`;
}

export function isDeveloper(user) {
  return !!user && String(user.email || "").toLowerCase() === DEVELOPER_EMAIL;
}

// ---------------------------------------------------------------------------
// Provider
// ---------------------------------------------------------------------------

const CloudContext = createContext(null);

export function CloudProvider({ children }) {
  const [config, setConfig] = useState(readConfig);
  const [client, setClient] = useState(null);
  const [user, setUser] = useState(null);
  const [ready, setReady] = useState(false);
  const [error, setError] = useState("");
  const [preview, setPreview] = useState(() => readPreview());
  const [cloud, setCloud] = useState({
    settings: { ...DEFAULT_SETTINGS },
    plans: [],
    models: [],
    content: {},
    entitlements: [],
    usage: []
  });
  const [busy, setBusy] = useState(false);
  const [notice, setNotice] = useState("");
  const mounted = useRef(true);

  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
    };
  }, []);

  const flash = useCallback((message) => {
    if (!mounted.current) return;
    setNotice(message);
    setTimeout(() => mounted.current && setNotice(""), 2600);
  }, []);

  const refresh = useCallback(
    async (sb, currentUser) => {
      if (!sb) return;
      const who = currentUser === undefined ? user : currentUser;
      try {
        const [settingsRes, plansRes, modelsRes, contentRes] = await Promise.all([
          sb.from(T.settings).select("*").eq("id", 1).maybeSingle(),
          sb.from(T.plans).select("*").order("sort", { ascending: true }),
          sb.from(T.models).select("*").order("sort", { ascending: true }),
          sb.from(T.content).select("*")
        ]);
        const map = {};
        (contentRes.data || []).forEach((row) => {
          map[row.key] = row.value;
        });
        let entitlements = [];
        let usage = [];
        if (who) {
          const [entRes, useRes] = await Promise.all([
            sb.from(T.entitlements).select("*").order("granted_at", { ascending: false }),
            sb.from(T.usage).select("*").order("created_at", { ascending: false }).limit(2000)
          ]);
          entitlements = entRes.data || [];
          usage = useRes.data || [];
        }
        if (!mounted.current) return;
        setCloud({
          settings: { ...DEFAULT_SETTINGS, ...(settingsRes.data || {}) },
          plans: plansRes.data || [],
          models: modelsRes.data || [],
          content: map,
          entitlements,
          usage
        });
        setError("");
      } catch (err) {
        if (mounted.current) setError(err && err.message ? err.message : "Could not read the shared settings.");
      }
    },
    [user]
  );

  useEffect(() => {
    let cancelled = false;
    if (!config.ready) {
      setReady(true);
      setClient(null);
      setUser(null);
      return () => {
        cancelled = true;
      };
    }
    (async () => {
      setReady(false);
      try {
        const sb = await loadSdk(config);
        if (cancelled) return;
        setClient(sb);
        const { data } = await sb.auth.getSession();
        const sessionUser = data && data.session ? data.session.user : null;
        if (cancelled) return;
        setUser(sessionUser);
        await refresh(sb, sessionUser);
        sb.auth.onAuthStateChange((_event, session) => {
          const nextUser = session ? session.user : null;
          setUser(nextUser);
          refresh(sb, nextUser);
        });
      } catch (err) {
        if (!cancelled) setError("Supabase could not be reached. Check the project URL and public key in Developer settings.");
      } finally {
        if (!cancelled) setReady(true);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [config.ready, config.url, config.anonKey]);

  // Preview-mode writes keep working with no backend.
  const previewWrite = useCallback((mutate) => {
    setPreview((current) => {
      const next = mutate({ ...current });
      writePreview(next);
      return next;
    });
  }, []);

  const entitlements = config.ready ? cloud.entitlements : preview.entitlements;
  const usage = config.ready ? cloud.usage : preview.usage;

  const activeEntitlements = useMemo(() => {
    const now = Date.now();
    return entitlements.filter((e) => {
      if (e.revoked) return false;
      if (e.expires_at && new Date(e.expires_at).getTime() < now) return false;
      return true;
    });
  }, [entitlements]);

  const activeEntitlement = activeEntitlements[0] || null;

  const plans = config.ready ? cloud.plans : preview.plans;
  const models = config.ready ? cloud.models : preview.models;

  // Purchases stack: the best download tier wins and the included AI adds up.
  const plan = useMemo(() => {
    const owned = activeEntitlements.map((e) => plans.find((p) => p.id === e.plan_id)).filter(Boolean);
    return (
      owned.sort(
        (a, b) => Number(b.download_tier || 0) - Number(a.download_tier || 0) || Number(b.cost_limit_cents || 0) - Number(a.cost_limit_cents || 0)
      )[0] || null
    );
  }, [plans, activeEntitlements]);

  const budget = useMemo(() => {
    const owned = activeEntitlements.map((e) => plans.find((p) => p.id === e.plan_id)).filter(Boolean);
    const limit = owned.reduce((sum, p) => sum + Number(p.cost_limit_cents || 0), 0);
    if (!limit) return { limit: 0, spent: 0, remaining: 0, unlimited: false };
    const hasSub = owned.some((p) => p.kind === "subscription");
    const since = hasSub ? new Date(new Date().getFullYear(), new Date().getMonth(), 1).getTime() : 0;
    const spent = usage
      .filter((u) => new Date(u.created_at || 0).getTime() >= since)
      .reduce((sum, u) => sum + Number(u.cost_cents || 0), 0);
    return { limit, spent, remaining: Math.max(0, limit - spent), unlimited: false };
  }, [plans, activeEntitlements, usage]);

  const isDev = config.ready ? isDeveloper(user) : true;

  const signIn = useCallback(
    async (email, password) => {
      if (!client) throw new Error("Connect Supabase first.");
      const { error: err } = await client.auth.signInWithPassword({ email, password });
      if (err) throw err;
    },
    [client]
  );

  const signUp = useCallback(
    async (email, password) => {
      if (!client) throw new Error("Connect Supabase first.");
      const { data, error: err } = await client.auth.signUp({ email, password, options: { emailRedirectTo: appRedirect() } });
      if (err) throw err;
      return data;
    },
    [client]
  );

  const magicLink = useCallback(
    async (email) => {
      if (!client) throw new Error("Connect Supabase first.");
      const { error: err } = await client.auth.signInWithOtp({ email, options: { emailRedirectTo: appRedirect() } });
      if (err) throw err;
    },
    [client]
  );

  const resetPassword = useCallback(
    async (email) => {
      if (!client) throw new Error("Connect Supabase first.");
      const { error: err } = await client.auth.resetPasswordForEmail(email, { redirectTo: appRedirect() });
      if (err) throw err;
    },
    [client]
  );

  // Used by the screen a recovery or invite link lands on. The link itself has
  // already signed the person in, so this only sets the new password.
  const updatePassword = useCallback(
    async (password) => {
      if (!client) throw new Error("Connect Supabase first.");
      const { error: err } = await client.auth.updateUser({ password });
      if (err) throw err;
    },
    [client]
  );

  // The six-digit code printed in the sign-in emails. Supabase labels the token
  // by the flow that produced it, so try the likely types in order and keep the
  // last refusal.
  const verifyCode = useCallback(
    async (email, token) => {
      if (!client) throw new Error("Connect Supabase first.");
      const types = ["signup", "invite", "recovery", "email", "magiclink"];
      let lastError = null;
      for (const type of types) {
        const { data, error: err } = await client.auth.verifyOtp({ email, token, type });
        if (!err && data && data.session) return data;
        lastError = err;
      }
      throw lastError || new Error("That code did not work.");
    },
    [client]
  );

  const signOut = useCallback(async () => {
    if (client) await client.auth.signOut();
    setUser(null);
  }, [client]);

  const connect = useCallback(async ({ url, anonKey }) => {
    saveConfig({ url, anonKey });
    setConfig(readConfig());
  }, []);

  const disconnect = useCallback(async () => {
    forgetConfig();
    setCloud({ settings: { ...DEFAULT_SETTINGS }, plans: [], models: [], content: {}, entitlements: [], usage: [] });
    setConfig(readConfig());
  }, []);

  // ---- writes -------------------------------------------------------------

  const upsertPlan = useCallback(
    async (next) => {
      if (!config.ready) {
        previewWrite((data) => ({ ...data, plans: [...data.plans.filter((p) => p.id !== next.id), next].sort((a, b) => (a.sort || 0) - (b.sort || 0)) }));
        return;
      }
      const { error: err } = await client.from(T.plans).upsert(next);
      if (err) throw err;
      await refresh(client);
    },
    [config.ready, client, previewWrite, refresh]
  );

  const deletePlan = useCallback(
    async (id) => {
      if (!config.ready) {
        previewWrite((data) => ({ ...data, plans: data.plans.filter((p) => p.id !== id) }));
        return;
      }
      const { error: err } = await client.from(T.plans).delete().eq("id", id);
      if (err) throw err;
      await refresh(client);
    },
    [config.ready, client, previewWrite, refresh]
  );

  const upsertModel = useCallback(
    async (next) => {
      if (!config.ready) {
        previewWrite((data) => ({ ...data, models: [...data.models.filter((m) => m.id !== next.id), next].sort((a, b) => (a.sort || 0) - (b.sort || 0)) }));
        return;
      }
      const { error: err } = await client.from(T.models).upsert(next);
      if (err) throw err;
      await refresh(client);
    },
    [config.ready, client, previewWrite, refresh]
  );

  const deleteModel = useCallback(
    async (id) => {
      if (!config.ready) {
        previewWrite((data) => ({ ...data, models: data.models.filter((m) => m.id !== id) }));
        return;
      }
      const { error: err } = await client.from(T.models).delete().eq("id", id);
      if (err) throw err;
      await refresh(client);
    },
    [config.ready, client, previewWrite, refresh]
  );

  const saveModelKey = useCallback(
    async (modelId, apiKey) => {
      if (!config.ready) {
        previewWrite((data) => ({ ...data, secrets: { ...(data.secrets || {}), [modelId]: apiKey } }));
        return;
      }
      const { error: err } = await client.from(T.secrets).upsert({ model_id: modelId, api_key: apiKey, updated_at: new Date().toISOString() });
      if (err) throw err;
    },
    [config.ready, client, previewWrite]
  );

  const setContent = useCallback(
    async (key, value) => {
      const clean = String(value == null ? "" : value);
      if (!config.ready) {
        previewWrite((data) => ({ ...data, content: { ...data.content, [key]: clean } }));
        return;
      }
      const { error: err } = await client
        .from(T.content)
        .upsert({ key, value: clean, updated_at: new Date().toISOString(), updated_by: (user && user.email) || "" });
      if (err) throw err;
      setCloud((c) => ({ ...c, content: { ...c.content, [key]: clean } }));
    },
    [config.ready, client, previewWrite, user]
  );

  const clearContent = useCallback(
    async (key) => {
      if (!config.ready) {
        previewWrite((data) => {
          const content = { ...data.content };
          delete content[key];
          return { ...data, content };
        });
        return;
      }
      const { error: err } = await client.from(T.content).delete().eq("key", key);
      if (err) throw err;
      setCloud((c) => {
        const content = { ...c.content };
        delete content[key];
        return { ...c, content };
      });
    },
    [config.ready, client, previewWrite]
  );

  const setSettings = useCallback(
    async (patch) => {
      if (!config.ready) {
        previewWrite((data) => ({ ...data, settings: { ...data.settings, ...patch } }));
        return;
      }
      const { error: err } = await client.from(T.settings).upsert({ id: 1, ...patch, updated_at: new Date().toISOString() });
      if (err) throw err;
      setCloud((c) => ({ ...c, settings: { ...c.settings, ...patch } }));
    },
    [config.ready, client, previewWrite]
  );

  const grantPlan = useCallback(
    async (email, planId, months = 1) => {
      if (!config.ready) {
        previewWrite((data) => ({
          ...data,
          entitlements: [
            { id: "preview-" + Date.now(), email, plan_id: planId, source: "grant", granted_at: new Date().toISOString(), expires_at: null, revoked: false },
            ...data.entitlements
          ]
        }));
        return;
      }
      const { error: err } = await client.from(T.entitlements).insert({
        email: String(email || "").toLowerCase(),
        plan_id: planId,
        source: "grant",
        expires_at: null
      });
      if (err) throw err;
      await refresh(client);
    },
    [config.ready, client, previewWrite, refresh]
  );

  const revokeGrant = useCallback(
    async (id) => {
      if (!config.ready) {
        previewWrite((data) => ({ ...data, entitlements: data.entitlements.map((e) => (e.id === id ? { ...e, revoked: true } : e)) }));
        return;
      }
      const { error: err } = await client.from(T.entitlements).update({ revoked: true }).eq("id", id);
      if (err) throw err;
      await refresh(client);
    },
    [config.ready, client, previewWrite, refresh]
  );

  const startCheckout = useCallback(
    async (chosen) => {
      if (!chosen) throw new Error("Pick a plan first.");
      if (!user) throw new Error("Sign in first, so the purchase can be attached to your account.");
      const settings = config.ready ? cloud.settings : preview.settings;
      if ((settings.checkout_mode || "function") === "payment_links") {
        if (!chosen.paypal_payment_link) {
          throw new Error("This plan has no PayPal payment link yet. Add one in Developer → Plans.");
        }
        window.location.href = chosen.paypal_payment_link;
        return { redirect: true };
      }
      if (!config.ready) throw new Error("PayPal checkout needs Supabase. Connect it in Developer settings.");
      const fn = settings.checkout_function || "paypal-checkout";
      const { data, error: err } = await client.functions.invoke(fn, {
        body: { plan_id: chosen.id, origin: window.location.origin }
      });
      if (err) {
        let message = err.message || "PayPal checkout could not start.";
        if (err.context && typeof err.context.json === "function") {
          try {
            const body = await err.context.json();
            if (body && body.message) message = body.message;
          } catch {
            // keep the original message
          }
        }
        throw new Error(message);
      }
      if (data && data.url) {
        window.location.href = data.url;
        return { redirect: true };
      }
      if (data && data.message) throw new Error(data.message);
      throw new Error("PayPal did not return an approval link.");
    },
    [user, client, config.ready, cloud.settings, preview.settings]
  );

  const hostedChat = useCallback(
    async (model, messages, onToken) => {
      if (!config.ready) throw new Error("Hosted models need Supabase. Connect it in Developer settings.");
      if (!user) throw new Error("Sign in to use the hosted models.");
      const { data: sessionData } = await client.auth.getSession();
      const token = sessionData && sessionData.session ? sessionData.session.access_token : "";
      const base = config.url;
      const res = await fetch(`${base}/functions/v1/ai`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
          apikey: config.anonKey
        },
        body: JSON.stringify({ model_id: model.id, messages, stream: true })
      });
      if (res.status === 402) {
        const info = await res.json().catch(() => ({}));
        throw new Error(info.message || "You have used your included model budget for this period.");
      }
      if (!res.ok) {
        const text = await res.text().catch(() => "");
        throw new Error(text || `The hosted model returned ${res.status}.`);
      }
      if (!res.body) {
        const data = await res.json();
        const text = (data && data.text) || "";
        onToken && onToken(text);
        return text;
      }
      const reader = res.body.getReader();
      const decoder = new TextDecoder();
      let buffer = "";
      let full = "";
      while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split("\n");
        buffer = lines.pop() || "";
        for (const line of lines) {
          const trimmed = line.trim();
          if (!trimmed.startsWith("data:")) continue;
          const payload = trimmed.slice(5).trim();
          if (payload === "[DONE]") continue;
          try {
            const json = JSON.parse(payload);
            const delta = (json.choices && json.choices[0] && json.choices[0].delta && json.choices[0].delta.content) || "";
            if (delta) {
              full += delta;
              onToken && onToken(full);
            }
          } catch {
            // wait for the rest of the line
          }
        }
      }
      return full;
    },
    [config, client, user]
  );

  const value = useMemo(
    () => ({
      config,
      configured: config.ready,
      mode: config.ready ? "cloud" : "preview",
      client,
      user,
      isDev,
      ready,
      error,
      notice,
      flash,
      settings: config.ready ? cloud.settings : preview.settings,
      plans,
      models,
      content: config.ready ? cloud.content : preview.content,
      entitlements,
      usage,
      plan,
      entitlement: activeEntitlement,
      budget,
      signIn,
      signUp,
      magicLink,
      resetPassword,
      updatePassword,
      verifyCode,
      signOut,
      connect,
      disconnect,
      upsertPlan,
      deletePlan,
      upsertModel,
      deleteModel,
      saveModelKey,
      setContent,
      clearContent,
      setSettings,
      grantPlan,
      revokeGrant,
      startCheckout,
      hostedChat,
      refresh: () => refresh(client),
      canDownload: (tier) => Number(tier || 0) <= 1 || (!!plan && Number(plan.download_tier || 0) >= Number(tier || 0)),
      canHost: (model) => !!model && budget.limit > 0 && budget.remaining > 0
    }),
    [
      config,
      client,
      user,
      isDev,
      ready,
      error,
      notice,
      flash,
      cloud,
      preview,
      plans,
      models,
      entitlements,
      usage,
      plan,
      activeEntitlement,
      activeEntitlements,
      budget,
      signIn,
      signUp,
      magicLink,
      resetPassword,
      updatePassword,
      verifyCode,
      signOut,
      connect,
      disconnect,
      upsertPlan,
      deletePlan,
      upsertModel,
      deleteModel,
      saveModelKey,
      setContent,
      clearContent,
      setSettings,
      grantPlan,
      revokeGrant,
      startCheckout,
      hostedChat,
      refresh
    ]
  );

  return html`<${CloudContext.Provider} value=${value}>${children}<//>`;
}

export function useCloud() {
  const value = useContext(CloudContext);
  if (!value) throw new Error("useCloud must be used inside CloudProvider");
  return value;
}