// UIComponents.jsx — Shared UI primitives
'use strict';
const { useState, useEffect, useRef } = React;

// ── Toast ──────────────────────────────────────────────────────────────────
function Toast({ toast, onRemove }) {
  useEffect(() => { const t = setTimeout(() => onRemove(toast.id), 3800); return () => clearTimeout(t); }, []);
  const cfg = {
    success: { bg:'#ECFDF5', border:'#10B981', icon:'CheckCircle', text:'#065F46' },
    error:   { bg:'#FEF2F2', border:'#EF4444', icon:'XCircle',     text:'#991B1B' },
    info:    { bg:'#EFF6FF', border:'#3B82F6', icon:'Info',         text:'#1E40AF' },
    warning: { bg:'#FFFBEB', border:'#F59E0B', icon:'AlertCircle',  text:'#92400E' },
  }[toast.type || 'success'];
  return (
    <div className="anim-toast flex items-start gap-3 rounded-xl shadow-card-lg px-4 py-3 min-w-72 max-w-sm"
      style={{ background: cfg.bg, borderLeft: `4px solid ${cfg.border}` }}>
      <Icon name={cfg.icon} size={18} color={cfg.border} style={{ marginTop: 1, flexShrink: 0 }} />
      <div className="flex-1 min-w-0">
        {toast.title && <p className="font-semibold text-sm" style={{ color: cfg.text }}>{toast.title}</p>}
        <p className="text-sm" style={{ color: cfg.text, opacity: toast.title ? 0.85 : 1 }}>{toast.msg}</p>
      </div>
      <button onClick={() => onRemove(toast.id)} className="ml-1 opacity-50 hover:opacity-100 transition-opacity mt-0.5">
        <Icon name="X" size={14} color={cfg.text} />
      </button>
    </div>
  );
}

function ToastContainer({ toasts, removeToast }) {
  return (
    <div className="fixed bottom-6 right-6 flex flex-col gap-2 z-[9999] no-print">
      {toasts.map(t => <Toast key={t.id} toast={t} onRemove={removeToast} />)}
    </div>
  );
}

// ── Modal ──────────────────────────────────────────────────────────────────
// Renderizado via portal no document.body para escapar de ancestrais com `transform`
// (que criam novo containing block e quebram `position: fixed`).
function Modal({ open, onClose, title, children, width = 'max-w-2xl', noPad = false }) {
  useEffect(() => {
    if (open) document.body.style.overflow = 'hidden';
    else document.body.style.overflow = '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);
  if (!open) return null;
  return ReactDOM.createPortal(
    <div className="fixed inset-0 z-[1000] flex items-center justify-center p-4 no-print"
      style={{ background: 'rgba(10,31,68,0.45)', backdropFilter: 'blur(3px)' }}
      onClick={e => e.target === e.currentTarget && onClose()}>
      <div className={`bg-white rounded-2xl shadow-card-lg w-full ${width} anim-modal flex flex-col`}
        style={{ maxHeight: '90vh' }}>
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100">
          <h2 className="text-lg font-semibold" style={{ color: '#0A1F44' }}>{title}</h2>
          <button onClick={onClose} className="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-slate-100 transition-colors">
            <Icon name="X" size={18} color="#64748b" />
          </button>
        </div>
        <div className={`overflow-y-auto flex-1 ${noPad ? '' : 'p-6'}`}>{children}</div>
      </div>
    </div>,
    document.body
  );
}

// ── ConfirmDialog ──────────────────────────────────────────────────────────
function ConfirmDialog({ open, onClose, onConfirm, title = 'Confirmar exclusão', message, confirmLabel = 'Excluir', danger = true }) {
  if (!open) return null;
  return ReactDOM.createPortal(
    <div className="fixed inset-0 z-[1100] flex items-center justify-center p-4"
      style={{ background: 'rgba(10,31,68,0.5)', backdropFilter: 'blur(3px)' }}>
      <div className="bg-white rounded-2xl shadow-card-lg p-6 w-full max-w-sm anim-modal">
        <div className={`w-12 h-12 rounded-full flex items-center justify-center mb-4 ${danger ? 'bg-red-100' : 'bg-amber-100'}`}>
          <Icon name="AlertCircle" size={24} color={danger ? '#EF4444' : '#F59E0B'} />
        </div>
        <h3 className="text-lg font-semibold mb-2" style={{ color: '#0A1F44' }}>{title}</h3>
        <p className="text-slate-500 text-sm mb-6">{message}</p>
        <div className="flex gap-3">
          <button onClick={onClose} className="flex-1 px-4 py-2.5 rounded-xl border border-slate-200 text-slate-600 font-medium hover:bg-slate-50 transition-colors text-sm">Cancelar</button>
          <button onClick={() => { onConfirm(); onClose(); }} className={`flex-1 px-4 py-2.5 rounded-xl font-medium text-white text-sm transition-colors ${danger ? 'bg-red-500 hover:bg-red-600' : 'bg-amber-500 hover:bg-amber-600'}`}>{confirmLabel}</button>
        </div>
      </div>
    </div>,
    document.body
  );
}

// ── StatusBadge ────────────────────────────────────────────────────────────
const STATUS_CFG = {
  'Aberta':         { bg:'#DBEAFE', color:'#1D4ED8', dot:'#3B82F6' },
  'Em andamento':   { bg:'#FEF3C7', color:'#B45309', dot:'#F59E0B' },
  'Aguardando peça':{ bg:'#FCE7F3', color:'#9D174D', dot:'#EC4899' },
  'Concluída':      { bg:'#D1FAE5', color:'#065F46', dot:'#10B981' },
  'Entregue':       { bg:'#E0E7FF', color:'#3730A3', dot:'#6366F1' },
  'pago':           { bg:'#D1FAE5', color:'#065F46', dot:'#10B981' },
  'pendente':       { bg:'#FEF3C7', color:'#B45309', dot:'#F59E0B' },
  'entrada':        { bg:'#D1FAE5', color:'#065F46', dot:'#10B981' },
  'saída':          { bg:'#FEE2E2', color:'#991B1B', dot:'#EF4444' },
  'Ativo':          { bg:'#D1FAE5', color:'#065F46', dot:'#10B981' },
  'Inativo':        { bg:'#F1F5F9', color:'#64748B', dot:'#94A3B8' },
};

function StatusBadge({ status, size = 'sm' }) {
  const cfg = STATUS_CFG[status] || { bg:'#F1F5F9', color:'#64748B', dot:'#94A3B8' };
  const px = size === 'xs' ? 'px-2 py-0.5 text-xs' : 'px-2.5 py-1 text-xs';
  return (
    <span className={`inline-flex items-center gap-1.5 rounded-full font-semibold ${px}`}
      style={{ background: cfg.bg, color: cfg.color }}>
      <span className="w-1.5 h-1.5 rounded-full" style={{ background: cfg.dot, flexShrink: 0 }} />
      {status}
    </span>
  );
}

// ── EmptyState ─────────────────────────────────────────────────────────────
function EmptyState({ icon = 'FileText', title, message, actionLabel, onAction }) {
  return (
    <div className="flex flex-col items-center justify-center py-16 px-8 text-center">
      <div className="w-16 h-16 rounded-2xl flex items-center justify-center mb-4" style={{ background: '#F1F5F9' }}>
        <Icon name={icon} size={28} color="#94A3B8" />
      </div>
      <h3 className="text-base font-semibold mb-1" style={{ color: '#1E293B' }}>{title}</h3>
      <p className="text-sm text-slate-400 max-w-xs mb-5" style={{ textWrap: 'pretty' }}>{message}</p>
      {actionLabel && onAction && (
        <button onClick={onAction} className="inline-flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold text-white transition-colors hover:opacity-90" style={{ background: '#FF6B35' }}>
          <Icon name="Plus" size={16} color="white" />
          {actionLabel}
        </button>
      )}
    </div>
  );
}

// ── Skeleton ───────────────────────────────────────────────────────────────
function Skeleton({ className = '', style = {} }) {
  return <div className={`anim-pulse rounded-lg bg-slate-200 ${className}`} style={style} />;
}

function SkeletonRow() {
  return (
    <div className="flex items-center gap-4 px-6 py-4 border-b border-slate-50">
      <Skeleton className="w-20 h-4" /><Skeleton className="w-32 h-4" />
      <Skeleton className="w-24 h-4" /><Skeleton className="w-16 h-6 rounded-full" />
      <Skeleton className="w-16 h-4" /><Skeleton className="w-20 h-4" />
    </div>
  );
}

// ── Form Controls ──────────────────────────────────────────────────────────
function FormField({ label, required, error, children, className = '' }) {
  return (
    <div className={className}>
      {label && <label className="block text-sm font-medium mb-1.5" style={{ color: '#374151' }}>
        {label}{required && <span className="text-red-500 ml-0.5">*</span>}
      </label>}
      {children}
      {error && <p className="mt-1 text-xs text-red-500">{error}</p>}
    </div>
  );
}

function Input({ className = '', error, ...props }) {
  return (
    <input {...props}
      className={`w-full px-3.5 py-2.5 rounded-xl border text-sm transition-colors ${error ? 'border-red-400 bg-red-50' : 'border-slate-200 bg-white hover:border-slate-300 focus:border-blue-400 focus:ring-2 focus:ring-blue-100'} ${className}`}
      style={{ color: '#1E293B', ...props.style }} />
  );
}

function Select({ className = '', children, ...props }) {
  return (
    <select {...props}
      className={`w-full px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-sm transition-colors hover:border-slate-300 focus:border-blue-400 focus:ring-2 focus:ring-blue-100 ${className}`}
      style={{ color: '#1E293B', ...props.style }}>
      {children}
    </select>
  );
}

function Textarea({ className = '', ...props }) {
  return (
    <textarea {...props}
      className={`w-full px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-sm transition-colors hover:border-slate-300 focus:border-blue-400 focus:ring-2 focus:ring-blue-100 resize-none ${className}`}
      style={{ color: '#1E293B', ...props.style }} />
  );
}

function Btn({ variant = 'primary', size = 'md', icon, children, className = '', ...props }) {
  const base = 'inline-flex items-center justify-center gap-2 font-semibold rounded-xl transition-all duration-150 disabled:opacity-50 disabled:cursor-not-allowed';
  const sz = { sm: 'px-3 py-1.5 text-xs', md: 'px-4 py-2.5 text-sm', lg: 'px-6 py-3 text-sm' }[size];
  const v = {
    primary:  'text-white hover:opacity-90 active:scale-95',
    ghost:    'text-slate-600 hover:bg-slate-100 active:bg-slate-200',
    outline:  'border border-slate-200 text-slate-600 hover:bg-slate-50',
    danger:   'text-white bg-red-500 hover:bg-red-600 active:scale-95',
  }[variant];
  const bg = variant === 'primary' ? { background: '#FF6B35' } : {};
  return (
    <button className={`${base} ${sz} ${v} ${className}`} style={bg} {...props}>
      {icon && <Icon name={icon} size={size === 'sm' ? 13 : 15} color="currentColor" />}
      {children}
    </button>
  );
}

// ── PageHeader ─────────────────────────────────────────────────────────────
function PageHeader({ title, subtitle, action }) {
  return (
    <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight" style={{ color: '#0A1F44' }}>{title}</h1>
        {subtitle && <p className="text-sm text-slate-400 mt-0.5">{subtitle}</p>}
      </div>
      {action}
    </div>
  );
}

// ── Card ───────────────────────────────────────────────────────────────────
function Card({ children, className = '', style = {}, onClick }) {
  return (
    <div onClick={onClick}
      className={`bg-white rounded-2xl shadow-card border border-slate-100 ${onClick ? 'cursor-pointer hover:shadow-card-md transition-shadow' : ''} ${className}`}
      style={style}>
      {children}
    </div>
  );
}

// ── Table ──────────────────────────────────────────────────────────────────
function Table({ columns, children, loading }) {
  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm">
        <thead>
          <tr className="border-b border-slate-100">
            {columns.map((c, i) => (
              <th key={i} className={`px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400 whitespace-nowrap ${c.className || ''}`}>{c.label}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {loading ? Array.from({ length: 5 }).map((_, i) => <SkeletonRow key={i} />) : children}
        </tbody>
      </table>
    </div>
  );
}

function TR({ children, className = '' }) {
  return <tr className={`border-b border-slate-50 hover:bg-slate-50 transition-colors group ${className}`}>{children}</tr>;
}

function TD({ children, className = '' }) {
  return <td className={`px-4 py-3.5 text-slate-700 ${className}`}>{children}</td>;
}

// ── SearchInput ────────────────────────────────────────────────────────────
function SearchInput({ value, onChange, placeholder = 'Pesquisar...', className = '' }) {
  return (
    <div className={`relative ${className}`}>
      <Icon name="Search" size={15} color="#94A3B8" style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)' }} />
      <input value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
        className="w-full pl-9 pr-4 py-2 rounded-xl border border-slate-200 bg-white text-sm focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-colors"
        style={{ color: '#1E293B' }} />
    </div>
  );
}

// ── Tab ───────────────────────────────────────────────────────────────────
function Tabs({ tabs, active, onChange }) {
  return (
    <div className="flex gap-1 p-1 rounded-xl bg-slate-100 w-fit">
      {tabs.map(t => (
        <button key={t.id} onClick={() => onChange(t.id)}
          className={`px-4 py-1.5 rounded-lg text-sm font-semibold transition-all ${active === t.id ? 'bg-white shadow-card text-slate-800' : 'text-slate-500 hover:text-slate-700'}`}>
          {t.label}
        </button>
      ))}
    </div>
  );
}

// ── Helpers ────────────────────────────────────────────────────────────────
function fmtCurrency(v) { return new Intl.NumberFormat('pt-BR', { style:'currency', currency:'BRL' }).format(v); }
function fmtDate(s) {
  if (!s) return '—';
  const [y, m, d] = s.split('-');
  return `${d}/${m}/${y}`;
}
function fmtPhone(p) { return p; }
function uid() { return Math.random().toString(36).slice(2, 9); }
function nextId(items, prefix) {
  const nums = items.map(x => parseInt(x.id.replace(/\D/g, ''), 10) || 0);
  return prefix + String(Math.max(0, ...nums) + 1).padStart(4, '0');
}

Object.assign(window, {
  Toast, ToastContainer, Modal, ConfirmDialog,
  StatusBadge, EmptyState, Skeleton, SkeletonRow,
  FormField, Input, Select, Textarea, Btn,
  PageHeader, Card, Table, TR, TD, SearchInput, Tabs,
  fmtCurrency, fmtDate, fmtPhone, uid, nextId, STATUS_CFG,
});
