// Shared UI primitives — Metal Padrão

const fmtBRL = (n) =>
  (n || 0).toLocaleString("pt-BR", { style: "currency", currency: "BRL" });

const fmtNumber = (n, d = 0) =>
  (n || 0).toLocaleString("pt-BR", { minimumFractionDigits: d, maximumFractionDigits: d });

const fmtDate = (iso) => {
  if (!iso) return "—";
  const [y, m, d] = iso.split("-");
  return `${d}/${m}/${y}`;
};

const fmtDateShort = (iso) => {
  if (!iso) return "—";
  const [, m, d] = iso.split("-");
  const meses = ["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"];
  return `${d} ${meses[parseInt(m,10)-1]}`;
};

// Button
const Button = ({ children, variant = "primary", size = "md", icon, onClick, type = "button", disabled, full, ...rest }) => {
  const cls = ["btn", `btn--${variant}`, `btn--${size}`, full && "btn--full", disabled && "btn--disabled"].filter(Boolean).join(" ");
  return (
    <button type={type} className={cls} onClick={onClick} disabled={disabled} {...rest}>
      {icon && <Icon name={icon} size={size === "sm" ? 14 : 16} />}
      <span>{children}</span>
    </button>
  );
};

// Field wrapper
const Field = ({ label, required, hint, error, children, span = 12 }) => (
  <label className={`field field--span-${span}`}>
    <div className="field__label">
      <span>{label}{required && <em>*</em>}</span>
      {hint && <span className="field__hint">{hint}</span>}
    </div>
    {children}
    {error && <div className="field__error">{error}</div>}
  </label>
);

// Input
const Input = React.forwardRef(({ prefix, suffix, ...rest }, ref) => (
  <div className={`input ${prefix ? "input--prefix" : ""} ${suffix ? "input--suffix" : ""}`}>
    {prefix && <span className="input__prefix">{prefix}</span>}
    <input ref={ref} {...rest} />
    {suffix && <span className="input__suffix">{suffix}</span>}
  </div>
));

// Select
const Select = ({ options, value, onChange, placeholder, ...rest }) => (
  <div className="input input--select">
    <select value={value ?? ""} onChange={e => onChange?.(e.target.value)} {...rest}>
      {placeholder && <option value="" disabled>{placeholder}</option>}
      {options.map(o => (
        <option key={o.value} value={o.value}>{o.label}</option>
      ))}
    </select>
    <Icon name="chevDown" size={14} />
  </div>
);

// Currency input
const InputMoney = ({ value, onChange, ...rest }) => {
  const handle = (e) => {
    const raw = e.target.value.replace(/[^\d]/g, "");
    onChange?.(raw ? parseInt(raw, 10) / 100 : 0);
  };
  return (
    <div className="input input--prefix">
      <span className="input__prefix">R$</span>
      <input
        inputMode="numeric"
        value={value ? value.toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : ""}
        onChange={handle}
        placeholder="0,00"
        {...rest}
      />
    </div>
  );
};

// Badge / status
const Badge = ({ children, color, bg, dot, size = "md" }) => (
  <span className={`badge badge--${size}`} style={{ "--badge-bg": bg, "--badge-fg": color }}>
    {dot && <span className="badge__dot" style={{ background: color }} />}
    {children}
  </span>
);

const StatusBadge = ({ statusId }) => {
  const s = window.MP_DATA.statusList.find(x => x.id === statusId);
  if (!s) return null;
  return <Badge color={s.cor} bg={s.bg} dot>{s.nome}</Badge>;
};

const CnpjPill = ({ cnpjId }) => {
  const c = window.MP_DATA.cnpjs.find(x => x.id === cnpjId);
  if (!c) return null;
  return <span className="cnpj-pill" data-cnpj={cnpjId}>{c.nome}</span>;
};

// Avatar (vendedor)
const Avatar = ({ vendedorId, size = 28 }) => {
  const v = window.MP_DATA.vendedores.find(x => x.id === vendedorId);
  if (!v) return null;
  return (
    <span className="avatar" style={{ width: size, height: size, background: v.cor, fontSize: size * 0.36 }}>
      {v.iniciais}
    </span>
  );
};

// Card
const Card = ({ children, title, action, padded = true, className = "" }) => (
  <div className={`card ${className}`}>
    {(title || action) && (
      <div className="card__head">
        <div className="card__title">{title}</div>
        {action}
      </div>
    )}
    <div className={padded ? "card__body" : ""}>{children}</div>
  </div>
);

// KPI tile
const KPI = ({ label, value, sub, accent, icon }) => (
  <div className="kpi" style={accent ? { "--kpi-accent": accent } : undefined}>
    <div className="kpi__head">
      {icon && <Icon name={icon} size={14} />}
      <span>{label}</span>
    </div>
    <div className="kpi__value">{value}</div>
    {sub && <div className="kpi__sub">{sub}</div>}
  </div>
);

// Empty state
const Empty = ({ icon = "sparkle", title, hint, action }) => (
  <div className="empty">
    <div className="empty__icon"><Icon name={icon} size={28} /></div>
    <div className="empty__title">{title}</div>
    {hint && <div className="empty__hint">{hint}</div>}
    {action && <div style={{ marginTop: 16 }}>{action}</div>}
  </div>
);

// Modal
const Modal = ({ open, onClose, title, children, footer, size = "md" }) => {
  if (!open) return null;
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className={`modal modal--${size}`} onClick={e => e.stopPropagation()}>
        <div className="modal__head">
          <h3>{title}</h3>
          <button className="icon-btn" onClick={onClose} aria-label="Fechar"><Icon name="x" size={16} /></button>
        </div>
        <div className="modal__body">{children}</div>
        {footer && <div className="modal__foot">{footer}</div>}
      </div>
    </div>
  );
};

// Drawer (slide from right)
const Drawer = ({ open, onClose, title, subtitle, children, footer }) => {
  if (!open) return null;
  return (
    <div className="drawer-overlay" onClick={onClose}>
      <div className="drawer" onClick={e => e.stopPropagation()}>
        <div className="drawer__head">
          <div>
            <div className="drawer__title">{title}</div>
            {subtitle && <div className="drawer__sub">{subtitle}</div>}
          </div>
          <button className="icon-btn" 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>
  );
};

Object.assign(window, {
  Button, Field, Input, InputMoney, Select,
  Badge, StatusBadge, CnpjPill, Avatar,
  Card, KPI, Empty, Modal, Drawer,
  fmtBRL, fmtNumber, fmtDate, fmtDateShort,
});
