/* global React */
/* ===========================================================
   VOLTLAB · QUADROS & DIAGRAMAS
   Dimensionamento de quadros de partida WEG
   (Partida Direta + Estrela-Triângulo)
=========================================================== */
const { useState, useMemo } = React;

/* ===========================================================
   DADOS WEG — extraídos do "Guia de Seleção de Partidas"
=========================================================== */
// Motores WEG W22 IR3 Premium — 60 Hz (Página 32)
const MOTOR_CURRENTS = {
  "220": {
    "1": 2.90, "1.5": 4.30, "2": 5.69, "3": 8.25, "4": 11.4, "5": 14.1,
    "6": 16.5, "7.5": 20.4, "10": 26.0, "12.5": 32.2, "15": 38.4,
  },
  "380": {
    "1": 1.68, "1.5": 2.49, "2": 3.29, "3": 4.78, "4": 6.60, "5": 8.16,
    "6": 9.55, "7.5": 11.8, "10": 15.1, "12.5": 18.6, "15": 22.2,
  },
};

// Tabela Partida Direta (3 componentes) — Página 4
// Faixa motor (A) → Disjuntor / Fusível / Contator / Relé Térmico
const TABELA_PARTIDA_DIRETA = [
  { min: 1.2, max: 1.6,  q1: "MPW18i-3-D016",  fus: "FDW-4S",   k1: "CWB9-11-30",   ft1: "RW27-2D3-D018" },
  { min: 1.2, max: 1.8,  q1: "MPW18i-3-D025",  fus: "FDW-6S",   k1: "CWB9-11-30",   ft1: "RW27-2D3-D018" },
  { min: 1.8, max: 2.5,  q1: "MPW18i-3-D025",  fus: "FDW-6S",   k1: "CWB9-11-30",   ft1: "RW27-2D3-D028" },
  { min: 1.8, max: 2.8,  q1: "MPW18i-3-U004",  fus: "FDW-10S",  k1: "CWB9-11-30",   ft1: "RW27-2D3-D028" },
  { min: 2.8, max: 4.0,  q1: "MPW18i-3-U004",  fus: "FDW-10S",  k1: "CWB9-11-30",   ft1: "RW27-2D3-U004" },
  { min: 4.0, max: 6.3,  q1: "MPW18i-3-D063",  fus: "FDW-10S",  k1: "CWB9-11-30",   ft1: "RW27-2D3-D063" },
  { min: 5.6, max: 8.0,  q1: "MPW18i-3-U010",  fus: "FDW-20S",  k1: "CWB9-11-30",   ft1: "RW27-2D3-U008" },
  { min: 7.0, max: 9.0,  q1: "MPW18i-3-U010",  fus: "FDW-20S",  k1: "CWB9-11-30",   ft1: "RW27-2D3-U010" },
  { min: 7.0, max: 10.0, q1: "MPW18i-3-U010",  fus: "FDW-25S",  k1: "CWB12-11-30",  ft1: "RW27-2D3-U010" },
  { min: 8.0, max: 12.0, q1: "MPW18i-3-U016",  fus: "FDW-25S",  k1: "CWB12-11-30",  ft1: "RW27-2D3-D125" },
  { min: 10.0, max: 15.0, q1: "MPW18i-3-U016", fus: "FDW-35S",  k1: "CWB18-11-30",  ft1: "RW27-2D3-U015" },
  { min: 11.0, max: 16.0, q1: "MPW18i-3-U016", fus: "FDW-35S",  k1: "CWB18-11-30",  ft1: "RW27-2D3-U017" },
  { min: 11.0, max: 17.0, q1: "MPW18i-3-U018", fus: "FDW-35S",  k1: "CWB18-11-30",  ft1: "RW27-2D3-U017" },
  { min: 15.0, max: 18.0, q1: "MPW18i-3-U018", fus: "FDW-50S",  k1: "CWB18-11-30",  ft1: "RW27-2D3-U023" },
  { min: 15.0, max: 20.0, q1: "MPW40i-3-U020", fus: "FDW-50S",  k1: "CWB25-11-30",  ft1: "RW27-2D3-U023" },
  { min: 15.0, max: 23.0, q1: "MPW40i-3-U025", fus: "FDW-50S",  k1: "CWB25-11-30",  ft1: "RW27-2D3-U023" },
  { min: 22.0, max: 25.0, q1: "MPW40i-3-U025", fus: "FDW-50S",  k1: "CWB25-11-30",  ft1: "RW27-2D3-U032" },
  { min: 22.0, max: 32.0, q1: "MPW40i-3-U032", fus: "FDW-50S",  k1: "CWB32-11-30",  ft1: "RW27-2D3-U032" },
  { min: 32.0, max: 38.0, q1: "MPW40i-3-U040", fus: "FDW-63S",  k1: "CWB38-11-30",  ft1: "RW27-2D3-U040" },
  { min: 25.0, max: 40.0, q1: "MPW80i-3-U040", fus: "FDW-63S",  k1: "CWB40-11-30",  ft1: "RW67-5D3-U040" },
];

// Tabela Partida Estrela-Triângulo (5 componentes) — Página 18
// faixa = I_motor / √3
const TABELA_ESTRELA_TRIANGULO = [
  { min: 6.9, max: 10.9, q1: "MPW40i-3-U016",  fus: "FDW-16S", k12: "CWB9-11-30",  k3: "CWB9-11-30",  ft1: "RW27-2D3-D063" },
  { min: 9.7, max: 13.8, q1: "MPW40i-3-U016",  fus: "FDW-20S", k12: "CWB9-11-30",  k3: "CWB9-11-30",  ft1: "RW27-2D3-U008" },
  { min: 12.1, max: 15.6, q1: "MPW40i-3-U016", fus: "FDW-20S", k12: "CWB9-11-30",  k3: "CWB9-11-30",  ft1: "RW27-2D3-U010" },
  { min: 12.1, max: 17.3, q1: "MPW40i-3-U020", fus: "FDW-25S", k12: "CWB12-11-30", k3: "CWB9-11-30",  ft1: "RW27-2D3-U010" },
  { min: 13.9, max: 20.8, q1: "MPW40i-3-U025", fus: "FDW-35S", k12: "CWB12-11-30", k3: "CWB9-11-30",  ft1: "RW27-2D3-D125" },
  { min: 17.3, max: 26.0, q1: "MPW40i-3-U032", fus: "FDW-35S", k12: "CWB18-11-30", k3: "CWB9-11-30",  ft1: "RW27-2D3-U015" },
  { min: 19.1, max: 27.0, q1: "MPW40i-3-U032", fus: "FDW-35S", k12: "CWB18-11-30", k3: "CWB9-11-30",  ft1: "RW27-2D3-U017" },
  { min: 19.1, max: 29.4, q1: "MPW40i-3-U032", fus: "FDW-50S", k12: "CWB18-11-30", k3: "CWB12-11-30", ft1: "RW27-2D3-U017" },
];

const POTENCIAS_DISPONIVEIS = ["1","1.5","2","3","4","5","6","7.5","10","12.5","15"];

function lookupPartidaDireta(In) {
  return TABELA_PARTIDA_DIRETA.find(r => In >= r.min && In <= r.max) || null;
}
function lookupEstrelaTriangulo(In) {
  const i = In / Math.sqrt(3);
  return TABELA_ESTRELA_TRIANGULO.find(r => i >= r.min && i <= r.max) || null;
}

function dimensionarPartida(potencia, tensao, metodo) {
  const In = MOTOR_CURRENTS[tensao]?.[potencia];
  if (!In) return null;
  if (metodo === "direta") {
    const sel = lookupPartidaDireta(In);
    if (!sel) return { In, error: "Sem componente compatível para " + In + " A" };
    return {
      In,
      metodo: "Partida Direta",
      faixa: `${sel.min} … ${sel.max} A`,
      components: [
        { tag: "Q1",  type: "Disjuntor-Motor", code: sel.q1,  desc: "Proteção magnética + sobrecarga" },
        { tag: "F1",  type: "Fusível gL/gG",  code: sel.fus,  desc: "Proteção contra curto-circuito" },
        { tag: "K1",  type: "Contator",      code: sel.k1,   desc: "Manobra e comando" },
        { tag: "FT1", type: "Relé Térmico",   code: sel.ft1, desc: "Proteção térmica do motor" },
      ],
    };
  } else {
    const sel = lookupEstrelaTriangulo(In);
    if (!sel) return { In, error: "Motor abaixo do mínimo recomendado para estrela-triângulo (≥ 5 cv 220V / 10 cv 380V)" };
    return {
      In,
      metodo: "Partida Estrela-Triângulo",
      faixa: `${sel.min} … ${sel.max} A (I/√3)`,
      components: [
        { tag: "Q1",  type: "Disjuntor-Motor", code: sel.q1,  desc: "Proteção magnética" },
        { tag: "F1",  type: "Fusível gL/gG",  code: sel.fus,  desc: "Proteção contra curto-circuito" },
        { tag: "K1",  type: "Contator linha", code: sel.k12, desc: "Contator principal" },
        { tag: "K2",  type: "Contator Δ",     code: sel.k12, desc: "Contator triângulo" },
        { tag: "K3",  type: "Contator ✱",     code: sel.k3,  desc: "Contator estrela" },
        { tag: "FT1", type: "Relé Térmico",   code: sel.ft1, desc: "Proteção térmica" },
      ],
    };
  }
}

/* ===========================================================
   ÍCONES (lucide-style)
=========================================================== */
const QIcon = ({ 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 paths = {
    plus:    <><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></>,
    trash:   <><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/><path d="M10 11v6M14 11v6"/></>,
    motor:   <><circle cx="12" cy="12" r="9"/><text x="12" y="16" textAnchor="middle" fontSize="10" fontFamily="JetBrains Mono" fontWeight="600" fill="currentColor" stroke="none">M</text></>,
    box:     <><rect x="3" y="4" width="18" height="16" rx="1"/><line x1="3" y1="9" x2="21" y2="9"/></>,
    chevron: <polyline points="9 6 15 12 9 18"/>,
    bolt:    <path d="M13 2L4 14h7l-2 8 9-12h-7z"/>,
    cog:     <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 00.3 1.8l.1.1a2 2 0 11-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.8-.3 1.7 1.7 0 00-1 1.5V21a2 2 0 11-4 0v-.1a1.7 1.7 0 00-1.1-1.5 1.7 1.7 0 00-1.8.3l-.1.1a2 2 0 11-2.8-2.8l.1-.1a1.7 1.7 0 00.3-1.8 1.7 1.7 0 00-1.5-1H3a2 2 0 110-4h.1a1.7 1.7 0 001.5-1.1 1.7 1.7 0 00-.3-1.8l-.1-.1a2 2 0 112.8-2.8l.1.1a1.7 1.7 0 001.8.3H9a1.7 1.7 0 001-1.5V3a2 2 0 114 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.8-.3l.1-.1a2 2 0 112.8 2.8l-.1.1a1.7 1.7 0 00-.3 1.8V9a1.7 1.7 0 001.5 1H21a2 2 0 110 4h-.1a1.7 1.7 0 00-1.5 1z"/></>,
    download: <><path d="M12 3v12"/><polyline points="7 10 12 15 17 10"/><line x1="4" y1="21" x2="20" y2="21"/></>,
    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"/></>,
    plug:    <><path d="M9 2v6M15 2v6M6 8h12v3a6 6 0 01-12 0z"/><path d="M12 17v5"/></>,
    fuse:    <><rect x="3" y="9" width="18" height="6" rx="1"/><line x1="8" y1="9" x2="8" y2="15"/><line x1="16" y1="9" x2="16" y2="15"/></>,
    contactor: <><rect x="4" y="4" width="16" height="16" rx="1"/><line x1="8" y1="4" x2="8" y2="12"/><line x1="12" y1="4" x2="12" y2="12"/><line x1="16" y1="4" x2="16" y2="12"/><line x1="8" y1="14" x2="8" y2="20"/><line x1="12" y1="14" x2="12" y2="20"/><line x1="16" y1="14" x2="16" y2="20"/></>,
    relay:   <><rect x="4" y="4" width="16" height="16" rx="1"/><path d="M8 9l3 6 3-6 3 6"/></>,
    breaker: <><rect x="6" y="3" width="12" height="18" rx="1"/><line x1="12" y1="8" x2="12" y2="13"/><circle cx="12" cy="15.5" r="1.5"/></>,
  };
  return <svg {...p}>{paths[name]}</svg>;
};

const COMP_ICON_BY_TAG = {
  "Q1": "breaker",
  "F1": "fuse",
  "K1": "contactor",
  "K2": "contactor",
  "K3": "contactor",
  "FT1": "relay",
};

/* ===========================================================
   SVG: QUADRO + MOTOR (diagrama do dimensionamento)
=========================================================== */
const QuadroDiagrama = ({ motor }) => {
  const dim = motor.dim;
  const comps = dim?.components || [];
  // layout: a vertical panel with 3 phases and components stacked
  const W = 420, H = 360;
  const railY = 36;       // bus top
  const panelX = 80, panelY = 60, panelW = 260, panelH = 200;
  const compH = comps.length ? (panelH - 30) / comps.length : 0;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="vl-quadro-svg">
      {/* 3-phase bus */}
      <g stroke="var(--fg-dim)" strokeWidth="1">
        <line x1="40" y1={railY} x2={W-40} y2={railY}/>
        <line x1="40" y1={railY+6} x2={W-40} y2={railY+6}/>
        <line x1="40" y1={railY+12} x2={W-40} y2={railY+12}/>
      </g>
      <g fontFamily="JetBrains Mono" fontSize="8" fill="var(--fg-mute)">
        <text x="32" y={railY+3} textAnchor="end">L1</text>
        <text x="32" y={railY+9} textAnchor="end">L2</text>
        <text x="32" y={railY+15} textAnchor="end">L3</text>
      </g>
      {/* drop lines from bus to panel */}
      <g stroke="var(--accent)" strokeWidth="1" opacity="0.6">
        <line x1={W/2-12} y1={railY+12} x2={W/2-12} y2={panelY}/>
        <line x1={W/2}    y1={railY+12} x2={W/2}    y2={panelY}/>
        <line x1={W/2+12} y1={railY+12} x2={W/2+12} y2={panelY}/>
      </g>
      {/* panel rectangle */}
      <rect x={panelX} y={panelY} width={panelW} height={panelH}
            rx="6" fill="var(--bg-0)" stroke="var(--accent)" strokeWidth="1.2"/>
      <rect x={panelX-3} y={panelY-3} width={panelW+6} height="14"
            fill="var(--accent-soft)" stroke="var(--accent)" rx="3" strokeWidth="0.8"/>
      <text x={panelX+8} y={panelY+5} fill="var(--accent)" fontSize="7"
            fontFamily="JetBrains Mono" letterSpacing="1.2">
        QUADRO · QGM-{String(motor.id).padStart(2,"0")}
      </text>
      <text x={panelX+panelW-8} y={panelY+5} fill="var(--accent)" fontSize="7"
            fontFamily="JetBrains Mono" textAnchor="end" letterSpacing="1.2">
        {dim?.metodo?.toUpperCase()}
      </text>
      {/* components inside panel */}
      {comps.map((c, i) => {
        const y = panelY + 22 + i*compH;
        return (
          <g key={i}>
            <rect x={panelX+12} y={y} width={panelW-24} height={compH-6}
                  rx="3" fill="var(--bg-1)" stroke="var(--border-2)" strokeWidth="0.8"/>
            <g transform={`translate(${panelX+22}, ${y + (compH-6)/2 - 8})`} color="var(--accent)">
              <QIcon name={COMP_ICON_BY_TAG[c.tag] || "box"} size={16}/>
            </g>
            <text x={panelX+50} y={y + (compH-6)/2 - 1}
                  fill="var(--accent)" fontSize="8" fontFamily="JetBrains Mono"
                  fontWeight="600" letterSpacing="0.8">
              {c.tag}
            </text>
            <text x={panelX+50} y={y + (compH-6)/2 + 8}
                  fill="var(--fg-dim)" fontSize="7" fontFamily="JetBrains Mono">
              {c.type}
            </text>
            <text x={panelX+panelW-16} y={y + (compH-6)/2 + 3}
                  fill="var(--fg)" fontSize="7" fontFamily="JetBrains Mono"
                  textAnchor="end">
              {c.code}
            </text>
          </g>
        );
      })}
      {/* panel → motor lines */}
      <g stroke="var(--accent)" strokeWidth="1" opacity="0.6">
        <line x1={W/2-12} y1={panelY+panelH} x2={W/2-12} y2={H-60}/>
        <line x1={W/2}    y1={panelY+panelH} x2={W/2}    y2={H-60}/>
        <line x1={W/2+12} y1={panelY+panelH} x2={W/2+12} y2={H-60}/>
      </g>
      {/* motor */}
      <g transform={`translate(${W/2}, ${H-30})`}>
        <circle r="26" fill="var(--bg-0)" stroke="var(--accent)" strokeWidth="1.5"/>
        <circle r="26" fill="none" stroke="var(--accent)" strokeWidth="3" opacity="0.18"/>
        <text y="3" textAnchor="middle" fill="var(--accent)" fontSize="18"
              fontFamily="Space Grotesk" fontWeight="600">M</text>
        <text y="14" textAnchor="middle" fill="var(--fg-mute)" fontSize="6"
              fontFamily="JetBrains Mono" letterSpacing="0.8">3~</text>
      </g>
      <text x={W/2} y={H-2} textAnchor="middle" fill="var(--fg-dim)"
            fontSize="9" fontFamily="JetBrains Mono">
        {motor.potencia} cv · {motor.tensao} V · In = {dim?.In} A
      </text>
    </svg>
  );
};

/* ===========================================================
   ITEM DO MOTOR (no canvas)
=========================================================== */
const MotorCard = ({ motor, selected, onSelect, onRemove }) => {
  const empty = !motor.dim;
  return (
    <div
      className={"vl-motor-card " + (selected ? "is-selected " : "") + (empty ? "is-empty " : "")}
      onClick={onSelect}
    >
      <div className="vl-motor-card-head">
        <div className="vl-motor-card-id">
          <span className="vl-motor-card-num">M-{String(motor.id).padStart(2,"0")}</span>
          {motor.dim?.error
            ? <span className="vl-pill-mini is-warn">erro</span>
            : motor.dim
              ? <span className="vl-pill-mini is-ok">dimensionado</span>
              : <span className="vl-pill-mini">configurar</span>
          }
        </div>
        <button className="vl-motor-card-del" onClick={(e) => { e.stopPropagation(); onRemove(); }} aria-label="remover">
          <QIcon name="trash" size={14}/>
        </button>
      </div>

      {motor.dim && !motor.dim.error
        ? <QuadroDiagrama motor={motor}/>
        : (
          <div className="vl-motor-empty">
            <div className="vl-motor-empty-icon"><QIcon name="motor" size={36}/></div>
            <div className="vl-motor-empty-text">
              {motor.dim?.error
                ? motor.dim.error
                : "Selecione potência, tensão e método para gerar o quadro"}
            </div>
          </div>
        )
      }
    </div>
  );
};

/* ===========================================================
   PAINEL DE CONFIGURAÇÃO (direita)
=========================================================== */
const ConfigPanel = ({ motor, onChange }) => {
  if (!motor) {
    return (
      <div className="vl-config-empty">
        <div className="vl-config-empty-icon"><QIcon name="motor" size={32}/></div>
        <h4>Nenhum motor selecionado</h4>
        <p>Adicione um motor à área de desenho e clique sobre ele para configurar potência, tensão e método de partida.</p>
      </div>
    );
  }

  const D = window.Dropdown_VL;
  return (
    <div className="vl-config">
      <div className="vl-config-head">
        <div className="vl-config-eyebrow">SELECIONADO</div>
        <h3>Motor M-{String(motor.id).padStart(2,"0")}</h3>
      </div>

      <div className="vl-config-body">
        <div className="vl-field">
          <label className="vl-field-label"><span>Potência do motor</span></label>
          <D value={motor.potencia} onChange={(v) => onChange({ potencia: v })}
             options={POTENCIAS_DISPONIVEIS.map(p => ({ value: p, label: `${p} cv` }))}/>
        </div>

        <div className="vl-field">
          <label className="vl-field-label"><span>Tensão de operação</span></label>
          <div className="seg">
            <button className={motor.tensao === "220" ? "is-active" : ""} onClick={() => onChange({ tensao: "220" })}>220 V</button>
            <button className={motor.tensao === "380" ? "is-active" : ""} onClick={() => onChange({ tensao: "380" })}>380 V</button>
          </div>
        </div>

        <div className="vl-field">
          <label className="vl-field-label"><span>Método de partida</span></label>
          <div className="seg seg-stack">
            <button className={motor.metodo === "direta" ? "is-active" : ""} onClick={() => onChange({ metodo: "direta" })}>
              <b>Partida Direta</b>
              <em>Disjuntor + Fusível + Contator + Relé</em>
            </button>
            <button className={motor.metodo === "estrela" ? "is-active" : ""} onClick={() => onChange({ metodo: "estrela" })}>
              <b>Estrela-Triângulo</b>
              <em>K1 + K2 + K3 + Q1 + Relé</em>
            </button>
          </div>
        </div>

        {motor.dim?.error ? (
          <div className="vl-banner vl-banner-warn">
            <QIcon name="info" size={14}/> {motor.dim.error}
          </div>
        ) : motor.dim ? (
          <>
            <div className="vl-stat-strip">
              <div>
                <span>CORRENTE NOMINAL</span>
                <b className="readout">{motor.dim.In} <em>A</em></b>
              </div>
              <div>
                <span>FAIXA ATENDIDA</span>
                <b className="readout">{motor.dim.faixa}</b>
              </div>
            </div>

            <div className="vl-comp-list">
              <div className="vl-comp-list-head">COMPONENTES DIMENSIONADOS · WEG</div>
              {motor.dim.components.map((c, i) => (
                <div className="vl-comp-row" key={i}>
                  <div className="vl-comp-icon"><QIcon name={COMP_ICON_BY_TAG[c.tag] || "box"} size={14}/></div>
                  <div className="vl-comp-meta">
                    <span className="vl-comp-tag">{c.tag}</span>
                    <span className="vl-comp-type">{c.type}</span>
                  </div>
                  <span className="vl-comp-code mono">{c.code}</span>
                </div>
              ))}
            </div>

            <button className="btn btn-primary btn-block">
              <QIcon name="download" size={14}/> Lista de materiais
            </button>
          </>
        ) : null}
      </div>
    </div>
  );
};

/* ===========================================================
   ROOT — Quadros & Diagramas
=========================================================== */
const QuadrosDiagramas = () => {
  const [motors, setMotors] = useState([
    { id: 1, potencia: "5",  tensao: "380", metodo: "direta" },
    { id: 2, potencia: "10", tensao: "380", metodo: "estrela" },
  ]);
  const [selectedId, setSelectedId] = useState(1);
  const nextId = useMemo(() => Math.max(0, ...motors.map(m => m.id)) + 1, [motors]);

  const enriched = motors.map(m => ({ ...m, dim: dimensionarPartida(m.potencia, m.tensao, m.metodo) }));
  const selected = enriched.find(m => m.id === selectedId) || null;

  const addMotor = () => {
    const m = { id: nextId, potencia: "5", tensao: "380", metodo: "direta" };
    setMotors(arr => [...arr, m]);
    setSelectedId(m.id);
  };
  const updateMotor = (id, patch) => setMotors(arr => arr.map(m => m.id === id ? { ...m, ...patch } : m));
  const removeMotor = (id) => {
    setMotors(arr => arr.filter(m => m.id !== id));
    if (selectedId === id) setSelectedId(null);
  };

  // Stats
  const dimensionados = enriched.filter(m => m.dim && !m.dim.error).length;
  const totalIn = enriched.reduce((s, m) => s + (m.dim?.In || 0), 0);

  return (
    <div className="vl-quadros">
      <div className="vl-quadros-grid">
        {/* CANVAS */}
        <section className="panel vl-canvas-panel">
          <div className="panel-head">
            <div>
              <div className="panel-eyebrow">ÁREA DE DESENHO · QUADROS DIMENSIONADOS</div>
              <h3>Diagrama de partidas WEG</h3>
            </div>
            <button className="btn btn-primary" onClick={addMotor}>
              <QIcon name="plus" size={14}/> Adicionar motor
            </button>
          </div>

          {/* mini KPIs */}
          <div className="vl-quadros-stats">
            <div><span>MOTORES</span><b className="readout">{String(motors.length).padStart(2,"0")}</b></div>
            <div><span>DIMENSIONADOS</span><b className="readout">{String(dimensionados).padStart(2,"0")} / {String(motors.length).padStart(2,"0")}</b></div>
            <div><span>CORRENTE TOTAL</span><b className="readout">{totalIn.toFixed(1)} <em>A</em></b></div>
            <div><span>NORMA</span><b>WEG · IEC 60947</b></div>
          </div>

          {/* Canvas grid */}
          {motors.length === 0 ? (
            <div className="vl-canvas-empty">
              <div className="vl-canvas-empty-icon"><QIcon name="motor" size={40}/></div>
              <h4>Comece adicionando um motor</h4>
              <p>Clique em <b>Adicionar motor</b> acima para começar o dimensionamento de quadros.</p>
            </div>
          ) : (
            <div className="vl-canvas-grid">
              {enriched.map(m => (
                <MotorCard
                  key={m.id}
                  motor={m}
                  selected={selectedId === m.id}
                  onSelect={() => setSelectedId(m.id)}
                  onRemove={() => removeMotor(m.id)}
                />
              ))}
              <button className="vl-canvas-add" onClick={addMotor}>
                <QIcon name="plus" size={18}/>
                <span>Adicionar motor</span>
              </button>
            </div>
          )}
        </section>

        {/* CONFIG PANEL */}
        <aside className="panel vl-config-panel">
          <ConfigPanel
            motor={selected}
            onChange={(patch) => updateMotor(selected.id, patch)}
          />
        </aside>
      </div>

      {/* Reference: motor current table */}
      <section className="panel">
        <div className="panel-head">
          <div>
            <div className="panel-eyebrow">REFERÊNCIA TÉCNICA · MOTORES WEG W22 IR3 PREMIUM (60 Hz)</div>
            <h3>Tabela orientativa de corrente nominal</h3>
          </div>
          <span className="dim mono small">F.S. 1,00 · IV polos</span>
        </div>
        <div className="ref-table vl-motor-ref">
          <div className="ref-head">
            <span>POTÊNCIA</span>
            <span>CORRENTE 220V</span>
            <span>CORRENTE 380V</span>
            <span>PARTIDA DIRETA</span>
            <span>ESTRELA-Δ</span>
          </div>
          {POTENCIAS_DISPONIVEIS.map(p => {
            const I220 = MOTOR_CURRENTS["220"][p];
            const I380 = MOTOR_CURRENTS["380"][p];
            const eStarOk380 = I380 / Math.sqrt(3) >= 6.9;
            return (
              <div key={p} className="ref-row">
                <span className="mono"><b>{p} cv</b></span>
                <span className="mono">{I220.toFixed(2)} A</span>
                <span className="mono">{I380.toFixed(2)} A</span>
                <span className="pill pill-ok">disponível</span>
                <span className={"pill pill-" + (eStarOk380 ? "ok" : "warn")}>
                  {eStarOk380 ? "disponível" : "abaixo do mínimo"}
                </span>
              </div>
            );
          })}
        </div>
      </section>
    </div>
  );
};

window.VL_Quadros = QuadrosDiagramas;
