/* ============================================================
   RESTO SUITE — SHELL
   One Rail hosting all modules over the shared plan (resto.plan.v1).
   Three steps: Business Model → Financial Feasibility → Pitch Summary.
   (plan.market / plan.location / plan.validation stay reserved in the
   schema but have no UI — their key checks are folded into step 01.)
   ============================================================ */

function useModules(t) {
  return [
    { key: "idea", n: "01", label: t("shell.navIdea"), live: true },
    { key: "financials", n: "02", label: t("shell.navFinancials"), live: true },
    { key: "pitch", n: "03", label: t("shell.navPitch"), live: true },
  ];
}

function moduleSub(key, plan, finLive, ideaCheck, t) {
  if (key === "idea") return ideaCheck.readiness > 0 ? `${ideaCheck.readiness}/100 ${t("shell.ready")}` : t("shell.startHere");
  if (key === "financials") return finLive.sales > 0 ? `${finLive.netProfit < 0 ? "−" : ""}${fmtBaht(Math.abs(finLive.netProfit))}${t("shell.afterTaxMo")}` : "—";
  if (key === "pitch") return finLive.sales > 0 && finLive.verdict.key !== "none" ? finLive.verdict.label : "—";
  return "—";
}

function PetalMark({ size = 40, ring = true }) {
  const c = 50, petal = "M50,50 C57,41 57,28 50,20 C43,28 43,41 50,50 Z";
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" style={{ display: "block", flexShrink: 0 }} aria-hidden="true">
      <defs>
        <linearGradient id="bpGold" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0" stopColor="var(--gold-1)" />
          <stop offset="1" stopColor="var(--gold-2)" />
        </linearGradient>
      </defs>
      {ring && <circle cx={c} cy={c} r="38" fill="none" stroke="var(--gold-2)" strokeWidth="1.2" opacity=".85" />}
      {ring && [[12, 12], [88, 12], [12, 88], [88, 88]].map(([x, y], i) => (
        <g key={i} stroke="var(--gold-2)" strokeWidth="1" opacity=".5"><line x1={x - 4} y1={y} x2={x + 4} y2={y} /><line x1={x} y1={y - 4} x2={x} y2={y + 4} /></g>
      ))}
      <g fill="url(#bpGold)">
        {[45, 135, 225, 315].map((a) => <path key={a} d={petal} transform={`rotate(${a} 50 50)`} />)}
      </g>
    </svg>
  );
}

function SuiteBrand({ dark, compact }) {
  const { t } = useLang();
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 13 }}>
      <PetalMark size={compact ? 34 : 42} />
      <div>
        <div style={{ fontWeight: 600, fontSize: compact ? 18 : 21, letterSpacing: "-.01em", lineHeight: 1 }}>
          <span style={{ color: dark ? "#fff" : "var(--ink)" }}>Blueprint</span><span style={{ color: "var(--brass)" }}>Sense</span>
        </div>
        {!compact && <div className="mono" style={{ fontSize: 8.5, letterSpacing: ".26em", textTransform: "uppercase", color: dark ? "var(--rail-soft)" : "var(--faint)", marginTop: 6 }}>{t("shell.tagline")}</div>}
      </div>
    </div>
  );
}

function SuiteRail({ active, setActive, plan, finLive, ideaCheck, openIE }) {
  const { t } = useLang();
  const MODULES = useModules(t);
  const heroProfit = finLive.netProfit;
  return (
    <aside style={{
      width: 348, flexShrink: 0, background: "linear-gradient(165deg, var(--rail-top), var(--rail-bot))",
      color: "#fff", padding: "40px 36px 32px", display: "flex", flexDirection: "column",
      position: "sticky", top: 0, height: "100vh", overflowY: "auto",
    }}>
      <div style={{ position: "absolute", inset: 0, pointerEvents: "none", overflow: "hidden" }}>
        <div style={{ position: "absolute", inset: 0, opacity: .5, backgroundImage: "linear-gradient(var(--rail-line) 1px, transparent 1px), linear-gradient(90deg, var(--rail-line) 1px, transparent 1px)", backgroundSize: "36px 36px" }} />
        <div style={{ position: "absolute", top: -120, right: -120, width: 300, height: 300, borderRadius: "50%", background: "radial-gradient(circle, rgba(211,169,84,.14), transparent 70%)" }} />
        <svg style={{ position: "absolute", bottom: -50, left: -70, width: 280, height: 280, opacity: .35 }} viewBox="0 0 200 200" fill="none" stroke="var(--brass)" strokeWidth=".6">
          <circle cx="100" cy="100" r="96" strokeDasharray="3 5" opacity=".6" />
          <circle cx="100" cy="100" r="60" opacity=".4" />
          <line x1="100" y1="88" x2="100" y2="112" /><line x1="88" y1="100" x2="112" y2="100" />
        </svg>
      </div>
      <div style={{ position: "relative" }}><SuiteBrand dark /></div>

      <div style={{ marginTop: 44, flex: 1 }}>
        {MODULES.map((m, i) => {
          const isActive = m.key === active;
          return (
            <button key={m.key} onClick={() => m.live && setActive(m.key)} disabled={!m.live}
              title={m.label}
              style={{ display: "flex", gap: 16, width: "100%", textAlign: "left", border: "none", background: "transparent", padding: 0, cursor: m.live ? "pointer" : "default", fontFamily: "inherit" }}>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flexShrink: 0 }}>
                <div className="mono" style={{
                  width: 30, height: 30, borderRadius: "50%", display: "grid", placeItems: "center",
                  fontSize: 11, fontWeight: 700, transition: "all .3s",
                  background: isActive ? "var(--brass)" : "transparent",
                  border: isActive ? "none" : `1.5px solid ${m.live ? "rgba(255,255,255,.3)" : "var(--rail-line)"}`,
                  color: isActive ? "#14233A" : m.live ? "#fff" : "var(--rail-softer)",
                  boxShadow: isActive ? "0 0 0 5px rgba(198,168,119,.18)" : "none",
                }}>{m.live ? m.n : "·"}</div>
                {i < MODULES.length - 1 && <div style={{ width: 1.5, flex: 1, minHeight: 22, margin: "6px 0", background: "var(--rail-line)" }} />}
              </div>
              <div style={{ paddingBottom: 18, paddingTop: 4, minWidth: 0 }}>
                <div style={{ fontSize: 15, fontWeight: isActive ? 700 : 500, color: isActive ? "#fff" : m.live ? "var(--rail-soft)" : "var(--rail-softer)", transition: "color .3s", display: "flex", alignItems: "center", gap: 8 }}>
                  {m.label}
                </div>
                <div className="serif-fig" style={{ fontSize: 15, color: isActive ? "var(--brass)" : "var(--rail-softer)", marginTop: 3 }}>{moduleSub(m.key, plan, finLive, ideaCheck, t)}</div>
              </div>
            </button>
          );
        })}
      </div>

      <div style={{ borderTop: "1px solid var(--rail-line)", paddingTop: 20 }}>
        <div className="mono" style={{ fontSize: 10, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--rail-softer)" }}>{t("shell.monthlyProfitAfterTax")}</div>
        <div className="serif-fig" style={{ fontSize: 38, color: heroProfit < 0 ? "var(--red)" : "var(--green-bright)", lineHeight: 1, marginTop: 8, transition: "color .3s" }}>
          {heroProfit < 0 ? "−" : ""}{fmtBaht(Math.abs(heroProfit))}
        </div>
        <div style={{ fontSize: 12.5, color: "var(--rail-soft)", marginTop: 7 }}>
          {finLive.sales > 0 ? (() => {
            const [pre, post] = t("shell.preTaxMargin", { pre: (finLive.profit < 0 ? "−" : "") + fmtBaht(Math.abs(finLive.profit)) }).split("%%MARGIN%%");
            return <span>{pre}<strong style={{ color: "#fff" }}>{fmtPct(finLive.netMargin)}</strong>{post}</span>;
          })() : t("shell.fromFinancialsStep")}
        </div>
        <button onClick={openIE} style={{ marginTop: 18, width: "100%", border: "1px solid var(--rail-line)", background: "rgba(255,255,255,.06)", color: "var(--rail-soft)", borderRadius: 11, padding: "11px 14px", fontSize: 13, fontWeight: 600, fontFamily: "inherit", cursor: "pointer" }}>
          {t("shell.importExport")}
        </button>
      </div>
    </aside>
  );
}

function SuiteTopBar({ active, setActive, finLive }) {
  const { t } = useLang();
  const MODULES = useModules(t);
  return (
    <header style={{ background: "linear-gradient(150deg, var(--rail-top), var(--rail-bot))", color: "#fff", padding: "18px 22px 14px", position: "sticky", top: 0, zIndex: 20 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <SuiteBrand dark compact />
        <div style={{ textAlign: "right" }}>
          <div className="mono" style={{ fontSize: 9, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--rail-softer)" }}>{t("shell.profitMoAfterTax")}</div>
          <div className="serif-fig" style={{ fontSize: 22, color: finLive.netProfit < 0 ? "var(--red)" : "var(--green-bright)", lineHeight: 1.1 }}>{finLive.netProfit < 0 ? "−" : ""}{fmtBaht(Math.abs(finLive.netProfit))}</div>
        </div>
      </div>
      <div style={{ display: "flex", gap: 6, marginTop: 14 }}>
        {MODULES.map((m) => (
          <button key={m.key} onClick={() => m.live && setActive(m.key)} style={{ flex: 1, border: "none", background: "transparent", padding: 0, cursor: m.live ? "pointer" : "default" }}>
            <div style={{ height: 4, borderRadius: 3, background: m.key === active ? "var(--brass)" : m.live ? "rgba(255,255,255,.3)" : "var(--rail-line)", transition: "background .3s" }} />
            <div style={{ fontSize: 10, marginTop: 6, color: m.key === active ? "#fff" : "var(--rail-softer)", fontWeight: m.key === active ? 700 : 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{m.label.split(" ")[0]}</div>
          </button>
        ))}
      </div>
    </header>
  );
}

const SUITE_TWEAKS = /*EDITMODE-BEGIN*/{
  "accent": "#1B3B5F",
  "coaching": true,
  "summary": true
}/*EDITMODE-END*/;

const SUITE_ACCENTS = {
  "#1B3B5F": { tint: "#EAF0F6", name: "Navy" },
  "#2F6F4F": { tint: "#E6F1EB", name: "Green" },
  "#1F1B16": { tint: "#EFEDEA", name: "Ink" },
  "#9A5B3B": { tint: "#F4EBE4", name: "Clay" },
};

function SuiteApp() {
  const { t, lang } = useLang();
  const [tweaks, setTweak] = useTweaks(SUITE_TWEAKS);
  const narrow = useMedia("(max-width: 920px)");
  const { plan, setNS, replacePlan } = usePlan();
  const MODULES = useModules(t);
  const [active, setActive] = React.useState(() => {
    try {
      const a = localStorage.getItem("resto.suite.active") || "idea";
      return ["idea", "financials", "pitch"].includes(a) ? a : "idea";
    } catch (e) { return "idea"; }
  });
  const [showIE, setShowIE] = React.useState(false);
  React.useEffect(() => { try { localStorage.setItem("resto.suite.active", active); } catch (e) {} }, [active]);

  React.useEffect(() => {
    const r = document.documentElement.style;
    r.setProperty("--accent", tweaks.accent);
    r.setProperty("--accent-tint", (SUITE_ACCENTS[tweaks.accent] || {}).tint || "#EAF0F6");
  }, [tweaks.accent]);

  const finLive = React.useMemo(() => computeFin(plan.financials, t), [plan.financials, t]);
  const ideaCheck = React.useMemo(() => computeIdea(plan.idea, t, lang), [plan.idea, t, lang]);

  const setIdea = (patch) => setNS("idea", patch);
  const setFin = (patch) => setNS("financials", patch);

  /* hand-off: pre-fill plan.financials from the idea — only fields still at their defaults */
  const goFinancialsPrefilled = () => {
    const idea = plan.idea, fin = plan.financials;
    const patch = {};
    const d = { ...fin.detailed };
    const band = idea.priceBand ? PRICE_BANDS[idea.priceBand] : null;
    if (idea.format.seats > 0 && d.seats === FIN_DEFAULTS.detailed.seats) d.seats = idea.format.seats;
    if (band && d.avgCheck === FIN_DEFAULTS.detailed.avgCheck) d.avgCheck = band.mid;
    patch.detailed = d;
    if (idea.format.sqm > 0 && !((fin.space || {}).shopSqm > 0)) patch.space = { ...(fin.space || {}), shopSqm: idea.format.sqm };
    if (idea.rentExpectation > 0 && fin.rent === FIN_DEFAULTS.rent && !((fin.costItems || {}).rent || []).length) patch.rent = idea.rentExpectation;
    if (idea.format.seats > 0 && fin.revMode === FIN_DEFAULTS.revMode) patch.revMode = "detailed";
    setNS("financials", patch);
    setActive("financials");
  };

  return (
    <div style={{ minHeight: "100vh", display: "flex", flexDirection: narrow ? "column" : "row" }}>
      {narrow
        ? <SuiteTopBar active={active} setActive={setActive} finLive={finLive} />
        : <SuiteRail active={active} setActive={setActive} plan={plan} finLive={finLive} ideaCheck={ideaCheck} openIE={() => setShowIE(true)} />}

      <div style={{ display: "flex", flexDirection: "column", flex: 1, minWidth: 0, background: "var(--paper)" }}>
        <main style={{ flex: 1, overflowY: "auto" }}>
          <div style={{ maxWidth: 720, margin: "0 auto", width: "100%", padding: narrow ? "32px 22px 64px" : "64px 56px 72px" }}>
            {active === "idea" && <IdeaModule idea={plan.idea} setIdea={setIdea} goFinancials={goFinancialsPrefilled} />}
            {active === "financials" && (
              <StepShell k="fin" kicker={t("fin.shellKicker")} title={t("fin.shellTitle")}
                lead={t("fin.shellLead")}>
                <FinancialModule fin={plan.financials} setFin={setFin} idea={plan.idea} narrow={narrow} summary={tweaks.summary} coaching={tweaks.coaching} />
              </StepShell>
            )}
            {active !== "idea" && active !== "financials" && <PitchDashboard plan={plan} setActive={setActive} openIE={() => setShowIE(true)} />}
          </div>
        </main>
        {narrow && (
          <div style={{ padding: "0 22px 28px" }}>
            <button onClick={() => setShowIE(true)} style={{ ...btnGhost, width: "100%", fontSize: 13.5, padding: "12px" }}>{t("shell.importExport")}</button>
          </div>
        )}
      </div>

      {showIE && <ImportExport plan={plan} replacePlan={replacePlan} onClose={() => setShowIE(false)} />}

      <TweaksPanel title={t("common.tweaks")}>
        <TweakSection label={t("common.look")} />
        <TweakColor label={t("common.accent")} value={tweaks.accent} options={Object.keys(SUITE_ACCENTS)} onChange={(v) => setTweak("accent", v)} />
        <TweakSection label={t("common.coachingSection")} />
        <TweakToggle label={t("common.financialSummaryToggle")} value={tweaks.summary} onChange={(v) => setTweak("summary", v)} />
        <TweakToggle label={t("common.coachingTips")} value={tweaks.coaching} onChange={(v) => setTweak("coaching", v)} />
      </TweaksPanel>
    </div>
  );
}

function SuiteRoot() {
  return (
    <LanguageProvider>
      <LanguageToggle />
      <SuiteApp />
    </LanguageProvider>
  );
}

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