Spaces:
Running

File size: 24,259 Bytes
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
import { html, useState } from "./runtime.js";
import { useCloud, money, planPeriod, DEVELOPER_EMAIL } from "./cloud.js";
import { Notice, Pill, Icon } from "./components.js";

function Shell({ children }) {
  return html`<main class="page narrow">${children}</main>`;
}

// ---------------------------------------------------------------------------
// Sign in / create account
// ---------------------------------------------------------------------------

export function SignIn({ onDone }) {
  const cloud = useCloud();
  const [mode, setMode] = useState("signin");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [showCode, setShowCode] = useState(false);
  const [code, setCode] = useState("");

  if (!cloud.configured) {
    return html`<${Shell}>
      <div class="eyebrow">Account</div>
      <h1 class="page-title">Explication has no accounts yet.</h1>
      <p class="subtitle">Logins run on Supabase. Connect a Supabase project and this page becomes a normal sign-in screen.</p>
      <div class="card" style=${{ marginTop: "16px" }}>
        <${Notice} kind="warn">No Supabase project is connected to this copy of the site.<//>
        <div class="row" style=${{ marginTop: "12px" }}>
          <a class="btn primary small" href="#/connect">Connect Supabase</a>
          <span class="tiny faint">${DEVELOPER_EMAIL} can do this.</span>
        </div>
      </div>
    <//>`;
  }

  if (cloud.user) {
    return html`<${Account} onDone=${onDone} />`;
  }

  const submit = async (event) => {
    event.preventDefault();
    setError("");
    setMessage("");
    setBusy(true);
    try {
      if (mode === "signin") await cloud.signIn(email.trim(), password);
      else {
        const result = await cloud.signUp(email.trim(), password);
        if (result && result.session) setMessage("Account created. You are signed in.");
        else setMessage("Account created. Check your email — the link signs you straight in, or paste the six-digit code below.");
      }
    } catch (err) {
      setError(err && err.message ? err.message : "That did not work.");
    }
    setBusy(false);
  };

  const sendLink = async () => {
    setError("");
    setMessage("");
    if (!email.trim()) {
      setError("Type your email first.");
      return;
    }
    setBusy(true);
    try {
      await cloud.magicLink(email.trim());
      setMessage("A sign-in link is on its way to " + email.trim() + ".");
    } catch (err) {
      setError(err && err.message ? err.message : "The link could not be sent.");
    }
    setBusy(false);
  };

  const forgot = async () => {
    setError("");
    setMessage("");
    if (!email.trim()) {
      setError("Type your email first, then press Forgot password.");
      return;
    }
    setBusy(true);
    try {
      await cloud.resetPassword(email.trim());
      setMessage("If " + email.trim() + " has an account, a reset link is on its way. It signs you in so you can choose a new password.");
    } catch (err) {
      setError(err && err.message ? err.message : "The reset email could not be sent.");
    }
    setBusy(false);
  };

  const submitCode = async (event) => {
    event.preventDefault();
    setError("");
    setMessage("");
    if (!email.trim()) {
      setError("Type your email first, then the code.");
      return;
    }
    if (!/^\d{6}$/.test(code.trim())) {
      setError("The code is six digits.");
      return;
    }
    setBusy(true);
    try {
      await cloud.verifyCode(email.trim(), code.trim());
      setMessage("Code accepted. You're signed in.");
    } catch (err) {
      setError(err && err.message ? err.message : "That code did not work.");
    }
    setBusy(false);
  };

  return html`<${Shell}>
    <div class="eyebrow">Account</div>
    <h1 class="page-title">${mode === "signin" ? "Welcome back." : "Make an account."}</h1>
    <p class="subtitle">
      An account keeps your plan, your model budget and any downloads you own. Your writing still stays in this browser.
    </p>

    <div class="card" style=${{ marginTop: "18px", maxWidth: "440px" }}>
      <div class="row" style=${{ marginBottom: "12px" }}>
        <button class=${"btn small " + (mode === "signin" ? "primary" : "ghost")} onClick=${() => setMode("signin")}>Sign in</button>
        <button class=${"btn small " + (mode === "signup" ? "primary" : "ghost")} onClick=${() => setMode("signup")}>Create account</button>
      </div>
      <form onSubmit=${submit} class="stack">
        <div class="field">
          <label>Email</label>
          <input class="input" type="email" value=${email} onInput=${(e) => setEmail(e.target.value)} autocomplete="email" placeholder="you@example.com" required />
        </div>
        <div class="field">
          <label>Password</label>
          <input class="input" type="password" value=${password} onInput=${(e) => setPassword(e.target.value)} autocomplete=${mode === "signin" ? "current-password" : "new-password"} placeholder="At least 6 characters" required />
        </div>
        ${mode === "signin" && html`<div class="row" style=${{ justifyContent: "flex-end", marginTop: "-4px" }}>
          <button class="btn link small" type="button" onClick=${forgot} disabled=${busy}>Forgot password?</button>
        </div>`}
        ${error && html`<${Notice} kind="error">${error}<//>`}
        ${message && html`<${Notice} kind="info">${message}<//>`}
        <button class="btn primary" type="submit" disabled=${busy}>
          ${busy ? html`<span class="spin"></span>` : html`<${Icon} name="lock" size=${13} />`} ${mode === "signin" ? "Sign in" : "Create account"}
        </button>
      </form>
      <div class="divider"></div>
      <div class="row between wrap">
        <span class="tiny faint">No password? Send a one-time link instead.</span>
        <button class="btn small" onClick=${sendLink} disabled=${busy}>Email me a link</button>
      </div>
      <div class="divider"></div>
      <div class="row between wrap">
        <span class="tiny faint">Got a six-digit code in the email?</span>
        <button class="btn small" onClick=${() => setShowCode(!showCode)}>${showCode ? "Hide" : "Use a code"}</button>
      </div>
      ${showCode && html`<form onSubmit=${submitCode} class="stack" style=${{ marginTop: "10px" }}>
        <div class="field">
          <label>Six-digit code</label>
          <input class="input" type="text" inputmode="numeric" maxlength="6" value=${code} onInput=${(e) => setCode(e.target.value.replace(/[^0-9]/g, ""))} placeholder="123456" autocomplete="one-time-code" />
        </div>
        <button class="btn primary" type="submit" disabled=${busy}>Verify code</button>
      </form>`}
    </div>

    <p class="tiny faint" style=${{ marginTop: "12px" }}>
      Plans and purchases are attached to this account. You can use every marking tool without one.
    </p>
  <//>`;
}

// ---------------------------------------------------------------------------
// Account / plan
// ---------------------------------------------------------------------------

function BudgetBar({ budget, plan }) {
  if (!plan) return null;
  if (!plan.cost_limit_cents) {
    return html`      <div class="tiny faint" style=${{ marginTop: "6px" }}>
      This pack is all offline: download the models and they are yours, with no allowance to run down.
    </div>`;
  }
  const pct = budget.limit ? Math.min(100, Math.round((budget.spent / budget.limit) * 100)) : 0;
  return html`<div style=${{ marginTop: "8px" }}>
    <div class="row between tiny">
      <span class="muted">Included AI this period</span>
      <span class="faint">${100 - pct}% left</span>
    </div>
    <div class="bar" style=${{ marginTop: "5px" }}><i style=${{ width: pct + "%" }}></i></div>
    <div class="tiny faint" style=${{ marginTop: "4px" }}>Your included AI tops up with your plan. Offline models and your own key never touch it.</div>
  </div>`;
}

export function Account({ onDone }) {
  const cloud = useCloud();
  const [busy, setBusy] = useState(false);

  if (!cloud.user) {
    return html`<${SignIn} />`;
  }

  const plan = cloud.plan;
  const signedOut = async () => {
    setBusy(true);
    await cloud.signOut();
    setBusy(false);
    if (onDone) onDone();
  };

  return html`<${Shell}>
    <div class="row between" style=${{ alignItems: "flex-start" }}>
      <div>
        <div class="eyebrow">Account</div>
        <h1 class="page-title">${cloud.user.email}</h1>
        <p class="subtitle">${cloud.isDev ? "This address is the developer account for this site." : "Your plan, budget and downloads live here."}</p>
      </div>
      <button class="btn small" onClick=${signedOut} disabled=${busy}>Sign out</button>
    </div>

    <div class="section-head"><h2 class="section-title">Your plan</h2>
      <a class="btn link small" href="#/pricing">${plan ? "Change plan" : "See plans"}</a>
    </div>
    <div class="card">
      ${plan
        ? html`<div class="row between wrap">
            <div>
              <div class="row"><span style=${{ fontWeight: 600, fontSize: "15px" }}>${plan.name}</span>
                <${Pill} tone=${plan.kind === "subscription" ? "green" : "neutral"}>${plan.kind === "one_time" ? "One-off" : "Subscription"}<//>
              </div>
              <div class="tiny faint" style=${{ marginTop: "2px" }}>${money(plan.price_cents, plan.currency)} ${planPeriod(plan)}</div>
            </div>
            <span class="tiny faint">${cloud.entitlement && cloud.entitlement.expires_at ? "Renews " + new Date(cloud.entitlement.expires_at).toLocaleDateString("en-GB") : "Active"}</span>
          </div>
          <${BudgetBar} budget=${cloud.budget} plan=${plan} />`
        : html`<div class="row between wrap">
            <div>
              <div style=${{ fontWeight: 600 }}>No plan yet</div>
              <div class="tiny faint" style=${{ marginTop: "2px" }}>Rule-based marking, chat setup and BYOK work without one.</div>
            </div>
            <a class="btn primary small" href="#/pricing">Choose a plan</a>
          </div>`}
    </div>

    <div class="section-head"><h2 class="section-title">Bring your own key</h2></div>
    <div class="card">
      <div class="row between wrap">
        <div style=${{ maxWidth: "520px" }}>
          <div style=${{ fontWeight: 600 }}>Your provider, your bill</div>
                      <div class="tiny faint" style=${{ marginTop: "3px", lineHeight: 1.55 }}>
            Add an OpenAI-compatible endpoint in Settings and every hosted feature runs on your own key. It never touches your included allowance, so you can keep going as long as you like.
          </div>
        </div>
        <a class="btn small" href="#/settings">Open Settings</a>
      </div>
    </div>

    ${cloud.isDev &&
    html`<div class="section-head"><h2 class="section-title">Developer</h2></div>
      <div class="card">
        <div class="row between wrap">
          <div style=${{ maxWidth: "520px" }}>
            <div style=${{ fontWeight: 600 }}>Developer console</div>
            <div class="tiny faint" style=${{ marginTop: "3px", lineHeight: 1.55 }}>Plans and prices, PayPal, models and keys, page wording, and who has access.</div>
          </div>
          <a class="btn primary small" href="#/developer">Open developer console</a>
        </div>
      </div>`}
  <//>`;
}

// ---------------------------------------------------------------------------
// Landing screens for email links
// ---------------------------------------------------------------------------

const WELCOME_COPY = {
  signup: {
    eyebrow: "Account confirmed",
    title: "You're in.",
    body: "Your email is confirmed and you're signed in. Your plan, budget and downloads stay with this account."
  },
  magiclink: {
    eyebrow: "Signed in",
    title: "You're signed in.",
    body: "The link worked — no password needed."
  },
  email_change: {
    eyebrow: "Address updated",
    title: "That's your new address.",
    body: "Your sign-in address has changed, and you're already signed in with it."
  },
  session: {
    eyebrow: "Signed in",
    title: "You're in.",
    body: "The link worked and you're signed in."
  }
};

function CentredCard({ children }) {
  return html`<div class="card" style=${{ maxWidth: "460px", margin: "7vh auto 0", textAlign: "center", padding: "28px 26px" }}>${children}</div>`;
}

function Tick({ tone = "good" }) {
  const good = tone === "good";
  return html`<div style=${{
    width: "56px", height: "56px", borderRadius: "50%",
    background: good ? "var(--accent-soft)" : "var(--warning-soft)",
    color: good ? "var(--accent-deep)" : "#7d4a1f",
    display: "grid", placeItems: "center", margin: "0 auto 14px"
  }}><${Icon} name=${good ? "check" : "x"} size=${26} stroke=${2.2} /></div>`;
}

function Waiting() {
  return html`<${CentredCard}>
    <span class="spin" style=${{ margin: "0 auto 14px" }}></span>
    <div style=${{ fontWeight: 600, fontSize: "15px" }}>Signing you in…</div>
    <p class="tiny faint" style=${{ marginTop: "4px" }}>Reading the link and setting up your session.</p>
  <//>`;
}

// Where a confirmed sign-up, magic link or email change lands.
export function Welcome({ kind, onDone }) {
  const cloud = useCloud();
  const copy = WELCOME_COPY[kind] || WELCOME_COPY.magiclink;

  if (!cloud.ready) {
    return html`<${Shell}><${Waiting} /><//>`;
  }

  if (!cloud.configured) {
    return html`<${Shell}>
      <${CentredCard}>
        <${Tick} tone="bad" />
        <h1 class="page-title" style=${{ fontSize: "26px" }}>No accounts yet.</h1>
        <p class="subtitle">This copy of the site has no Supabase project, so there is no account to confirm.</p>
        <div class="row" style=${{ justifyContent: "center", marginTop: "16px" }}>
          <a class="btn primary" href="#/connect">Connect Supabase</a>
        </div>
      <//>
    <//>`;
  }

  if (!cloud.user) {
    return html`<${Shell}>
      <${CentredCard}>
        <${Tick} tone="bad" />
        <h1 class="page-title" style=${{ fontSize: "26px" }}>That link didn't sign you in.</h1>
        <p class="subtitle">Email links work once and expire after an hour. Sign in with your password, or send yourself a fresh one from the sign-in page.</p>
        <div class="row" style=${{ justifyContent: "center", marginTop: "16px" }}>
          <button class="btn primary" onClick=${onDone}>Go to sign in</button>
        </div>
      <//>
    <//>`;
  }

  return html`<${Shell}>
    <${CentredCard}>
      <${Tick} />
      <div class="eyebrow">${copy.eyebrow}</div>
      <h1 class="page-title" style=${{ fontSize: "30px", marginTop: "4px" }}>${copy.title}</h1>
      <p class="subtitle">${copy.body}</p>
      <p class="tiny faint" style=${{ marginTop: "8px" }}>Signed in as ${cloud.user.email}</p>
      <div class="row" style=${{ justifyContent: "center", marginTop: "16px" }}>
        <button class="btn primary" onClick=${onDone}>Start marking</button>
      </div>
      <p class="tiny faint" style=${{ marginTop: "14px" }}><a href="#/pricing">See the plans</a></p>
    <//>
  <//>`;
}

// Where a password-reset or invite link lands. The link has already signed the
// person in; this screen is the missing step that sets the password.
export function NewPassword({ kind, onDone }) {
  const cloud = useCloud();
  const [password, setPassword] = useState("");
  const [again, setAgain] = useState("");
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState("");

  const submit = async (event) => {
    event.preventDefault();
    setError("");
    if (password.length < 6) {
      setError("Use at least six characters.");
      return;
    }
    if (password !== again) {
      setError("The two passwords don't match.");
      return;
    }
    setBusy(true);
    try {
      await cloud.updatePassword(password);
      setDone(true);
    } catch (err) {
      setError(err && err.message ? err.message : "The password could not be changed.");
    }
    setBusy(false);
  };

  if (!cloud.ready) {
    return html`<${Shell}><${Waiting} /><//>`;
  }

  if (!cloud.configured) {
    return html`<${Shell}>
      <${CentredCard}>
        <${Tick} tone="bad" />
        <h1 class="page-title" style=${{ fontSize: "26px" }}>No accounts yet.</h1>
        <p class="subtitle">This copy of the site has no Supabase project, so there is no password to change.</p>
        <div class="row" style=${{ justifyContent: "center", marginTop: "16px" }}>
          <a class="btn primary" href="#/connect">Connect Supabase</a>
        </div>
      <//>
    <//>`;
  }

  if (!cloud.user) {
    return html`<${Shell}>
      <${CentredCard}>
        <${Tick} tone="bad" />
        <h1 class="page-title" style=${{ fontSize: "26px" }}>This link has expired.</h1>
        <p class="subtitle">Password links work once and last an hour. Ask for a new one from the sign-in page.</p>
        <div class="row" style=${{ justifyContent: "center", marginTop: "16px" }}>
          <button class="btn primary" onClick=${onDone}>Back to sign in</button>
        </div>
      <//>
    <//>`;
  }

  if (done) {
    return html`<${Shell}>
      <${CentredCard}>
        <${Tick} />
        <div class="eyebrow">Password changed</div>
        <h1 class="page-title" style=${{ fontSize: "28px", marginTop: "4px" }}>You're all set.</h1>
        <p class="subtitle">Use your new password the next time you sign in.</p>
        <div class="row" style=${{ justifyContent: "center", marginTop: "16px" }}>
          <button class="btn primary" onClick=${onDone}>Go to my account</button>
        </div>
      <//>
    <//>`;
  }

  return html`<${Shell}>
    <${CentredCard}>
      <div class="eyebrow">${kind === "invite" ? "Welcome" : "Password reset"}</div>
      <h1 class="page-title" style=${{ fontSize: "28px", marginTop: "4px" }}>${kind === "invite" ? "Choose a password." : "Choose a new password."}</h1>
      <p class="subtitle">${kind === "invite" ? "Set a password for " + cloud.user.email + " and you're in." : "You're signed in as " + cloud.user.email + ". Pick something you'll remember."}</p>
      <form onSubmit=${submit} class="stack" style=${{ marginTop: "16px", textAlign: "left" }}>
        <div class="field">
          <label>New password</label>
          <input class="input" type="password" value=${password} onInput=${(e) => setPassword(e.target.value)} autocomplete="new-password" placeholder="At least 6 characters" required />
        </div>
        <div class="field">
          <label>One more time</label>
          <input class="input" type="password" value=${again} onInput=${(e) => setAgain(e.target.value)} autocomplete="new-password" placeholder="Same password" required />
        </div>
        ${error && html`<${Notice} kind="error">${error}<//>`}
        <button class="btn primary" type="submit" disabled=${busy}>
          ${busy ? html`<span class="spin"></span>` : html`<${Icon} name="lock" size=${13} />`} Save password
        </button>
      </form>
    <//>
  <//>`;
}

// When Supabase itself reports the link is bad or used.
export function LinkProblem({ onDone }) {
  return html`<${Shell}>
    <${CentredCard}>
      <${Tick} tone="bad" />
      <h1 class="page-title" style=${{ fontSize: "26px" }}>That link has expired.</h1>
      <p class="subtitle">Email links work once and last an hour. Ask for a fresh one from the sign-in page — it takes a moment.</p>
      <div class="row" style=${{ justifyContent: "center", marginTop: "16px" }}>
        <button class="btn primary" onClick=${onDone}>Back to sign in</button>
      </div>
    <//>
  <//>`;
}

// ---------------------------------------------------------------------------
// Connect Supabase
// ---------------------------------------------------------------------------

export function Connect() {
  const cloud = useCloud();
  const [url, setUrl] = useState(cloud.configured ? cloud.config.url : "");
  const [anonKey, setAnonKey] = useState(cloud.configured ? cloud.config.anonKey : "");
  const [error, setError] = useState("");
  const [done, setDone] = useState(false);
  const [copied, setCopied] = useState(false);

  const connect = async (event) => {
    event.preventDefault();
    setError("");
    const clean = url.trim().replace(/\/+$/, "");
    if (!/^https?:\/\/.+/.test(clean)) {
      setError("The project URL looks like https://yourproject.supabase.co");
      return;
    }
    if (anonKey.trim().length < 20) {
      setError("Paste the anon public key from Supabase → Project Settings → API.");
      return;
    }
    cloud.connect({ url: clean, anonKey: anonKey.trim() });
    setDone(true);
  };

  const copySchema = async () => {
    try {
      const res = await fetch("supabase/schema.sql");
      const text = await res.text();
      await navigator.clipboard.writeText(text);
      setCopied(true);
      setTimeout(() => setCopied(false), 2400);
    } catch {
      setError("Could not copy the schema. Open supabase/schema.sql in the folder instead.");
    }
  };

  if (done || (cloud.configured && !error)) {
    return html`<${Shell}>
      <div class="eyebrow">Connected</div>
      <h1 class="page-title">Supabase is connected.</h1>
      <p class="subtitle">
        This browser now reads accounts, plans, models and page wording from ${cloud.config.url}.
      </p>
      <div class="card" style=${{ marginTop: "16px" }}>
        <div class="row" style=${{ marginBottom: "8px" }}><${Pill} tone="green">Connected</${Pill}><span class="tiny faint mono">${cloud.config.url}</span></div>
        <${Notice} kind="info">
          Two things left in the Supabase dashboard: run the SQL in <span class="mono">supabase/schema.sql</span> in the SQL editor, then paste the same URL and key into <span class="mono">js/config.js</span> so every visitor gets them automatically.
        <//>
        <div class="row wrap" style=${{ marginTop: "10px" }}>
          <button class="btn small" onClick=${copySchema}>${copied ? "Copied" : "Copy schema SQL"}</button>
          <a class="btn small primary" href="SETUP.html" target="_blank" rel="noreferrer">Open the picture guide</a>
          <a class="btn small" href="#/pricing">See the plans page</a>
          <a class="btn small" href="#/developer">Developer console</a>
        </div>
      </div>
      <p class="tiny faint" style=${{ marginTop: "12px" }}>
        This setup screen disappears from the site once a project is connected. It stays available in Developer → Supabase.
      </p>
    <//>`;
  }

  return html`<${Shell}>
    <div class="eyebrow">Setup</div>
    <h1 class="page-title">Connect Supabase.</h1>
    <p class="subtitle">
      Supabase holds the accounts, the plans, the shared page wording and the model budgets. Create a free project, then paste two values from Project Settings → API.
    </p>
    <div class="card" style=${{ marginTop: "16px", maxWidth: "560px" }}>
      <form class="stack" onSubmit=${connect}>
        <div class="field">
          <label>Project URL</label>
          <input class="input" value=${url} onInput=${(e) => setUrl(e.target.value)} placeholder="https://abcdefgh.supabase.co" />
        </div>
        <div class="field">
          <label>Anon public key</label>
          <textarea class="textarea plain" style=${{ minHeight: "84px" }} value=${anonKey} onInput=${(e) => setAnonKey(e.target.value)} placeholder="eyJhbGciOi…"></textarea>
        </div>
        ${error && html`<${Notice} kind="error">${error}<//>`}
        <button class="btn primary" type="submit">Connect this site</button>
      </form>
      <div class="divider"></div>
      <div class="tiny faint" style=${{ lineHeight: 1.6 }}>
        Only the anon public key goes in the browser. It is safe to publish: row-level security in the schema stops anyone but ${DEVELOPER_EMAIL} from changing plans, models or wording. Never paste the service_role key here.
      </div>
    </div>
    <p class="tiny faint" style=${{ marginTop: "12px" }}>
      Full instructions: <a href="SETUP.html" target="_blank" rel="noreferrer">the picture guide</a>.
    </p>
  <//>`;
}