// WeWire team dashboard — tokens, icons, primitives, layout shell.

const T = {
  orange: '#FF4D07', orange2: '#FF7139', orangeDeep: '#D63E05', orangeSoft: '#FFE5D8', amber: '#FF7139',
  ink: '#0E0E0E', ink2: '#1E1C1A', cream: '#FBF7F0', sand: '#F1EADD', white: '#FFFFFF',
  green: '#365A33', greenSoft: '#ECF6D6', red: '#C0392B', redSoft: '#F8E5E2',
  blue: '#3256FC', blueDeep: '#1638CD', blueSoft: '#F1F3FF', purple: '#5F29B3', purpleSoft: '#D8DCFF',
  muted: '#6A645B', subtle: '#9A938A', line: 'rgba(14,14,14,0.10)', lineStrong: 'rgba(14,14,14,0.20)',
  panel: '#F6F1E8',
};
const FONT = '"Hanken Grotesk", ui-sans-serif, system-ui, sans-serif';
const DISP = '"Fraunces", Georgia, "Times New Roman", serif';

const STATUS = {
  in_review: { label: 'In review', tone: 'neutral' },
  advancing: { label: 'Advancing', tone: 'blue' },
  shortlist: { label: 'Shortlisted', tone: 'warm' },
  offer:     { label: 'Offer', tone: 'green' },
  rejected:  { label: 'Not advancing', tone: 'red' },
};

const ESSAY_STAGE_KEYS = new Set(['written', 'case', 'interview']);

function normalizeStageScore(key, value) {
  if (value == null) return null;
  return ESSAY_STAGE_KEYS.has(key) ? value * 10 : value;
}

// score helpers
function presentScores(s) { return Object.values(s).filter(v => v != null); }
function overall(s) {
  const entries = Object.entries(s || {}).filter(([, v]) => v != null);
  if (!entries.length) return null;
  const sum = entries.reduce((acc, [k, v]) => acc + normalizeStageScore(k, v), 0);
  return Math.round(sum / entries.length);
}

const I = {
  grid: 'M3 3h7v7H3zM14 3h7v7h-7zM14 14h7v7h-7zM3 14h7v7H3z',
  list: 'M8 6h13M8 12h13M8 18h13|M3 6h.01M3 12h.01M3 18h.01',
  compare: 'M9 3v18M3 7h6M3 17h6|M15 3v18M21 9l-6-3 6-3z',
  search: 'M21 21l-4.3-4.3|', user: 'M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2|',
  check: 'M20 6L9 17l-5-5', x: 'M18 6L6 18M6 6l12 12', arrow: 'M5 12h14M13 6l6 6-6 6',
  up: 'M7 14l5-5 5 5', down: 'M7 10l5 5 5-5', star: 'M12 3l2.9 6 6.1.9-4.5 4.3 1.1 6.1L12 17.8 6.4 20.3l1.1-6.1L3 9.9 9.1 9z',
  pin: 'M12 21s7-6.5 7-12a7 7 0 1 0-14 0c0 5.5 7 12 7 12z|', clock: '|M12 7v5l3 2',
  chevron: 'M9 18l6-6-6-6', flag: 'M4 22V4h13l-2 4 2 4H4', dots: 'M12 5h.01M12 12h.01M12 19h.01',
  edit: 'M12 20h9|M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z',
  filter: 'M3 5h18M6 12h12M10 19h4', logout: 'M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4|M16 17l5-5-5-5M21 12H9',
};
function Icon({ name, size = 18, color = 'currentColor', sw = 2, style = {} }) {
  const segs = (I[name] || '').split('|').filter(Boolean);
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={sw}
      strokeLinecap="round" strokeLinejoin="round" style={style}>
      {name === 'search' && <circle cx="11" cy="11" r="7" />}
      {name === 'user' && <circle cx="12" cy="7" r="4" />}
      {name === 'clock' && <circle cx="12" cy="12" r="9" />}
      {name === 'pin' && <circle cx="12" cy="9" r="2.5" />}
      {segs.map((d, i) => <path key={i} d={d} />)}
    </svg>
  );
}

function Avatar({ name, size = 38, color }) {
  const initials = name.split(' ').map(w => w[0]).slice(0, 2).join('');
  const colors = [T.orange, T.blue, T.green, T.amber, T.ink2];
  const c = color || colors[name.charCodeAt(0) % colors.length];
  return (
    <div style={{ width: size, height: size, borderRadius: '50%', background: c, color: '#fff', flex: 'none',
      display: 'grid', placeItems: 'center', fontFamily: DISP, fontWeight: 600, fontSize: size * 0.38 }}>{initials}</div>
  );
}

function Badge({ status, size = 'md' }) {
  const tones = {
    neutral: { background: T.sand, color: T.muted }, blue: { background: T.blueSoft, color: T.blue },
    warm: { background: T.orangeSoft, color: T.orangeDeep }, green: { background: T.greenSoft, color: T.green },
    red: { background: T.redSoft, color: T.red },
  };
  const s = STATUS[status] || { label: status, tone: 'neutral' };
  const pad = size === 'sm' ? '3px 9px' : '5px 12px';
  const fs = size === 'sm' ? 11 : 12.5;
  return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: pad, borderRadius: 999,
    fontSize: fs, fontWeight: 700, letterSpacing: '0.01em', ...tones[s.tone] }}>
    <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'currentColor' }} />{s.label}</span>;
}

function ScoreBar({ value, w = 100, showVal = true, label, max = 100 }) {
  const pct = value == null ? null : Math.round((value / max) * 100);
  const c = pct == null ? T.subtle : pct >= 85 ? T.green : pct >= 70 ? T.amber : pct >= 55 ? T.orange : T.red;
  const display = value == null ? '—' : (max === 10 ? `${value}/10` : value);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      {label && <span style={{ fontSize: 13, color: T.muted, width: 132, flex: 'none' }}>{label}</span>}
      <div style={{ flex: 1, minWidth: w === 'full' ? 0 : w, maxWidth: w === 'full' ? 'none' : w, height: 8,
        background: T.sand, borderRadius: 999, overflow: 'hidden' }}>
        {pct != null && <div style={{ width: `${pct}%`, height: '100%', background: c, borderRadius: 999 }} />}
      </div>
      {showVal && <span style={{ fontSize: 13, fontWeight: 700, width: max === 10 ? 42 : 34, textAlign: 'right',
        color: value == null ? T.subtle : T.ink, fontVariantNumeric: 'tabular-nums' }}>{display}</span>}
    </div>
  );
}

function Btn({ children, variant = 'primary', onClick, icon, size = 'md', style = {}, disabled }) {
  const h = size === 'sm' ? 36 : 44;
  const base = { height: h, padding: size === 'sm' ? '0 14px' : '0 18px', borderRadius: 10, border: 'none',
    cursor: disabled ? 'not-allowed' : 'pointer', fontFamily: FONT, fontSize: size === 'sm' ? 13 : 14.5, fontWeight: 600,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8, opacity: disabled ? 0.45 : 1,
    transition: 'transform 120ms, background 180ms, box-shadow 180ms', whiteSpace: 'nowrap' };
  const variants = {
    primary: { background: T.orange, color: '#fff' }, dark: { background: T.ink, color: T.cream },
    green: { background: T.green, color: '#fff' }, red: { background: T.white, color: T.red, boxShadow: `inset 0 0 0 1.5px ${T.red}` },
    ghost: { background: T.white, color: T.ink, boxShadow: `inset 0 0 0 1px ${T.lineStrong}` },
    soft: { background: T.orangeSoft, color: T.orangeDeep },
  };
  return <button onClick={disabled ? undefined : onClick} style={{ ...base, ...variants[variant], ...style }}
    onMouseDown={(e) => !disabled && (e.currentTarget.style.transform = 'scale(0.97)')}
    onMouseUp={(e) => (e.currentTarget.style.transform = 'scale(1)')}
    onMouseLeave={(e) => (e.currentTarget.style.transform = 'scale(1)')}>
    {icon && <Icon name={icon} size={size === 'sm' ? 15 : 17} />}{children}</button>;
}

function Card({ children, style = {}, pad = 22 }) {
  return <div style={{ background: T.white, borderRadius: 18, border: `1px solid ${T.line}`, padding: pad,
    boxShadow: '0 1px 3px rgba(27,24,19,0.04)', ...style }}>{children}</div>;
}

function Eyebrow({ children, color = T.muted, style = {} }) {
  return <div style={{ fontFamily: FONT, fontSize: 11.5, fontWeight: 700, letterSpacing: '0.14em',
    textTransform: 'uppercase', color, ...style }}>{children}</div>;
}

// ── Sidebar + shell ──────────────────────────────────────────
function Sidebar({ view, setView, adminEmail, onSignOut, onExport }) {
  const { PROGRAM } = window.WWData;
  const items = [['overview', 'Overview', 'grid'], ['pipeline', 'Pipeline', 'list'], ['compare', 'Compare', 'compare'],
    ['prompts', 'Prompts', 'edit'], ['interviews', 'Interviews', 'clock'], ['team', 'Team', 'user']];
  const displayName = adminEmail ? adminEmail.split('@')[0].replace(/\./g, ' ') : 'Recruiter';
  return (
    <aside style={{ width: 248, flex: 'none', background: T.ink, color: T.cream, display: 'flex', flexDirection: 'column',
      padding: '26px 18px', boxSizing: 'border-box', height: '100%' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '0 8px 4px' }}>
        <img src="../assets/wewire-logo-cream.svg" alt="WeWire" style={{ height: 24, display: 'block' }} />
        <div style={{ fontSize: 10.5, color: 'rgba(251,247,240,0.55)', letterSpacing: '0.1em', borderLeft: '1px solid rgba(251,247,240,0.2)', paddingLeft: 11 }}>TALENT</div>
      </div>

      <div style={{ marginTop: 30, display: 'flex', flexDirection: 'column', gap: 4 }}>
        {items.map(([k, label, ic]) => {
          const on = view === k;
          return (
            <button key={k} onClick={() => setView(k)} style={{ display: 'flex', alignItems: 'center', gap: 12,
              padding: '11px 14px', borderRadius: 11, border: 'none', cursor: 'pointer', textAlign: 'left',
              background: on ? 'rgba(255,77,7,0.18)' : 'transparent', color: on ? '#fff' : 'rgba(251,247,240,0.7)',
              fontFamily: FONT, fontSize: 14.5, fontWeight: 600, transition: 'background 160ms' }}>
              <Icon name={ic} size={18} color={on ? T.orange : 'rgba(251,247,240,0.6)'} />{label}
            </button>
          );
        })}
      </div>

      <div style={{ flex: 1 }} />
      <div style={{ background: 'rgba(251,247,240,0.06)', borderRadius: 14, padding: 16 }}>
        <div style={{ fontFamily: DISP, fontWeight: 600, fontSize: 30, color: T.orange, lineHeight: 1 }}>{PROGRAM.seats}</div>
        <div style={{ fontSize: 12.5, color: 'rgba(251,247,240,0.7)', marginTop: 6, lineHeight: 1.45 }}>
          seats this cohort · in person at {PROGRAM.location.split('·')[1] || 'Accra'}</div>
        <div style={{ fontSize: 11.5, color: 'rgba(251,247,240,0.5)', marginTop: 10 }}>Applications close {PROGRAM.applyClose}</div>
        {onExport && (
          <button type="button" onClick={onExport} style={{ marginTop: 12, width: '100%', padding: '10px 12px', borderRadius: 10,
            border: '1px solid rgba(251,247,240,0.2)', background: 'transparent', color: T.cream, fontFamily: FONT,
            fontSize: 12.5, fontWeight: 600, cursor: 'pointer' }}>Export CSV ↓</button>
        )}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 16, padding: '0 6px' }}>
        <Avatar name={displayName} size={32} color={T.amber} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{displayName}</div>
          <div style={{ fontSize: 11, color: 'rgba(251,247,240,0.5)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{adminEmail || 'People & Talent'}</div>
        </div>
        {onSignOut && (
          <button type="button" onClick={onSignOut} aria-label="Sign out" style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4 }}>
            <Icon name="logout" size={16} color="rgba(251,247,240,0.45)" />
          </button>
        )}
      </div>
    </aside>
  );
}

Object.assign(window, { T, FONT, DISP, STATUS, Icon, Avatar, Badge, ScoreBar, Btn, Card, Eyebrow, Sidebar, overall, presentScores, ESSAY_STAGE_KEYS, normalizeStageScore });
