// Mercomercio — calculator logic + UI
const { useState, useMemo, useEffect } = React;

// Costos base: USD por unidad (textil ligero ~0.4kg promedio).
// freight_py    = flete origen → hub Paraguay
// freight_direct = flete origen → destino directo (sin hub)
// estimación de mercado 2025-26 — reemplazar con cotización real antes de uso comercial
// Display names are resolved from i18n catalog by `code` at render time.
const ORIGINS = {
  Europa: [
    { code: "ES", flag: "🇪🇸", freight_py: 0.45, freight_direct: 0.50 },
    { code: "PT", flag: "🇵🇹", freight_py: 0.45, freight_direct: 0.50 },
    { code: "IT", flag: "🇮🇹", freight_py: 0.45, freight_direct: 0.50 },
    { code: "FR", flag: "🇫🇷", freight_py: 0.48, freight_direct: 0.52 },
    { code: "TR", flag: "🇹🇷", freight_py: 0.40, freight_direct: 0.45 },
    { code: "GB", flag: "🇬🇧", freight_py: 0.55, freight_direct: 0.60 },
    { code: "DE", flag: "🇩🇪", freight_py: 0.55, freight_direct: 0.60 },
    { code: "NL", flag: "🇳🇱", freight_py: 0.55, freight_direct: 0.60 },
    { code: "PL", flag: "🇵🇱", freight_py: 0.55, freight_direct: 0.60 },
    { code: "CZ", flag: "🇨🇿", freight_py: 0.55, freight_direct: 0.60 },
    { code: "FI", flag: "🇫🇮", freight_py: 0.58, freight_direct: 0.62 },
    { code: "SE", flag: "🇸🇪", freight_py: 0.58, freight_direct: 0.62 },
  ],
  Sudamérica: [
    { code: "PE", flag: "🇵🇪", freight_py: 0.30, freight_direct: 0.35 },
    { code: "CO", flag: "🇨🇴", freight_py: 0.32, freight_direct: 0.38 },
    { code: "EC", flag: "🇪🇨", freight_py: 0.32, freight_direct: 0.38 },
  ],
};

// Aranceles e impuestos por destino — TEC Mercosur + tributos locales habituales 2025-26.
// duty_intra es 0% para los tres porque Paraguay → Mercosur es intrazona.
const DESTINATIONS = {
  BR: { code: "BR", flag: "🇧🇷", freight_from_py: 0.30, duty_direct: 0.20, duty_intra: 0.00, tax_direct: 0.18, tax_intra: 0.12 },
  AR: { code: "AR", flag: "🇦🇷", freight_from_py: 0.25, duty_direct: 0.23, duty_intra: 0.00, tax_direct: 0.25, tax_intra: 0.21 },
  UY: { code: "UY", flag: "🇺🇾", freight_from_py: 0.35, duty_direct: 0.18, duty_intra: 0.00, tax_direct: 0.22, tax_intra: 0.22 },
};

// Costos fijos comunes a todas las rutas (USD por unidad)
const C = {
  SEGURO: 0.25,
  SEGURO_PY: 0.20,
  SERVICIOS: 3.50,
  ARANCEL_PY: 0.01,
  IVA_PY: 0.10,
  DESPACHO_DIRECT: 0.50,
  DESPACHO_PY: 0.30,
  TRANSPORTE_LOCAL: 0.60,
};

const CURRENCIES = {
  USD: { symbol: "$", locale: "en-US", label: "USD $" },
  EUR: { symbol: "€", locale: "es-ES", label: "EUR €" },
  GBP: { symbol: "£", locale: "en-GB", label: "GBP £" },
};

function formatMoney(n, currency, opts = {}) {
  const { decimals = 0, sign = false } = opts;
  const cur = CURRENCIES[currency] || CURRENCIES.USD;
  const v = Math.round(n * Math.pow(10, decimals)) / Math.pow(10, decimals);
  const fmt = new Intl.NumberFormat(cur.locale, {
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals,
  }).format(Math.abs(v));
  const s = sign && v > 0 ? "+" : v < 0 ? "−" : "";
  return `${s}${cur.symbol}${fmt}`;
}

function calcDirect(price, origin, dest, t) {
  const flete = origin.freight_direct;
  const cif = price + flete + C.SEGURO;
  const arancel = cif * dest.duty_direct;
  const tax = (cif + arancel) * dest.tax_direct;
  const total = cif + arancel + tax + C.DESPACHO_DIRECT + C.TRANSPORTE_LOCAL;
  const originName = t.originNames[origin.code];
  const destName = t.destNames[dest.code];
  const destLabels = t.destLabels[dest.code];
  return {
    rows: [
      { label: t.calc.fobPrice, v: price },
      { label: t.calc.freightDirect(originName, destName), v: flete },
      { label: t.calc.insurance, v: C.SEGURO },
      { label: t.calc.cifDest, v: cif, sub: true },
      { label: destLabels.duty_direct, v: arancel, danger: true },
      { label: destLabels.tax_direct, v: tax, danger: true },
      { label: t.calc.customs, v: C.DESPACHO_DIRECT },
      { label: t.calc.localTransport, v: C.TRANSPORTE_LOCAL },
    ],
    total,
  };
}

function calcMerco(price, origin, dest, t) {
  const fletePY = origin.freight_py;
  const fleteFromPY = dest.freight_from_py;
  const cifPY = price + fletePY + C.SEGURO_PY;
  const arancelPY = cifPY * C.ARANCEL_PY;
  const ivaPY = cifPY * C.IVA_PY;
  const tax = cifPY * dest.tax_intra;
  const total =
    cifPY +
    arancelPY +
    ivaPY +
    C.SERVICIOS +
    fleteFromPY +
    tax +
    C.DESPACHO_PY +
    C.TRANSPORTE_LOCAL;
  const originName = t.originNames[origin.code];
  const destName = t.destNames[dest.code];
  const destLabels = t.destLabels[dest.code];
  return {
    rows: [
      { label: t.calc.fobPrice, v: price },
      { label: t.calc.freightToPY(originName), v: fletePY },
      { label: t.calc.insurance, v: C.SEGURO_PY },
      { label: t.calc.cifPY, v: cifPY, sub: true },
      { label: t.calc.arancelPY, v: arancelPY },
      { label: t.calc.ivaPY, v: ivaPY },
      { label: t.calc.services, v: C.SERVICIOS, accent: true },
      { label: t.calc.freightFromPY(destName), v: fleteFromPY },
      { label: destLabels.tax_intra, v: tax },
      { label: t.calc.customs, v: C.DESPACHO_PY },
      { label: t.calc.localTransport, v: C.TRANSPORTE_LOCAL },
    ],
    total,
  };
}

function useAnimatedNumber(target, duration = 700) {
  const [v, setV] = useState(target);
  useEffect(() => {
    const start = v;
    const t0 = performance.now();
    let raf;
    const step = (now) => {
      const k = Math.min(1, (now - t0) / duration);
      const eased = 1 - Math.pow(1 - k, 3);
      setV(start + (target - start) * eased);
      if (k < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
    // eslint-disable-next-line
  }, [target]);
  return v;
}

function Calculator() {
  const { t } = useT();
  const [country, setCountry] = useState("ES");
  const [destCode, setDestCode] = useState("BR");
  const [product, setProduct] = useState("textiles");
  const [price, setPrice] = useState(30);
  const [units, setUnits] = useState(50000);
  const [currency, setCurrency] = useState("USD");
  const [view, setView] = useState("merco"); // "direct" | "merco"

  const allOrigins = [...ORIGINS.Europa, ...ORIGINS.Sudamérica];
  const origin = allOrigins.find((c) => c.code === country) || allOrigins[0];
  const dest = DESTINATIONS[destCode] || DESTINATIONS.BR;
  const cur = CURRENCIES[currency] || CURRENCIES.USD;

  const direct = useMemo(() => calcDirect(price, origin, dest, t), [price, origin, dest, t]);
  const merco = useMemo(() => calcMerco(price, origin, dest, t), [price, origin, dest, t]);

  const annual = units * 12;
  const directAnnual = direct.total * annual;
  const mercoAnnual = merco.total * annual;
  const savings = Math.max(0, directAnnual - mercoAnnual);
  const pct = directAnnual > 0 ? (savings / directAnnual) * 100 : 0;
  const perUnit = savings / Math.max(1, annual);

  const animSavings = useAnimatedNumber(savings);
  const animPct = useAnimatedNumber(pct);
  const animPer = useAnimatedNumber(perUnit);

  const active = view === "merco" ? merco : direct;
  const otherTotal = view === "merco" ? direct.total : merco.total;
  const originName = t.originNames[origin.code];
  const destName = t.destNames[dest.code];

  return (
    <div className="calc">
      <div className="calc-head">
        <div>{t.calc.headLeft}</div>
        <div>{t.calc.headRight}</div>
      </div>
      <div className="calc-body">
        <div className="calc-inputs">
          <div className="field">
            <div className="field-label">
              <span>{t.calc.labelOrigin}</span>
              <span className="num">01</span>
            </div>
            <div className="country-group">{t.calc.groupEurope}</div>
            <div className="country-grid">
              {ORIGINS.Europa.map((c) => (
                <button
                  key={c.code}
                  className={`country-chip${country === c.code ? " active" : ""}`}
                  onClick={() => setCountry(c.code)}
                  type="button"
                >
                  <span className="flag-emoji">{c.flag}</span>
                  <span>{t.originNames[c.code]}</span>
                </button>
              ))}
            </div>
            <div className="country-group">{t.calc.groupSouth}</div>
            <div className="country-grid">
              {ORIGINS.Sudamérica.map((c) => (
                <button
                  key={c.code}
                  className={`country-chip${country === c.code ? " active" : ""}`}
                  onClick={() => setCountry(c.code)}
                  type="button"
                >
                  <span className="flag-emoji">{c.flag}</span>
                  <span>{t.originNames[c.code]}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="field">
            <div className="field-label">
              <span>{t.calc.labelDest}</span>
              <span className="num">02</span>
            </div>
            <div className="country-grid">
              {Object.values(DESTINATIONS).map((d) => (
                <button
                  key={d.code}
                  className={`country-chip${destCode === d.code ? " active" : ""}`}
                  onClick={() => setDestCode(d.code)}
                  type="button"
                >
                  <span className="flag-emoji">{d.flag}</span>
                  <span>{t.destNames[d.code]}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="field">
            <div className="field-label">
              <span>{t.calc.labelProduct}</span>
              <span className="num">03</span>
            </div>
            <div className="product-tabs">
              {t.calc.products.map((p) => (
                <button
                  key={p.id}
                  className={`product-tab${product === p.id ? " active" : ""}`}
                  onClick={() => setProduct(p.id)}
                  type="button"
                >
                  <span className="ico">{p.ico}</span>
                  <span className="name">{p.name}</span>
                  <span className="sub">{p.sub}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="field">
            <div className="field-label">
              <span>{t.calc.labelPrice}</span>
              <span className="num">04</span>
            </div>
            <div className="num-input">
              <input
                type="number"
                min="0.5"
                max="10000"
                step="0.5"
                value={price}
                onChange={(e) => setPrice(Math.max(0.5, Number(e.target.value) || 0))}
              />
              <select value={currency} onChange={(e) => setCurrency(e.target.value)}>
                {Object.entries(CURRENCIES).map(([code, c]) => (
                  <option key={code} value={code}>{c.label}</option>
                ))}
              </select>
            </div>
          </div>

          <div className="field" style={{ marginBottom: 0 }}>
            <div className="field-label">
              <span>{t.calc.labelUnits}</span>
              <span className="num">05</span>
            </div>
            <div className="num-input">
              <input
                type="number"
                min="1000"
                max="1000000"
                step="1000"
                value={units}
                onChange={(e) =>
                  setUnits(Math.max(1000, Math.min(1000000, Number(e.target.value) || 1000)))
                }
              />
              <span style={{ padding: "0 12px", color: "rgba(255,255,255,.5)", fontFamily: "var(--font-mono)", fontSize: 12 }}>{t.calc.perMonth}</span>
            </div>
            <input
              type="range"
              className="slider"
              min="1000"
              max="200000"
              step="1000"
              value={Math.min(200000, units)}
              onChange={(e) => setUnits(Number(e.target.value))}
            />
            <div className="slider-row">
              <span>{new Intl.NumberFormat(cur.locale).format(1000)}</span>
              <span>{new Intl.NumberFormat(cur.locale).format(50000)}</span>
              <span>{new Intl.NumberFormat(cur.locale).format(100000)}</span>
              <span>{new Intl.NumberFormat(cur.locale).format(200000)}+</span>
            </div>
          </div>
        </div>

        <div className="calc-results">
          <div className="savings-hero">
            <div className="l">{t.calc.savingsTitle}</div>
            <div className="big">
              <span className="currency">{cur.symbol}</span>
              {new Intl.NumberFormat(cur.locale, { maximumFractionDigits: 0 }).format(animSavings)}
            </div>
            <div className="sub">
              {formatMoney(animPer, currency, { decimals: 2 })}{t.calc.perUnit}
              {new Intl.NumberFormat(cur.locale).format(units * 12)}{t.calc.perYear}
            </div>
            <div className="savings-pct">{t.calc.savingsPct(animPct.toFixed(1))}</div>
          </div>

          <div className="compare-toggle">
            <button className={view === "direct" ? "on" : ""} onClick={() => setView("direct")}>
              {t.calc.tabDirect}
            </button>
            <button className={`${view === "merco" ? "on green" : ""}`} onClick={() => setView("merco")}>
              {t.calc.tabMerco}
            </button>
          </div>

          <div className="breakdown">
            <div className="breakdown-row head">
              <div className="lbl">{t.calc.headConcept}</div>
              <div className="unit">{t.calc.headPerUnit}</div>
              <div className="annual">{t.calc.headPerYear}</div>
            </div>
            {active.rows.map((r, i) => (
              <div
                key={i}
                className={`breakdown-row${r.danger ? " tax-direct" : ""}${r.accent ? " savings" : ""}`}
              >
                <div className="lbl" style={r.sub ? { fontWeight: 600, color: "white" } : {}}>
                  {r.label}
                </div>
                <div className="unit">{formatMoney(r.v, currency, { decimals: 2 })}</div>
                <div className="annual">{formatMoney(r.v * annual, currency)}</div>
              </div>
            ))}
            <div className="breakdown-row total">
              <div className="lbl">{t.calc.total}</div>
              <div className="unit">{formatMoney(active.total, currency, { decimals: 2 })}</div>
              <div className="annual">{formatMoney(active.total * annual, currency)}</div>
            </div>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                marginTop: 10,
                fontFamily: "var(--font-mono)",
                fontSize: 11,
                color: "rgba(255,255,255,.4)",
                textTransform: "uppercase",
                letterSpacing: "0.12em",
              }}
            >
              <span>{view === "merco" ? t.calc.vsDirect : t.calc.vsMerco}</span>
              <span>{formatMoney(otherTotal * annual, currency)}</span>
            </div>
          </div>
        </div>
      </div>

      <div className="calc-flow">
        <div className="flow-node">
          <div className="f">{origin.flag}</div>
          <div className="t">
            <div className="top">{originName}</div>
            <div className="bot">{t.calc.flowOriginSub}</div>
          </div>
        </div>
        <div className="flow-arrow" />
        <div className="flow-node hub">
          <div className="f">🇵🇾</div>
          <div className="t">
            <div className="top">Paraguay</div>
            <div className="bot">{t.calc.flowHubSub}</div>
          </div>
        </div>
        <div className="flow-arrow" />
        <div className="flow-node">
          <div className="f">{dest.flag}</div>
          <div className="t">
            <div className="top">{destName}</div>
            <div className="bot">{t.calc.flowDestSub}</div>
          </div>
        </div>
      </div>

      <div className="cta-band">
        <div className="t">
          {t.calc.ctaText(formatMoney(savings, currency))}
        </div>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          <a className="btn btn-ghost" style={{ borderColor: "rgba(255,255,255,.3)", color: "white" }} href="#contacto">
            {t.calc.ctaInfo}
          </a>
          <a className="btn btn-primary" href="#contacto">
            {t.calc.ctaPropose}
          </a>
        </div>
      </div>
    </div>
  );
}

window.Calculator = Calculator;
