// Shipment Intake (Fiche PR) — main app
const { useState, useEffect, useMemo, useCallback } = React;
const { Field, Input, Textarea, Select, RadioPills, FileDrop, Section } = window.FormBits;

const PR_STORAGE = "cumarex.pr.v1";
const SUPABASE_URL = "https://svvspjtctoyhxwjithgu.supabase.co";
const SUPABASE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InN2dnNwanRjdG95aHh3aml0aGd1Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjY4Mzk5MjUsImV4cCI6MjA4MjQxNTkyNX0.5Au5UAIoMlrMSX5w1Yz_0LGgIMgHTaOIBrIxn3csjFk";
const BUCKET = "cumarex-pr-photos";
function todayLocal(lang) {
  const opts = { year: "numeric", month: "long", day: "numeric" };
  const locale = { en: "en-US", fr: "fr-FR", es: "es-ES" }[lang] || "en-US";
  return new Date().toLocaleDateString(locale, opts);
}

const INITIAL = {
  // Product
  species: "", speciesOther: "", state: "fresh", presentation: "whole", presentationOther: "",
  moule: "", qtyEst: "", price: "", currency: "USD",
  // Conservation
  iceLevel: "", portTemp: "", qualityField: "",
  // Field quality
  qualityField: "", histamineRisk: "no",
  // Origin
  vessel: "", flag: "", fao: "", portExp: "", portOrig: "", catchMethod: "purse",
  // Transport
  truckReg: "", fridgeSerial: "", driverName: "", driverPhone: "",
  departTime: "", eta: "", transitWindow: "48", deliveryState: "transit",
  // Photos
  upLot: null, upProduct: null, upIce: null, upLabels: null, obs: "",
  // Submit
  operatorName: "", operatorId: "", agree: false,
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#0a4f6e",
  "density": "regular",
  "lang": "en"
}/*EDITMODE-END*/;

function Crest() {
  return (
    <div className="crest" aria-hidden="true">
      <img src="cumarex-logo.png" alt="Cumarex"/>
    </div>
  );
}
function WaveBg() {
  return (
    <div className="bg" aria-hidden="true">
      <svg preserveAspectRatio="none" viewBox="0 0 1200 800">
        <defs>
          <pattern id="wave" x="0" y="0" width="120" height="40" patternUnits="userSpaceOnUse">
            <path d="M0 20 Q30 4 60 20 T120 20" fill="none" stroke="#0a4f6e" strokeWidth="0.6" opacity="0.3"/>
          </pattern>
        </defs>
        <rect width="1200" height="800" fill="url(#wave)"/>
      </svg>
    </div>
  );
}

// Histamine risk score: combines ice level, port temp, field quality.
function computeRisk(d) {
  let score = 0;
  if (d.iceLevel === "none") score += 4;
  else if (d.iceLevel === "low") score += 2;
  else if (d.iceLevel === "med") score += 1;
  const temp = parseFloat(d.portTemp);
  if (!isNaN(temp)) {
    if (temp >= 8) score += 4;
    else if (temp >= 5) score += 2;
    else if (temp >= 3) score += 1;
  }
  if (score >= 7) return "critical";
  if (score >= 4) return "high";
  if (score >= 2) return "moderate";
  return "low";
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [data, setData] = useState(() => {
    try { const s = localStorage.getItem(PR_STORAGE); if (s) return { ...INITIAL, ...JSON.parse(s) }; }
    catch (e) {}
    return INITIAL;
  });
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [serverPrRef, setServerPrRef] = useState(null);

  useEffect(() => {
    try { localStorage.setItem(PR_STORAGE, JSON.stringify(data)); } catch (e) {}
  }, [data]);

  const lang = t.lang || "en";
  const L = window.I18N_PR[lang];
  const issuedToday = useMemo(() => todayLocal(lang), [lang]);
  useEffect(() => { document.documentElement.lang = lang; }, [lang]);

  const set = useCallback((k, v) => setData(d => ({ ...d, [k]: v })), []);

  const risk = useMemo(() => computeRisk(data), [data]);
  const riskMsg = { critical: L.riskCritical, high: L.riskHigh, moderate: L.riskMod, low: L.riskLow }[risk];

  const completion = useMemo(() => {
    const checks = [
      !!data.species, !!data.moule, !!data.qtyEst,
      !!data.iceLevel, !!data.portTemp,
      !!data.vessel, !!data.portExp,
      !!data.truckReg, !!data.driverName, !!data.driverPhone,
      data.agree,
    ];
    return Math.round(checks.filter(Boolean).length / checks.length * 100);
  }, [data]);

  const sectionDone = {
    s1: !!data.species && !!data.qtyEst,
    s2: !!data.iceLevel && !!data.portTemp,
    s3: true,
    s4: !!data.vessel && !!data.portExp,
    s5: !!data.truckReg && !!data.driverName && !!data.driverPhone,
    s6: !!data.upLot && !!data.upProduct,
    s7: data.agree,
  };

  useEffect(() => {
    document.documentElement.dataset.density = t.density;
    document.documentElement.style.setProperty("--accent", t.accent);
    document.documentElement.style.setProperty("--accent-soft", t.accent + "14");
    document.documentElement.style.setProperty("--accent-line", t.accent + "33");
  }, [t.density, t.accent]);

  const onSubmit = (e) => { e?.preventDefault?.(); setConfirmOpen(true); };

  const sendEmail = (prRef) => {
    const speciesLabel = data.species ? (data.species === "other" ? (data.speciesOther || L.sp_other) : L[`sp_${data.species}`]) : "—";
    const subject = `[${prRef}] PR — ${speciesLabel} · ${data.vessel || "—"}`;
    const lines = [];
    const push = (k, v) => { if (v !== undefined && v !== null && v !== "" && v !== false) lines.push(`${k}: ${v}`); };
    const head = (txt) => { lines.push(""); lines.push(`── ${txt.toUpperCase()} ──`); };

    lines.push(L.docTitle);
    lines.push(`${L.refLabel}: ${prRef} · ${L.issuedLabel}: ${issuedToday}`);
    lines.push(`Histamine risk: ${risk.toUpperCase()}`);

    head(L.s1Title);
    push(L.species, data.species ? (data.species === "other" ? `${L.sp_other} (${data.speciesOther})` : L[`sp_${data.species}`]) : "");
    push(L.state, L[`state_${data.state}`]);
    push(L.presentation, data.presentation === "other" ? `${L.pres_other} (${data.presentationOther})` : L[`pres_${data.presentation}`]);
    push(L.moule, data.moule);
    push(L.qtyEst, data.qtyEst);
    push(L.price, data.price ? `${data.price} ${data.currency}` : "");

    head(L.s2Title);
    push(L.iceLevel, data.iceLevel ? L[`ice_${data.iceLevel}`] : "");
    push(L.portTemp, data.portTemp);

    head(L.s4Title);
    push(L.vessel, data.vessel);
    push(L.portExp, data.portExp);
    push(L.portOrig, data.portOrig);
    push(L.catchMethod, data.catchMethod ? L[`cm_${data.catchMethod}`] : "");

    head(L.s5Title);
    push(L.truckReg, data.truckReg);
    push(L.driverName, data.driverName);
    push(L.driverPhone, data.driverPhone);
    push(L.departTime, data.departTime);
    push(L.eta, data.eta);
    push(L.transitWindow, (() => {
      if (!data.departTime || !data.eta) return "";
      const d = new Date(data.departTime).getTime();
      const a = new Date(data.eta).getTime();
      if (!isFinite(d) || !isFinite(a) || a <= d) return "";
      const mins = Math.round((a - d) / 60000);
      return `${Math.floor(mins/60)}h ${String(mins%60).padStart(2,"0")}m`;
    })());

    head(L.obs);
    push(L.obs, data.obs);

    head(L.s7Title);
    push(L.agree, data.agree ? "✓" : "—");

    const url = `mailto:?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(lines.join("\n"))}`;
    window.location.href = url;
  };

  const submitToSupabase = async () => {
    setSubmitting(true);
    try {
      const uploadId = crypto.randomUUID();
      const photoUrls = {};
      const photoFields = [
        ["photo_lot_url", data.upLot],
        ["photo_product_url", data.upProduct],
        ["photo_ice_url", data.upIce],
        ["photo_labels_url", data.upLabels],
      ];
      for (const [col, field] of photoFields) {
        if (field?.file) {
          const ext = field.name.split(".").pop();
          const path = `${uploadId}/${col}.${ext}`;
          const res = await fetch(`${SUPABASE_URL}/storage/v1/object/${BUCKET}/${path}`, {
            method: "POST",
            headers: { Authorization: `Bearer ${SUPABASE_KEY}`, "Content-Type": field.file.type || "application/octet-stream" },
            body: field.file,
          });
          if (res.ok) photoUrls[col] = `${SUPABASE_URL}/storage/v1/object/${BUCKET}/${path}`;
        }
      }
      const payload = {
        lang, status: "submitted", risk_level: risk,
        species: data.species || null, species_other: data.speciesOther || null,
        state: data.state || null, presentation: data.presentation || null,
        presentation_other: data.presentationOther || null, moule: data.moule || null,
        qty_est: data.qtyEst ? parseFloat(data.qtyEst) : null,
        price: data.price ? parseFloat(data.price) : null, currency: data.currency || null,
        ice_level: data.iceLevel || null, port_temp: data.portTemp ? parseFloat(data.portTemp) : null,
        quality_field: data.qualityField || null, histamine_risk: data.histamineRisk || null,
        vessel: data.vessel || null, flag: data.flag || null, fao_zone: data.fao || null,
        port_exp: data.portExp || null, port_orig: data.portOrig || null, catch_method: data.catchMethod || null,
        truck_reg: data.truckReg || null, fridge_serial: data.fridgeSerial || null,
        driver_name: data.driverName || null, driver_phone: data.driverPhone || null,
        depart_time: data.departTime || null, eta: data.eta || null,
        transit_window: data.transitWindow || null, delivery_state: data.deliveryState || null,
        observations: data.obs || null, operator_name: data.operatorName || null,
        operator_id: data.operatorId || null, ...photoUrls,
      };
      const res = await fetch(`${SUPABASE_URL}/rest/v1/cumarex_shipment_intakes`, {
        method: "POST",
        headers: { Authorization: `Bearer ${SUPABASE_KEY}`, apikey: SUPABASE_KEY, "Content-Type": "application/json", Prefer: "return=representation" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error(await res.text());
      const [record] = await res.json();
      setServerPrRef(record.pr_ref);
      setSubmitted(true);
      try { localStorage.removeItem(PR_STORAGE); localStorage.removeItem("cumarex.prCurrent"); } catch (e) {}
    } catch (err) {
      alert((lang === "fr" ? "Erreur : " : lang === "es" ? "Error: " : "Submission failed: ") + err.message);
    } finally {
      setSubmitting(false);
      setConfirmOpen(false);
    }
  };

  const onReset = () => {
    if (!confirm(lang === "en" ? "Clear all fields and start a new PR?" : lang === "fr" ? "Effacer et démarrer une nouvelle PR ?" : "¿Borrar y comenzar una nueva PR?")) return;
    setData(INITIAL);
    try {
      localStorage.removeItem(PR_STORAGE);
      localStorage.removeItem("cumarex.prCurrent");
    } catch (e) {}
    window.location.reload();
  };

  return (
    <>
      <WaveBg />
      <div className="shell">
        {/* Print-only branded header */}
        <header className="print-header" aria-hidden="true">
          <div className="ph-left">
            <img className="ph-logo" src="cumarex-logo.png" alt="Cumarex"/>
            <div>
              <div className="ph-name">CUMAREX S.A.</div>
              <div className="ph-tag">Maître Conserveur · Fish & Seafood Export</div>
              <div className="ph-title">{L.docTitle}</div>
            </div>
          </div>
          <div className="ph-meta">
            <div><strong>{L.refLabel}:</strong> {serverPrRef || "—"}</div>
            <div><strong>{L.issuedLabel}:</strong> {issuedToday}</div>
            <div>{L.versionLabel}: {submitted ? (lang==="fr"?"Soumis":lang==="es"?"Enviado":"Submitted") : L.statusDraft}</div>
          </div>
        </header>
        <div className="topbar">
          <div className="brand-mark">
            <Crest />
            <div>
              <div className="name">{L.brand}</div>
              <div className="since">{L.tagline}</div>
            </div>
          </div>
          <div className="lang-switch" role="tablist">
            {["en","fr","es"].map(c => (
              <button key={c} type="button" aria-pressed={lang === c} onClick={() => setTweak("lang", c)}>{c.toUpperCase()}</button>
            ))}
          </div>
        </div>

        <header className="doc-head">
          <div className="doc-eyebrow">{L.docTitle}</div>
          <h1 className="doc-title">{L.docTitle}</h1>
          <p className="doc-subtitle">{L.docSubtitle}</p>
          <div className="doc-meta">
            <div><div className="lbl">{L.refLabel}</div><div className="val">{serverPrRef || "—"}</div></div>
            <div><div className="lbl">{L.issuedLabel}</div><div className="val">{issuedToday}</div></div>
            <div><div className="lbl">{L.versionLabel}</div><div className="val">{submitted ? (lang==="fr"?"Soumis":lang==="es"?"Enviado":"Submitted") : L.statusDraft}</div></div>
            <div><div className="lbl">{L.languageLabel}</div><div className="val">{lang.toUpperCase()}</div></div>
          </div>
        </header>

        {/* Risk banner */}
        <div className={`risk-banner risk-${risk}`}>
          <span className="risk-dot" aria-hidden="true"/>
          <span>{riskMsg}</span>
        </div>

        <div className="progress-bar">
          <span className="lbl">{L.progressLabel}</span>
          <div className="track"><div className="fill" style={{ width: `${completion}%` }}/></div>
          <span className="pct">{completion}%</span>
        </div>

        <form onSubmit={onSubmit} noValidate>
          {/* 1 — Product */}
          <Section index={1} title={L.s1Title} desc={L.s1Desc} complete={sectionDone.s1}>
            <div className="row">
              <Field label={L.species} required span={6}>
                <Select value={data.species} onChange={(e) => set("species", e.target.value)}>
                  <option value="">{L.speciesPlaceholder}</option>
                  {["tuna","sardine","mackerel","anchovy","octopus","squid","shrimp","salmon","whitefish","other"].map(k => (
                    <option key={k} value={k}>{L[`sp_${k}`]}</option>
                  ))}
                </Select>
                {data.species === "other" && (
                  <Input style={{ marginTop: 8 }} value={data.speciesOther} onChange={(e) => set("speciesOther", e.target.value)} placeholder={L.speciesOther}/>
                )}
              </Field>
              <Field label={L.state} span={6}>
                <RadioPills name="state" value={data.state} onChange={(v) => set("state", v)} options={[
                  { value: "fresh", label: L.state_fresh },
                  { value: "frozen", label: L.state_frozen },
                ]}/>
              </Field>
            </div>
            <div className="row">
              <Field label={L.presentation} span={6}>
                <RadioPills name="pres" value={data.presentation} onChange={(v) => set("presentation", v)} options={[
                  { value: "whole", label: L.pres_whole },
                  { value: "hgt", label: L.pres_hgt },
                  { value: "other", label: L.pres_other },
                ]}/>
                {data.presentation === "other" && (
                  <Input style={{ marginTop: 8 }} value={data.presentationOther} onChange={(e) => set("presentationOther", e.target.value)} placeholder={L.presentationOther}/>
                )}
              </Field>
              <Field label={L.moule} required span={3}>
                <Input value={data.moule} onChange={(e) => set("moule", e.target.value)} placeholder={L.moulePh}/>
              </Field>
              <Field label={L.qtyEst} required span={3}>
                <Input type="number" min="0" value={data.qtyEst} onChange={(e) => set("qtyEst", e.target.value)} placeholder="0"/>
              </Field>
            </div>
            <div className="row">
              <Field label={L.price} span={8}>
                <Input type="number" min="0" step="0.01" value={data.price} onChange={(e) => set("price", e.target.value)} placeholder="0.00"/>
              </Field>
              <Field label={L.total} span={4}>
                <Input readOnly tabIndex={-1} value={(() => {
                  const p = parseFloat(data.price), q = parseFloat(data.qtyEst);
                  if (!isFinite(p) || !isFinite(q)) return "";
                  return (p * q).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                })()} placeholder="0.00"/>
              </Field>
            </div>
          </Section>

          {/* 2 — Conservation */}
          <Section index={2} title={L.s2Title} desc={L.s2Desc} complete={sectionDone.s2}>
            <div className="row">
              <Field label={L.iceLevel} required span={12}>
                <RadioPills name="ice" value={data.iceLevel} onChange={(v) => set("iceLevel", v)} options={[
                  { value: "full", label: L.ice_full },
                  { value: "med", label: L.ice_med },
                  { value: "low", label: L.ice_low },
                  { value: "none", label: L.ice_none },
                ]}/>
              </Field>
            </div>
            <div className="row">
              <Field label={L.portTemp} required span={6}>
                <Input type="number" step="0.1" value={data.portTemp} onChange={(e) => set("portTemp", e.target.value)} placeholder={L.tempPh}/>
              </Field>
            </div>
          </Section>

          {/* 3 — Origin */}
          <Section index={3} title={L.s4Title} desc={L.s4Desc} complete={sectionDone.s4}>
            <div className="row">
              <Field label={L.vessel} required span={12}>
                <Input value={data.vessel} onChange={(e) => set("vessel", e.target.value)}/>
              </Field>
            </div>
            <div className="row">
              <Field label={L.catchMethod} span={6}>
                <Select value={data.catchMethod} onChange={(e) => set("catchMethod", e.target.value)}>
                  {["purse","long","trawl","handline","other"].map(m => <option key={m} value={m}>{L[`cm_${m}`]}</option>)}
                </Select>
              </Field>
            </div>
            <div className="row">
              <Field label={L.portExp} required span={6}>
                <Input value={data.portExp} onChange={(e) => set("portExp", e.target.value)}/>
              </Field>
              <Field label={L.portOrig} hint={L.portOrigHint} span={6}>
                <Input value={data.portOrig} onChange={(e) => set("portOrig", e.target.value)}/>
              </Field>
            </div>
          </Section>

          {/* 4 — Transport */}
          <Section index={4} title={L.s5Title} desc={L.s5Desc} complete={sectionDone.s5}>
            <div className="row">
              <Field label={L.truckReg} required span={12}>
                <Input value={data.truckReg} onChange={(e) => set("truckReg", e.target.value)}/>
              </Field>
            </div>
            <div className="row">
              <Field label={L.driverName} required span={6}>
                <Input value={data.driverName} onChange={(e) => set("driverName", e.target.value)}/>
              </Field>
              <Field label={L.driverPhone} required span={6}>
                <Input type="tel" value={data.driverPhone} onChange={(e) => set("driverPhone", e.target.value)} placeholder="+212 ..."/>
              </Field>
            </div>
            <div className="row">
              <Field label={L.departTime} span={4}>
                <Input type="datetime-local" value={data.departTime} onChange={(e) => set("departTime", e.target.value)}/>
              </Field>
              <Field label={L.eta} span={4}>
                <Input type="datetime-local" value={data.eta} onChange={(e) => set("eta", e.target.value)}/>
              </Field>
              <Field label={L.transitWindow} span={4}>
                <Input readOnly tabIndex={-1} value={(() => {
                  if (!data.departTime || !data.eta) return "";
                  const d = new Date(data.departTime).getTime();
                  const a = new Date(data.eta).getTime();
                  if (!isFinite(d) || !isFinite(a) || a <= d) return "";
                  const mins = Math.round((a - d) / 60000);
                  const h = Math.floor(mins / 60);
                  const m = mins % 60;
                  return `${h}h ${String(m).padStart(2, "0")}m`;
                })()} placeholder="—"/>
              </Field>
            </div>
          </Section>

          {/* 5 — Observations */}
          <Section index={5} title={L.obs} desc={L.obsPh} complete={!!data.obs}>
            <div className="row">
              <Field label={L.obs} required span={12}>
                <Textarea value={data.obs} onChange={(e) => { set("obs", e.target.value); if (e.target.value.trim() && !data.agree) set("agree", true); }} placeholder={L.obsPh}/>
              </Field>
            </div>
          </Section>

          {/* 6 — Submit */}
          <Section index={6} title={L.s7Title} desc={L.s7Desc} complete={sectionDone.s7}>
            <div className="declaration">{L.confirmText}</div>
            <div className="row">
              <label className={`check ${data.agree ? "on" : ""}`} style={{ gridColumn: "span 12" }}>
                <input type="checkbox" checked={data.agree} onChange={(e) => set("agree", e.target.checked)}/>
                <span className="check-box">
                  <svg viewBox="0 0 14 14"><path d="M3 7.4 5.7 10 11 4.4" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </span>
                <span className="check-label">{L.agree}</span>
              </label>
            </div>
          </Section>

          <div className="actions">
            <span className="req-note">{L.requiredNote}</span>
            <button type="button" className="btn ghost" onClick={onReset}>{L.resetBtn}</button>
            <button type="button" className="btn" onClick={() => window.print()}>{L.printBtn}</button>
            <button type="submit" className="btn primary">{L.submitBtn}</button>
          </div>
        </form>

        <footer className="footer">
          <span>{L.footer}</span>
          <span className="conf">{L.confidential}</span>
        </footer>

        <p style={{ marginTop: 18, fontSize: 12, color: "var(--ink-3)" }}>
          <a href="Vendor Self-Assessment.html" style={{ color: "var(--accent)" }}>← {lang==="fr"?"Auto-évaluation fournisseur":lang==="es"?"Autoevaluación del proveedor":"Vendor self-assessment"}</a>
        </p>
      </div>

      {confirmOpen && (
        <div className="toast-back" onClick={() => !submitting && setConfirmOpen(false)}>
          <div className="toast" onClick={(e) => e.stopPropagation()}>
            <h3>{L.submitBtn}</h3>
            <p>{lang==="fr" ? "Les données et photos seront enregistrées dans la base Cumarex." : lang==="es" ? "Los datos y fotos se guardarán en la base Cumarex." : "Data and photos will be saved to the Cumarex database."}</p>
            <div className="actions-row">
              <button type="button" className="btn ghost" onClick={() => setConfirmOpen(false)} disabled={submitting}>
                {lang==="en"?"Cancel":lang==="fr"?"Annuler":"Cancelar"}
              </button>
              <button type="button" className="btn primary" onClick={submitToSupabase} disabled={submitting}>
                {submitting ? (lang==="fr"?"Envoi…":lang==="es"?"Enviando…":"Submitting…") : L.submitBtn}
              </button>
            </div>
          </div>
        </div>
      )}

      {submitted && (
        <div className="toast-back">
          <div className="toast">
            <h3 style={{ color: "var(--accent)" }}>
              {lang==="fr" ? "✓ Soumis avec succès" : lang==="es" ? "✓ Enviado con éxito" : "✓ Submitted successfully"}
            </h3>
            <p style={{ fontFamily: "var(--mono)", fontSize: 15, fontWeight: 600 }}>{serverPrRef}</p>
            <p style={{ fontSize: 13, color: "var(--ink-2)" }}>
              {lang==="fr" ? "La fiche PR a été enregistrée dans la base Cumarex." : lang==="es" ? "La ficha PR ha sido guardada en la base Cumarex." : "The PR record has been saved to the Cumarex database."}
            </p>
            <div className="actions-row">
              <button type="button" className="btn ghost" onClick={() => sendEmail(serverPrRef)}>{L.submitBtn}</button>
              <button type="button" className="btn" onClick={() => window.print()}>{L.printBtn}</button>
              <button type="button" className="btn primary" onClick={onReset}>
                {lang==="fr" ? "Nouvelle PR" : lang==="es" ? "Nueva PR" : "New PR"}
              </button>
            </div>
          </div>
        </div>
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Appearance">
          <TweakColor label="Accent" value={t.accent} options={["#0a4f6e","#1e6f5c","#234a73","#7a3b2a"]} onChange={(v) => setTweak("accent", v)}/>
          <TweakRadio label="Density" value={t.density} options={["compact","regular","comfy"]} onChange={(v) => setTweak("density", v)}/>
        </TweakSection>
        <TweakSection label="Document">
          <TweakRadio label="Language" value={t.lang} options={["en","fr","es"]} onChange={(v) => setTweak("lang", v)}/>
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
