/* global React */
/* ===========================================================
   VOLTLAB · CONVERSOR DE UNIDADES
   Conversões úteis para engenharia elétrica:
   Potência · Tensão · Corrente · Comprimento · Seção (AWG↔mm²)
   100% no padrão visual VoltLab (reutiliza classes app.css).
=========================================================== */
const { useState, useEffect, useMemo, useRef } = React;

/* ---------- persistência segura ---------- */
const useCvPersist = (k, v) => (window.useLocalStorage ? window.useLocalStorage(k, v) : useState(v));

/* ---------- ícones (mesmo traço dos demais módulos) ---------- */
const CvIcon = ({ name, size = 16 }) => {
  const p = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" };
  const d = {
    swap:   <><polyline points="7 4 3 8 7 12"/><line x1="3" y1="8" x2="17" y2="8"/><polyline points="17 12 21 16 17 20"/><line x1="21" y1="16" x2="7" y2="16"/></>,
    bolt:   <path d="M13 2L4 14h7l-2 8 9-12h-7z"/>,
    wave:   <path d="M2 12c2 0 2-6 4-6s2 12 4 12 2-12 4-12 2 6 4 6 2-3 4-3"/>,
    current:<><line x1="4" y1="12" x2="20" y2="12"/><polyline points="9 7 4 12 9 17"/><polyline points="15 7 20 12 15 17"/></>,
    ruler:  <><path d="M3 17L17 3l4 4L7 21z"/><path d="M7.5 12.5l2 2M10 10l2 2M12.5 7.5l2 2"/></>,
    cable:  <><path d="M4 4c4 0 4 8 8 8s4-8 8-8"/><path d="M4 20c4 0 4-8 8-8s4 8 8 8"/></>,
    check:  <polyline points="20 6 9 17 4 12"/>,
    info:   <><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></>,
    copy:   <><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></>,
  };
  return <svg {...p}>{d[name] || null}</svg>;
};

/* ---------- dropdown idêntico ao do app (.vl-dd) ---------- */
const CvDropdown = ({ value, onChange, options }) => {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, [open]);
  const cur = options.find(o => o.value === value) || options[0];
  return (
    <div className={"vl-dd " + (open ? "is-open" : "")} ref={ref}>
      <button type="button" className="vl-dd-trigger" onClick={() => setOpen(o => !o)}>
        <span>{cur?.label}</span>
        <span className="vl-dd-chev"/>
      </button>
      {open && (
        <div className="vl-dd-menu">
          {options.map(o => (
            <div key={o.value} className={"vl-dd-opt " + (o.value === value ? "is-sel" : "")}
                 onClick={() => { onChange(o.value); setOpen(false); }}>
              {o.label}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

/* ---------- formatação de números ---------- */
function fmtNum(n) {
  if (!isFinite(n)) return "—";
  if (n === 0) return "0";
  const abs = Math.abs(n);
  let s;
  if (abs >= 1e6 || abs < 1e-4) s = n.toExponential(4);
  else s = n.toPrecision(7);
  // limpa zeros à direita
  if (s.indexOf("e") === -1 && s.indexOf(".") !== -1) s = s.replace(/\.?0+$/, "");
  return s;
}

/* ===========================================================
   DEFINIÇÃO DAS GRANDEZAS LINEARES (fator → unidade base SI)
=========================================================== */
const CATS = {
  potencia: {
    label: "Potência", icon: "bolt", base: "W", baseName: "watt",
    units: [
      { u: "W",  f: 1,           n: "Watt" },
      { u: "kW", f: 1e3,         n: "Quilowatt" },
      { u: "MW", f: 1e6,         n: "Megawatt" },
      { u: "cv", f: 735.49875,   n: "Cavalo-vapor (métrico)" },
      { u: "HP", f: 745.699872,  n: "Horsepower (mecânico)" },
    ],
  },
  tensao: {
    label: "Tensão", icon: "wave", base: "V", baseName: "volt",
    units: [
      { u: "mV", f: 1e-3, n: "Milivolt" },
      { u: "V",  f: 1,    n: "Volt" },
      { u: "kV", f: 1e3,  n: "Quilovolt" },
    ],
  },
  corrente: {
    label: "Corrente", icon: "current", base: "A", baseName: "ampère",
    units: [
      { u: "mA", f: 1e-3, n: "Miliampère" },
      { u: "A",  f: 1,    n: "Ampère" },
      { u: "kA", f: 1e3,  n: "Quiloampère" },
    ],
  },
  comprimento: {
    label: "Comprimento", icon: "ruler", base: "m", baseName: "metro",
    units: [
      { u: "mm", f: 1e-3, n: "Milímetro" },
      { u: "cm", f: 1e-2, n: "Centímetro" },
      { u: "m",  f: 1,    n: "Metro" },
      { u: "km", f: 1e3,  n: "Quilômetro" },
    ],
  },
};

/* ===========================================================
   TABELA AWG (gerada pela fórmula da bitola americana)
   d(mm) = 0.127 · 92^((36 - n)/39)  ·  área = π/4 · d²
=========================================================== */
const IEC_SECOES = [0.5,0.75,1,1.5,2.5,4,6,10,16,25,35,50,70,95,120,150,185,240,300,400,500];

function buildAWG() {
  // n: 0000(-3) … 24 ; rotulamos os 1/0..4/0
  const rows = [];
  const defs = [
    { n: -3, label: "4/0 (0000)" },
    { n: -2, label: "3/0 (000)" },
    { n: -1, label: "2/0 (00)" },
    { n: 0,  label: "1/0 (0)" },
  ];
  for (let i = 1; i <= 24; i++) defs.push({ n: i, label: String(i) });
  defs.forEach(({ n, label }) => {
    const d_mm = 0.127 * Math.pow(92, (36 - n) / 39);
    const area = Math.PI / 4 * d_mm * d_mm;
    const cmil = area / 5.067e-4; // 1 cmil = 5.067e-4 mm²
    rows.push({ awg: label, key: label, d_mm, area, cmil });
  });
  return rows;
}
const AWG_ROWS = buildAWG();

function nearestIEC(area) {
  // menor seção comercial que comporta a área (próximo valor ≥)
  return IEC_SECOES.find(s => s >= area - 1e-9) || IEC_SECOES[IEC_SECOES.length - 1];
}
function nearestAWG(area) {
  // AWG cuja seção é a mais próxima da área informada
  let best = AWG_ROWS[0], diff = Infinity;
  AWG_ROWS.forEach(r => { const dd = Math.abs(r.area - area); if (dd < diff) { diff = dd; best = r; } });
  return best;
}

/* ---------- átomos visuais (classes do app.css) ---------- */
const Field = ({ label, hint, children }) => (
  <div className="vl-field">
    <label className="vl-field-label"><span>{label}</span>{hint && <span className="vl-field-hint">{hint}</span>}</label>
    {children}
  </div>
);
const NumInput = ({ value, onChange, suffix }) => (
  <div className="vl-input">
    <input type="number" value={value} onChange={e => onChange(e.target.value)} step="any"/>
    {suffix && <span className="vl-input-suffix">{suffix}</span>}
  </div>
);
const Banner = ({ kind, children }) => (
  <div className={"vl-banner vl-banner-" + kind}>
    <CvIcon name={kind === "ok" ? "check" : "info"} size={16}/>
    <span>{children}</span>
  </div>
);
const Metric = ({ label, value, unit }) => (
  <div className="vl-metric">
    <div className="vl-metric-label">{label}</div>
    <div className="vl-metric-value"><span className="readout">{value}</span>{unit && <em>{unit}</em>}</div>
  </div>
);

/* ===========================================================
   COMPONENTE PRINCIPAL
=========================================================== */
const Conversor = () => {
  const [cat, setCat] = useCvPersist("vl_conv_cat", "potencia");

  // estado linear
  const [val, setVal]   = useCvPersist("vl_conv_val", "1");
  const [from, setFrom] = useCvPersist("vl_conv_from", "kW");
  const [to, setTo]     = useCvPersist("vl_conv_to", "cv");

  // estado AWG
  const [awgDir, setAwgDir] = useCvPersist("vl_conv_awgdir", "a2m"); // a2m | m2a
  const [awgSel, setAwgSel] = useCvPersist("vl_conv_awg", "10");
  const [mmVal, setMmVal]   = useCvPersist("vl_conv_mm", "6");

  const isAWG = cat === "secao";
  const def = CATS[cat];

  // garante que from/to pertencem à categoria atual
  useEffect(() => {
    if (isAWG) return;
    const us = def.units.map(u => u.u);
    if (!us.includes(from)) setFrom(us[0]);
    if (!us.includes(to))   setTo(us[Math.min(1, us.length - 1)]);
  }, [cat]); // eslint-disable-line

  /* -------- cálculo linear -------- */
  const linear = useMemo(() => {
    if (isAWG) return null;
    const v = parseFloat(val);
    const fU = def.units.find(u => u.u === from) || def.units[0];
    const tU = def.units.find(u => u.u === to) || def.units[0];
    if (!isFinite(v)) return { invalid: true, fU, tU };
    const base = v * fU.f;          // em unidade SI
    const out = base / tU.f;        // na unidade destino
    const factor = fU.f / tU.f;     // multiplicador direto
    const table = def.units.map(u => ({ ...u, conv: base / u.f }));
    return { v, fU, tU, base, out, factor, table };
  }, [cat, val, from, to, isAWG]);

  /* -------- cálculo AWG -------- */
  const awg = useMemo(() => {
    if (!isAWG) return null;
    if (awgDir === "a2m") {
      const row = AWG_ROWS.find(r => r.key === awgSel) || AWG_ROWS[0];
      return { mode: "a2m", row, iec: nearestIEC(row.area) };
    } else {
      const a = parseFloat(mmVal);
      if (!isFinite(a) || a <= 0) return { mode: "m2a", invalid: true };
      const row = nearestAWG(a);
      return { mode: "m2a", area: a, row, iec: nearestIEC(a) };
    }
  }, [isAWG, awgDir, awgSel, mmVal]);

  const swap = () => { const a = from; setFrom(to); setTo(a); };

  /* =========================================================
     RENDER
  ========================================================= */
  return (
    <div className="eletroduto">
      <div className="el-grid">
        {/* ---------- ENTRADA ---------- */}
        <section className="panel">
          <div className="panel-head">
            <div>
              <div className="panel-eyebrow">CONVERSÃO DE UNIDADES</div>
              <h3>Selecione a grandeza e converta</h3>
            </div>
            <div className="status-chip"><span className="status-dot status-ok"/>TEMPO REAL</div>
          </div>

          {/* categorias */}
          <Field label="Grandeza">
            <div className="seg vl-conv-cats">
              {Object.entries(CATS).map(([id, c]) => (
                <button key={id} className={cat === id ? "is-active" : ""} onClick={() => setCat(id)}>
                  <CvIcon name={c.icon} size={14}/> {c.label}
                </button>
              ))}
              <button className={isAWG ? "is-active" : ""} onClick={() => setCat("secao")}>
                <CvIcon name="cable" size={14}/> Seção (AWG)
              </button>
            </div>
          </Field>

          {!isAWG ? (
            <>
              <div className="form-row form-row-2">
                <Field label="Valor a converter">
                  <NumInput value={val} onChange={setVal} suffix={from}/>
                </Field>
                <Field label="Unidade de origem">
                  <CvDropdown value={from} onChange={setFrom}
                    options={def.units.map(u => ({ value: u.u, label: `${u.u} · ${u.n}` }))}/>
                </Field>
              </div>

              <div className="vl-conv-swap-row">
                <span className="vl-conv-line"/>
                <button className="vl-conv-swap" onClick={swap} title="Inverter unidades">
                  <CvIcon name="swap" size={16}/>
                </button>
                <span className="vl-conv-line"/>
              </div>

              <Field label="Unidade de destino">
                <CvDropdown value={to} onChange={setTo}
                  options={def.units.map(u => ({ value: u.u, label: `${u.u} · ${u.n}` }))}/>
              </Field>

              <div className="vl-quick-stats">
                <div><span>Grandeza</span><b>{def.label}</b></div>
                <div><span>Base SI</span><b className="readout">{def.base}</b></div>
                <div><span>Fator direto</span><b className="readout">×{linear && !linear.invalid ? fmtNum(linear.factor) : "—"}</b></div>
              </div>
            </>
          ) : (
            <>
              <Field label="Sentido da conversão">
                <div className="seg">
                  <button className={awgDir === "a2m" ? "is-active" : ""} onClick={() => setAwgDir("a2m")}>AWG → mm²</button>
                  <button className={awgDir === "m2a" ? "is-active" : ""} onClick={() => setAwgDir("m2a")}>mm² → AWG</button>
                </div>
              </Field>

              {awgDir === "a2m" ? (
                <Field label="Bitola AWG" hint="padrão americano">
                  <CvDropdown value={awgSel} onChange={setAwgSel}
                    options={AWG_ROWS.map(r => ({ value: r.key, label: `AWG ${r.awg}` }))}/>
                </Field>
              ) : (
                <Field label="Seção transversal" hint="informe em mm²">
                  <NumInput value={mmVal} onChange={setMmVal} suffix="mm²"/>
                </Field>
              )}

              <div className="vl-quick-stats">
                <div><span>Padrão</span><b>AWG ⇄ IEC</b></div>
                <div><span>Referência</span><b className="readout">25,4 mm/in</b></div>
                <div><span>1 cmil</span><b className="readout">5,067e-4 mm²</b></div>
              </div>
            </>
          )}
        </section>

        {/* ---------- RESULTADO ---------- */}
        <aside className="panel el-result">
          <div className="panel-head">
            <div>
              <div className="panel-eyebrow">RESULTADO · CONVERSÃO</div>
              <h3>Valor convertido</h3>
            </div>
          </div>

          {!isAWG ? (
            <>
              <div className="vl-result-big">
                <div className="vl-result-corner vl-result-corner-tl"/>
                <div className="vl-result-corner vl-result-corner-tr"/>
                <div className="vl-result-corner vl-result-corner-bl"/>
                <div className="vl-result-corner vl-result-corner-br"/>
                <div className="vl-result-label">{linear?.fU?.u} → {linear?.tU?.u}</div>
                <div className="vl-result-row">
                  <span className="readout vl-result-val">{linear && !linear.invalid ? fmtNum(linear.out) : "—"}</span>
                  <em>{to}</em>
                </div>
              </div>

              <div className="vl-mini-grid">
                <Metric label="VALOR DE ENTRADA" value={linear && !linear.invalid ? fmtNum(linear.v) : "—"} unit={from}/>
                <Metric label={"EM " + def.base + " (SI)"} value={linear && !linear.invalid ? fmtNum(linear.base) : "—"} unit={def.base}/>
              </div>

              {linear && !linear.invalid
                ? <Banner kind="ok">{fmtNum(linear.v)} {from} equivalem a {fmtNum(linear.out)} {to}</Banner>
                : <Banner kind="info">Informe um valor numérico para converter</Banner>}
            </>
          ) : (
            <>
              <div className="vl-result-big">
                <div className="vl-result-corner vl-result-corner-tl"/>
                <div className="vl-result-corner vl-result-corner-tr"/>
                <div className="vl-result-corner vl-result-corner-bl"/>
                <div className="vl-result-corner vl-result-corner-br"/>
                <div className="vl-result-label">{awg?.mode === "a2m" ? "SEÇÃO EQUIVALENTE" : "BITOLA AWG MAIS PRÓXIMA"}</div>
                <div className="vl-result-row">
                  {awg && !awg.invalid && awg.mode === "a2m" && (
                    <><span className="readout vl-result-val">{fmtNum(awg.row.area)}</span><em>mm²</em></>
                  )}
                  {awg && !awg.invalid && awg.mode === "m2a" && (
                    <><span className="readout vl-result-val">{awg.row.awg}</span><em>AWG</em></>
                  )}
                  {(!awg || awg.invalid) && <span className="readout vl-result-val">—</span>}
                </div>
              </div>

              {awg && !awg.invalid && (
                <>
                  <div className="vl-mini-grid vl-mini-grid-3">
                    <Metric label="DIÂMETRO" value={fmtNum(awg.row.d_mm)} unit="mm"/>
                    <Metric label="CIRCULAR MILS" value={fmtNum(awg.row.cmil)} unit="cmil"/>
                    <Metric label="SEÇÃO COMERCIAL IEC" value={fmtNum(awg.iec)} unit="mm²"/>
                  </div>
                  <Banner kind="ok">
                    {awg.mode === "a2m"
                      ? `AWG ${awg.row.awg} ≈ ${fmtNum(awg.row.area)} mm² · use ${fmtNum(awg.iec)} mm² (comercial)`
                      : `${fmtNum(awg.area)} mm² ≈ AWG ${awg.row.awg} · comercial ${fmtNum(awg.iec)} mm²`}
                  </Banner>
                </>
              )}
              {awg && awg.invalid && <Banner kind="info">Informe uma seção válida em mm²</Banner>}
            </>
          )}
        </aside>
      </div>

      {/* ---------- TABELA DE REFERÊNCIA ---------- */}
      {!isAWG ? (
        <section className="panel">
          <div className="panel-head">
            <div>
              <div className="panel-eyebrow">TABELA DE EQUIVALÊNCIA</div>
              <h3>{linear && !linear.invalid ? `${fmtNum(linear.v)} ${from}` : "Valor de entrada"} em todas as unidades de {def.label}</h3>
            </div>
            <span className="dim mono small">Base: 1 {def.base} ({def.baseName})</span>
          </div>
          <div className="ref-table vl-conv-ref">
            <div className="ref-head">
              <span>UNIDADE</span>
              <span>NOME</span>
              <span>VALOR EQUIVALENTE</span>
              <span>FATOR P/ {def.base}</span>
            </div>
            {(linear?.table || def.units.map(u => ({ ...u, conv: NaN }))).map(u => {
              const sel = u.u === to;
              return (
                <div key={u.u} className={"ref-row " + (sel ? "is-sel" : "")}>
                  <span className="mono"><b>{u.u}</b></span>
                  <span className="dim">{u.n}</span>
                  <span className="mono">{isFinite(u.conv) ? fmtNum(u.conv) : "—"} {u.u}</span>
                  <span className="mono dim">×{fmtNum(u.f)}</span>
                </div>
              );
            })}
          </div>
        </section>
      ) : (
        <section className="panel">
          <div className="panel-head">
            <div>
              <div className="panel-eyebrow">TABELA DE REFERÊNCIA · AWG ⇄ mm²</div>
              <h3>Bitolas americanas e seções comerciais IEC</h3>
            </div>
            <span className="dim mono small">d = 0,127 · 92^((36−n)/39)</span>
          </div>
          <div className="ref-table vl-awg-ref">
            <div className="ref-head">
              <span>AWG</span>
              <span>Ø (mm)</span>
              <span>SEÇÃO (mm²)</span>
              <span>CIRCULAR MILS</span>
              <span>COMERCIAL IEC</span>
            </div>
            {AWG_ROWS.map(r => {
              const sel = awg && !awg.invalid && awg.row.key === r.key;
              return (
                <div key={r.key} className={"ref-row " + (sel ? "is-sel" : "")}>
                  <span className="mono"><b>{r.awg}</b></span>
                  <span className="mono dim">{r.d_mm.toFixed(2)}</span>
                  <span className="mono">{fmtNum(r.area)}</span>
                  <span className="mono dim">{Math.round(r.cmil).toLocaleString("pt-BR")}</span>
                  <span className="pill pill-ok">{fmtNum(nearestIEC(r.area))} mm²</span>
                </div>
              );
            })}
          </div>
        </section>
      )}
    </div>
  );
};

window.VL_Conversores = Conversor;
