// WTS Cyprus — Shared primitive components (Codelia Design System)
const { useState, useRef, useEffect, createContext, useContext, useCallback } = React;

const cn = (...xs) => xs.filter(Boolean).join(' ');

// ── Icon (Lucide via CDN) ─────────────────────────────────────────────────
const Icon = ({ name, size = 16, style, className }) => (
  <img
    src={`https://unpkg.com/lucide-static@latest/icons/${name}.svg`}
    width={size} height={size}
    className={className}
    style={{ display: 'inline-block', verticalAlign: 'middle', flexShrink: 0, ...style }}
    alt=""
  />
);

// ── Button ────────────────────────────────────────────────────────────────
const Button = ({ variant = 'default', size = 'default', className, children, ...rest }) => (
  <button
    className={cn('ck-btn', `ck-btn--${variant}`, size !== 'default' && `ck-btn--${size}`, className)}
    {...rest}
  >
    {children}
  </button>
);

// ── Badge ─────────────────────────────────────────────────────────────────
const Badge = ({ variant = 'secondary', children, className, style }) => (
  <span className={cn('ck-badge', `ck-badge--${variant}`, className)} style={style}>
    {children}
  </span>
);

// ── StatusBadge — coloured semantic variants ──────────────────────────────
const STATUS_MAP = {
  // Engagements
  active:      { label: 'Active',       bg: 'hsl(142 50% 94%)', color: 'hsl(142 55% 26%)' },
  on_hold:     { label: 'On hold',      bg: 'hsl(0 0% 96%)',    color: 'hsl(0 0% 38%)',    border: '1px solid var(--border)' },
  completed:   { label: 'Completed',    bg: 'hsl(213 90% 95%)', color: 'hsl(213 80% 32%)' },
  inactive:    { label: 'Inactive',     bg: 'hsl(0 0% 96%)',    color: 'hsl(0 0% 40%)',    border: '1px solid var(--border)' },
  // Request-item lifecycle (Pending → Submitted → Accepted | Change requested)
  pending:          { label: 'Pending',          bg: 'transparent',      color: 'var(--muted-foreground)', border: '1px solid var(--border)' },
  submitted:        { label: 'Submitted',        bg: 'hsl(213 90% 95%)', color: 'hsl(213 80% 35%)' },
  accepted:         { label: 'Accepted',         bg: 'hsl(142 50% 94%)', color: 'hsl(142 55% 26%)' },
  change_requested: { label: 'Change requested', bg: 'hsl(38 95% 93%)',  color: 'hsl(28 90% 32%)' },
  // Studies
  complete:    { label: 'Complete',     bg: 'hsl(142 50% 94%)', color: 'hsl(142 55% 26%)' },
  archived:    { label: 'Archived',     bg: 'hsl(0 0% 96%)',    color: 'hsl(0 0% 40%)',    border: '1px solid var(--border)' },
  review:      { label: 'In review',    bg: 'hsl(255 70% 95%)', color: 'hsl(255 70% 42%)' },
  running:     { label: 'Running',      bg: 'hsl(38 95% 93%)',  color: 'hsl(28 90% 35%)' },
  draft:       { label: 'Draft',        bg: 'transparent',      color: 'var(--muted-foreground)', border: '1px solid var(--border)' },
  // Analyst verdicts (candidate-level)
  'v-accept':  { label: 'Accept',       bg: 'hsl(142 50% 94%)', color: 'hsl(142 55% 26%)' },
  'v-reject':  { label: 'Reject',       bg: 'hsl(0 85% 96%)',   color: 'hsl(0 72% 40%)' },
  'v-pending': { label: 'Pending',      bg: 'transparent',      color: 'var(--muted-foreground)', border: '1px solid var(--border)' },
};
const StatusBadge = ({ status, label }) => {
  const s = STATUS_MAP[status] || { label: status, bg: 'var(--secondary)', color: 'var(--secondary-foreground)' };
  return (
    <span className="ck-badge" style={{ background: s.bg, color: s.color, border: s.border || '1px solid transparent' }}>
      {label || s.label}
    </span>
  );
};

// ── Card family ───────────────────────────────────────────────────────────
const Card = ({ className, children, style, onClick, ...rest }) => (
  <div className={cn('ck-card', className)} style={style} onClick={onClick} {...rest}>{children}</div>
);
const CardHeader = ({ children, style }) => <div className="ck-card__header" style={style}>{children}</div>;
const CardTitle = ({ children }) => <div className="ck-card__title">{children}</div>;
const CardDescription = ({ children }) => <div className="ck-card__desc">{children}</div>;
const CardContent = ({ children, className, style }) => (
  <div className={cn('ck-card__content', className)} style={style}>{children}</div>
);

// ── ProgressBar ───────────────────────────────────────────────────────────
const ProgressBar = ({ value, max, color, height = 5 }) => {
  const pct = max > 0 ? Math.min(100, Math.round((value / max) * 100)) : 0;
  return (
    <div style={{ background: 'var(--border)', borderRadius: 4, height, overflow: 'hidden', width: '100%' }}>
      <div style={{ width: `${pct}%`, height: '100%', background: color || 'var(--primary)', borderRadius: 4, transition: 'width 400ms ease' }} />
    </div>
  );
};

// ── AvatarStack ──────────────────────────────────────────────────────────
const AVATAR_COLORS = [
  ['hsl(213 70% 92%)', 'hsl(213 70% 32%)'],
  ['hsl(142 50% 92%)', 'hsl(142 50% 26%)'],
  ['hsl(28 80% 93%)',  'hsl(28 80% 32%)'],
  ['hsl(280 50% 93%)', 'hsl(280 50% 32%)'],
  ['hsl(0 60% 93%)',   'hsl(0 60% 36%)'],
  ['hsl(180 40% 92%)', 'hsl(180 40% 28%)'],
];
const colorFor = (id) => {
  const i = (String(id).charCodeAt(0) + String(id).charCodeAt(String(id).length - 1)) % AVATAR_COLORS.length;
  return AVATAR_COLORS[i];
};
const Avatar = ({ user, size = 24 }) => {
  if (!user) return null;
  const [bg, fg] = colorFor(user.id);
  const initials = user.name.split(' ').map(s => s[0]).slice(0, 2).join('');
  return (
    <span style={{
      width: size, height: size, borderRadius: '50%', background: bg, color: fg,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontSize: Math.round(size * 0.42), fontWeight: 600, flexShrink: 0,
      fontFamily: 'var(--font-mono)', letterSpacing: '-0.02em',
    }} title={user.name}>{initials}</span>
  );
};
const AvatarStack = ({ users, size = 22, max = 3 }) => {
  const shown = users.slice(0, max);
  const extra = users.length - shown.length;
  return (
    <span style={{ display: 'inline-flex' }}>
      {shown.map((u, i) => (
        <span key={u.id} style={{ marginLeft: i === 0 ? 0 : -6, position: 'relative', zIndex: max - i, border: '1.5px solid var(--card)', borderRadius: '50%', display: 'inline-flex' }}>
          <Avatar user={u} size={size} />
        </span>
      ))}
      {extra > 0 && (
        <span style={{
          marginLeft: -6, width: size, height: size, borderRadius: '50%',
          background: 'var(--secondary)', color: 'var(--muted-foreground)',
          fontSize: Math.round(size * 0.40), fontWeight: 600,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          border: '1.5px solid var(--card)', fontFamily: 'var(--font-mono)',
        }}>+{extra}</span>
      )}
    </span>
  );
};

// ── Tooltip (hover popup) ─────────────────────────────────────────────────
const Tooltip = ({ content, children, width = 248, side = 'top' }) => {
  const [vis, setVis] = useState(false);
  const positions = {
    top:    { bottom: 'calc(100% + 6px)', left: '50%', transform: 'translateX(-50%)' },
    bottom: { top:    'calc(100% + 6px)', left: '50%', transform: 'translateX(-50%)' },
  };
  return (
    <span style={{ position: 'relative', display: 'inline-flex', alignItems: 'center' }}
      onMouseEnter={() => setVis(true)} onMouseLeave={() => setVis(false)}>
      {children}
      {vis && (
        <span style={{
          position: 'absolute', ...positions[side],
          background: 'hsl(0 0% 10%)', color: '#fff', fontSize: 12, lineHeight: 1.5,
          padding: '7px 11px', borderRadius: 6, width, zIndex: 60, pointerEvents: 'none',
          boxShadow: 'var(--shadow-lg)', whiteSpace: 'normal',
        }}>
          {content}
        </span>
      )}
    </span>
  );
};

// ── Sparkline (pure SVG — no external deps) ──────────────────────────────
const Sparkline = ({ data, dataKey = 'v' }) => {
  const values = data.map(d => d[dataKey]);
  const min = Math.min(...values);
  const max = Math.max(...values);
  const range = max - min || 1;
  const W = 80, H = 36, pad = 2;
  const pts = values.map((v, i) => {
    const x = (i / (values.length - 1)) * W;
    const y = H - pad - ((v - min) / range) * (H - pad * 2);
    return [x, y];
  });
  const line  = pts.map(([x,y], i) => `${i===0?'M':'L'}${x.toFixed(1)},${y.toFixed(1)}`).join(' ');
  const area  = `${line} L${W},${H} L0,${H} Z`;
  const stroke = 'oklch(0.21 0.006 285.885)';
  return (
    <svg width="100%" height={H} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display:'block' }}>
      <defs>
        <linearGradient id="sg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%"   stopColor={stroke} stopOpacity="0.13" />
          <stop offset="100%" stopColor={stroke} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill="url(#sg)" />
      <path d={line} fill="none" stroke={stroke} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" />
    </svg>
  );
};

// ── Toast system ──────────────────────────────────────────────────────────
const ToastCtx = createContext({ push: () => {} });
const useToast = () => useContext(ToastCtx);
const ToastProvider = ({ children }) => {
  const [items, setItems] = useState([]);
  const push = useCallback((t) => {
    const id = Math.random().toString(36).slice(2);
    setItems((xs) => [...xs, { id, ...t }]);
    setTimeout(() => setItems((xs) => xs.filter((x) => x.id !== id)), t.duration || 3000);
  }, []);
  const api = {
    success: (title, description) => push({ tone: 'success', title, description }),
    info:    (title, description) => push({ tone: 'info',    title, description }),
    error:   (title, description) => push({ tone: 'error',   title, description }),
  };
  return (
    <ToastCtx.Provider value={api}>
      {children}
      <div className="wts-toasts">
        {items.map((t) => {
          const iconName = { success: 'check', info: 'info', error: 'circle-x' }[t.tone || 'info'];
          return (
            <div key={t.id} className={cn('wts-toast', `wts-toast--${t.tone || 'info'}`)}>
              <span className="wts-toast__icon"><Icon name={iconName} size={14} /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="wts-toast__title">{t.title}</div>
                {t.description && <div className="wts-toast__desc">{t.description}</div>}
              </div>
            </div>
          );
        })}
      </div>
    </ToastCtx.Provider>
  );
};

// ── Modal ────────────────────────────────────────────────────────────────
const Modal = ({ open, onClose, title, children, footer, width = 460 }) => {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="wts-modal-overlay" onClick={onClose}>
      <div className="wts-modal" style={{ maxWidth: width }} onClick={(e) => e.stopPropagation()}>
        <div className="wts-modal__header">
          <div style={{ fontSize: 15, fontWeight: 600 }}>{title}</div>
          <button type="button" className="wts-icon-btn" onClick={onClose} aria-label="Close"><Icon name="x" size={15} /></button>
        </div>
        <div className="wts-modal__body">{children}</div>
        {footer && <div className="wts-modal__footer">{footer}</div>}
      </div>
    </div>
  );
};

// ── Drawer (right-side slide-in) ──────────────────────────────────────────
const Drawer = ({ open, onClose, width = 480, children }) => {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  return (
    <>
      <div className={cn('wts-drawer-overlay', open && 'wts-drawer-overlay--open')} onClick={onClose} />
      <aside className={cn('wts-drawer', open && 'wts-drawer--open')} style={{ width }}>
        {open && children}
      </aside>
    </>
  );
};

// ── Switch ────────────────────────────────────────────────────────────────
const Switch = ({ checked, onChange, label }) => (
  <label style={{ display: 'inline-flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
    <span className={cn('wts-switch', checked && 'wts-switch--on')} role="switch" aria-checked={checked} onClick={() => onChange(!checked)}>
      <span className="wts-switch__thumb" />
    </span>
    {label && <span style={{ fontSize: 13.5 }}>{label}</span>}
  </label>
);

// ── Input / Textarea / Label ──────────────────────────────────────────────
const Input    = ({ className, ...rest }) => <input className={cn('wts-input', className)} {...rest} />;
const Textarea = ({ className, ...rest }) => <textarea className={cn('wts-input', className)} style={{ minHeight: 78, padding: 8, height: 'auto', lineHeight: '1.4', resize: 'vertical' }} {...rest} />;
const Label    = ({ children, htmlFor }) => <label className="wts-label" htmlFor={htmlFor}>{children}</label>;

// ── Segmented control (filter chip group) ─────────────────────────────────
const Segmented = ({ options, value, onChange }) => (
  <div className="wts-segmented" role="tablist">
    {options.map(opt => (
      <button
        key={opt.value}
        type="button"
        role="tab"
        aria-selected={value === opt.value}
        data-active={value === opt.value}
        className="wts-segmented__item"
        onClick={() => onChange(opt.value)}
      >
        {opt.label}
        {opt.count != null && (
          <span className="wts-segmented__count">{opt.count}</span>
        )}
      </button>
    ))}
  </div>
);

// ── Kebab menu ────────────────────────────────────────────────────────────
const KebabMenu = ({ items }) => {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [open]);
  return (
    <span style={{ position: 'relative' }} ref={ref}>
      <button
        type="button"
        className="wts-icon-btn"
        onClick={(e) => { e.stopPropagation(); setOpen(o => !o); }}
        aria-label="More actions"
      >
        <Icon name="more-horizontal" size={15} />
      </button>
      {open && (
        <div className="wts-dropdown" style={{ right: 0, top: 'calc(100% + 4px)', minWidth: 168 }}>
          {items.map((it, i) => (
            <button
              key={i}
              type="button"
              className={cn('wts-dropdown__item', it.danger && 'wts-dropdown__item--danger')}
              onClick={(e) => { e.stopPropagation(); setOpen(false); it.onClick && it.onClick(); }}
            >
              {it.icon && <Icon name={it.icon} size={13} />}
              {it.label}
            </button>
          ))}
        </div>
      )}
    </span>
  );
};

Object.assign(window, {
  cn, Icon, Button, Badge, StatusBadge,
  Card, CardHeader, CardTitle, CardDescription, CardContent,
  ProgressBar, Avatar, AvatarStack, Tooltip, Sparkline,
  ToastProvider, useToast,
  Modal, Drawer, Switch, Input, Textarea, Label,
  Segmented, KebabMenu,
});
