/* global React */
/* ===========================================================
   VOLTLAB · INFRAESTRUTURA
   Quantitativo (BOM) de eletrocalhas, leitos, perfilados e
   eletrodutos a partir das distâncias do projeto.
   Adaptado para rodar dentro do shell VoltLab.
=========================================================== */
const { useState: useStateInfra, useMemo: useMemoInfra } = React;

const useInfraPersist = (key, initial) =>
  window.useLocalStorage ? window.useLocalStorage(key, initial) : useStateInfra(initial);

/* ── Cálculo (fórmulas da planilha) ───────────────────── */
const INFRA_CALC = {
  eletrocalha(m) {
    const d = parseFloat(m) || 0; if (d <= 0) return null;
    const u = Math.ceil(d / 3);
    return [
      { item: "Eletrocalha (barra 3m)",            qtd: u },
      { item: "Emendas tipo tala/simples",          qtd: u * 2 },
      { item: 'Parafusos lentilha 1/4" × 3/4"',     qtd: u * 8 },
      { item: 'Porcas 1/4"',                         qtd: u * 8 },
      { item: 'Arruelas lisas 1/4"',                 qtd: u * 8 },
      { item: "Mão francesa (paraf. fix. 3/8)",      qtd: u * 2 },
      { item: "Fixação / bucha / parabolts",         qtd: u * 4 },
    ];
  },
  leito(m) {
    const d = parseFloat(m) || 0; if (d <= 0) return null;
    const u = Math.ceil(d / 3);
    return [
      { item: "Leito portacabos (barra 3m)",         qtd: u },
      { item: "Emendas tipo tala/simples",            qtd: u * 2 },
      { item: 'Parafusos lentilha 3/8" × 3/4"',      qtd: u * 8 },
      { item: 'Porcas 3/8"',                          qtd: u * 8 },
      { item: 'Arruelas lisas 3/8"',                  qtd: u * 8 },
      { item: "Mão francesa (paraf. fix. 3/8)",       qtd: u * 2 },
      { item: "Fixação / bucha / parabolts",          qtd: u * 4 },
    ];
  },
  perfilado(m) {
    const d = parseFloat(m) || 0; if (d <= 0) return null;
    const u = Math.ceil(d / 6);
    return [
      { item: "Perfilado 38×38 (barra 6m)",          qtd: u },
      { item: "Suporte / gancho perfilado 38×38",     qtd: u * 4 },
      { item: 'Parafuso lentilha 1/4" × 3/4"',       qtd: u * 8 },
      { item: 'Porca 1/4"',                           qtd: u * 8 },
      { item: 'Arruela lisa 1/4"',                    qtd: u * 8 },
      { item: "Mão francesa",                         qtd: u * 4 },
      { item: "Fixação / bucha / parabolts",          qtd: (u * 8) + 1 },
    ];
  },
  eletroduto(m, ce) {
    const d = parseFloat(m) || 0; if (d <= 0) return null;
    const u = Math.ceil(d / 3);
    const c = parseInt(ce) || 0;
    return [
      { item: "Eletroduto galvanizado (barra 3m)",         qtd: u },
      { item: "Luvas",                                      qtd: Math.max(0, u - 1) },
      { item: "Abraçadeiras",                               qtd: u * 2 },
      { item: "Parafusos auto-atarraxante 4,8mm × 50mm",  qtd: u * 2 },
      { item: "Buchas nylon S8",                            qtd: u * 2 },
      { item: "Conduletes (trechos retos/curvas)",          qtd: c },
    ];
  },
};

const INFRA_TONE = {
  eletrocalha: "var(--accent)",
  leito:       "var(--accent-2)",
  perfilado:   "var(--ok)",
  eletroduto:  "var(--warn)",
};

const InfraIc = ({ n, s = 18 }) => {
  const p = { width: s, height: s, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" };
  const d = {
    tray:  <><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2"/></>,
    rail:  <><path d="M4 6h16M4 12h16M4 18h16"/></>,
    bolt:  <path d="M13 2L4 14h7l-2 8 9-12h-7z"/>,
    ring:  <><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="4"/></>,
    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"/></>,
    dl:    <><path d="M12 3v12"/><polyline points="7 10 12 15 17 10"/><line x1="4" y1="21" x2="20" y2="21"/></>,
    reset: <><path d="M21 12a9 9 0 11-3-6.7L21 8"/><path d="M21 3v5h-5"/></>,
  };
  return <svg {...p}>{d[n]}</svg>;
};

const InfraBanner = ({ kind, children }) => (
  <div className={"vl-banner vl-banner-" + kind}>
    <InfraIc n={kind === "ok" ? "check" : "info"} s={15}/>
    <span>{children}</span>
  </div>
);

const InfraNum = ({ label, hint, value, onChange, suffix }) => (
  <div className="vl-field">
    <label className="vl-field-label">
      <span>{label}</span>
      {hint && <span className="vl-field-hint">{hint}</span>}
    </label>
    <div className="vl-input">
      <input type="number" value={value} min="0" step="0.5" placeholder="0" onChange={e => onChange(e.target.value)}/>
      {suffix && <span className="vl-input-suffix">{suffix}</span>}
    </div>
  </div>
);

const InfraMatTable = ({ title, icon, tipo, items, dist, barra }) => {
  const cor = INFRA_TONE[tipo];
  if (!items) return (
    <div className="panel" style={{ opacity: 0.42 }}>
      <div className="panel-head" style={{ marginBottom: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--fg-mute)" }}>
          <InfraIc n={icon} s={16}/> <span style={{ fontSize: 13 }}>{title}</span>
        </div>
        <span style={{ fontSize: 11, color: "var(--fg-faint)", fontFamily: "var(--ff-mono)" }}>— informe a distância</span>
      </div>
    </div>
  );
  return (
    <div className="panel" style={{ borderLeft: `3px solid ${cor}` }}>
      <div className="panel-head">
        <div>
          <div className="panel-eyebrow" style={{ color: cor }}>{title.toUpperCase()}</div>
          <h3 style={{ display: "flex", alignItems: "center", gap: 8, margin: 0, color: cor }}>
            <InfraIc n={icon} s={16}/> {title}
          </h3>
        </div>
        <div style={{ textAlign: "right" }}>
          <div className="readout" style={{ fontSize: 26, color: cor, fontWeight: 700, lineHeight: 1 }}>{items[0].qtd}</div>
          <div style={{ fontSize: 10, color: "var(--fg-mute)", letterSpacing: "0.06em", fontFamily: "var(--ff-mono)", marginTop: 2 }}>
            BARRAS · {dist}m ÷ {barra}m
          </div>
        </div>
      </div>
      <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
        <thead>
          <tr style={{ borderBottom: "1px solid var(--border-2)" }}>
            <th style={{ textAlign: "left", padding: "5px 0", color: "var(--fg-mute)", fontSize: 10, letterSpacing: "0.08em", fontWeight: 600 }}>MATERIAL</th>
            <th style={{ textAlign: "right", padding: "5px 0", color: "var(--fg-mute)", fontSize: 10, letterSpacing: "0.08em", fontWeight: 600, width: 70 }}>QTD.</th>
          </tr>
        </thead>
        <tbody>
          {items.map((row, i) => (
            <tr key={i} style={{
              borderBottom: i < items.length - 1 ? "1px solid var(--border)" : "none",
              background: i === 0 ? `oklch(from ${cor} l c h / 0.08)` : "transparent",
            }}>
              <td style={{ padding: "8px 0", color: i === 0 ? "var(--fg)" : "var(--fg-dim)", fontWeight: i === 0 ? 600 : 400 }}>{row.item}</td>
              <td style={{ padding: "8px 0", textAlign: "right", fontFamily: "var(--ff-mono)", fontWeight: 700, color: i === 0 ? cor : "var(--fg)", fontSize: i === 0 ? 17 : 14 }}>{row.qtd}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

const InfraDiagram = ({ dc, dl, dp, de }) => {
  const vals = [
    { label: "Eletrocalha", m: parseFloat(dc) || 0, cor: INFRA_TONE.eletrocalha },
    { label: "Leito",       m: parseFloat(dl) || 0, cor: INFRA_TONE.leito },
    { label: "Perfilado",   m: parseFloat(dp) || 0, cor: INFRA_TONE.perfilado },
    { label: "Eletroduto",  m: parseFloat(de) || 0, cor: INFRA_TONE.eletroduto },
  ].filter(v => v.m > 0);
  if (!vals.length) return null;
  const max = Math.max(...vals.map(v => v.m));
  return (
    <div style={{ background: "var(--bg-0)", border: "1px solid var(--border)", borderRadius: 8, padding: "14px 16px", marginTop: 20 }}>
      <div className="panel-eyebrow" style={{ marginBottom: 12 }}>ESCALA VISUAL</div>
      {vals.map((v, i) => (
        <div key={i} style={{ marginBottom: i < vals.length - 1 ? 12 : 0 }}>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, marginBottom: 5 }}>
            <span style={{ color: "var(--fg-dim)" }}>{v.label}</span>
            <span className="readout" style={{ color: v.cor, fontWeight: 700 }}>{v.m} m</span>
          </div>
          <div style={{ height: 7, background: "var(--bg-3)", borderRadius: 4, overflow: "hidden" }}>
            <div style={{ height: "100%", borderRadius: 4, background: v.cor, width: `${(v.m / max) * 100}%`, transition: "width 0.4s ease" }}/>
          </div>
        </div>
      ))}
    </div>
  );
};

const InfraBOM = ({ res }) => {
  const tipos = ["eletrocalha", "leito", "perfilado", "eletroduto"];
  const labels = { eletrocalha: "Eletrocalha", leito: "Leito", perfilado: "Perfilado", eletroduto: "Eletroduto" };
  const ativos = tipos.filter(t => res[t]);
  if (!ativos.length) return (
    <div style={{ padding: "40px 0" }}>
      <InfraBanner kind="info">Informe ao menos uma distância na aba Dimensionamento.</InfraBanner>
    </div>
  );

  const mapa = {};
  tipos.forEach(tipo => { (res[tipo] || []).forEach(r => { if (!mapa[r.item]) mapa[r.item] = { item: r.item, tipos: {} }; mapa[r.item].tipos[tipo] = r.qtd; }); });
  const totais = {};
  ativos.forEach(t => { totais[t] = (res[t] || []).reduce((s, r) => s + r.qtd, 0); });

  const exportCSV = () => {
    const rows = [["MATERIAL", ...ativos.map(t => labels[t].toUpperCase())]];
    Object.values(mapa).forEach(r => rows.push([r.item, ...ativos.map(t => r.tipos[t] ?? "")]));
    const csv = rows.map(r => r.join(";")).join("\n");
    const a = document.createElement("a");
    a.href = URL.createObjectURL(new Blob(["\uFEFF" + csv], { type: "text/csv;charset=utf-8" }));
    a.download = "infraestrutura-bom.csv"; a.click();
    if (window.vlToast) window.vlToast("✓ CSV exportado");
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12 }}>
        {tipos.map(tipo => {
          const it = res[tipo]; const cor = INFRA_TONE[tipo];
          return (
            <div key={tipo} style={{ background: "var(--bg-1)", borderRadius: 8, padding: "14px 16px", borderLeft: it ? `3px solid ${cor}` : "3px solid var(--border)", opacity: it ? 1 : 0.35 }}>
              <div style={{ fontSize: 10, color: "var(--fg-mute)", letterSpacing: "0.07em", fontFamily: "var(--ff-mono)", marginBottom: 6 }}>{labels[tipo].toUpperCase()}</div>
              <div className="readout" style={{ fontSize: 22, fontWeight: 700, color: it ? cor : "var(--fg-faint)", lineHeight: 1 }}>{it ? it[0].qtd : "—"}</div>
              <div style={{ fontSize: 10, color: "var(--fg-faint)", marginTop: 4 }}>barras/peças</div>
            </div>
          );
        })}
      </div>

      <div className="panel">
        <div className="panel-head">
          <div>
            <div className="panel-eyebrow">CONSOLIDADO · BILL OF MATERIALS</div>
            <h3>Quantitativo geral do projeto</h3>
          </div>
          <button className="btn btn-primary" style={{ padding: "7px 14px", fontSize: 12 }} onClick={exportCSV}>
            <InfraIc n="dl" s={14}/> Exportar CSV
          </button>
        </div>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
            <thead>
              <tr style={{ borderBottom: "2px solid var(--border-2)" }}>
                <th style={{ textAlign: "left", padding: "8px", color: "var(--fg-mute)", fontSize: 10, letterSpacing: "0.07em", fontWeight: 600 }}>MATERIAL</th>
                {ativos.map(t => (<th key={t} style={{ textAlign: "center", padding: "8px", color: INFRA_TONE[t], fontSize: 10, letterSpacing: "0.07em", fontWeight: 700 }}>{labels[t].toUpperCase()}</th>))}
                <th style={{ textAlign: "right", padding: "8px", color: "var(--fg-mute)", fontSize: 10, letterSpacing: "0.07em", fontWeight: 600 }}>TOTAL</th>
              </tr>
            </thead>
            <tbody>
              {Object.values(mapa).map((row, i) => {
                const total = ativos.reduce((s, t) => s + (row.tipos[t] || 0), 0);
                return (
                  <tr key={i} style={{ borderBottom: "1px solid var(--border)" }}>
                    <td style={{ padding: "8px 8px", color: "var(--fg-dim)" }}>{row.item}</td>
                    {ativos.map(t => (<td key={t} style={{ padding: "8px", textAlign: "center", fontFamily: "var(--ff-mono)", fontWeight: row.tipos[t] ? 700 : 400, color: row.tipos[t] ? "var(--fg)" : "var(--fg-faint)" }}>{row.tipos[t] || "—"}</td>))}
                    <td style={{ padding: "8px", textAlign: "right", fontFamily: "var(--ff-mono)", fontWeight: 700, color: "var(--accent)" }}>{total || "—"}</td>
                  </tr>
                );
              })}
            </tbody>
            <tfoot>
              <tr style={{ borderTop: "2px solid var(--border-2)" }}>
                <td style={{ padding: "8px", fontWeight: 700, color: "var(--fg)" }}>TOTAL DE ITENS</td>
                {ativos.map(t => (<td key={t} style={{ padding: "8px", textAlign: "center", fontFamily: "var(--ff-mono)", fontWeight: 700, color: INFRA_TONE[t] }}>{totais[t]}</td>))}
                <td style={{ padding: "8px", textAlign: "right", fontFamily: "var(--ff-mono)", fontWeight: 700, color: "var(--accent)" }}>{ativos.reduce((s, t) => s + totais[t], 0)}</td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
    </div>
  );
};

/* ── Componente principal ─────────────────────────────── */
const Infraestrutura = () => {
  const [dc, setDc] = useInfraPersist("vl_infra_calha", "");
  const [dl, setDl] = useInfraPersist("vl_infra_leito", "");
  const [dp, setDp] = useInfraPersist("vl_infra_perf", "");
  const [de, setDe] = useInfraPersist("vl_infra_eldt", "");
  const [cond, setCond] = useInfraPersist("vl_infra_cond", "0");
  const [tab, setTab] = useStateInfra("calc");

  const res = useMemoInfra(() => ({
    eletrocalha: INFRA_CALC.eletrocalha(dc),
    leito:       INFRA_CALC.leito(dl),
    perfilado:   INFRA_CALC.perfilado(dp),
    eletroduto:  INFRA_CALC.eletroduto(de, cond),
  }), [dc, dl, dp, de, cond]);

  const ativos = Object.values(res).filter(Boolean).length;
  const totalItens = Object.values(res).filter(Boolean).flatMap(r => r).reduce((s, r) => s + r.qtd, 0);
  const totalDist = [dc, dl, dp, de].reduce((s, v) => s + (parseFloat(v) || 0), 0);

  const reset = () => { setDc(""); setDl(""); setDp(""); setDe(""); setCond("0"); if (window.vlToast) window.vlToast("✓ Campos limpos"); };

  const Sync = window.VL_ProjetoSync;

  return (
    <div className="eletroduto">
      {/* Abas */}
      <div style={{ display: "flex", marginBottom: 20, borderBottom: "1px solid var(--border)" }}>
        {[{ id: "calc", label: "Dimensionamento" }, { id: "resumo", label: "Resumo / BOM" }].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            display: "flex", alignItems: "center", gap: 6, padding: "10px 18px", background: "none", border: "none",
            borderBottom: `2px solid ${tab === t.id ? "var(--accent)" : "transparent"}`,
            color: tab === t.id ? "var(--accent)" : "var(--fg-mute)", fontWeight: tab === t.id ? 600 : 400,
            fontSize: 13, cursor: "pointer", transition: "all .15s", marginBottom: -1, fontFamily: "var(--ff-body)",
          }}>
            {t.label}
            {t.id === "resumo" && ativos > 0 && (
              <span style={{ background: "var(--accent-soft)", color: "var(--accent)", border: "1px solid var(--accent)", borderRadius: 999, fontSize: 10, fontFamily: "var(--ff-mono)", padding: "1px 7px" }}>{ativos}</span>
            )}
          </button>
        ))}
        <div style={{ flex: 1 }}/>
        <button className="btn btn-ghost" style={{ fontSize: 12, alignSelf: "center" }} onClick={reset}>
          <InfraIc n="reset" s={14}/> Limpar
        </button>
      </div>

      {tab === "resumo" ? (
        <InfraBOM res={res}/>
      ) : (
        <div className="el-grid" style={{ gridTemplateColumns: "320px 1fr", display: "grid", gap: "var(--gap-grid)", alignItems: "start" }}>
          <section className="panel" style={{ alignSelf: "start" }}>
            <div className="panel-head">
              <div>
                <div className="panel-eyebrow">ENTRADA · DISTÂNCIAS</div>
                <h3>Dados do projeto</h3>
              </div>
              <div className="status-chip"><span className="status-dot status-ok"/>AUTO</div>
            </div>

            {Sync && (
              <Sync
                source="Infraestrutura"
                reads={["comprimento"]}
                pull={(s) => { const c = s.get("comprimento"); if (c != null) setDe(String(c)); }}
                push={() => ({ comprimento: parseFloat(de) || undefined })}
              />
            )}

            <div style={{ display: "flex", flexDirection: "column", gap: 16, marginTop: 16 }}>
              <InfraNum label="Eletrocalhas" hint="barra 3m" value={dc} onChange={setDc} suffix="m"/>
              <InfraNum label="Leitos portacabos" hint="barra 3m" value={dl} onChange={setDl} suffix="m"/>
              <InfraNum label="Perfilados 38×38" hint="barra 6m" value={dp} onChange={setDp} suffix="m"/>
              <InfraNum label="Eletrodutos galvanizados" hint="barra 3m" value={de} onChange={setDe} suffix="m"/>
              <InfraNum label="Conduletes extras" hint="curvas / caixas" value={cond} onChange={setCond} suffix="un"/>
            </div>

            <InfraDiagram dc={dc} dl={dl} dp={dp} de={de}/>

            <div className="vl-memory" style={{ marginTop: 20 }}>
              <div className="vl-memory-head"><div className="vl-memory-eyebrow">FÓRMULAS DE REFERÊNCIA</div></div>
              {[
                ["01", "Eletrocalha / Leito", "N = ⌈ distância ÷ 3 ⌉"],
                ["02", "Perfilado 38×38", "N = ⌈ distância ÷ 6 ⌉"],
                ["03", "Eletroduto galv.", "N = ⌈ distância ÷ 3 ⌉"],
              ].map(([n, title, formula]) => (
                <div className="vl-mem-step" key={n}>
                  <div className="vl-mem-step-head">
                    <span className="vl-mem-step-n">{n}</span>
                    <span className="vl-mem-step-title">{title}</span>
                  </div>
                  <div className="vl-mem-step-body is-formula">{formula}</div>
                </div>
              ))}
            </div>

            {ativos === 0 && (<div style={{ marginTop: 16 }}><InfraBanner kind="info">Informe uma distância para gerar o quantitativo.</InfraBanner></div>)}
          </section>

          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <InfraMatTable title="Eletrocalhas" icon="tray" tipo="eletrocalha" items={res.eletrocalha} dist={parseFloat(dc) || "—"} barra={3}/>
            <InfraMatTable title="Leitos portacabos" icon="rail" tipo="leito" items={res.leito} dist={parseFloat(dl) || "—"} barra={3}/>
            <InfraMatTable title="Perfilados 38×38" icon="bolt" tipo="perfilado" items={res.perfilado} dist={parseFloat(dp) || "—"} barra={6}/>
            <InfraMatTable title="Eletrodutos galvanizados" icon="ring" tipo="eletroduto" items={res.eletroduto} dist={parseFloat(de) || "—"} barra={3}/>
          </div>
        </div>
      )}
    </div>
  );
};

window.VL_Infraestrutura = Infraestrutura;
