/* global React */
// Primitive UI components for the TopMix ERP kit.
// All visual styles live in styles.css — these are tiny wrappers.

const { useState, useEffect, useRef } = React;

// ---------- Icon ---------- //
// React owns ONLY the wrapper <span>. lucide.createIcons() swaps the inner
// <i data-lucide> for an <svg>, but that mutation stays inside the span —
// React never reconciles the span's children, so unmounting is conflict-free.
// (Letting lucide replace a React-rendered <i> directly causes a fatal
// "removeChild: node is not a child" crash when React later unmounts it.)
function Icon({ name, size = 16, className = "", style = {} }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el || !window.lucide) return;
    el.textContent = "";
    const i = document.createElement("i");
    i.setAttribute("data-lucide", name);
    el.appendChild(i);
    try { window.lucide.createIcons({ nameAttr: "data-lucide" }); } catch (e) {}
  }, [name, size]);
  return (
    <span ref={ref} className={`lucide ${className}`}
       style={{ display: "inline-flex", alignItems: "center", justifyContent: "center",
                width: size, height: size, flexShrink: 0, ...style }} />
  );
}

// ---------- Button ---------- //
function Button({ variant = "secondary", size = "md", icon, children, onClick, disabled, style }) {
  return (
    <button
      className={`btn ${variant} ${size === "sm" ? "sm" : size === "lg" ? "lg" : ""}`}
      onClick={onClick}
      disabled={disabled}
      style={style}
    >
      {icon && <Icon name={icon} size={14} />}
      {children}
    </button>
  );
}

// ---------- Badge ---------- //
function Badge({ tone = "neutral", children }) {
  return (
    <span className={`badge ${tone}`}>
      <span className="dot"></span>
      {children}
    </span>
  );
}

// ---------- Chip ---------- //
function Chip({ active, onClick, children, removable }) {
  return (
    <span className={`chip ${active ? "active" : ""}`} onClick={onClick}>
      {children}
      {removable && <span className="x">×</span>}
    </span>
  );
}

// ---------- Card ---------- //
function Card({ title, action, children, padded = false, style }) {
  return (
    <div className="card" style={style}>
      {title && (
        <div className="card-head">
          <h3>{title}</h3>
          {action}
        </div>
      )}
      <div className={padded ? "card-pad" : ""}>{children}</div>
    </div>
  );
}

// ---------- Avatar ---------- //
function Avatar({ name, size = "sm" }) {
  const initial = (name || "?").trim()[0]?.toUpperCase();
  return <div className={`avatar ${size}`}>{initial}</div>;
}

// ---------- KPI ---------- //
function KPI({ label, value, cents, delta, deltaTone = "up", deltaLabel, sparkColor = "#C9A36B", points }) {
  return (
    <div className="kpi">
      <div className="lbl">{label}</div>
      <div className="val">
        {value}
        {cents !== undefined && <span className="cents">,{cents}</span>}
      </div>
      <div className="delta">
        <span className={deltaTone}>{delta}</span>
        {deltaLabel && <span>{deltaLabel}</span>}
      </div>
      {points && (
        <svg className="spark" viewBox="0 0 200 30" preserveAspectRatio="none">
          <polyline points={points} fill="none" stroke={sparkColor} strokeWidth="1.5" />
        </svg>
      )}
    </div>
  );
}

// ---------- Money formatter ---------- //
function brl(n) {
  return n.toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

// ---------- Empty state ---------- //
function EmptyState({ icon = "inbox", title, msg, action }) {
  return (
    <div className="empty">
      <div className="ico"><Icon name={icon} size={20} /></div>
      <div style={{ color: "var(--tm-fg-1)", fontWeight: 500 }}>{title}</div>
      {msg && <div className="msg">{msg}</div>}
      {action}
    </div>
  );
}

// ---------- Drawer ---------- //
// Right-side panel for record details, edit, and create flows.
// Header (title + close) — scrollable body — sticky footer (actions).
function Drawer({ open, onClose, title, subtitle, eyebrow, children, footer, width = 520 }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
    document.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prev;
    };
  }, [open, onClose]);

  if (!open) return null;
  return (
    <div className="drawer-root" onClick={onClose}>
      <div
        className="drawer"
        style={{ width }}
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
      >
        <div className="drawer-head">
          <div style={{ flex: 1, minWidth: 0 }}>
            {eyebrow && <div className="drawer-eyebrow">{eyebrow}</div>}
            <div className="drawer-title">{title}</div>
            {subtitle && <div className="drawer-sub">{subtitle}</div>}
          </div>
          <button className="drawer-close" onClick={onClose} aria-label="Fechar">
            <Icon name="x" size={18} />
          </button>
        </div>
        <div className="drawer-body">{children}</div>
        {footer && <div className="drawer-foot">{footer}</div>}
      </div>
    </div>
  );
}

// ---------- Field ---------- //
// Labelled input row used inside drawers / forms.
function Field({ label, value, onChange, type = "text", placeholder, hint, suffix, children }) {
  return (
    <label className="field">
      <span>{label}</span>
      {children ? children : (
        <div style={{ position: "relative" }}>
          <input
            className="input"
            type={type}
            value={value ?? ""}
            placeholder={placeholder}
            onChange={(e) => onChange && onChange(e.target.value)}
          />
          {suffix && <span className="field-suffix">{suffix}</span>}
        </div>
      )}
      {hint && <span className="field-hint">{hint}</span>}
    </label>
  );
}

Object.assign(window, { Icon, Button, Badge, Chip, Card, Avatar, KPI, EmptyState, Drawer, Field, brl });
