/* ============================================================
   RESTO SUITE — PITCH SUMMARY DASHBOARD (step 03)
   READ-ONLY. Synthesizes plan.idea + plan.financials into a
   one-page investor/lender summary. Collects no inputs,
   writes nothing. Never crashes on partial data.
   ============================================================ */

function PitchMeta({ items }) {
  const parts = items.filter(Boolean);
  if (!parts.length) return null;
  return (
    <div style={{ color: "var(--muted)", fontSize: 14, marginTop: 10, display: "flex", flexWrap: "wrap", gap: "4px 10px", alignItems: "baseline" }}>
      {parts.map((p, i) => (
        <span key={i} style={{ display: "inline-flex", gap: 10, alignItems: "baseline" }}>
          {i > 0 && <span style={{ color: "var(--faint)" }}>·</span>}
          <span>{p}</span>
        </span>
      ))}
    </div>
  );
}

function PitchEmpty({ missing, setActive }) {
  const { t } = useLang();
  return (
    <div style={{ ...card, textAlign: "center", padding: 48 }}>
      <div className="serif" style={{ fontSize: 30 }}>{t("pitch.almostThere")}</div>
      <p style={{ color: "var(--muted)", fontSize: 15, maxWidth: 420, margin: "10px auto 0", lineHeight: 1.55 }}>
        {t("pitch.emptyBase")}
        {missing === "both" ? t("pitch.emptyBoth") :
         missing === "idea" ? t("pitch.emptyIdea") :
         t("pitch.emptyFin")}
      </p>
      <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 24, flexWrap: "wrap" }}>
        {(missing === "both" || missing === "idea") && <button onClick={() => setActive("idea")} style={btnPrimary}>{t("pitch.goToIdea")}</button>}
        {missing === "fin" && <button onClick={() => setActive("financials")} style={btnPrimary}>{t("pitch.goToFin")}</button>}
      </div>
    </div>
  );
}

function PitchPnlRow({ label, value, sub, strong, tone, indent }) {
  const col = tone === "green" ? "var(--green)" : tone === "red" ? "var(--red)" : "var(--ink)";
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 14, padding: "9px 0", paddingLeft: indent ? 16 : 0, borderBottom: strong ? "none" : "1px dashed var(--border)", borderTop: strong ? "1px solid var(--border)" : "none", marginTop: strong ? 4 : 0 }}>
      <span style={{ minWidth: 0 }}>
        <span style={{ fontSize: 14, fontWeight: strong ? 700 : 500, color: strong ? col : "var(--ink)" }}>{label}</span>
        {sub && <span style={{ fontSize: 11.5, color: "var(--faint)", display: "block", marginTop: 1 }}>{sub}</span>}
      </span>
      <span className="serif-fig" style={{ fontSize: strong ? 20 : 16.5, color: strong ? col : "var(--ink)", whiteSpace: "nowrap" }}>{value}</span>
    </div>
  );
}

function PitchDashboard({ plan, setActive, openIE }) {
  const { t, lang } = useLang();
  const ol = (v) => optLabel(lang, v);
  const idea = plan.idea || IDEA_DEFAULTS;
  const fin = plan.financials || FIN_DEFAULTS;
  const live = computeFin(fin, t);
  const check = computeIdea(idea, t, lang);

  const ideaReady = !!(idea.conceptName || idea.category || idea.usp || check.readiness >= 25);
  const finReady = live.sales > 0 && live.investment > 0;
  if (!ideaReady || !finReady) {
    return (
      <StepShell k="pitch" kicker={t("pitch.kicker")} title={t("pitch.title")} lead={t("pitch.lead")}>
        <PitchEmpty missing={!ideaReady && !finReady ? "both" : !ideaReady ? "idea" : "fin"} setActive={setActive} />
      </StepShell>
    );
  }

  const v = live.verdict;
  const dash = (s) => (s && String(s).trim() ? s : null);
  const mix = idea.channelMix || { dineIn: 0, delivery: 0, takeaway: 0 };
  const seats = (idea.format || {}).seats || 0;
  const sqm = (idea.format || {}).sqm || 0;
  const who = (idea.targetCustomer || []).map(ol).join(", ");
  const neg = (n) => `${n < 0 ? "−" : ""}${fmtBaht(Math.abs(n))}`;

  const conceptLines = [
    who ? t("pitch.builtFor", { who: who.toLowerCase() })
      + (idea.locationType ? t("pitch.inSetting", { loc: ol(idea.locationType).toLowerCase() }) : "")
      + (idea.priceBand ? t("pitch.atPrices", { band: ol(idea.priceBand).toLowerCase(), range: priceRange(idea.priceBand, lang) }) : "") + "." : null,
    seats || sqm ? t("pitch.theFormat", {
      seatsPart: seats ? t("pitch.seatsCount", { n: seats }) : t("pitch.noSeating"),
      sqmPart: sqm ? t("pitch.onSqm", { n: sqm }) : "",
      svc: (idea.format || {}).serviceStyle ? `, ${ol(idea.format.serviceStyle).toLowerCase()}` : "",
      dine: mix.dineIn, del: mix.delivery, take: mix.takeaway,
    }) : null,
  ].filter(Boolean);

  const watchFlags = check.flags.filter((f) => f.tone !== "green").slice(0, 5);

  return (
    <StepShell k="pitch" kicker={t("pitch.kicker")} title={t("pitch.title")} lead={t("pitch.lead2")}>
      <div data-pitch-page="">

        {/* a) header */}
        <div style={{ background: "var(--surface)", borderRadius: 20, boxShadow: "var(--shadow-lg)", overflow: "hidden", border: "1px solid var(--border)" }}>
          <div style={{ height: 4, background: toneVar(v.tone, "fg") }} />
          <div style={{ padding: "28px 32px", display: "flex", justifyContent: "space-between", gap: 20, flexWrap: "wrap", alignItems: "flex-start" }}>
            <div style={{ minWidth: 240, flex: 1 }}>
              <h2 className="serif" style={{ fontSize: 36, fontWeight: 400, margin: 0, letterSpacing: "-.015em", lineHeight: 1.1 }}>{dash(idea.conceptName) || t("pitch.untitledConcept")}</h2>
              {dash(idea.tagline) && <div className="serif" style={{ color: "var(--muted)", fontSize: 17, marginTop: 6, fontStyle: "italic" }}>“{idea.tagline}”</div>}
              <PitchMeta items={[dash(ol(idea.category)), dash(ol(idea.cuisine)), idea.priceBand ? `${ol(idea.priceBand)} · ${priceRange(idea.priceBand, lang)}` : null, dash(ol(idea.locationType))]} />
            </div>
            <div style={{ textAlign: "right", flexShrink: 0 }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--muted)" }}>{t("pitch.investmentVerdict")}</div>
              <span style={{ display: "inline-block", marginTop: 8, padding: "8px 18px", borderRadius: 99, background: toneVar(v.tone, "bg"), border: `1px solid ${toneVar(v.tone, "bd")}` }}>
                <span className="serif" style={{ fontSize: 22, color: toneVar(v.tone, "fg") }}>{v.label}</span>
              </span>
              <div style={{ fontSize: 11.5, color: "var(--faint)", marginTop: 7 }}>{t("pitch.fromAfterTaxMargin")}</div>
            </div>
          </div>
        </div>

        {/* b) the ask */}
        <div className="mono" style={{ fontSize: 10.5, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--brass-deep)", fontWeight: 600, margin: "24px 0 12px", display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 12, height: 1.5, background: "var(--brass)" }} />{t("pitch.theAsk")}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 14 }}>
          <Stat label={t("pitch.totalToOpen")} value={fmtBaht(live.investment)} sub={t("pitch.oneTimeInvestment")} />
          <Stat label={t("pitch.profitMoAfterTax")} value={neg(live.netProfit)} sub={t("pitch.preTax", { x: neg(live.profit) })} tone={live.netProfit >= 0 ? "green" : "red"} />
          <Stat label={t("pitch.netMargin")} value={fmtPct(live.netMargin)} sub={t("pitch.afterTax")} tone={live.netMargin >= 0.12 ? "green" : live.netMargin > 0 ? "amber" : "red"} />
          <Stat label={t("pitch.breakEvenSales")} value={fmtBaht(live.breakEven)} sub={t("pitch.perDayShort", { x: fmt(live.breakEvenDaily) })} />
          <Stat label={t("pitch.payback")} value={fmtMonths(live.paybackAfterTax)} sub={t("pitch.afterTax")} tone={isFinite(live.paybackAfterTax) && live.paybackAfterTax <= 36 ? "green" : "amber"} />
        </div>

        {/* c) the concept */}
        {(conceptLines.length > 0 || dash(idea.usp)) && (
          <div style={{ ...card, marginTop: 20, padding: 28 }}>
            <h3 className="serif" style={{ fontSize: 23, fontWeight: 400, margin: 0 }}>{t("pitch.theConcept")}</h3>
            {conceptLines.map((l, i) => <p key={i} style={{ fontSize: 15, lineHeight: 1.6, color: "var(--ink)", margin: "10px 0 0" }}>{l}</p>)}
            {dash(idea.usp) && (
              <div style={{ marginTop: 14, padding: "13px 17px", background: "var(--surface-2)", borderRadius: 12 }}>
                <span className="mono" style={{ fontSize: 9.5, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--brass-deep)", fontWeight: 600 }}>{t("pitch.theDifferentiator")}</span>
                <div className="serif" style={{ fontSize: 17.5, marginTop: 5, lineHeight: 1.45 }}>{idea.usp}</div>
              </div>
            )}
          </div>
        )}

        {/* d) the numbers */}
        <div style={{ ...card, marginTop: 16, padding: 28 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12, flexWrap: "wrap" }}>
            <h3 className="serif" style={{ fontSize: 23, fontWeight: 400, margin: 0 }}>{t("pitch.theNumbersMonthly")}</h3>
            <span style={{ display: "inline-flex", gap: 10, alignItems: "center" }}>
              <SourceTag kind="estimate" />
              <button onClick={() => setActive("financials")} className="no-print" style={{ border: "none", background: "transparent", color: "var(--accent)", fontSize: 13, fontWeight: 700, cursor: "pointer", fontFamily: "inherit", padding: 0 }}>{t("pitch.seeFullFinancials")}</button>
            </span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(250px, 1fr))", gap: "10px 40px", marginTop: 14 }}>
            <div>
              <PitchPnlRow label={t("pitch.sales")} sub={live.vatApplies && live.tax.pricesIncludeVat ? t("pitch.grossShownNet", { x: fmt(live.sales) }) : t("pitch.totalRevenue")} value={fmtBaht(live.netSales)} />
              <PitchPnlRow label={t("pitch.foodDrinkCost")} sub={t("pitch.ofSales", { pct: fmtPct(live.foodPct) })} value={"−" + fmtBaht(live.foodCost)} indent />
              <PitchPnlRow label={t("pitch.fixedOperatingCosts")} sub={t("pitch.fixedOperatingSub")} value={"−" + fmtBaht(live.fixed)} indent />
              <PitchPnlRow label={t("pitch.taxesStatutoryEst")} sub={t("pitch.taxesSetAside")} value={"−" + fmtBaht(live.taxTotal)} indent />
              <PitchPnlRow label={t("pitch.netProfitAfterTax")} sub={t("pitch.marginLabel", { pct: fmtPct(live.netMargin) })} value={neg(live.netProfit)} strong tone={live.netProfit >= 0 ? "green" : "red"} />
            </div>
            <div>
              <PitchPnlRow label={t("pitch.ebitdaPreTax")} sub={t("pitch.marginLabel", { pct: fmtPct(live.margin) })} value={neg(live.profit)} />
              <PitchPnlRow label={t("pitch.capexBuildSystems")} sub={t("pitch.capexSub")} value={fmtBaht(live.capex)} />
              <PitchPnlRow label={t("pitch.depositsStockReserve")} value={fmtBaht(Math.max(0, live.investment - live.capex))} />
              <PitchPnlRow label={t("pitch.totalCapitalRequired")} value={fmtBaht(live.investment)} strong />
            </div>
          </div>
        </div>

        {/* e) what to watch */}
        <div style={{ ...card, marginTop: 16, padding: 28 }}>
          <h3 className="serif" style={{ fontSize: 23, fontWeight: 400, margin: 0 }}>{t("pitch.whatToWatch")}</h3>
          <div style={{ color: "var(--muted)", fontSize: 13.5, marginTop: 5, marginBottom: 16 }}>{t("pitch.whatToWatchDesc")}</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
            {watchFlags.length > 0
              ? watchFlags.map((f, i) => <Flag key={i} tone={f.tone} text={f.text} />)
              : <Flag tone="green" text={t("pitch.noFlags")} />}
          </div>
          {check.riskiest && (
            <div style={{ marginTop: 16, padding: "14px 18px", background: "var(--surface-2)", borderRadius: 12, display: "flex", gap: 12, alignItems: "flex-start" }}>
              <span className="mono" style={{ fontSize: 9.5, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--brass-deep)", fontWeight: 700, flexShrink: 0, marginTop: 3 }}>{t("pitch.testFirst")}</span>
              <span style={{ fontSize: 14.5, lineHeight: 1.55 }}>{check.riskiest.text}</span>
            </div>
          )}
        </div>

        <div style={{ fontSize: 12, color: "var(--faint)", marginTop: 14, lineHeight: 1.5 }}>
          {t("pitch.disclaimer")}
        </div>

        {/* f) actions */}
        <div className="no-print" style={{ display: "flex", gap: 12, marginTop: 22, justifyContent: "center", flexWrap: "wrap" }}>
          <button onClick={openIE} style={btnGhost}>{t("pitch.exportPlan")}</button>
          <button onClick={() => window.print()} style={btnPrimary}>{t("pitch.printPdf")}</button>
        </div>
      </div>
    </StepShell>
  );
}

Object.assign(window, { PitchDashboard });
