// ═══════════════════════════════════════════════════════════════
// MezzanineTaxFlow — drops into detail.jsx Group C in place of the
// plain <p>{taxCopy}</p>. Renders the heading + visual breakdown.
//
// Numbers are computed live from the slider `amount` and the product's
// projected exit (passed in from detail.jsx so we stay in sync with the
// Calculator card above). Stays vertical at all viewport widths — the
// detail panel can be as narrow as ~440px on tablet.
//
// Conventions match detail.jsx: inline styles for color tokens (so dark
// mode resolves correctly), CSS classes for layout (see the
// `.r-tax-*` block in index.html).
// ═══════════════════════════════════════════════════════════════

const { useMemo } = React;

function MezzanineTaxFlow({ product, amount, projectedExit, lang, dark, t, taxCopy }) {
  // Mirror the color resolution used elsewhere in detail.jsx so theme
  // flips stay 1:1 with the surrounding sections.
  const text   = dark ? "#FAF7F3" : "#393433";
  const muted  = dark ? "#8A827F" : "#6B6361";
  const faint  = dark ? "#5A5654" : "#9A9290";
  const line   = dark ? "#2A2825" : "#E2E0DF";
  const line2  = dark ? "#3F3D3A" : "#C8C4BF";
  const bg     = dark ? "#1A1817" : "#FFFFFF";
  const accent = "#4866B2";
  const lime   = "#EDFE38";
  const warn   = "#D97757";
  const warnBg = dark ? "rgba(217, 119, 87, 0.10)" : "#FFF4ED";

  const taxLabel = (t && t.tax) || (lang === "es" ? "Impuestos" : "Tax");

  // ─────────────────────────────────────────────────────────────
  // Live calculation. Falls back to the displayed product mid-rate
  // if projectedExit isn't provided (e.g. unit tests).
  // ─────────────────────────────────────────────────────────────
  const calc = useMemo(() => {
    const principal = amount || product?.minimumInvestment?.amount || 0;
    let gross = (projectedExit ?? principal) - principal;
    if (gross <= 0) {
      const r = product?.targetReturn || {};
      const years = product?.holdPeriodYears
        ? (product.holdPeriodYears[0] + product.holdPeriodYears[1]) / 2
        : 2;
      if (r.yield)    gross = principal * ((r.yield[0]    + r.yield[1])    / 200) * years;
      else if (r.irr) gross = principal * ((r.irr[0]      + r.irr[1])      / 200) * years;
    }
    const whtRate    = (product?.whtRate    ?? 0.15);
    const usRate     = (product?.usMarginal ?? 0.37);
    const wht        = gross * whtRate;
    const netToLlc   = gross - wht;
    const usGrossTax = gross * usRate;
    const ftc        = wht;                          // assumed fully creditable
    const netUsTax   = usGrossTax - ftc;
    const totalTax   = usGrossTax;                   // FTC offsets WHT 1:1
    return { principal, gross, whtRate, usRate, wht, netToLlc, usGrossTax, ftc, netUsTax, totalTax };
  }, [product, amount, projectedExit]);

  const fmt  = (n) => (window.formatCurrency      ? window.formatCurrency(n)      : `$${Math.round(n).toLocaleString()}`);
  const fmtS = (n) => (window.formatCurrencyShort ? window.formatCurrencyShort(n) : fmt(n));
  const pct  = (n) => `${(n * 100).toFixed(0)}%`;

  // ─────────────────────────────────────────────────────────────
  // Copy. Spanish strings inline; the host-provided `t` may not have
  // tax-specific keys yet, so we keep them local to ship without a
  // sheet round-trip. Wire to t.* later if/when added.
  // ─────────────────────────────────────────────────────────────
  const es = lang === "es";
  const L = {
    heading:     taxLabel,
    leadStart:   es ? "Inversionista de EE.UU. extiende financiamiento mezzanine a un SPV mexicano vía un vehículo de paso. Ilustrativo: "
                    : "U.S. investor extending mezzanine financing to a Mexican SPV through a domestic pass-through vehicle. Illustrative: ",
    leadJoin:    es ? " de compromiso con " : " commitment at ",
    leadEnd:     es ? "× MOIC."             : "× MOIC.",
    keyInvest:   es ? "Inversión"           : "Investment",
    keyMoic:     "MOIC",
    keyInterest: es ? "Intereses brutos"    : "Interest",
    structureH:  es ? "Estructura y flujos" : "Structure & cash flows",
    nodeUsInv:   es ? "Inversionista de EE.UU." : "U.S. Investor",
    nodeUsLlc:   es ? "LLC en EE.UU."       : "U.S. LLC",
    nodeMxSpv:   es ? "SAPI de C.V. mexicana" : "Mexican SAPI de C.V.",
    tagProvider: es ? "Proveedor de capital" : "Capital provider",
    tagPool:     es ? "Vehículo de agrupación" : "Pooling vehicle",
    tagBorrower: es ? "SPV del proyecto / prestatario" : "Project SPV / borrower",
    metaLlc:     es ? "Entidad de paso (disregarded)" : "Pass-through entity (disregarded)",
    descLlc:     es ? "Agrupa capital y administra la facilidad mezzanine al SPV." : "Pools investor capital and administers the mezzanine facility to the project SPV.",
    descSpv:     es ? "Despliega los recursos al desarrollo subyacente; remite intereses netos de retención." : "Deploys proceeds into the underlying development; remits interest net of withholding.",
    personMary:  "Mary",
    personRole:  es ? "Persona física · contribuyente de EE.UU. · recibe K-1" : "Individual · U.S. taxpayer · K-1 recipient",
    step1:       es ? "como capital" : "as equity",
    step1Sub:    es ? "Compromiso inicial al LLC" : "Initial commitment into the LLC",
    step2:       es ? "préstamo mezzanine" : "mezzanine loan",
    step2Sub:    es ? "Dispuesto contra línea de crédito comprometida" : "Drawn against committed line of credit",
    step3:       es ? "intereses netos" : "net interest",
    step3Sub:    (g, w) => es
      ? `Bruto ${fmt(g)} menos retención mexicana 15% (${fmt(w)})`
      : `Gross ${fmt(g)} less 15% Mexican WHT (${fmt(w)})`,
    byLevelH:    es ? "Tratamiento fiscal por nivel" : "Tax treatment by level",
    lvl1:        es ? "Inversionista de EE.UU." : "U.S. Investor",
    lvl2:        es ? "LLC de EE.UU."           : "U.S. LLC",
    lvl3:        es ? "México — Retención"      : "Mexico — Withholding Tax",
    bullet1a:    (g) => es
      ? <>Reporta <b>{fmt(g)}</b> como intereses ordinarios en la declaración de EE.UU. (K-1).</>
      : <>Reports <b>{fmt(g)}</b> of ordinary interest income on the U.S. return (K-1).</>,
    bullet1b:    es ? <>Acreditable: <b>foreign tax credit</b> por la retención mexicana pagada en origen.</>
                    : <>Eligible to claim a <b>foreign tax credit</b> for Mexican withholding paid at source.</>,
    bullet1c:    (r) => es
      ? <>Tasa marginal ordinaria federal — <b>{pct(r)}</b> en este ejemplo.</>
      : <>Interest taxed at ordinary federal rates — <b>{pct(r)}</b> top marginal in this example.</>,
    bullet2a:    es ? "No considerada para efectos del ISR federal de EE.UU. — sin impuesto a nivel entidad."
                    : "Disregarded for U.S. federal income-tax purposes — no entity-level tax on the investor.",
    bullet2b:    es ? "Ingresos y gastos fluyen a los miembros vía Schedule K-1."
                    : "Interest income and expenses flow through to members via Schedule K-1.",
    bullet2c:    (n) => es
      ? <>Recibe <span style={{ color: accent, fontVariantNumeric: "tabular-nums" }}>{fmt(n)}</span> netos tras retención mexicana del 15%.</>
      : <>Receives <span style={{ color: accent, fontVariantNumeric: "tabular-nums" }}>{fmt(n)}</span> net interest after 15% Mexican withholding.</>,
    bullet3a:    (r) => es
      ? <>SPV retiene <b>{pct(r)}</b> ISR mexicano sobre intereses bajo <b>Art. 11</b> del tratado EE.UU./MX.</>
      : <>SPV withholds <b>{pct(r)}</b> Mexican WHT on interest under <b>Art. 11</b> of the U.S./MX treaty.</>,
    bullet3b:    (g) => es ? <>Sobre <b>{fmt(g)}</b> de intereses brutos:</>
                           : <>On <b>{fmt(g)}</b> of gross interest:</>,
    bullet3c:    es ? <>Retención remitida por el SPV al <b>SAT</b> (autoridad fiscal mexicana).</>
                    : <>Withholding remitted by SPV to <b>SAT</b> (Mexican tax authority).</>,
    sgWHT:       es ? "ISR 15%"        : "WHT (15%)",
    sgNet:       es ? "Neto al LLC"    : "Net paid to LLC",
    sumH:        es ? "Resumen fiscal del inversionista" : "U.S. Investor Tax Summary",
    sumLineCol:  es ? "Concepto"        : "Line item",
    sumUsdCol:   "USD",
    sumOrdinary: es ? "Intereses ordinarios (K-1)"          : "Ordinary interest income (per K-1)",
    sumUsGross:  es ? "ISR federal EE.UU. @ 37% (bruto)"    : "U.S. federal tax @ 37% (gross)",
    sumFtc:      es ? "Menos: foreign tax credit (ISR MX)"  : "Less: Foreign tax credit (MX WHT)",
    sumNetUs:    es ? "ISR federal EE.UU. neto"             : "Net U.S. federal tax",
    sumTotal:    es ? "ISR total sobre intereses (US + MX)" : "Total tax on interest (US + MX)",
    sumRate:     es ? "Tasa efectiva"                       : "Effective rate",
    takeawayH:   es ? "Conclusión" : "Key takeaway",
    takeawayA:   (tot, eff) => es
      ? <>Asumiendo que la retención mexicana es totalmente acreditable, el impuesto agregado sobre los intereses es <b>{fmt(tot)}</b> — una tasa efectiva de <b>{(eff * 100).toFixed(1)}%</b>.</>
      : <>Assuming the Mexican withholding is fully creditable, aggregate tax on the interest is <b>{fmt(tot)}</b> — an effective rate of <b>{(eff * 100).toFixed(1)}%</b>.</>,
    takeawayB:   es ? "Económicamente idéntico a obtener los intereses domésticamente: la estructura transfronteriza no impone fricción fiscal incremental a nivel del inversionista."
                    : "Economically identical to earning the interest domestically: cross-border structuring imposes no incremental tax friction at the investor level.",
    disclaimer:  es ? "Solo ilustrativo. Asume elegibilidad del tratado, suficiente ingreso de fuente extranjera para absorber el FTC, y sin impuestos estatales. No constituye asesoría legal ni fiscal."
                    : "Illustrative only. Assumes treaty eligibility, sufficient foreign-source income to absorb the FTC, and no state-level tax. Not legal or tax advice.",
  };

  const moic = useMemo(() => {
    if (calc.principal <= 0) return null;
    return ((calc.principal + calc.gross) / calc.principal).toFixed(2);
  }, [calc]);

  const effectiveRate = calc.gross > 0 ? (calc.totalTax / calc.gross) : 0;

  return (
    <div className="r-tax-root">
      <h3 className="r-detail-h3-tight" style={{ color: text }}>{L.heading}</h3>

      <div className="r-tax-body" style={{ border: `1px solid ${line}` }}>

      <p className="r-detail-body-p r-tax-lede" style={{ color: muted }}>
        {L.leadStart}<b style={{ color: text, fontWeight: 400 }}>{fmt(calc.principal)}</b>{L.leadJoin}<b style={{ color: text, fontWeight: 400 }}>{moic || "—"}</b>{L.leadEnd}
      </p>

      {/* Key economics — 3-up stat grid */}
      <div className="r-tax-keystats" style={{ background: bg, border: `1px solid ${line}` }}>
        <KeyStat label={L.keyInvest}   value={fmtS(calc.principal)}        muted={muted} text={text} />
        <KeyStat label={L.keyMoic}     value={moic ? `${moic}×` : "—"}     muted={muted} text={text} mono />
        <KeyStat label={L.keyInterest} value={fmtS(calc.gross)}            muted={muted} text={text} />
      </div>

      <hr className="r-detail-divider" aria-hidden="true" style={{ borderTop: `1px dashed ${line2}` }} />

      {/* Structure & cash flows */}
      <h3 className="r-detail-h3-tight" style={{ color: text }}>{L.structureH}</h3>

      <div className="r-tax-structure">
        <Node bg={bg} line={line} text={text} muted={muted}
              tag={L.tagProvider} flag="us" title={L.nodeUsInv}>
          <div className="r-tax-person">
            <div className="r-tax-avatar" style={{ background: dark ? "#22201E" : "#FAF7F3", border: `1px solid ${line}`, color: text }}>
              {L.personMary.charAt(0)}
            </div>
            <div className="r-tax-person-meta" style={{ color: muted }}>
              <b style={{ color: text }}>{L.personMary}</b>
              {L.personRole}
            </div>
          </div>
        </Node>

        <FlowStep n={1} ink={text} muted={muted} faint={faint} accent={accent}
                  amount={fmt(calc.principal)} verb={L.step1} sub={L.step1Sub} />

        <Node bg={bg} line={line} text={text} muted={muted}
              tag={L.tagPool} flag="us" title={L.nodeUsLlc} meta={L.metaLlc} desc={L.descLlc} />

        <FlowStep n={2} ink={text} muted={muted} faint={faint} accent={accent}
                  amount={fmt(calc.principal)} verb={L.step2} sub={L.step2Sub} />

        <Node bg={bg} line={line} text={text} muted={muted}
              tag={L.tagBorrower} flag="mx" title={L.nodeMxSpv} desc={L.descSpv} />

        <FlowStep n={3} up ink={text} muted={muted} faint={faint} accent={accent}
                  amount={fmt(calc.netToLlc)} verb={L.step3} sub={L.step3Sub(calc.gross, calc.wht)} />
      </div>

      <hr className="r-detail-divider" aria-hidden="true" style={{ borderTop: `1px dashed ${line2}` }} />

      {/* Tax by level — three stacked cards. Always stacked: never side-by-side
          at panel widths (panel can be ~440px on tablet). */}
      <h3 className="r-detail-h3-tight" style={{ color: text }}>{L.byLevelH}</h3>

      <div className="r-tax-cards">
        <TaxCard variant="us"     idx={1} title={L.lvl1} flag="us" bg={bg} line={line} accent={text}    text={text} muted={muted}>
          <li>{L.bullet1a(calc.gross)}</li>
          <li>{L.bullet1b}</li>
          <li>{L.bullet1c(calc.usRate)}</li>
        </TaxCard>

        <TaxCard variant="entity" idx={2} title={L.lvl2} flag="us" bg={bg} line={line} accent={accent}  text={text} muted={muted}>
          <li>{L.bullet2a}</li>
          <li>{L.bullet2b}</li>
          <li>{L.bullet2c(calc.netToLlc)}</li>
        </TaxCard>

        <TaxCard variant="mx"     idx={3} title={L.lvl3} flag="mx" bg={warnBg} line={line} accent={warn} text={text} muted={muted}>
          <li>{L.bullet3a(calc.whtRate)}</li>
          <li>
            {L.bullet3b(calc.gross)}
            <div className="r-tax-subgrid" style={{ color: muted, borderLeft: `1px solid ${line2}` }}>
              <span>{L.sgWHT}<b style={{ color: text, fontWeight: 400 }}>{fmt(calc.wht)}</b></span>
              <span>{L.sgNet}<b style={{ color: text, fontWeight: 400 }}>{fmt(calc.netToLlc)}</b></span>
            </div>
          </li>
          <li>{L.bullet3c}</li>
        </TaxCard>
      </div>

      <hr className="r-detail-divider" aria-hidden="true" style={{ borderTop: `1px dashed ${line2}` }} />

      {/* Summary table */}
      <h3 className="r-detail-h3-tight" style={{ color: text }}>{L.sumH}</h3>

      <table className="r-tax-summary">
        <thead>
          <tr>
            <th style={{ color: muted, borderBottom: `1px solid ${text}` }}>{L.sumLineCol}</th>
            <th className="r" style={{ color: muted, borderBottom: `1px solid ${text}` }}>{L.sumUsdCol}</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td style={{ color: text, borderBottom: `1px solid ${line}` }}>{L.sumOrdinary}</td>
            <td className="r" style={{ color: text, borderBottom: `1px solid ${line}` }}>{fmt(calc.gross)}</td>
          </tr>
          <tr>
            <td style={{ color: text, borderBottom: `1px solid ${line}` }}>{L.sumUsGross}</td>
            <td className="r neg" style={{ color: warn, borderBottom: `1px solid ${line}` }}>({fmt(calc.usGrossTax)})</td>
          </tr>
          <tr>
            <td style={{ color: text, borderBottom: `1px solid ${line}` }}>{L.sumFtc}</td>
            <td className="r" style={{ color: text, borderBottom: `1px solid ${line}` }}>{fmt(calc.ftc)}</td>
          </tr>
          <tr>
            <td style={{ color: text, borderBottom: `1px solid ${line}` }}>{L.sumNetUs}</td>
            <td className="r neg" style={{ color: warn, borderBottom: `1px solid ${line}` }}>({fmt(calc.netUsTax)})</td>
          </tr>
          <tr className="r-tax-total">
            <td style={{ color: text, borderTop: `1px solid ${text}`, borderBottom: `1px solid ${text}` }}>{L.sumTotal}</td>
            <td className="r neg" style={{ color: warn, borderTop: `1px solid ${text}`, borderBottom: `1px solid ${text}` }}>{fmt(calc.totalTax)}</td>
          </tr>
          <tr className="r-tax-rate">
            <td style={{ color: muted }}>{L.sumRate}</td>
            <td className="r" style={{ color: accent }}>{(effectiveRate * 100).toFixed(1)}%</td>
          </tr>
        </tbody>
      </table>

      {/* Key takeaway — lime-marker accent */}
      <div className="r-tax-takeaway" style={{ background: bg, border: `1px solid ${line}`, borderLeft: `3px solid ${lime}` }}>
        <div className="r-tax-takeaway-head" style={{ color: text }}>{L.takeawayH}</div>
        <p style={{ color: text }}>{L.takeawayA(calc.totalTax, effectiveRate)}</p>
        <p style={{ color: text }}>{L.takeawayB}</p>
      </div>

      <div className="r-tax-disclaimer" style={{ color: faint, borderTop: `1px solid ${line}` }}>
        {L.disclaimer}
      </div>

      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Sub-components
// ─────────────────────────────────────────────────────────────
function KeyStat({ label, value, muted, text, mono }) {
  return (
    <div className="r-tax-keystat">
      <div className="r-tax-keystat-lbl" style={{ color: muted }}>{label}</div>
      <div className={"r-tax-keystat-val" + (mono ? " mono" : "")} style={{ color: text }}>{value}</div>
    </div>
  );
}

function Flag({ kind }) {
  return (
    <span className="r-tax-flag">
      <span className={"r-tax-pip" + (kind === "mx" ? " mx" : "")}/>
      {kind === "mx" ? "MX" : "US"}
    </span>
  );
}

function Node({ tag, flag, title, meta, desc, children, bg, line, text, muted }) {
  return (
    <div className="r-tax-node" style={{ background: bg, border: `1px solid ${line}` }}>
      <div className="r-tax-node-row">
        <span className="r-tax-node-tag" style={{ color: muted }}>{tag}</span>
        <Flag kind={flag}/>
      </div>
      <h4 className="r-tax-node-title" style={{ color: text }}>{title}</h4>
      {meta && <div className="r-tax-node-meta" style={{ color: muted }}>{meta}</div>}
      {desc && <div className="r-tax-node-desc" style={{ color: text }}>{desc}</div>}
      {children}
    </div>
  );
}

function FlowStep({ n, up, ink, muted, faint, accent, amount, verb, sub }) {
  const headColor = up ? accent : ink;
  return (
    <div className={"r-tax-flow" + (up ? " up" : "")}>
      <div className="r-tax-step" style={{ background: headColor, color: "#FAF7F3" }}>{n}</div>
      <div className="r-tax-arrow">
        {up ? (
          <div className="r-tax-arrow-head" style={{ borderBottom: `6px solid ${headColor}` }}/>
        ) : null}
        <div className="r-tax-arrow-line" style={{ background: headColor }}/>
        {!up ? (
          <div className="r-tax-arrow-head down" style={{ borderTop: `6px solid ${headColor}` }}/>
        ) : null}
      </div>
      <div className="r-tax-flow-label" style={{ color: ink }}>
        <span className="r-tax-flow-amt" style={{ color: headColor }}>{amount}</span> {verb}
        <div className="r-tax-flow-sub" style={{ color: faint }}>{sub}</div>
      </div>
    </div>
  );
}

function TaxCard({ variant, idx, title, flag, children, bg, line, accent, text, muted }) {
  return (
    <div className={"r-tax-card r-tax-card-" + variant}
         style={{ background: bg, border: `1px solid ${line}`, borderLeft: `3px solid ${accent}` }}>
      <div className="r-tax-card-head">
        <div className="r-tax-card-ix" style={{ background: accent, color: "#FAF7F3" }}>{idx}</div>
        <div className="r-tax-card-title" style={{ color: text }}>{title}</div>
        <Flag kind={flag}/>
      </div>
      <ul className="r-tax-card-list" style={{ color: text }}>
        {children}
      </ul>
    </div>
  );
}

window.MezzanineTaxFlow = MezzanineTaxFlow;
