// UI primitives — LIGHT enterprise theme.

const { useState, useEffect, useRef, useMemo, useCallback, createContext, useContext } = React;

// ---------- Toast ----------
const ToastCtx = createContext(null);
function ToastProvider({ children }) {
  const [toasts, setToasts] = useState([]);
  const push = useCallback((t) => {
    const id = Math.random().toString(36).slice(2, 9);
    setToasts((cur) => [...cur, { id, ...t }]);
    setTimeout(() => setToasts((cur) => cur.filter((x) => x.id !== id)), t.duration || 3800);
  }, []);
  return (
    <ToastCtx.Provider value={{ push }}>
      {children}
      <div className="fixed bottom-6 right-6 z-[120] flex flex-col gap-2 w-[380px] pointer-events-none">
        {toasts.map((t) => (
          <div
            key={t.id}
            className="pointer-events-auto bg-white border border-line rounded-xl px-4 py-3 shadow-pop animate-slide-in-right flex gap-3"
          >
            <div className={`mt-0.5 h-7 w-7 rounded-md flex items-center justify-center shrink-0 ${
              t.tone === 'success' ? 'bg-emerald-50 text-emerald-700' :
              t.tone === 'amber'   ? 'bg-ai-50 text-ai-700' :
              t.tone === 'brand'   ? 'bg-brand-50 text-brand-600' :
                                     'bg-ink-50 text-ink-700'
            }`}>
              <Icon.CheckCircle size={16} />
            </div>
            <div className="text-sm flex-1">
              <div className="font-medium text-ink-900">{t.title}</div>
              {t.body && <div className="text-ink-500 text-xs mt-0.5">{t.body}</div>}
            </div>
          </div>
        ))}
      </div>
    </ToastCtx.Provider>
  );
}
const useToast = () => useContext(ToastCtx);

// ---------- Button ----------
function Button({
  children, variant = 'default', size = 'md', icon, iconRight,
  className = '', onClick, disabled, type = 'button',
}) {
  const sizes = {
    sm: 'h-7 px-2.5 text-xs gap-1.5 rounded-md',
    md: 'h-9 px-3.5 text-sm gap-2 rounded-lg',
    lg: 'h-11 px-5 text-sm gap-2 rounded-lg',
  };
  const variants = {
    default:  'bg-white text-ink-800 border border-line hover:bg-ink-50 hover:border-ink-200',
    primary:  'gradient-bg text-white border border-brand-700/30 hover:opacity-95 shadow-sm',
    soft:     'bg-brand-50 text-brand-600 border border-brand-100 hover:bg-brand-100',
    amber:    'bg-ai-50 text-ai-700 border border-ai-100 hover:bg-ai-100',
    ghost:    'text-ink-700 hover:bg-ink-50 border border-transparent',
    success:  'bg-emerald-50 text-emerald-700 border border-emerald-100 hover:bg-emerald-100',
    danger:   'bg-rose-50 text-rose-700 border border-rose-100 hover:bg-rose-100',
    whatsapp: 'bg-emerald-600 text-white hover:bg-emerald-700 border border-emerald-700/40',
    call:     'bg-brand-500 text-white border border-brand-600/40 hover:bg-brand-600',
  };
  return (
    <button
      type={type}
      onClick={onClick}
      disabled={disabled}
      className={`inline-flex items-center justify-center font-medium hover-lift focus-ring disabled:opacity-50 disabled:cursor-not-allowed ${sizes[size]} ${variants[variant]} ${className}`}
    >
      {icon && <span className="shrink-0">{icon}</span>}
      {children}
      {iconRight && <span className="shrink-0">{iconRight}</span>}
    </button>
  );
}

// ---------- IconButton ----------
function IconButton({ icon, onClick, title, variant = 'default', size = 'md', className = '' }) {
  const sizes = { sm: 'h-7 w-7', md: 'h-9 w-9', lg: 'h-10 w-10' };
  const variants = {
    default: 'bg-white border border-line text-ink-700 hover:bg-ink-50 hover:text-ink-900',
    ghost:   'text-ink-500 hover:bg-ink-50 hover:text-ink-900 border border-transparent',
    primary: 'gradient-bg text-white border border-brand-700/30 shadow-sm',
    soft:    'bg-brand-50 text-brand-600 border border-brand-100 hover:bg-brand-100',
  };
  return (
    <button
      onClick={onClick}
      title={title}
      className={`inline-flex items-center justify-center rounded-lg hover-lift focus-ring ${sizes[size]} ${variants[variant]} ${className}`}
    >
      {icon}
    </button>
  );
}

// ---------- Pill ----------
function Pill({ children, tone = 'slate', icon, size = 'md', className = '' }) {
  const tones = {
    slate:   'bg-ink-50 text-ink-700 border-line',
    brand:   'bg-brand-50 text-brand-600 border-brand-100',
    amber:   'bg-ai-50 text-ai-700 border-ai-100',
    emerald: 'bg-emerald-50 text-emerald-700 border-emerald-100',
    sky:     'bg-sky-50 text-sky-700 border-sky-100',
    rose:    'bg-rose-50 text-rose-700 border-rose-100',
    fuchsia: 'bg-fuchsia-50 text-fuchsia-700 border-fuchsia-100',
    white:   'bg-white text-ink-700 border-line',
  };
  const sizes = {
    sm: 'h-5 text-[10px] px-1.5 gap-1',
    md: 'h-6 text-xs px-2 gap-1.5',
    lg: 'h-7 text-[13px] px-2.5 gap-1.5',
  };
  return (
    <span className={`inline-flex items-center font-medium rounded-full border ${tones[tone]} ${sizes[size]} ${className}`}>
      {icon && <span className="shrink-0">{icon}</span>}
      {children}
    </span>
  );
}

function StageBadge({ stage }) {
  const map = {
    'Applied':     { tone: 'slate',   icon: <Icon.Inbox size={11} /> },
    'AI Screened': { tone: 'brand',   icon: <Icon.Bot size={11} /> },
    'Shortlisted': { tone: 'amber',   icon: <Icon.Star size={11} /> },
    'Interview':   { tone: 'sky',     icon: <Icon.CalendarClock size={11} /> },
    'Submitted':   { tone: 'fuchsia', icon: <Icon.Send size={11} /> },
    'Hired':       { tone: 'emerald', icon: <Icon.CheckCircle size={11} /> },
  };
  const cfg = map[stage] || { tone: 'slate', icon: null };
  return <Pill tone={cfg.tone} icon={cfg.icon} size="sm">{stage}</Pill>;
}

function RecoBadge({ value }) {
  if (value === 'Advance') return <Pill tone="emerald" icon={<Icon.ThumbsUp size={11} />}>Advance</Pill>;
  if (value === 'Hold')    return <Pill tone="amber"   icon={<Icon.Hand size={11} />}>Hold</Pill>;
  if (value === 'Reject')  return <Pill tone="rose"    icon={<Icon.ThumbsDown size={11} />}>Reject</Pill>;
  return <Pill tone="slate">—</Pill>;
}

function PriorityBadge({ value }) {
  if (value === 'High')   return <Pill tone="rose" icon={<Icon.Flame size={11} />} size="sm">Alta</Pill>;
  if (value === 'Medium') return <Pill tone="amber" size="sm">Media</Pill>;
  return <Pill tone="slate" size="sm">Baja</Pill>;
}

// ---------- Avatar ----------
function Avatar({ name, initials, color = 'from-indigo-500 to-violet-400', size = 36, online, ring }) {
  const ini = initials || (name ? name.split(' ').filter(Boolean).slice(0, 2).map((s) => s[0]).join('') : '?');
  return (
    <div className="relative shrink-0" style={{ width: size, height: size }}>
      <div
        className={`w-full h-full rounded-full bg-gradient-to-br ${color} flex items-center justify-center text-white font-semibold ${ring ? 'ring-2 ring-brand-100 ring-offset-2 ring-offset-white' : ''}`}
        style={{ fontSize: size * 0.36 }}
      >
        {ini}
      </div>
      {online && (
        <span className="absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full bg-emerald-500 ring-2 ring-white" />
      )}
    </div>
  );
}

// ---------- Card ----------
function Card({ children, className = '', interactive, onClick }) {
  return (
    <div
      onClick={onClick}
      className={`bg-white border border-line rounded-xl shadow-card ${interactive ? 'hover-lift hover:border-ink-200 cursor-pointer' : ''} ${className}`}
    >
      {children}
    </div>
  );
}

// ---------- KPI ----------
function KpiCard({ label, value, sub, icon, trend, accent }) {
  return (
    <Card className="p-5 relative overflow-hidden">
      {accent && (
        <div className="absolute -top-12 -right-12 h-32 w-32 rounded-full opacity-[0.12] blur-2xl pointer-events-none"
             style={{ background: accent }} />
      )}
      <div className="flex items-center justify-between mb-3 relative">
        <div className="text-[11px] uppercase tracking-[0.16em] text-ink-500 font-medium">{label}</div>
        <div className="h-8 w-8 rounded-lg bg-ink-50 border border-line2 flex items-center justify-center text-ink-600">
          {icon}
        </div>
      </div>
      <div className="flex items-baseline gap-2 relative">
        <div className="text-[28px] font-semibold tabular tracking-tight text-ink-900 leading-none">{value}</div>
        {trend && (
          <span className={`text-xs flex items-center gap-0.5 ${trend.dir === 'up' ? 'text-emerald-600' : trend.dir === 'down' ? 'text-rose-600' : 'text-ink-500'}`}>
            {trend.dir === 'up' ? <Icon.ArrowUp size={12} /> : trend.dir === 'down' ? <Icon.ArrowDown size={12} /> : null}
            {trend.value}
          </span>
        )}
      </div>
      {sub && <div className="text-xs text-ink-500 mt-1.5 relative">{sub}</div>}
    </Card>
  );
}

// ---------- Sparkline ----------
function Sparkline({ data, color = '#4f46e5', height = 28, width = 120 }) {
  const max = Math.max(...data), min = Math.min(...data);
  const span = Math.max(1, max - min);
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * width;
    const y = height - ((v - min) / span) * (height - 4) - 2;
    return `${x},${y}`;
  }).join(' ');
  const area = `M0,${height} L${pts.split(' ').join(' L')} L${width},${height} Z`;
  const gid = `sg-${color.replace('#', '')}`;
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} className="overflow-visible">
      <defs>
        <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor={color} stopOpacity="0.22" />
          <stop offset="1" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill={`url(#${gid})`} />
      <polyline fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" points={pts} />
    </svg>
  );
}

// ---------- Match bar ----------
function MatchBar({ value, size = 'md', showLabel = true }) {
  const color = value >= 90 ? '#4f46e5' : value >= 80 ? '#7c3aed' : value >= 70 ? '#a855f7' : value >= 60 ? '#d97706' : '#ef4444';
  const heights = { sm: 4, md: 6, lg: 8 };
  return (
    <div className="flex items-center gap-2 w-full">
      <div className="flex-1 bg-ink-100 rounded-full overflow-hidden" style={{ height: heights[size] }}>
        <div
          className="h-full rounded-full transition-all"
          style={{
            width: `${value}%`,
            background: `linear-gradient(90deg, ${color}, ${color}cc)`,
          }}
        />
      </div>
      {showLabel && <div className="tabular text-xs font-semibold text-ink-900 w-9 text-right">{value}%</div>}
    </div>
  );
}

// ---------- Tabs ----------
function Tabs({ tabs, value, onChange }) {
  return (
    <div className="inline-flex p-1 bg-ink-100 border border-line2 rounded-lg gap-1">
      {tabs.map((t) => (
        <button
          key={t.id}
          onClick={() => onChange(t.id)}
          className={`px-3 h-7 rounded-md text-xs font-medium transition-all flex items-center gap-1.5 ${
            value === t.id
              ? 'bg-white text-ink-900 shadow-sm border border-line'
              : 'text-ink-600 hover:text-ink-900'
          }`}
        >
          {t.icon}
          {t.label}
          {t.count != null && (
            <span className={`tabular text-[10px] px-1.5 h-4 rounded-full inline-flex items-center ${value === t.id ? 'bg-brand-50 text-brand-600' : 'bg-ink-100 text-ink-600'}`}>
              {t.count}
            </span>
          )}
        </button>
      ))}
    </div>
  );
}

// ---------- Input ----------
function Input({ value, onChange, placeholder, icon, className = '', size = 'md', type = 'text', onKeyDown }) {
  const sizes = { sm: 'h-8 text-xs', md: 'h-9 text-sm', lg: 'h-11 text-sm' };
  return (
    <div className={`flex items-center gap-2 bg-white border border-line hover:border-ink-200 focus-within:border-brand-400 focus-within:ring-4 focus-within:ring-brand-100 rounded-lg px-3 transition ${sizes[size]} ${className}`}>
      {icon && <span className="text-ink-400 shrink-0">{icon}</span>}
      <input
        value={value}
        onChange={(e) => onChange?.(e.target.value)}
        onKeyDown={onKeyDown}
        type={type}
        placeholder={placeholder}
        className="bg-transparent outline-none flex-1 text-ink-900 placeholder:text-ink-400"
      />
    </div>
  );
}

// ---------- Checkbox ----------
function Check({ checked, onChange, label, className = '' }) {
  return (
    <label className={`inline-flex items-center gap-2 cursor-pointer select-none group ${className}`}>
      <span
        onClick={() => onChange?.(!checked)}
        className={`h-4 w-4 rounded border flex items-center justify-center transition-colors ${
          checked ? 'bg-brand-500 border-brand-500' : 'bg-white border-ink-200 group-hover:border-ink-300'
        }`}
      >
        {checked && <Icon.Check size={10} className="text-white" strokeWidth={3} />}
      </span>
      {label && <span className="text-sm text-ink-800">{label}</span>}
    </label>
  );
}

// ---------- Funnel ----------
function Funnel({ data }) {
  const max = Math.max(...data.map((d) => d.count));
  return (
    <div className="space-y-2.5">
      {data.map((d, i) => (
        <div key={d.stage} className="group">
          <div className="flex items-center justify-between text-xs mb-1">
            <div className="flex items-center gap-2 text-ink-700">
              <span className="h-2 w-2 rounded-full" style={{ background: d.color }} />
              <span className="font-medium">{d.stage}</span>
            </div>
            <div className="flex items-center gap-3">
              <span className="tabular text-ink-600">{d.count.toLocaleString()}</span>
              <span className="tabular text-ink-400 w-10 text-right">{d.conv}%</span>
            </div>
          </div>
          <div className="relative h-7 rounded-md overflow-hidden bg-ink-100">
            <div
              className="h-full transition-all"
              style={{
                width: `${(d.count / max) * 100}%`,
                background: `linear-gradient(90deg, ${d.color}66, ${d.color})`,
              }}
            />
            {i < data.length - 1 && (
              <div className="absolute right-1 top-0 bottom-0 flex items-center text-white/80">
                <Icon.ChevronRight size={12} />
              </div>
            )}
          </div>
        </div>
      ))}
    </div>
  );
}

// ---------- Skeleton ----------
function Skeleton({ className = '' }) {
  return <div className={`shimmer-bg animate-shimmer rounded-md ${className}`} />;
}

// ---------- Radar ----------
function Radar({ axes, data, size = 240 }) {
  const cx = size / 2, cy = size / 2;
  const r = size / 2 - 30;
  const n = axes.length;
  const angle = (i) => (Math.PI * 2 * i) / n - Math.PI / 2;

  const polyPoints = (vals) =>
    vals.map((v, i) => {
      const rr = (v / 100) * r;
      return `${cx + Math.cos(angle(i)) * rr},${cy + Math.sin(angle(i)) * rr}`;
    }).join(' ');

  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <defs>
        <linearGradient id="radarGradL" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0" stopColor="#4f46e5" stopOpacity="0.32" />
          <stop offset="1" stopColor="#a855f7" stopOpacity="0.32" />
        </linearGradient>
      </defs>
      {[20, 40, 60, 80, 100].map((p) => (
        <polygon
          key={p}
          fill="none"
          stroke="#e6e8ec"
          strokeDasharray="2 4"
          strokeWidth="1"
          points={axes.map((_, i) => {
            const rr = (p / 100) * r;
            return `${cx + Math.cos(angle(i)) * rr},${cy + Math.sin(angle(i)) * rr}`;
          }).join(' ')}
        />
      ))}
      {axes.map((_, i) => (
        <line key={i} x1={cx} y1={cy} x2={cx + Math.cos(angle(i)) * r} y2={cy + Math.sin(angle(i)) * r}
              stroke="#e6e8ec" strokeWidth="1" />
      ))}
      <polygon points={polyPoints(data.requirement)} fill="#d97706" fillOpacity="0.10"
               stroke="#d97706" strokeOpacity="0.6" strokeDasharray="3 3" strokeWidth="1.25" />
      <polygon points={polyPoints(data.candidate)} fill="url(#radarGradL)" stroke="#4f46e5" strokeWidth="1.5" />
      {axes.map((label, i) => {
        const lx = cx + Math.cos(angle(i)) * (r + 18);
        const ly = cy + Math.sin(angle(i)) * (r + 18);
        return (
          <text key={label} x={lx} y={ly} textAnchor="middle" dominantBaseline="middle"
                fontSize="10" fill="#5c5c78" className="font-medium">
            {label}
          </text>
        );
      })}
      {data.candidate.map((v, i) => {
        const rr = (v / 100) * r;
        return <circle key={i} cx={cx + Math.cos(angle(i)) * rr} cy={cy + Math.sin(angle(i)) * rr} r="3" fill="#4f46e5" />;
      })}
    </svg>
  );
}

// ---------- Modal ----------
function Modal({ open, onClose, children, size = 'md', className = '' }) {
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === 'Escape') onClose?.(); };
    document.addEventListener('keydown', h);
    return () => document.removeEventListener('keydown', h);
  }, [open, onClose]);
  if (!open) return null;
  const widths = { sm: 'max-w-md', md: 'max-w-xl', lg: 'max-w-3xl', xl: 'max-w-5xl' };
  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 animate-fade-in">
      <div className="absolute inset-0 bg-ink-900/40 backdrop-blur-sm" onClick={onClose} />
      <div className={`relative bg-white border border-line rounded-2xl shadow-pop w-full ${widths[size]} max-h-[88vh] overflow-hidden flex flex-col animate-slide-up ${className}`}>
        {children}
      </div>
    </div>
  );
}

function ModalHeader({ icon, title, subtitle, onClose }) {
  return (
    <div className="px-6 py-4 border-b border-line flex items-center gap-4">
      {icon && <div className="h-10 w-10 rounded-lg bg-brand-50 border border-brand-100 text-brand-600 flex items-center justify-center shrink-0">{icon}</div>}
      <div className="flex-1">
        <div className="text-base font-semibold text-ink-900">{title}</div>
        {subtitle && <div className="text-xs text-ink-500 mt-0.5">{subtitle}</div>}
      </div>
      <IconButton icon={<Icon.X size={16} />} variant="ghost" onClick={onClose} />
    </div>
  );
}

function Divider({ className = '' }) {
  return <div className={`h-px bg-line ${className}`} />;
}

// ---------- Section header ----------
function SectionHeader({ kicker, title, action }) {
  return (
    <div className="flex items-end justify-between mb-4">
      <div>
        {kicker && <div className="text-[11px] uppercase tracking-[0.18em] text-ink-500 mb-1 font-medium">{kicker}</div>}
        {title && <h2 className="text-base font-semibold text-ink-900">{title}</h2>}
      </div>
      {action}
    </div>
  );
}

Object.assign(window, {
  ToastProvider, useToast,
  Button, IconButton, Pill, StageBadge, RecoBadge, PriorityBadge,
  Avatar, Card, SectionHeader, KpiCard, Sparkline, MatchBar,
  Tabs, Input, Check, Funnel, Skeleton, Radar, Modal, ModalHeader, Divider,
});
