/* Cotizador — componente React reutilizable. Exporta window.Cotizador */
const { useState, useMemo } = React;
/* Ciudad de origen oculta para reducir fricción (no afecta el cálculo). Cambiar a true para mostrarla. */
const SHOW_ORIGIN_CITY = false;

function CotIcon({ d, s = 18, c = "currentColor", sw = 2 }) {
  return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round"><path d={d} /></svg>;
}

function Cotizador({ layout = "split", showClpDefault = false, showMargin = true, accent = "#84CC16", idp = "cot" }) {
  const [volume, setVolume] = useState("3");
  const [cat, setCat] = useState("electronica");
  const [city, setCity] = useState("shenzhen");
  const [tlc, setTlc] = useState(true);
  const [fob, setFob] = useState("5000");
  const [showClp, setShowClp] = useState(showClpDefault);
  const [salePrice, setSalePrice] = useState("");
  const [tipOpen, setTipOpen] = useState(false);

  const vol = parseFloat(volume);
  const fobN = parseFloat(fob);
  const volErr = volume !== "" && (isNaN(vol) || vol <= 0);
  const hasVol = !isNaN(vol) && vol > 0;
  const isMin = hasVol && vol < 1;
  const category = M3.CATEGORIES.find(c => c.value === cat);
  const restriction = category && category.restriction ? M3.RESTRICTION_INFO[category.restriction] : null;

  const calc = useMemo(() => {
    if (!hasVol) return null;
    const freight = M3.calculateFreight(vol);
    const surcharge = M3.smallShipmentSurcharge(vol);
    const cu = M3.calculateCustoms(isNaN(fobN) ? 0 : fobN, tlc);
    const total = freight + surcharge + cu.advalorem + cu.iva;
    return { freight, surcharge, service: freight + surcharge, ...cu, total, rate: M3.getRate(vol).rateUsd };
  }, [vol, fobN, tlc, hasVol, M3.TARIFF.updatedAt]);

  const margin = useMemo(() => {
    const sale = parseFloat(salePrice);
    if (!calc || isNaN(sale) || sale <= 0 || isNaN(fobN)) return null;
    const cost = fobN + calc.total;
    const costNet = cost - calc.iva; // IVA se recupera como crédito fiscal
    return {
      profit: sale - cost, pct: ((sale - cost) / sale) * 100, cost,
      profitNet: sale - costNet, pctNet: ((sale - costNet) / sale) * 100, costNet, iva: calc.iva,
    };
  }, [salePrice, calc, fobN]);

  const usd = (n, d = 0) => M3.fmtUsd(n, d);
  const clp = (n) => M3.fmtClp(n * M3.USD_CLP);

  const stacked = layout === "stacked";

  /* ---------- FORM ---------- */
  const form = (
    <div className="cot-form">
      <div className="field">
        <label className="label" htmlFor={idp+"-vol"}>Volumen de tu carga</label>
        <div style={{ position: "relative" }}>
          <input id={idp+"-vol"} className={"input" + (volErr ? " error" : "")} type="number" step="0.1" min="0" inputMode="decimal"
            value={volume} onChange={e => setVolume(e.target.value)} placeholder="Ej: 3" style={{ paddingRight: 48, fontFamily: "var(--font-mono)", fontWeight: 600 }} />
          <span style={{ position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)", fontWeight: 600, fontSize: 14 }}>m³</span>
        </div>
        {volErr && <span className="input-err-msg">Ingresa un volumen mayor a 0.</span>}
        {isMin && !volErr && <span className="badge badge-warning" style={{ alignSelf: "flex-start" }}><CotIcon d="M12 9v4m0 4h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z" s={13} />Carga mínima: se cobra como 1 m³</span>}
      </div>

      <div className="field">
        <label className="label" htmlFor={idp+"-cat"}>¿Qué vas a importar?</label>
        <select id={idp+"-cat"} className="select" value={cat} onChange={e => setCat(e.target.value)}>
          {M3.CATEGORIES.map(c => <option key={c.value} value={c.value}>{c.label}{c.restriction ? "  ⚠" : ""}</option>)}
        </select>
      </div>

      {restriction && (
        <div className="restriction-banner" role="status">
          <CotIcon d="M12 9v4m0 4h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z" s={18} c="#D97706" />
          <div>
            <div style={{ fontWeight: 700, color: "#92590b", fontSize: 13.5 }}>Requiere {restriction.agency} · {restriction.name}</div>
            <div style={{ fontSize: 13, color: "#7c5410", marginTop: 2 }}>{restriction.text}</div>
          </div>
        </div>
      )}

      <div className={SHOW_ORIGIN_CITY ? "cot-grid2" : undefined}>
        {SHOW_ORIGIN_CITY && <div className="field">
          <label className="label" htmlFor={idp+"-city"}>Ciudad de origen</label>
          <select id={idp+"-city"} className="select" value={city} onChange={e => setCity(e.target.value)}>
            {M3.CITIES.map(c => <option key={c.value} value={c.value}>{c.label}</option>)}
          </select>
        </div>}
        <div className="field">
          <label className="label" htmlFor={idp+"-fob"}>Valor mercadería (FOB)</label>
          <div style={{ position: "relative" }}>
            <span style={{ position: "absolute", left: 13, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)", fontWeight: 600 }}>$</span>
            <input id={idp+"-fob"} className="input" type="number" min="0" inputMode="numeric" value={fob} onChange={e => setFob(e.target.value)}
              placeholder="5000" style={{ paddingLeft: 26, fontFamily: "var(--font-mono)", fontWeight: 600 }} />
          </div>
        </div>
      </div>

      <div className="tlc-row">
        <button className={"toggle" + (tlc ? " on" : "")} role="switch" aria-checked={tlc} onClick={() => setTlc(!tlc)} aria-label="Tratado de Libre Comercio" />
        <div style={{ flex: 1 }}>
          <div className="row aic gap-6">
            <span style={{ fontWeight: 600, fontSize: 14 }}>Mi producto tiene TLC China–Chile</span>
            <button className="tlc-info" onMouseEnter={() => setTipOpen(true)} onMouseLeave={() => setTipOpen(false)} onClick={() => setTipOpen(!tipOpen)} aria-label="Qué es TLC">?
              {tipOpen && <span className="tooltip">El <strong>Tratado de Libre Comercio</strong> Chile–China deja el Ad valorem en {M3.pct(M3.TARIFF.adValoremTlc)} (en vez de {M3.pct(M3.TARIFF.adValoremNoTlc)}) para la mayoría de productos. La mayoría califica.</span>}
            </button>
          </div>
          <div style={{ fontSize: 12.5, color: "var(--ink-3)" }}>Baja el arancel de {M3.pct(M3.TARIFF.adValoremNoTlc)} a {M3.pct(M3.TARIFF.adValoremTlc)}</div>
        </div>
      </div>
    </div>
  );

  /* ---------- RESULT ---------- */
  const result = (
    <div className="cot-result">
      {!hasVol ? (
        <div className="cot-empty">
          <div className="cot-empty-ic"><CotIcon d="M3 3v18h18M7 15l3-4 3 2 4-6" s={30} c="var(--brand-300)" sw={2} /></div>
          <div style={{ fontWeight: 700, fontSize: 16, color: "var(--ink-2)" }}>Ingresa el volumen para ver tu precio</div>
          <div style={{ fontSize: 13.5, color: "var(--ink-3)", maxWidth: 240, textAlign: "center" }}>Cálculo instantáneo de flete + impuestos. Sin esperar 24 horas.</div>
        </div>
      ) : (
        <div className="fade-in">
          <div className="cot-total-card">
            <div className="row between aic">
              <span style={{ fontSize: 12.5, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase", color: "rgba(255,255,255,.6)" }}>Total estimado</span>
              <span className="badge" style={{ background: "rgba(132,204,22,.2)", color: accent }}><span className="dot" />puerta a puerta</span>
            </div>
            <div className="cot-total-num mono" data-testid="total-usd">{usd(calc.total)}<span style={{ fontSize: 22, opacity: .55 }}> USD</span></div>
            {showClp && <div className="mono" style={{ color: "rgba(255,255,255,.55)", fontSize: 14, marginTop: 2 }}>≈ {clp(calc.total)} CLP · TC {M3.USD_CLP}</div>}
            <div style={{ fontSize: 12.5, color: "rgba(255,255,255,.55)", marginTop: 8 }}>Lo que cobramos + impuestos aduaneros. No incluye el valor de la mercadería.</div>
          </div>

          {(() => {
            const taxes = calc.advalorem + calc.iva;
            const realCost = calc.total - calc.iva; // el IVA se recupera como crédito fiscal
            const grpHead = { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, margin: "14px 0 2px" };
            const eyebrow = { display: "inline-flex", alignItems: "center", gap: 7, fontSize: 11.5, fontWeight: 700, letterSpacing: ".04em", textTransform: "uppercase" };
            return (
              <div className="cot-break">
                {/* GRUPO 1 — lo que cobra m3-cargo */}
                <div style={grpHead}>
                  <span style={{ ...eyebrow, color: "var(--brand-700)" }}>
                    <CotIcon d="M16.5 9.4 7.5 4.2 M21 16V8a2 2 0 0 0-1-1.7l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.7l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z M3.3 7 12 12l8.7-5 M12 22V12" s={14} c="var(--brand-600)" />
                    Lo que cobra m3-cargo
                  </span>
                  <span className="mono fw700" style={{ fontSize: 15 }}>{usd(calc.service)}</span>
                </div>
                <Line label="Flete marítimo LCL" sub={`${(isMin ? M3.TARIFF.minimumBillableM3 : vol).toLocaleString("de-DE")} m³ × ${usd(calc.rate)}/m³`} val={usd(calc.freight)} testid="freight-usd"
                  tag={<span className="break-tag" style={{ color: "var(--brand-700)", background: "var(--brand-50)" }} title="Nuestro servicio puerta a puerta">nuestro servicio</span>} />
                {calc.surcharge > 0 && <Line label="Recargo carga pequeña" sub={`envíos bajo ${M3.TARIFF.smallShipment.belowM3.toLocaleString("de-DE")} m³`} val={usd(calc.surcharge)} testid="surcharge-usd" />}

                {/* GRUPO 2 — impuestos del Estado */}
                <div style={{ ...grpHead, borderTop: "1px solid var(--border)", paddingTop: 12, marginTop: 10 }}>
                  <span style={{ ...eyebrow, color: "var(--ink-2)" }}>
                    <CotIcon d="M3 21h18 M5 21V8l7-5 7 5v13 M9 21v-6h6v6" s={14} c="var(--ink-3)" />
                    Impuestos en aduana
                  </span>
                  <span className="mono fw700" style={{ fontSize: 15 }}>{usd(taxes)}</span>
                </div>
                <Line label="Ad valorem" sub={tlc ? `${M3.pct(M3.TARIFF.adValoremTlc)} sobre CIF · con TLC` : `${M3.pct(M3.TARIFF.adValoremNoTlc)} sobre CIF · sin TLC`} val={usd(calc.advalorem)} testid="advalorem-usd"
                  tag={<span className="break-tag" title="Arancel sobre el valor CIF. Es un costo, no se recupera.">arancel · costo</span>} />
                <Line label="IVA" sub={`${M3.pct(M3.TARIFF.ivaPct)} sobre (CIF + Ad valorem)`} val={usd(calc.iva)} testid="iva-usd"
                  tag={<span className="break-tag" style={{ color: "var(--lime-700)", background: "var(--lime-200)" }} title="El IVA de importación es crédito fiscal: lo recuperas con tu próxima declaración si importas con factura de empresa.">recuperable</span>} />

                {/* Callout: IVA recuperable */}
                <div style={{ display: "flex", gap: 10, alignItems: "flex-start", background: "var(--success-bg)", border: "1px solid #bfe7cd", borderRadius: "var(--r-sm)", padding: "11px 13px", marginTop: 10 }}>
                  <CotIcon d="M22 11.08V12a10 10 0 1 1-5.93-9.14 M22 4 12 14.01l-3-3" s={17} c="var(--success)" />
                  <div style={{ fontSize: 12.5, color: "#15643a", lineHeight: 1.45 }}>
                    Importando con <strong>factura de empresa</strong>, el IVA de <strong className="mono">{usd(calc.iva)}</strong> lo recuperas como <strong>crédito fiscal</strong>. El arancel y nuestro flete sí son costo.
                  </div>
                </div>

                {/* Costo real para la empresa */}
                <div className="break-row" style={{ borderTop: "1px dashed var(--border-2)", marginTop: 6, paddingTop: 12 }}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 14 }}>Costo real para tu empresa</div>
                    <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 1 }}>Total menos el IVA que recuperas</div>
                  </div>
                  <span className="mono fw700" style={{ fontSize: 17, color: "var(--success)" }}>{usd(realCost)}</span>
                </div>
                <div className="break-row" style={{ paddingTop: 6 }}>
                  <span style={{ fontWeight: 600, color: "var(--ink-3)", fontSize: 13 }}>CIF estimado</span>
                  <span className="mono" style={{ color: "var(--ink-3)" }}>{usd(calc.cif)}</span>
                </div>
              </div>
            );
          })()}

          <div className="row gap-8" style={{ marginTop: 16 }}>
            <button className="btn btn-accent btn-block">Recibir cotización por email</button>
            <button className="btn btn-ghost" title="Abre WhatsApp" style={{ flex: "none", padding: "11px 14px" }} aria-label="WhatsApp ejecutivo">
              <CotIcon d="M21 11.5a8.38 8.38 0 0 1-8.5 8.5 8.38 8.38 0 0 1-4-1L3 21l2-5.5a8.38 8.38 0 0 1-1-4 8.5 8.5 0 0 1 17 0z" s={18} c="var(--brand-600)" />
            </button>
          </div>
          <button className="cot-clp-toggle" onClick={() => setShowClp(!showClp)}>{showClp ? "Ocultar" : "Ver"} referencia en pesos (CLP)</button>

          {showMargin && (
            <details className="cot-margin">
              <summary><CotIcon d="M3 3v18h18M7 14l3-3 3 2 5-6" s={15} c="var(--lime-600)" />¿Te conviene? Calcula tu margen</summary>
              <div className="cot-margin-body">
                <div className="field" style={{ marginBottom: 10 }}>
                  <label className="label fz13" htmlFor={idp+"-sale"}>Precio de venta estimado en Chile (USD)</label>
                  <input id={idp+"-sale"} className="input" type="number" inputMode="numeric" placeholder="Ej: 9000" value={salePrice} onChange={e => setSalePrice(e.target.value)} style={{ fontFamily: "var(--font-mono)" }} />
                </div>
                {margin ? (
                  <div className="cot-margin-grid">
                    <div><div className="fz12 muted-txt">Costo total puesto en Chile</div><div className="mono fw700 fz18">{usd(margin.cost)}</div></div>
                    <div><div className="fz12 muted-txt">Margen bruto</div><div className="mono fw700 fz18" style={{ color: margin.profit >= 0 ? "var(--success)" : "var(--danger)" }}>{usd(margin.profit)} · {margin.pct.toFixed(0)}%</div></div>
                    <div style={{ gridColumn: "1 / -1", borderTop: "1px dashed var(--border-2)", paddingTop: 12, display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 12 }}>
                      <div style={{ minWidth: 0 }}>
                        <div className="row aic gap-6"><span className="fz13 fw700">Margen bruto con IVA recuperado</span><span className="break-tag" style={{ color: "var(--lime-700)", background: "var(--lime-200)" }}>+{usd(margin.iva)} crédito</span></div>
                        <div className="fz12 muted-txt" style={{ marginTop: 1 }}>Descontando el IVA que recuperas como empresa</div>
                      </div>
                      <div className="mono fw700 fz18" style={{ color: margin.profitNet >= 0 ? "var(--success)" : "var(--danger)", whiteSpace: "nowrap" }}>{usd(margin.profitNet)} · {margin.pctNet.toFixed(0)}%</div>
                    </div>
                  </div>
                ) : <div className="fz13 muted-txt">Ingresa tu precio de venta para ver el margen.</div>}
              </div>
            </details>
          )}
        </div>
      )}
    </div>
  );

  return (
    <div className={"cot-wrap " + (stacked ? "cot-stacked" : "cot-split")}>
      <div className="cot-panel cot-panel-form">{form}</div>
      <div className="cot-panel cot-panel-result">{result}</div>
    </div>
  );
}

function Line({ label, sub, val, testid, tag }) {
  return (
    <div className="break-row">
      <div style={{ minWidth: 0 }}>
        <div className="row aic gap-8"><span style={{ fontWeight: 600, fontSize: 14 }}>{label}</span>{tag}</div>
        <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 1 }}>{sub}</div>
      </div>
      <span className="mono" data-testid={testid} style={{ fontWeight: 600, fontSize: 15 }}>{val}</span>
    </div>
  );
}

window.Cotizador = Cotizador;
