/* ============================================================
   Vela — app root: auth, routing, case transitions, tweaks
   ============================================================ */
(function () {
  const { useState, useEffect } = React;
  const { Sidebar, Topbar } = window.Shell;

  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "accent": ["#1466FF", "#2B7BFF", "#E9F1FF", "#CFE0FF"],
    "density": "regular",
    "fontScale": 15,
    "radius": "soft"
  }/*EDITMODE-END*/;

  const ACCENTS = {
    "Electric":     ["#1466FF", "#2B7BFF", "#E9F1FF", "#CFE0FF"],
    "Cyan":         ["#0A93C7", "#10A6DC", "#E0F4FB", "#BFE8F4"],
    "Indigo":       ["#4F46E5", "#6366F1", "#ECECFE", "#D2D2F8"],
    "Signal green": ["#0E9466", "#15A878", "#E2F6EE", "#BFE9D6"],
  };
  const RADII = { sharp: [3, 6, 8, 12], soft: [5, 8, 12, 18], round: [8, 12, 18, 26] };

  function App() {
    const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
    const [authed, setAuthed] = useState(() => { try { return localStorage.getItem("vela_auth") === "1"; } catch { return false; } });
    const [route, setRoute] = useState(() => { try { return JSON.parse(localStorage.getItem("vela_route")) || { name: "queue" }; } catch { return { name: "queue" }; } });
    const [search, setSearch] = useState("");
    const [newCase, setNewCase] = useState(false);
    const [tplEditor, setTplEditor] = useState(null); // null | { template } | { isNew:true }
    const [whatsapp, setWhatsapp] = useState(null);
    const [toast, setToast] = useState(null);
    const [, setTick] = useState(0);
    const bump = () => setTick((n) => n + 1);

    const go = (r) => { setRoute(r); try { localStorage.setItem("vela_route", JSON.stringify(r)); } catch {} const m = document.getElementById("vela-main"); if (m) m.scrollTop = 0; };
    const openCase = (id) => go({ name: "case", id });
    const signIn = () => { setAuthed(true); try { localStorage.setItem("vela_auth", "1"); } catch {} go({ name: "queue" }); };

    const showToast = (msg) => { setToast(msg); setTimeout(() => setToast(null), 4000); };

    // ---- transitions ----
    const startCollecting = (id) => {
      const c = window.VELA.cases.find((x) => x.id === id);
      if (c) { c.status = "COLLECTING"; c.activity = "Just now"; bump(); showToast(`Collection started — the agent is now messaging ${c.borrower.split(" ")[0]} on WhatsApp`); }
    };
    const approve = (id) => {
      const c = window.VELA.cases.find((x) => x.id === id);
      if (c) { c.status = "COMPLETED"; c.completed = "Today"; c.activity = "Just now"; c.queue = null; bump(); showToast(`${c.borrower} · case approved and completed`); go({ name: "case", id }); }
    };
    const createCase = ({ borrower, coapps }) => {
      if (!borrower) return;
      const n = 2060 + window.VELA.cases.filter((c) => c.id.startsWith("EXP-20")).length;
      const initialsOf = (nm) => { const p = (nm || "").trim().split(/\s+/).filter(Boolean); return ((p[0] || "N")[0] + (p[1] ? p[1][0] : "E")).toUpperCase(); };
      // Each participant carries their own employment profile → their own document bundle.
      const mkParticipant = (e, role) => {
        const tplObj = window.UI.templateOf(e.template);
        const docNames = (tplObj ? tplObj.docs : []).concat(e.extraDocs || []);
        return { name: e.name, role, initials: initialsOf(e.name), docs: docNames.map((dn) => ({ name: dn, status: "waiting", note: "" })) };
      };
      const participants = [mkParticipant(borrower, "Primary borrower")]
        .concat((coapps || []).filter((co) => co.name).map((co) => mkParticipant(co, "Co-applicant")));
      const newC = {
        id: "EXP-" + n, borrower: borrower.name, initials: initialsOf(borrower.name), template: borrower.template, status: "DRAFT",
        created: "Today", activity: "Just now",
        property: { address: "Property not yet identified", price: 0 },
        agency: "—", appraiser: "—", participants,
      };
      window.VELA.cases.unshift(newC);
      setNewCase(false); bump(); showToast(`Case ${newC.id} created — ${borrower.name}`); go({ name: "case", id: newC.id });
    };

    useEffect(() => {
      const root = document.documentElement;
      const acc = Array.isArray(t.accent) ? t.accent : ACCENTS["Vela gold"];
      root.style.setProperty("--gold", acc[0]); root.style.setProperty("--gold-2", acc[1]);
      root.style.setProperty("--gold-soft", acc[2]); root.style.setProperty("--gold-line", acc[3]);
      root.setAttribute("data-density", t.density);
      document.body.style.fontSize = t.fontScale + "px";
      const r = RADII[t.radius] || RADII.soft;
      root.style.setProperty("--r-xs", r[0] + "px"); root.style.setProperty("--r-sm", r[1] + "px");
      root.style.setProperty("--r-md", r[2] + "px"); root.style.setProperty("--r-lg", r[3] + "px");
    }, [t]);

    if (!authed) return (<><window.Login onSignIn={signIn} /><Tweaks t={t} setTweak={setTweak} /></>);

    const activeCase = route.name === "case" ? window.VELA.cases.find((c) => c.id === route.id) : null;
    const isReview = activeCase && activeCase.status === "UNDER_REVIEW";

    const saveTemplate = (data) => {
      if (data.key) {
        const t = window.VELA.TEMPLATES.find((x) => x.key === data.key);
        if (t) { t.label = data.label; t.en = data.en; t.desc = data.desc; t.docs = data.docs; }
      } else {
        window.VELA.TEMPLATES.push({ key: "tpl-" + Date.now().toString(36), label: data.label, en: data.en, desc: data.desc, docs: data.docs });
      }
      setTplEditor(null); bump(); showToast(data.key ? `Template “${data.label}” updated` : `Template “${data.label}” created`);
    };

    let title = "Action queue", crumb = null;
    if (route.name === "cases") title = "Cases";
    if (route.name === "templates") title = "Templates";
    if (route.name === "case" && activeCase) {
      if (isReview) { title = "Review · " + activeCase.borrower; }
      else title = activeCase.borrower;
      crumb = { label: route.from === "cases" ? "Cases" : "Action queue", to: route.from === "cases" ? "cases" : "queue" };
    }

    return (
      <div style={{ display: "flex", height: "100%", overflow: "hidden" }}>
        <Sidebar route={route} go={go} />
        <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0, height: "100%" }}>
          {!isReview && (
            <Topbar title={title} crumb={crumb} go={go} search={search} onSearch={setSearch}>
              {(route.name === "queue" || route.name === "cases") && <button className="btn btn-gold" onClick={() => setNewCase(true)}><Icon name="plus" size={15} stroke={2.2} /> New case</button>}
              {route.name === "templates" && <button className="btn btn-gold" onClick={() => setTplEditor({ isNew: true })}><Icon name="plus" size={15} stroke={2.2} /> New template</button>}
            </Topbar>
          )}
          <main id="vela-main" style={{ flex: 1, overflowY: isReview ? "hidden" : "auto" }}>
            {route.name === "queue" && <window.Queue go={go} openCase={openCase} onNew={() => setNewCase(true)} search={search} />}
            {route.name === "cases" && <window.CasesList openCase={openCase} search={search} />}
            {route.name === "templates" && <window.Templates onEdit={(t) => setTplEditor({ template: t })} onNew={() => setTplEditor({ isNew: true })} />}
            {route.name === "case" && <window.CaseDetail caseId={route.id} go={go} onStart={startCollecting} onWhatsApp={() => setWhatsapp(route.id)} onApprove={approve} notify={showToast} />}
          </main>
        </div>

        {newCase && <window.NewCase onClose={() => setNewCase(false)} onCreate={createCase} />}
        {tplEditor && <window.TemplateEditor template={tplEditor.template || null} onClose={() => setTplEditor(null)} onSave={saveTemplate} />}
        {whatsapp && <window.WhatsApp caseId={whatsapp} onClose={() => setWhatsapp(null)} />}

        {toast && (
          <div style={{ position: "fixed", bottom: 26, left: "50%", transform: "translateX(-50%)", zIndex: 200, background: "var(--ink)", color: "var(--ink-inv)", padding: "13px 20px", borderRadius: 11, boxShadow: "var(--sh-lg)", display: "flex", alignItems: "center", gap: 11, fontSize: 13.5, fontWeight: 500, animation: "fadeUp .3s ease both", maxWidth: 460 }}>
            <div style={{ width: 22, height: 22, borderRadius: "50%", background: "var(--green)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="check" size={13} stroke={3} /></div>
            {toast}
          </div>
        )}

        <Tweaks t={t} setTweak={setTweak} />
      </div>
    );
  }

  function Tweaks({ t, setTweak }) {
    return (
      <TweaksPanel>
        <TweakSection label="Brand" />
        <TweakColor label="Accent" value={t.accent} options={Object.values(ACCENTS)} onChange={(v) => setTweak("accent", v)} />
        <TweakSection label="Layout" />
        <TweakRadio label="Density" value={t.density} options={["compact", "regular", "comfy"]} onChange={(v) => setTweak("density", v)} />
        <TweakRadio label="Corners" value={t.radius} options={["sharp", "soft", "round"]} onChange={(v) => setTweak("radius", v)} />
        <TweakSlider label="Base text" value={t.fontScale} min={13} max={17} step={1} unit="px" onChange={(v) => setTweak("fontScale", v)} />
      </TweaksPanel>
    );
  }

  window.VelaApp = App;
})();
