import { html, useEffect, useState } from "./runtime.js"; import { useCloud, money, DEVELOPER_EMAIL, DEFAULT_MODELS } from "./cloud.js"; import { useEditMode } from "./copy.js"; import { Icon, Notice, Pill } from "./components.js"; // --------------------------------------------------------------------------- // Small form pieces // --------------------------------------------------------------------------- function Head({ kicker, title, subtitle, right }) { return html`
${kicker}

${title}

${subtitle && html`

${subtitle}

`}
${right}
`; } function Field({ label, hint, children }) { return html`
${children}
`; } function Text({ label, hint, value, onChange, placeholder, type = "text", mono = false }) { return html`<${Field} label=${label} hint=${hint}> onChange(e.target.value)} placeholder=${placeholder || ""} spellCheck=${false} /> `; } function Area({ label, hint, value, onChange, placeholder, rows = 3 }) { return html`<${Field} label=${label} hint=${hint}> `; } function Select({ label, hint, value, onChange, options }) { return html`<${Field} label=${label} hint=${hint}> `; } function Check({ label, hint, checked, onChange }) { return html``; } function Stat({ label, value, note }) { return html`
${label}
${value}
${note}
`; } // --------------------------------------------------------------------------- // Plans // --------------------------------------------------------------------------- const BLANK_PLAN = { id: "", name: "", kind: "subscription", price_cents: 0, currency: "GBP", interval: "month", blurb: "", features: [], cost_limit_cents: 0, download_tier: 0, byok: true, paypal_plan_id: "", paypal_payment_link: "", active: true, sort: 0 }; function PlanEditor({ plan, onDone }) { const cloud = useCloud(); const [draft, setDraft] = useState(plan || BLANK_PLAN); const [price, setPrice] = useState(((plan || BLANK_PLAN).price_cents / 100).toFixed(2)); const [limit, setLimit] = useState(((plan || BLANK_PLAN).cost_limit_cents / 100).toFixed(2)); const [features, setFeatures] = useState((plan && plan.features ? plan.features : []).join("\n")); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const set = (patch) => setDraft((d) => ({ ...d, ...patch })); const save = async () => { setError(""); const id = (draft.id || draft.name || "").trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); if (!draft.name.trim()) return setError("Give the plan a name."); if (!id) return setError("Give the plan an identifier, for example scholar."); setBusy(true); try { await cloud.upsertPlan({ ...draft, id, price_cents: Math.round((Number(price) || 0) * 100), cost_limit_cents: Math.round((Number(limit) || 0) * 100), interval: draft.kind === "subscription" ? draft.interval || "month" : null, features: features.split("\n").map((f) => f.trim()).filter(Boolean), sort: Number(draft.sort) || 0 }); cloud.flash("Plan saved."); onDone(); } catch (err) { setError(err && err.message ? err.message : "Could not save the plan."); } setBusy(false); }; // A plan's identity is its id; keep it stable once it exists. const lockedId = !!(plan && plan.id); return html`
${lockedId ? "Edit " + plan.name : "New plan"}
<${Text} label="Name" value=${draft.name} onChange=${(v) => set({ name: v, id: lockedId ? draft.id : draft.id || "" })} placeholder="Scholar" /> <${Text} label="Identifier" hint="used in links" value=${draft.id} onChange=${(v) => !lockedId && set({ id: v })} placeholder="scholar" mono=${true} /> <${Select} label="Type" value=${draft.kind} onChange=${(v) => set({ kind: v })} options=${[{ value: "subscription", label: "Subscription" }, { value: "one_time", label: "One-off purchase" }]} /> ${draft.kind === "subscription" ? html`<${Select} label="Billing period" value=${draft.interval || "month"} onChange=${(v) => set({ interval: v })} options=${[{ value: "month", label: "Monthly" }, { value: "year", label: "Yearly" }]} />` : html`<${Text} label="Sort order" value=${draft.sort} onChange=${(v) => set({ sort: Number(v) || 0 })} type="number" />`} <${Text} label="Price" hint="in pounds" value=${price} onChange=${setPrice} type="number" /> <${Text} label="Included AI allowance" hint="pounds included in the price" value=${limit} onChange=${setLimit} type="number" /> <${Text} label="Download tier" hint="0–4 models unlocked" value=${draft.download_tier} onChange=${(v) => set({ download_tier: Number(v) || 0 })} type="number" /> <${Text} label="Sort order" value=${draft.sort} onChange=${(v) => set({ sort: Number(v) || 0 })} type="number" />
<${Area} label="Short description" value=${draft.blurb} onChange=${(v) => set({ blurb: v })} rows=${2} />
<${Area} label="Features" hint="one per line" value=${features} onChange=${setFeatures} rows=${4} />
<${Text} label="PayPal billing plan ID" hint="optional · P-… · API mode" value=${draft.paypal_plan_id} onChange=${(v) => set({ paypal_plan_id: v })} mono=${true} /> <${Text} label="PayPal payment link" hint="for payment-link mode" value=${draft.paypal_payment_link} onChange=${(v) => set({ paypal_payment_link: v })} mono=${true} />
<${Check} label="Published" checked=${draft.active} onChange=${(v) => set({ active: v })} /> <${Check} label="Allow BYOK" checked=${draft.byok} onChange=${(v) => set({ byok: v })} />
${error && html`
<${Notice} kind="error">${error}
`}
`; } function PlansTab() { const cloud = useCloud(); const [editing, setEditing] = useState(null); const [confirm, setConfirm] = useState(""); return html`
Plans appear on the plans page the moment they are published.
${editing && html`<${PlanEditor} plan=${editing === BLANK_PLAN ? null : editing} onDone=${() => setEditing(null)} />`}
${cloud.plans.length === 0 && html`
No plans yet.
`} ${cloud.plans.map( (p) => html`
${p.name} ${p.kind === "subscription" ? "Subscription" : "One-off"} ${p.active === false && html`Hidden`}
${money(p.price_cents, p.currency)} ${p.kind === "subscription" ? "per " + (p.interval || "month") : "once"} · ${p.cost_limit_cents ? money(p.cost_limit_cents, p.currency) + " model usage" : "no hosted usage"} · ${p.download_tier} download${p.download_tier === 1 ? "" : "s"}
${confirm === p.id ? html` ` : html``}
` )}
`; } // --------------------------------------------------------------------------- // Models // --------------------------------------------------------------------------- const BLANK_MODEL = { id: "", name: "", host: "", endpoint_url: "", model_name: "", cost_in_per_million: 0, cost_out_per_million: 0, min_tier: 1, download_size: "", note: "", enabled: true, sort: 0 }; function ModelEditor({ model, onDone }) { const cloud = useCloud(); const [draft, setDraft] = useState(model || BLANK_MODEL); const [apiKey, setApiKey] = useState(""); const [error, setError] = useState(""); const [saved, setSaved] = useState(false); const [busy, setBusy] = useState(false); const set = (patch) => setDraft((d) => ({ ...d, ...patch })); const save = async () => { setError(""); setBusy(true); try { const id = (draft.id || draft.model_name || draft.name || "").trim(); if (!draft.name.trim() || !id) throw new Error("The model needs a name and an identifier."); await cloud.upsertModel({ ...draft, id, cost_in_per_million: Number(draft.cost_in_per_million) || 0, cost_out_per_million: Number(draft.cost_out_per_million) || 0, min_tier: Number(draft.min_tier) || 0, sort: Number(draft.sort) || 0 }); if (apiKey.trim()) { await cloud.saveModelKey(id, apiKey.trim()); setApiKey(""); } cloud.flash("Model saved."); setSaved(true); setTimeout(() => setSaved(false), 2000); onDone(); } catch (err) { setError(err && err.message ? err.message : "Could not save the model."); } setBusy(false); }; return html`
${model ? "Edit " + model.name : "New model"}
<${Text} label="Display name" value=${draft.name} onChange=${(v) => set({ name: v })} placeholder="Qwen2.5 7B" /> <${Text} label="Identifier" value=${draft.id} onChange=${(v) => set({ id: v })} placeholder="Qwen2.5-7B-Instruct-q4f16_1-MLC" mono=${true} /> <${Text} label="Host" hint="shown to students" value=${draft.host} onChange=${(v) => set({ host: v })} placeholder="OpenRouter" /> <${Text} label="Model name at the host" value=${draft.model_name} onChange=${(v) => set({ model_name: v })} placeholder="qwen/qwen-2.5-7b-instruct" mono=${true} /> <${Text} label="Endpoint base URL" hint="OpenAI-compatible" value=${draft.endpoint_url} onChange=${(v) => set({ endpoint_url: v })} placeholder="https://openrouter.ai/api/v1" mono=${true} /> <${Text} label="API key" hint="stored write-only" value=${apiKey} onChange=${setApiKey} placeholder=${model && model.id ? "Paste a new key to replace" : "sk-…"} type="password" /> <${Text} label="Input cost" hint="per million tokens" value=${draft.cost_in_per_million} onChange=${(v) => set({ cost_in_per_million: v })} type="number" /> <${Text} label="Output cost" hint="per million tokens" value=${draft.cost_out_per_million} onChange=${(v) => set({ cost_out_per_million: v })} type="number" /> <${Text} label="Minimum download tier" hint="0–4" value=${draft.min_tier} onChange=${(v) => set({ min_tier: Number(v) || 0 })} type="number" /> <${Text} label="Download size" value=${draft.download_size} onChange=${(v) => set({ download_size: v })} placeholder="~4.5 GB" />
<${Area} label="Note" value=${draft.note} onChange=${(v) => set({ note: v })} rows=${2} placeholder="What this model is good for." />
${error && html`
<${Notice} kind="error">${error}
`}
<${Check} label="Enabled" checked=${draft.enabled} onChange=${(v) => set({ enabled: v })} />
The key is used only by the hosted model function on Supabase. It is never sent to a browser.
`; } function ModelsTab() { const cloud = useCloud(); const [editing, setEditing] = useState(null); const [confirm, setConfirm] = useState(""); return html`
Each model has its own host, endpoint and key. Students download the ones their plan unlocks; the rest run through the hosted function using these keys.
${editing && html`<${ModelEditor} model=${editing === BLANK_MODEL ? null : editing} onDone=${() => setEditing(null)} />`}
${cloud.models.map( (m) => html`
${m.name} ${m.enabled === false && html`Off`}
${m.host || "Browser"} · tier ${m.min_tier} · ${m.download_size || "no download"} · ${m.cost_in_per_million || 0}/${m.cost_out_per_million || 0} per M tokens
${confirm === m.id ? html` ` : html``}
` )} ${cloud.models.length === 0 && html`
No models yet.
`}
`; } // --------------------------------------------------------------------------- // Wording / edit mode // --------------------------------------------------------------------------- function WordingTab() { const cloud = useCloud(); const { editing, setEditing } = useEditMode(); const keys = Object.keys(cloud.content || {}).sort(); return html`
Edit mode
Turn it on, then open any page and click the writing. Every change is saved and shown to everyone, in every browser.

Changed wording

${keys.length === 0 ? html`
Nothing has been reworded yet. Turn on edit mode and click a heading on the Today or Plans page.
` : html`
${keys.map( (key) => html`
${key}
${cloud.content[key]}
` )}
`}
Every edit is stored by key, so it survives a refresh and reaches every visitor. Only the developer account can change it — row-level security in Supabase enforces that even if someone opens the developer page.
`; } // --------------------------------------------------------------------------- // PayPal // --------------------------------------------------------------------------- function PayPalTab() { const cloud = useCloud(); const [client, setClient] = useState(cloud.settings.paypal_client_id || ""); const [mode, setMode] = useState(cloud.settings.paypal_mode || "live"); const [checkout, setCheckout] = useState(cloud.settings.checkout_mode || "function"); const [fn, setFn] = useState(cloud.settings.checkout_function || "paypal-checkout"); const [busy, setBusy] = useState(false); const [saved, setSaved] = useState(false); const save = async () => { setBusy(true); try { await cloud.setSettings({ paypal_client_id: client.trim(), paypal_mode: mode, checkout_mode: checkout, checkout_function: fn.trim() || "paypal-checkout" }); setSaved(true); setTimeout(() => setSaved(false), 2000); } catch (err) { cloud.flash(err && err.message ? err.message : "Could not save."); } setBusy(false); }; return html`
PayPal
<${Text} label="Client ID" hint="live or sandbox app" value=${client} onChange=${setClient} mono=${true} /> <${Select} label="PayPal mode" value=${mode} onChange=${setMode} options=${[{ value: "live", label: "Live" }, { value: "sandbox", label: "Sandbox" }]} /> <${Select} label="Checkout mode" value=${checkout} onChange=${setCheckout} options=${[ { value: "function", label: "PayPal API · automatic access" }, { value: "payment_links", label: "PayPal payment links · manual access" } ]} /> <${Text} label="Checkout function" hint="deployed in Supabase" value=${fn} onChange=${setFn} mono=${true} />
Where the secrets go
Never in this page. Add PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET and PAYPAL_WEBHOOK_ID in Supabase → Edge Functions → Secrets, then deploy paypal-checkout and paypal-webhook. Point a PayPal webhook at https://YOUR-PROJECT.supabase.co/functions/v1/paypal-webhook. Steps are in supabase/SETUP.md.
${checkout === "function" ? "Prices and intervals come from the plans table. PayPal billing plans are created automatically the first time someone subscribes." : "Paste a PayPal payment link on each plan in Plans. The site sends buyers there, but payment links do not say who paid — grant access in People after each sale."}
`; } // --------------------------------------------------------------------------- // Supabase + people // --------------------------------------------------------------------------- function SupabaseTab() { const cloud = useCloud(); const [url, setUrl] = useState(cloud.config.url); const [key, setKey] = useState(cloud.config.anonKey); const [confirm, setConfirm] = useState(false); const [error, setError] = useState(""); const apply = () => { setError(""); const clean = url.trim().replace(/\/+$/, ""); if (!/^https?:\/\/.+/.test(clean) || key.trim().length < 20) { setError("Both values are needed. The URL looks like https://yourproject.supabase.co and the key starts with eyJ."); return; } cloud.connect({ url: clean, anonKey: key.trim() }); cloud.flash("Connection updated."); }; return html`
Project
${cloud.configured ? cloud.config.url : "not connected"}
<${Pill} tone=${cloud.configured ? "green" : "warn"}>${cloud.configured ? "Connected" : "Preview mode"}
<${Text} label="Project URL" value=${url} onChange=${setUrl} placeholder="https://abcdefgh.supabase.co" mono=${true} /> <${Field} label="Anon public key" hint="safe to publish">
${error && html`
<${Notice} kind="error">${error}
`}
Open the picture guide
This is the same connection first-run visitors see. Once it is saved, the setup prompt disappears from the site permanently — it lives here from then on.
Disconnect
Removes the connection from this browser and returns the site to preview mode. Nothing is deleted in Supabase.
${confirm ? html` ` : html``}
`; } function PeopleTab() { const cloud = useCloud(); const [email, setEmail] = useState(""); const [planId, setPlanId] = useState(cloud.plans[0] ? cloud.plans[0].id : ""); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const grant = async () => { setError(""); if (!/^\S+@\S+\.\S+$/.test(email.trim())) return setError("Type the buyer's email."); if (!planId) return setError("Pick a plan."); setBusy(true); try { await cloud.grantPlan(email.trim(), planId); cloud.flash("Access granted to " + email.trim() + "."); setEmail(""); } catch (err) { setError(err && err.message ? err.message : "Could not grant access."); } setBusy(false); }; return html`
Give someone a plan
For payments taken outside PayPal, or to fix a webhook that missed. The plan stays until you revoke it.
<${Text} label="Buyer's email" value=${email} onChange=${setEmail} placeholder="student@example.com" /> <${Select} label="Plan" value=${planId} onChange=${setPlanId} options=${cloud.plans.map((p) => ({ value: p.id, label: p.name + " · " + money(p.price_cents, p.currency) }))} />
${error && html`
<${Notice} kind="error">${error}
`}

Access

${cloud.entitlements.length === 0 ? html`
No plans have been granted yet.
` : html`
${cloud.entitlements.map( (e) => html`
${e.email || e.user_id || "—"} ${e.plan_id} ${e.revoked && html`Revoked`}
${e.source || "grant"} · ${new Date(e.granted_at || Date.now()).toLocaleDateString("en-GB")}${e.expires_at ? " → " + new Date(e.expires_at).toLocaleDateString("en-GB") : ""}
${!e.revoked && html``}
` )}
`}

Recent model spend

${cloud.usage.length === 0 ? html`
No hosted model calls have been recorded yet.
` : html`
${cloud.usage.slice(0, 12).map( (u) => html`
${u.model_id}
${new Date(u.created_at || Date.now()).toLocaleString("en-GB")} · ${u.tokens_in || 0} in / ${u.tokens_out || 0} out
${money(u.cost_cents)}
` )}
`}
`; } // --------------------------------------------------------------------------- // Console // --------------------------------------------------------------------------- const TABS = [ { id: "overview", label: "Overview" }, { id: "plans", label: "Plans" }, { id: "models", label: "Models & keys" }, { id: "wording", label: "Wording" }, { id: "paypal", label: "PayPal" }, { id: "people", label: "People" }, { id: "supabase", label: "Supabase" } ]; export function Developer() { const cloud = useCloud(); const [tab, setTab] = useState("overview"); const { editing, setEditing } = useEditMode(); if (!cloud.isDev) { return html`
<${Head} kicker="Developer" title="This area is not yours." subtitle=${cloud.configured ? "Only " + DEVELOPER_EMAIL + " can change plans, prices, models or wording." : "Connect Supabase first."} />
${cloud.configured ? html`<${Notice} kind="warn">Signed in${cloud.user ? " as " + cloud.user.email : " as a guest"}. The developer console belongs to ${DEVELOPER_EMAIL}.` : html`<${Notice} kind="info">This copy is not connected to Supabase yet, so there is no developer account to check against. Connect it to lock this page down.`}
`; } return html`
<${Head} kicker="Developer" title="Console" subtitle=${cloud.configured ? "Signed in as " + cloud.user.email : "Preview mode — changes stay in this browser until Supabase is connected."} right=${cloud.configured ? html`<${Pill} tone="green">Developer` : html`<${Pill} tone="warn">Preview`} />
${TABS.map((t) => html``)}
${tab === "overview" && html`
<${Stat} label="Plans" value=${cloud.plans.length} note=${cloud.plans.filter((p) => p.active !== false).length + " published"} /> <${Stat} label="Models" value=${cloud.models.length} note=${cloud.models.filter((m) => m.enabled !== false).length + " enabled"} /> <${Stat} label="People" value=${cloud.entitlements.filter((e) => !e.revoked).length} note="with access" /> <${Stat} label="Spend" value=${money(cloud.usage.reduce((s, u) => s + Number(u.cost_cents || 0), 0))} note="recent model usage" />
Payments
Mode${cloud.settings.paypal_mode}
Checkout${cloud.settings.checkout_mode}
Client ID${cloud.settings.paypal_client_id ? "set" : "missing"}
Plans with a link or plan ID${cloud.plans.filter((p) => p.paypal_payment_link || p.paypal_plan_id).length}/${cloud.plans.length}
The page itself
Change any wording a visitor reads, without editing code. Turn edit mode on, then click the text.
${!cloud.configured && html`
Connect Supabase to share any of this
In preview mode plans, models and wording live in this browser only. Connecting a project puts logins and shared content in place.
Connect Supabase
`}
`} ${tab === "plans" && html`<${PlansTab} />`} ${tab === "models" && html`<${ModelsTab} />`} ${tab === "wording" && html`<${WordingTab} />`} ${tab === "paypal" && html`<${PayPalTab} />`} ${tab === "people" && html`<${PeopleTab} />`} ${tab === "supabase" && html`<${SupabaseTab} />`}
`; }