// Componentes UI compartilhados Destaca
// Carrega APÓS React; expõe ícones e blocos comuns em window.DUI

const DUI = {};

// Ícones (stroke 1.5, currentColor), desenhados como inline SVG
DUI.Icon = function ({ name, size = 16, style }) {
  const s = size;
  const common = {
    width: s,
    height: s,
    viewBox: "0 0 24 24",
    fill: "none",
    stroke: "currentColor",
    strokeWidth: 1.6,
    strokeLinecap: "round",
    strokeLinejoin: "round",
    style,
  };
  const paths = {
    plus: <path d="M12 5v14M5 12h14" />,
    chevR: <path d="M9 6l6 6-6 6" />,
    chevD: <path d="M6 9l6 6 6-6" />,
    chevU: <path d="M6 15l6-6 6 6" />,
    home: (
      <>
        <path d="M3 11l9-7 9 7" />
        <path d="M5 10v10h14V10" />
      </>
    ),
    folder: (
      <path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
    ),
    layers: (
      <>
        <path d="M12 3l9 5-9 5-9-5z" />
        <path d="M3 13l9 5 9-5" />
        <path d="M3 18l9 5 9-5" />
      </>
    ),
    search: (
      <>
        <circle cx="11" cy="11" r="7" />
        <path d="M21 21l-4.3-4.3" />
      </>
    ),
    book: <path d="M4 4h12a4 4 0 0 1 4 4v12H8a4 4 0 0 1-4-4z" />,
    chart: (
      <>
        <path d="M3 3v18h18" />
        <path d="M7 14l4-4 3 3 5-6" />
      </>
    ),
    user: (
      <>
        <circle cx="12" cy="8" r="4" />
        <path d="M4 21c1-4 4-6 8-6s7 2 8 6" />
      </>
    ),
    bell: (
      <>
        <path d="M6 8a6 6 0 1 1 12 0c0 7 3 8 3 8H3s3-1 3-8z" />
        <path d="M10 21a2 2 0 0 0 4 0" />
      </>
    ),
    set: (
      <>
        <circle cx="12" cy="12" r="3" />
        <path d="M19 12a7 7 0 0 0-.1-1.4l2-1.6-2-3.4-2.4 1a7 7 0 0 0-2.4-1.4L13.5 3h-3l-.6 2.6a7 7 0 0 0-2.4 1.4l-2.4-1-2 3.4 2 1.6A7 7 0 0 0 5 12a7 7 0 0 0 .1 1.4l-2 1.6 2 3.4 2.4-1a7 7 0 0 0 2.4 1.4l.6 2.6h3l.6-2.6a7 7 0 0 0 2.4-1.4l2.4 1 2-3.4-2-1.6c.07-.5.1-1 .1-1.4z" />
      </>
    ),
    pile: (
      <>
        <path d="M12 2v20M8 5l4-3 4 3M8 11l4-3 4 3M8 17l4-3 4 3" />
      </>
    ),
    truck: (
      <>
        <path d="M1 7h13v9H1zM14 10h4l3 3v3h-7" />
        <circle cx="6" cy="18" r="2" />
        <circle cx="17" cy="18" r="2" />
      </>
    ),
    pkg: (
      <>
        <path d="M3 7l9-4 9 4-9 4z" />
        <path d="M3 7v10l9 4 9-4V7" />
        <path d="M12 11v10" />
      </>
    ),
    money: (
      <>
        <circle cx="12" cy="12" r="9" />
        <path d="M9 14c0 1.1 1.3 2 3 2s3-.9 3-2-1.3-2-3-2-3-.9-3-2 1.3-2 3-2 3 .9 3 2" />
        <path d="M12 7v10" />
      </>
    ),
    calc: (
      <>
        <rect x="5" y="3" width="14" height="18" rx="2" />
        <path d="M8 7h8M8 11h2M12 11h2M16 11h0M8 14h2M12 14h2M16 14h0M8 17h2M12 17h2M16 17h0" />
      </>
    ),
    download: (
      <>
        <path d="M12 4v12M6 12l6 6 6-6" />
        <path d="M4 20h16" />
      </>
    ),
    share: (
      <>
        <circle cx="6" cy="12" r="2.5" />
        <circle cx="18" cy="6" r="2.5" />
        <circle cx="18" cy="18" r="2.5" />
        <path d="M8 11l8-4M8 13l8 4" />
      </>
    ),
    eye: (
      <>
        <path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z" />
        <circle cx="12" cy="12" r="3" />
      </>
    ),
    edit: (
      <>
        <path d="M12 20h9" />
        <path d="M16 4l4 4L8 20H4v-4z" />
      </>
    ),
    trash: (
      <>
        <path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M6 6l1 14a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-14" />
      </>
    ),
    dot: <circle cx="12" cy="12" r="3" fill="currentColor" />,
    clock: (
      <>
        <circle cx="12" cy="12" r="9" />
        <path d="M12 7v5l3 2" />
      </>
    ),
    pin: (
      <>
        <path d="M12 22s7-7 7-12a7 7 0 0 0-14 0c0 5 7 12 7 12z" />
        <circle cx="12" cy="10" r="2.5" />
      </>
    ),
    info: (
      <>
        <circle cx="12" cy="12" r="9" />
        <path d="M12 11v6M12 8h0" />
      </>
    ),
    check: <path d="M5 12l5 5 9-11" />,
    filter: <path d="M3 5h18l-7 8v6l-4 2v-8z" />,
    burger: <path d="M4 7h16M4 12h16M4 17h16" />,
    flag: (
      <>
        <path d="M5 21V4M5 4h13l-2 4 2 4H5" />
      </>
    ),
    sparkle: (
      <path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z" />
    ),
    spinner: (
      <>
        <circle cx="12" cy="12" r="9" opacity="0.2" />
        <path d="M21 12a9 9 0 0 0-9-9" />
      </>
    ),
    weld: (
      <>
        <path d="M3 18l4-9 4 9M14 18l4-9 4 9" />
        <path d="M5 14h4M16 14h4" />
      </>
    ),
    excel: (
      <>
        <rect x="3" y="3" width="18" height="18" rx="2" />
        <path d="M8 8l8 8M16 8l-8 8" />
      </>
    ),
  };
  return <svg {...common}>{paths[name] || null}</svg>;
};

// Mini logo (mark only, copia o triângulo da identidade)
DUI.Mark = function ({ size = 22 }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 32 32"
      style={{ flex: "none" }}
    >
      <path d="M2 2 L18 16 L2 30 Z" fill="#0E2A47" />
      <path d="M11 2 L27 16 L11 30 Z" fill="#22A94A" />
    </svg>
  );
};

DUI.Logo = function ({ small }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
      <DUI.Mark size={small ? 22 : 26} />
      <div style={{ lineHeight: 1 }}>
        <div
          style={{
            font: "800 " + (small ? "15px" : "17px") + "/1 Inter, sans-serif",
            letterSpacing: "0.01em",
            color: "#0E2A47",
          }}
        >
          DESTACA
        </div>
        {!small && (
          <div
            style={{
              font: "500 8px/1 Inter, sans-serif",
              letterSpacing: "0.18em",
              color: "#22A94A",
              marginTop: 4,
            }}
          >
            ENGENHARIA DE FUNDAÇÕES
          </div>
        )}
      </div>
    </div>
  );
};

// Status pill mapeado ao status do projeto
DUI.StatusPill = function ({ status }) {
  const map = {
    rascunho: {
      label: "Rascunho",
      bg: "#eef0f4",
      fg: "#4b5468",
      dot: "#7c8597",
    },
    "em-revisao": {
      label: "Em revisão",
      bg: "#fff8e6",
      fg: "#a46a02",
      dot: "#d97706",
    },
    enviado: { label: "Enviado", bg: "#e8effa", fg: "#1d4f97", dot: "#2363b8" },
    aprovado: {
      label: "Aprovado",
      bg: "#e6f5ea",
      fg: "#1a8a3c",
      dot: "#22A94A",
    },
    perdido: { label: "Perdido", bg: "#fbeae9", fg: "#9d2520", dot: "#c8302a" },
  };
  const s = map[status] || map["rascunho"];
  return (
    <span
      className="chip"
      style={{ background: s.bg, color: s.fg, height: 22 }}
    >
      <span
        style={{
          width: 6,
          height: 6,
          borderRadius: 100,
          background: s.dot,
          display: "inline-block",
        }}
      ></span>
      {s.label}
    </span>
  );
};

// KPI block
DUI.Kpi = function ({ label, value, sub, accent }) {
  return (
    <div
      style={{
        padding: "14px 16px",
        borderRight: "1px solid var(--d-border)",
        minWidth: 0,
      }}
    >
      <div
        style={{
          font: "600 10.5px/1 Inter",
          letterSpacing: "0.06em",
          textTransform: "uppercase",
          color: "var(--d-text-3)",
        }}
      >
        {label}
      </div>
      <div
        className="d-mono"
        style={{
          font: "700 22px/1.1 JetBrains Mono",
          marginTop: 8,
          color: accent || "var(--d-text)",
          whiteSpace: "nowrap",
        }}
      >
        {value}
      </div>
      {sub && (
        <div
          style={{
            font: "500 11.5px/1.3 Inter",
            color: "var(--d-text-3)",
            marginTop: 4,
          }}
        >
          {sub}
        </div>
      )}
    </div>
  );
};

// Sidebar nav item
DUI.NavItem = function ({ icon, label, active, badge, onClick, indent }) {
  return (
    <button
      onClick={onClick}
      className="d-nav-item"
      style={{
        display: "flex",
        alignItems: "center",
        gap: 10,
        width: "100%",
        padding: "7px 10px",
        paddingLeft: 10 + (indent || 0) * 14,
        borderRadius: 6,
        border: "none",
        cursor: "pointer",
        background: active ? "rgba(34,169,74,0.10)" : "transparent",
        color: active ? "#1a8a3c" : "#4b5468",
        font: "500 13px/1 Inter",
        textAlign: "left",
      }}
    >
      {icon && <DUI.Icon name={icon} size={16} />}
      <span
        style={{
          flex: 1,
          overflow: "hidden",
          textOverflow: "ellipsis",
          whiteSpace: "nowrap",
        }}
      >
        {label}
      </span>
      {badge != null && (
        <span
          style={{
            font: "600 10px/1 JetBrains Mono",
            color: "var(--d-text-3)",
          }}
        >
          {badge}
        </span>
      )}
    </button>
  );
};

// ============================================================
// v3, Wireframe-feel components
// ============================================================

// Banner global topo (dispensável)
DUI.Banner = function () {
  const [hidden, setHidden] = React.useState(false);
  if (hidden) return null;
  return (
    <div className="wf-banner">
      <span className="wf-banner-tag">Wireframe</span>
      <span className="wf-banner-text">
        Material de apoio para validação do fluxo. Visual e interações são
        ilustrativos; não refletem o produto final.
      </span>
      <span className="wf-banner-actions">
        <button onClick={() => setHidden(true)}>Ocultar</button>
      </span>
    </div>
  );
};

// Stamp diagonal canto inferior
DUI.Stamp = function () {
  return <div className="wf-stamp">Rascunho · Não implementado</div>;
};

// Wrapper visual: marca área como mockada/não-funcional
DUI.MockArea = function ({ label = "a definir", children, style, inline }) {
  if (inline) {
    return (
      <span
        className="wf-mock-inline"
        title="Área não implementada, visual ilustrativo"
      >
        {children}
      </span>
    );
  }
  return (
    <div
      className="wf-mock"
      data-mock-label={label}
      style={{ padding: 12, ...style }}
    >
      {children}
    </div>
  );
};

// Callout Figma-style, toggle global via context
DUI.CalloutsContext = React.createContext({ visible: true });

DUI.Callout = function ({
  num,
  anchor = "left",
  top,
  left,
  right,
  bottom,
  width = 240,
  children,
}) {
  const ctx = React.useContext(DUI.CalloutsContext);
  if (!ctx.visible) return null;
  const arrowMap = {
    left: "left",
    right: "right",
    top: "top",
    bottom: "bottom",
  };
  return (
    <div
      className="wf-callout"
      data-arrow={arrowMap[anchor]}
      style={{ top, left, right, bottom, maxWidth: width }}
    >
      {num != null && <span className="wf-callout-num">{num}</span>}
      {children}
    </div>
  );
};

// Tooltip glossário, termo sublinhado on-hover
const GLOSSARIO_TIPS = {
  BDI: "Benefício e Despesas Indiretas, % aplicado sobre custo direto (lucro + impostos + indiretos + riscos).",
  Periculosidade:
    "Adicional de 30% sobre salário base para trabalho em condição de risco (gás, alta tensão, etc.).",
  Insalubridade: "Adicional 10/20/40% para exposição a agente nocivo à saúde.",
  Baixada:
    "Repatriamento da equipe à base (Sertãozinho/SP) em ciclo de 60-90 dias.",
  Embarcada: "Obra em barcaça/pontão (offshore), logística e custos especiais.",
  Tricone:
    "Broca de perfuração de rocha (consumível ~7 unid por 100m perfurados).",
  Performance:
    "Modo de orçamento: cliente define ritmo (estacas/mês) → sistema calcula prazo.",
  Prazo:
    "Modo de orçamento: cliente define data → sistema dimensiona equipes/equipamentos.",
  Frente:
    "Unidade autossuficiente de produção: equipe + equipamentos + materiais alocados a um trecho.",
  Dissídio:
    "Reajuste anual de salário (categoria de Destaca aplica em outubro).",
};

DUI.Term = function ({ children, tip }) {
  const text = typeof children === "string" ? children : "";
  const finalTip = tip || GLOSSARIO_TIPS[text] || "";
  return (
    <span className="wf-term" data-tip={finalTip}>
      {children}
    </span>
  );
};

// Recalculando badge
DUI.Recalc = function ({ label = "Recalculando" }) {
  return <span className="wf-recalc">{label}</span>;
};

// Hook utilitário: mostra "recalculando" por X ms quando dependências mudam
DUI.useRecalc = function (deps, ms = 800) {
  const [recalcing, setRecalcing] = React.useState(false);
  const first = React.useRef(true);
  React.useEffect(() => {
    if (first.current) {
      first.current = false;
      return;
    }
    setRecalcing(true);
    const t = setTimeout(() => setRecalcing(false), ms);
    return () => clearTimeout(t);
  }, deps);
  return recalcing;
};

window.DUI = DUI;
