// ═══════════════════════════════════════════════════════════════
// 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;

// Illustrative U.S. top marginal income tax rate used in the per-level
// bullets. Pedagogical only — not legal advice. If this needs to be
// admin-editable in the future, promote to a per-product key in data.js
// or wire up data-static-data.js plumbing on the site.
const US_MARGINAL_RATE_EXAMPLE = 0.37;

// Resolve bullets for a given level/language, falling back from
// `lang` to `en` if the requested locale is empty. One-shot console
// warn to surface seed-data gaps without spamming.
const _bulletWarnedLevels = new Set();
function bulletsFor(taxVisual, level, lang) {
  const node = taxVisual && taxVisual.bullets && taxVisual.bullets[level];
  if (!node) return [];
  const primary = node[lang];
  if (primary && primary.length) return primary;
  const fallback = node.en;
  if (fallback && fallback.length) {
    const key = `${level}:${lang}`;
    if (!_bulletWarnedLevels.has(key)) {
      _bulletWarnedLevels.add(key);
      console.warn(`[MezzanineTaxFlow] bullets for ${key} empty; falling back to en`);
    }
    return fallback;
  }
  return [];
}

function MezzanineTaxFlow({ product, amount, projectedExit, lang, dark, t, taxCopy, taxVisual }) {
  // 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    = (taxVisual?.whtRate ?? 0.15);
    const usRate     = US_MARGINAL_RATE_EXAMPLE;
    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
    const moicMid = product?.targetReturn?.moic
      ? (product.targetReturn.moic[0] + product.targetReturn.moic[1]) / 2
      : null;
    return { principal, gross, whtRate, usRate, wht, netToLlc, usGrossTax, ftc, netUsTax, totalTax, moic: moicMid };
  }, [product, amount, projectedExit, taxVisual]);

  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 según los datos anteriores" : "Tax treatment based on the inputs above",
    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",
    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}` }}>

      {taxCopy && taxCopy.split(/\n\s*\n/).map((para, i) => (
        <p key={i} className="r-detail-body-p r-tax-intro" style={{ color: muted }}>{para}</p>
      ))}

      {/* 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, marginTop: "20px" }}>{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}>
          <BulletList bullets={bulletsFor(taxVisual, "level1", lang)} calc={calc} line2={line2} text={text} muted={muted} />
        </TaxCard>

        <TaxCard variant="entity" idx={2} title={L.lvl2} flag="us" bg={bg} line={line} accent={accent}  text={text} muted={muted}>
          <BulletList bullets={bulletsFor(taxVisual, "level2", lang)} calc={calc} line2={line2} text={text} muted={muted} />
        </TaxCard>

        <TaxCard variant="mx"     idx={3} title={L.lvl3} flag="mx" bg={warnBg} line={line} accent={warn} text={text} muted={muted}>
          <BulletList bullets={bulletsFor(taxVisual, "level3", lang)} calc={calc} line2={line2} text={text} muted={muted} />
        </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>
  );
}

// Renders a tax-card bullet list. Parent strings render as <li>; lines of the
// form `| label | value |` attach as a sub-grid row to the previous <li>. See
// tax-bullet-parser.jsx → groupTaxBullets.
function BulletList({ bullets, calc, line2, text, muted }) {
  const grouped = window.groupTaxBullets ? window.groupTaxBullets(bullets) : (bullets || []).map(function(b){ return { text: b, rows: null }; });
  return (
    <ul className="r-tax-bullets">
      {grouped.map(function (b, i) {
        return (
          <li key={i}>
            {window.renderTaxBullet(b.text, calc)}
            {b.rows && (
              <div className="r-tax-subgrid" style={{ color: muted, borderLeft: `1px solid ${line2}` }}>
                {b.rows.map(function (row, j) {
                  return (
                    <span key={j}>
                      <span>{window.renderTaxBullet(row[0] || "", calc)}</span>
                      <b style={{ color: text, fontWeight: 400 }}>{window.renderTaxBullet(row[1] || "", calc)}</b>
                    </span>
                  );
                })}
              </div>
            )}
          </li>
        );
      })}
    </ul>
  );
}

function Flag({ kind }) {
  const isMx = kind === "mx";
  return (
    <span className="r-tax-flag">
      <span className="r-tax-flag-emoji" role="img" aria-label={isMx ? "Mexico" : "United States"}>
        {isMx ? "🇲🇽" : "🇺🇸"}
      </span>
      {isMx ? "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>
      {children}
    </div>
  );
}

window.MezzanineTaxFlow = MezzanineTaxFlow;
