// OrchestAI — page: Workspace (valuation model)

function PageWorkspace({ t, lang, projectId }) {
  const db = useDB();
  const project = db.projects.find(p => p.id === projectId) || db.projects[0];

  if (!project) {
    return (
      <div style={{ padding: "60px 0" }}>
        <EmptyState
          icon={Icon.bolt}
          title="Sin proyecto activo"
          sub="Seleccione un proyecto desde la lista o cree uno nuevo."
          action={null}
        />
      </div>
    );
  }

  const [tab, setTab] = React.useState("assumptions");
  const [wacc, setWacc] = React.useState(0.118);
  const [g, setG] = React.useState(0.025);

  // DCF state — starts empty, user fills projections
  const emptyYears = [new Date().getFullYear() - 1, new Date().getFullYear(), new Date().getFullYear() + 1,
                      new Date().getFullYear() + 2, new Date().getFullYear() + 3, new Date().getFullYear() + 4];
  const [rev,    setRev]    = React.useState(Array(emptyYears.length).fill(""));
  const [ebitda, setEbitda] = React.useState(Array(emptyYears.length).fill(""));
  const [capex,  setCapex]  = React.useState(Array(emptyYears.length).fill(""));
  const [nwc,    setNwc]    = React.useState(Array(emptyYears.length).fill(""));
  const [netDebt, setNetDebt] = React.useState("");
  const [shares,  setShares]  = React.useState("");

  const [comps, setComps] = React.useState([]);
  const [compForm, setCompForm] = React.useState({ ticker: "", name: "", mcap: "", ev_ebitda: "", ev_sales: "", pe: "" });
  const [showCompForm, setShowCompForm] = React.useState(false);

  const [aiLoading, setAiLoading] = React.useState(false);
  const [aiNote, setAiNote] = React.useState("");

  const runAiAnalysis = async () => {
    setAiLoading(true);
    setAiNote("");
    try {
      const system = `Sos un analista financiero senior especializado en valuación de empresas en mercados emergentes latinoamericanos.
Generás supuestos de proyección realistas y fundamentados basados en el perfil de la empresa.
Respondés ÚNICAMENTE con JSON válido, sin texto adicional, sin markdown, sin bloques de código.`;

      const userMsg = `Empresa: ${project.name}
Sector: ${project.sector}
País: ${project.country}
Moneda: ${project.currency}
Mandato: ${project.mandate}
Métodos de valuación: ${(project.methods || []).join(", ")}

Generá proyecciones para 6 períodos (1 histórico real + año actual estimado + 4 proyectados) en ${project.currency}M.
Usá supuestos conservadores pero realistas para el sector y mercado indicados.
Devolvé SOLO este JSON (sin ningún texto extra):
{
  "rev": [n1, n2, n3, n4, n5, n6],
  "ebitda": [n1, n2, n3, n4, n5, n6],
  "capex": [n1, n2, n3, n4, n5, n6],
  "nwc": [n1, n2, n3, n4, n5, n6],
  "wacc": 0.XX,
  "g": 0.0XX,
  "rationale": "string con los supuestos clave: crecimiento de revenue, márgenes EBITDA, WACC y tasa terminal justificados por sector/país"
}`;

      const text = await window.callAI(system, [{ role: "user", content: userMsg }], 900, "claude-sonnet-4-6");
      const clean = text.replace(/```json\n?|\n?```/g, "").trim();
      const json = JSON.parse(clean);

      if (Array.isArray(json.rev))    setRev(json.rev.map(String));
      if (Array.isArray(json.ebitda)) setEbitda(json.ebitda.map(String));
      if (Array.isArray(json.capex))  setCapex(json.capex.map(String));
      if (Array.isArray(json.nwc))    setNwc(json.nwc.map(String));
      if (json.wacc) setWacc(parseFloat(json.wacc));
      if (json.g)    setG(parseFloat(json.g));
      if (json.rationale) setAiNote(json.rationale);
    } catch (e) {
      setAiNote("Error: " + e.message + ". Verificá que ANTHROPIC_API_KEY esté configurada en Vercel.");
    }
    setAiLoading(false);
  };

  // Simple EV calc from last projected EBITDA + multiple
  const lastEbitda = parseFloat(ebitda[ebitda.length - 1]) || 0;
  const compMedianEvEbitda = comps.length
    ? comps.reduce((a, c) => a + (parseFloat(c.ev_ebitda) || 0), 0) / comps.length
    : 7.0;
  const evMultiples  = lastEbitda * compMedianEvEbitda;
  const evDcf        = lastEbitda > 0
    ? Math.max(0, lastEbitda * (1 - 0.35) / (wacc - g))
    : 0;
  const evBase       = evDcf > 0 ? Math.round((evDcf * 0.6 + evMultiples * 0.4)) : 0;
  const equityBase   = evBase - (parseFloat(netDebt) || 0);
  const sharesN      = parseFloat(shares) || 1;
  const perShare     = equityBase / sharesN;

  const addComp = () => {
    if (!compForm.ticker) return;
    setComps(prev => [...prev, { ...compForm, id: Date.now() }]);
    setCompForm({ ticker: "", name: "", mcap: "", ev_ebitda: "", ev_sales: "", pe: "" });
    setShowCompForm(false);
  };

  const tabs = [
    { k: "assumptions", l: t("assumptions") },
    { k: "outputs",     l: t("outputs") },
    { k: "comps",       l: t("comps_title") },
    { k: "risk",        l: t("risk_title") },
    { k: "report",      l: t("report") }
  ];

  return (
    <div>
      <div className="ws-header">
        <div className="ws-title-block">
          <div className="oai-row" style={{ gap: 8, marginBottom: 6 }}>
            <span className="mono" style={{ fontSize: 11.5, color: "var(--oai-ink-3)" }}>{project.code}</span>
            <Pill tone={project.status === "running" ? "amber" : project.status === "delivered" ? "lime" : "neutral"}>
              {t("status." + project.status)}
            </Pill>
            <Pill icon={Icon.globe}>{project.country} · {project.currency}</Pill>
            <Pill>{t("mandates." + project.mandate)}</Pill>
          </div>
          <h1>{project.name}</h1>
          <p style={{ marginTop: 4 }}>
            {t("sectors." + project.sector)} · {(project.methods || []).map(m => t("methods." + m).split(" ")[0].replace(/[()]/g,"")).join(" · ")}
          </p>
        </div>
        <div className="oai-row" style={{ gap: 6 }}>
          <Button kind="outline" icon={Icon.book}>{t("save_to_wiki")}</Button>
          <Button kind="outline" icon={Icon.export}>{t("export")}</Button>
          <Button kind="accent" icon={Icon.bolt} onClick={runAiAnalysis} disabled={aiLoading}>
            {aiLoading ? "Analizando…" : t("run_analysis")}
          </Button>
        </div>
      </div>

      {/* KPI bar */}
      <div className="ws-summary">
        <div className="kpi kpi--accent">
          <div className="kpi__label">{t("ev")} · {t("base_case")}</div>
          <div className="kpi__value">{evBase > 0 ? fmt(evBase, { decimals: 0, prefix: project.currency + " ", suffix: "M" }) : "—"}</div>
          <div className="kpi__sub">{evBase > 0 ? `Rango ${fmt(evBase * 0.88, { decimals: 0 })}–${fmt(evBase * 1.13, { decimals: 0 })}` : "Complete los supuestos"}</div>
        </div>
        <div className="kpi">
          <div className="kpi__label">{t("equity_value")}</div>
          <div className="kpi__value">{equityBase > 0 ? fmt(equityBase, { decimals: 0, prefix: project.currency + " ", suffix: "M" }) : "—"}</div>
          <div className="kpi__sub">{netDebt ? `Deuda neta ${fmt(parseFloat(netDebt), { decimals: 0 })}` : "—"}</div>
        </div>
        <div className="kpi">
          <div className="kpi__label">{t("per_share")}</div>
          <div className="kpi__value">{perShare > 0 ? fmt(perShare, { decimals: 2, prefix: project.currency + " " }) : "—"}</div>
          <div className="kpi__sub">{shares ? shares + "M acciones" : "—"}</div>
        </div>
        <div className="kpi">
          <div className="kpi__label">{t("implied_multiple")} EV/EBITDA</div>
          <div className="kpi__value">{lastEbitda > 0 && evBase > 0 ? (evBase / lastEbitda).toFixed(1) + "x" : "—"}</div>
          <div className="kpi__sub">{comps.length > 0 ? `Peer median ${compMedianEvEbitda.toFixed(1)}x` : "Agregue comparables"}</div>
        </div>
      </div>

      {/* AI rationale note */}
      {aiNote && (
        <div style={{ marginTop: 12, padding: "10px 16px", borderRadius: 8, background: "var(--oai-accent-sub)", border: "1px solid var(--oai-accent)", fontSize: 12.5, lineHeight: 1.6, color: "var(--oai-accent-ink)" }}>
          <Icon.sparkle style={{ width: 13, height: 13, display: "inline", verticalAlign: "-2px", marginRight: 6 }}/>
          {aiNote}
        </div>
      )}

      {/* Tabs */}
      <div className="oai-tabs" style={{ marginTop: 24 }}>
        {tabs.map(x => (
          <button key={x.k} className={classNames("oai-tab", tab === x.k && "is-active")} onClick={() => setTab(x.k)}>{x.l}</button>
        ))}
      </div>

      {tab === "assumptions" && (
        <div className="oai-grid" style={{ gridTemplateColumns: "2fr 1fr", gap: 20 }}>
          <Card>
            <h3 style={{ marginBottom: 10 }}>{t("projection")} · {project.currency}M</h3>
            <table className="oai-table dcf-table">
              <thead>
                <tr>
                  <th>{t("metric")}</th>
                  {emptyYears.map((y, i) => <th key={y} className="num" style={{ fontFamily: "var(--oai-font-mono)" }}>{y}{i === 1 ? "E" : i > 1 ? "P" : "A"}</th>)}
                  <th className="num">{t("terminal")}</th>
                </tr>
              </thead>
              <tbody>
                {[
                  { label: t("revenue"), vals: rev, set: setRev },
                  { label: t("ebitda"),  vals: ebitda, set: setEbitda },
                  { label: t("capex"),   vals: capex, set: setCapex },
                  { label: "Δ " + t("nwc"), vals: nwc, set: setNwc }
                ].map(row => (
                  <tr key={row.label}>
                    <td style={{ fontWeight: 500 }}>{row.label}</td>
                    {row.vals.map((v, i) => (
                      <td key={i} className="num">
                        <input
                          className={classNames(i >= 2 && "is-proj")}
                          value={v}
                          placeholder="0"
                          onChange={e => { const a = [...row.vals]; a[i] = e.target.value; row.set(a); }}
                        />
                      </td>
                    ))}
                    <td className="num is-term">—</td>
                  </tr>
                ))}
                <tr>
                  <td className="muted">{t("margin")}</td>
                  {ebitda.map((v, i) => {
                    const r = parseFloat(rev[i]) || 0;
                    const e = parseFloat(v) || 0;
                    return <td key={i} className="num muted">{r > 0 ? pct(e / r, 1) : "—"}</td>;
                  })}
                  <td className="num muted">—</td>
                </tr>
              </tbody>
            </table>
          </Card>
          <Card>
            <h3 style={{ marginBottom: 14 }}>{t("discount_params")}</h3>
            <Field label={t("wacc") + " · " + pct(wacc, 2)}>
              <input type="range" min="0.07" max="0.22" step="0.001" value={wacc} onChange={e => setWacc(+e.target.value)} style={{ width: "100%" }} />
            </Field>
            <Field label={t("growth_terminal") + " · " + pct(g, 2)}>
              <input type="range" min="0" max="0.05" step="0.001" value={g} onChange={e => setG(+e.target.value)} style={{ width: "100%" }} />
            </Field>
            <hr className="oai-hr" />
            <Field label={t("net_debt") + " (" + project.currency + "M)"}>
              <Input type="number" placeholder="0" value={netDebt} onChange={e => setNetDebt(e.target.value)} />
            </Field>
            <Field label={t("shares_mm")}>
              <Input type="number" placeholder="0" value={shares} onChange={e => setShares(e.target.value)} />
            </Field>
            <Field label={t("tax_rate") + " · 35.0%"}>
              <input type="range" min="0.20" max="0.45" step="0.005" defaultValue="0.35" style={{ width: "100%" }} />
            </Field>
          </Card>
        </div>
      )}

      {tab === "outputs" && (
        <div>
          {evBase > 0 ? (
            <Card>
              <div className="chart-title"><h3>{t("football_title")}</h3><span className="mono muted" style={{ fontSize: 11 }}>{project.currency}M</span></div>
              <div style={{ fontSize: 13, lineHeight: 1.8, marginTop: 16 }}>
                <div className="oai-grid" style={{ gridTemplateColumns: "repeat(3,1fr)", gap: 14 }}>
                  <div style={{ background: "var(--oai-bg-sunk)", borderRadius: 10, padding: "14px 18px", textAlign: "center" }}>
                    <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.07em", fontWeight: 600 }}>{t("dcf_weight")}</div>
                    <div style={{ fontSize: 24, fontWeight: 700, fontFamily: "var(--oai-font-display)", marginTop: 8 }}>{fmt(evDcf, { decimals: 0 })}</div>
                  </div>
                  <div style={{ background: "var(--oai-accent-sub)", borderRadius: 10, padding: "14px 18px", textAlign: "center", border: "1px solid var(--oai-accent)" }}>
                    <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.07em", fontWeight: 600, color: "var(--oai-accent-ink)" }}>EV BASE</div>
                    <div style={{ fontSize: 24, fontWeight: 700, fontFamily: "var(--oai-font-display)", marginTop: 8, color: "var(--oai-accent-ink)" }}>{fmt(evBase, { decimals: 0 })}</div>
                  </div>
                  <div style={{ background: "var(--oai-bg-sunk)", borderRadius: 10, padding: "14px 18px", textAlign: "center" }}>
                    <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.07em", fontWeight: 600 }}>{t("multiples_weight")}</div>
                    <div style={{ fontSize: 24, fontWeight: 700, fontFamily: "var(--oai-font-display)", marginTop: 8 }}>{fmt(evMultiples, { decimals: 0 })}</div>
                  </div>
                </div>
              </div>
            </Card>
          ) : (
            <EmptyState
              icon={Icon.chart}
              title="Sin resultados aún"
              sub="Complete los supuestos de proyección y los parámetros de descuento para ver el football field."
            />
          )}
        </div>
      )}

      {tab === "comps" && (
        <Card>
          <div className="oai-row" style={{ marginBottom: 12 }}>
            <h3 style={{ flex: 1 }}>{t("comps_title")}</h3>
            <Button kind="outline" size="sm" icon={Icon.plus} onClick={() => setShowCompForm(v => !v)}>{t("add_comp")}</Button>
          </div>

          {showCompForm && (
            <div className="oai-card oai-card--padded" style={{ marginBottom: 14, background: "var(--oai-bg-sunk)" }}>
              <div className="oai-grid" style={{ gridTemplateColumns: "1fr 2fr 1fr 1fr 1fr 1fr", gap: 8, marginBottom: 10 }}>
                <Input placeholder="Ticker" value={compForm.ticker} onChange={e => setCompForm({ ...compForm, ticker: e.target.value.toUpperCase() })} />
                <Input placeholder="Empresa" value={compForm.name} onChange={e => setCompForm({ ...compForm, name: e.target.value })} />
                <Input placeholder="MCap" type="number" value={compForm.mcap} onChange={e => setCompForm({ ...compForm, mcap: e.target.value })} />
                <Input placeholder="EV/EBITDA" type="number" value={compForm.ev_ebitda} onChange={e => setCompForm({ ...compForm, ev_ebitda: e.target.value })} />
                <Input placeholder="EV/Sales" type="number" value={compForm.ev_sales} onChange={e => setCompForm({ ...compForm, ev_sales: e.target.value })} />
                <Input placeholder="P/E" type="number" value={compForm.pe} onChange={e => setCompForm({ ...compForm, pe: e.target.value })} />
              </div>
              <div className="oai-row" style={{ justifyContent: "flex-end", gap: 6 }}>
                <Button kind="ghost" size="sm" onClick={() => setShowCompForm(false)}>{t("cancel")}</Button>
                <Button kind="accent" size="sm" icon={Icon.check} onClick={addComp}>Agregar</Button>
              </div>
            </div>
          )}

          {comps.length > 0 ? (
            <table className="oai-table">
              <thead>
                <tr>
                  <th>{t("ticker")}</th>
                  <th>Empresa</th>
                  <th className="num">{t("mcap")}</th>
                  <th className="num">{t("ev_ebitda")}</th>
                  <th className="num">{t("ev_sales")}</th>
                  <th className="num">{t("pe")}</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {comps.map(c => (
                  <tr key={c.id}>
                    <td><span className="mono" style={{ fontWeight: 700 }}>{c.ticker}</span></td>
                    <td>{c.name}</td>
                    <td className="num">{c.mcap ? parseFloat(c.mcap).toLocaleString() : "—"}</td>
                    <td className="num">{c.ev_ebitda ? parseFloat(c.ev_ebitda).toFixed(1) + "x" : "—"}</td>
                    <td className="num">{c.ev_sales ? parseFloat(c.ev_sales).toFixed(2) + "x" : "—"}</td>
                    <td className="num">{c.pe ? parseFloat(c.pe).toFixed(1) + "x" : "—"}</td>
                    <td>
                      <button className="oai-btn oai-btn--ghost oai-btn--sm" onClick={() => setComps(prev => prev.filter(x => x.id !== c.id))}>
                        <Icon.trash className="oai-btn__icon"/>
                      </button>
                    </td>
                  </tr>
                ))}
                {comps.length > 1 && (
                  <tr style={{ background: "var(--oai-accent-sub)" }}>
                    <td colSpan="2" style={{ fontWeight: 700, color: "var(--oai-accent-ink)" }}>{t("median")}</td>
                    <td className="num" style={{ fontWeight: 600 }}>—</td>
                    <td className="num" style={{ fontWeight: 700, color: "var(--oai-accent-ink)" }}>
                      {(comps.reduce((a,c) => a + (parseFloat(c.ev_ebitda)||0), 0) / comps.length).toFixed(1)}x
                    </td>
                    <td className="num" style={{ fontWeight: 700, color: "var(--oai-accent-ink)" }}>
                      {(comps.reduce((a,c) => a + (parseFloat(c.ev_sales)||0), 0) / comps.length).toFixed(2)}x
                    </td>
                    <td className="num" style={{ fontWeight: 700, color: "var(--oai-accent-ink)" }}>
                      {(comps.reduce((a,c) => a + (parseFloat(c.pe)||0), 0) / comps.length).toFixed(1)}x
                    </td>
                    <td></td>
                  </tr>
                )}
              </tbody>
            </table>
          ) : (
            <EmptyState icon={Icon.chart} title="Sin comparables" sub="Agregue empresas comparables para calcular el múltiplo de mercado." />
          )}
        </Card>
      )}

      {tab === "risk" && (
        <div className="oai-col" style={{ gap: 20 }}>
          <Card>
            <div className="oai-row" style={{ marginBottom: 14 }}>
              <h3 style={{ flex: 1 }}>{t("risk_title")}</h3>
              <Pill tone="cobalt" icon={Icon.globe}>{t("source_label")}: BCRA · JP Morgan · Damodaran</Pill>
            </div>
            <div className="risk-board">
              {[
                { label: t("ar_country_risk"), value: "—", delta: "bps", note: t("enter_manually") },
                { label: t("bcra_fx") + " ARS/USD", value: "—", delta: "", note: t("enter_manually") },
                { label: t("inflation"), value: "—", delta: "", note: "" },
                { label: t("rating"), value: "—", delta: "", note: "S&P · estable" }
              ].map((r, i) => (
                <div key={i} className="risk-cell">
                  <div className="risk-cell__label">{r.label}</div>
                  <div className="risk-cell__value">{r.value}</div>
                  <div className="risk-cell__delta mono muted">{r.note}</div>
                </div>
              ))}
            </div>
          </Card>
          <Card>
            <h3 style={{ marginBottom: 10 }}>Impacto en valuación</h3>
            <p style={{ fontSize: 13, lineHeight: 1.7 }}>
              {t("country_risk_body")}
            </p>
          </Card>
        </div>
      )}

      {tab === "report" && (
        <Card>
          <div className="oai-row" style={{ marginBottom: 14 }}>
            <h3 style={{ flex: 1 }}>Reporte ejecutivo · {project.name}</h3>
            <Button kind="outline" size="sm" icon={Icon.export}>{t("export_pdf")}</Button>
            <Button kind="outline" size="sm" icon={Icon.export}>{t("export_xlsx")}</Button>
            <Button kind="outline" size="sm" icon={Icon.export}>{t("export_pptx")}</Button>
          </div>
          {evBase > 0 ? (
            <div style={{ fontSize: 13.5, lineHeight: 1.7, maxWidth: 760 }}>
              <h4 style={{ marginBottom: 8 }}>{t("exec_summary")}</h4>
              <p>El análisis de valuación de <b>{project.name}</b> sitúa el Enterprise Value en un rango de
                <b> {project.currency} {fmt(evBase * 0.88, { decimals: 0 })}M – {fmt(evBase * 1.13, { decimals: 0 })}M</b>,
                con caso base de {project.currency} {fmt(evBase, { decimals: 0 })}M.
                El múltiplo EV/EBITDA implícito es {lastEbitda > 0 ? (evBase / lastEbitda).toFixed(1) + "x" : "—"}.
              </p>
              <h4 style={{ marginTop: 18, marginBottom: 8 }}>Metodología</h4>
              <ul style={{ paddingLeft: 20, color: "var(--oai-ink-2)" }}>
                {(project.methods || []).map(m => <li key={m}>{t("methods." + m)}</li>)}
              </ul>
            </div>
          ) : (
            <EmptyState icon={Icon.doc} title="Sin datos suficientes" sub="Complete los supuestos de proyección para generar el reporte ejecutivo." />
          )}
        </Card>
      )}
    </div>
  );
}

window.PageWorkspace = PageWorkspace;
