// Candidate Pool + Candidate Detail (slide-over). LIGHT.

const { useState: usC, useMemo: umC } = React;

function CandidatesScreen({ onOpenCandidate, onOpenChat, onOpenCall, onOpenCampaign }) {
  const [search, setSearch] = usC('');
  const [reqId, setReqId] = usC(DATA.REQUISITIONS[0].id);
  const [filters, setFilters] = usC({
    skills: [],
    experience: [0, 10],
    languages: [],
    location: 'Todas',
    salary: 2500,
    availability: [],
    source: [],
    shortlistOnly: false,
  });

  const toggleArr = (key, val) =>
    setFilters((f) => ({
      ...f,
      [key]: f[key].includes(val) ? f[key].filter((x) => x !== val) : [...f[key], val],
    }));

  const allSkills = ['Inglés C1', 'Inglés B2', 'Negociación', 'Salesforce', 'Power BI', 'POS', 'WhatsApp Business', 'Coaching'];
  const allLangs = ['Español', 'Inglés', 'Portugués', 'Francés'];
  const allCities = ['Todas', 'San Salvador', 'Guatemala City', 'San Pedro Sula', 'Tegucigalpa', 'Mixco'];
  const allAvail = ['Inmediata', '15 días', '30 días', 'A convenir'];
  const allSources = ['Portal SOFIA', 'Referido', 'LinkedIn', 'WhatsApp Campaign', 'Job Fair'];

  const filtered = umC(() => {
    return DATA.CANDIDATES.filter((c) => {
      if (search && !c.name.toLowerCase().includes(search.toLowerCase()) &&
          !c.role.toLowerCase().includes(search.toLowerCase())) return false;
      if (filters.skills.length && !filters.skills.some((s) => c.skills.includes(s))) return false;
      if (c.yearsExperience < filters.experience[0] || c.yearsExperience > filters.experience[1]) return false;
      if (filters.languages.length && !filters.languages.some((l) => c.languages.includes(l))) return false;
      if (filters.location !== 'Todas' && c.city !== filters.location) return false;
      if (c.salaryNum > filters.salary) return false;
      if (filters.availability.length && !filters.availability.includes(c.availability)) return false;
      if (filters.source.length && !filters.source.includes(c.source)) return false;
      if (filters.shortlistOnly && !c.shortlistedFor) return false;
      return true;
    }).sort((a, b) => b.matchScore - a.matchScore);
  }, [search, filters]);

  return (
    <Page id="candidates">
      <div className="flex items-end justify-between mb-5">
        <div>
          <div className="text-[11px] uppercase tracking-[0.18em] text-ink-500 mb-1.5 flex items-center gap-2 font-medium">
            <Icon.Users size={12} /> Pool de candidatos
          </div>
          <h1 className="text-2xl font-semibold tracking-tight text-ink-900">Candidatos disponibles</h1>
          <p className="text-sm text-ink-500 mt-1">
            <b className="text-ink-900">{DATA.CANDIDATES.length}</b> perfiles · rankeados por match score para la vacante seleccionada.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <select
            value={reqId}
            onChange={(e) => setReqId(e.target.value)}
            className="h-9 bg-white border border-line rounded-lg px-3 text-sm text-ink-900 focus-ring hover:border-ink-200"
          >
            {DATA.REQUISITIONS.map((r) => (
              <option key={r.id} value={r.id}>Match contra: {r.title} · {r.client}</option>
            ))}
          </select>
          <Button variant="default" icon={<Icon.Megaphone size={14} />} onClick={onOpenCampaign}>Campaña masiva</Button>
        </div>
      </div>

      <div className="grid grid-cols-[296px_1fr] gap-6">
        {/* Filters */}
        <FiltersPanel
          filters={filters}
          setFilters={setFilters}
          toggleArr={toggleArr}
          allSkills={allSkills}
          allLangs={allLangs}
          allCities={allCities}
          allAvail={allAvail}
          allSources={allSources}
        />

        {/* Grid */}
        <div>
          <div className="flex items-center gap-3 mb-4">
            <div className="flex-1">
              <Input value={search} onChange={setSearch} placeholder="Buscar por nombre, rol o habilidad…" icon={<Icon.Search size={13} />} />
            </div>
            <div className="text-xs text-ink-500 tabular">
              <b className="text-ink-900">{filtered.length}</b> resultados
            </div>
            <Tabs
              value="match" onChange={() => {}}
              tabs={[
                { id: 'match', label: 'Match', icon: <Icon.Brain size={11} /> },
                { id: 'new',   label: 'Nuevos' },
                { id: 'avail', label: 'Disponibles' },
              ]}
            />
          </div>

          {filtered.length === 0 ? (
            <Card className="p-10 text-center">
              <div className="mx-auto h-12 w-12 rounded-full bg-ink-50 border border-line flex items-center justify-center mb-3">
                <Icon.FileSearch size={20} className="text-ink-500" />
              </div>
              <div className="text-base font-semibold text-ink-900">Sin candidatos para estos filtros</div>
              <div className="text-sm text-ink-500 mt-1">Prueba ampliando rangos o usa SOFIA para descubrir perfiles afines.</div>
            </Card>
          ) : (
            <div className="grid grid-cols-2 gap-3">
              {filtered.map((c) => (
                <CandidateCard key={c.id} c={c}
                  onOpen={() => onOpenCandidate(c)}
                  onChat={() => onOpenChat(c)}
                  onCall={() => onOpenCall(c)} />
              ))}
            </div>
          )}
        </div>
      </div>
    </Page>
  );
}

function FilterGroup({ title, badge, children, defaultOpen = true }) {
  const [open, setOpen] = React.useState(defaultOpen);
  return (
    <div className="border-b border-line2 last:border-0">
      <button
        onClick={() => setOpen((v) => !v)}
        className="w-full flex items-center justify-between py-3 group"
      >
        <div className="flex items-center gap-2">
          <span className="text-[11px] uppercase tracking-[0.16em] text-ink-700 font-semibold">{title}</span>
          {badge != null && badge > 0 && (
            <span className="tabular text-[10px] px-1.5 h-4 inline-flex items-center rounded-full bg-brand-500 text-white font-semibold">{badge}</span>
          )}
        </div>
        <Icon.ChevronDown size={13} className={`text-ink-400 group-hover:text-ink-700 transition-transform ${open ? '' : '-rotate-90'}`} />
      </button>
      {open && <div className="pb-4">{children}</div>}
    </div>
  );
}

// ---------- Filters panel ----------
function FiltersPanel({ filters, setFilters, toggleArr, allSkills, allLangs, allCities, allAvail, allSources }) {
  const activeCount =
    filters.skills.length +
    filters.languages.length +
    filters.availability.length +
    filters.source.length +
    (filters.location !== 'Todas' ? 1 : 0) +
    (filters.salary !== 2500 ? 1 : 0) +
    (filters.experience[0] !== 0 || filters.experience[1] !== 10 ? 1 : 0) +
    (filters.shortlistOnly ? 1 : 0);

  const reset = () => setFilters({
    skills: [], experience: [0, 10], languages: [], location: 'Todas',
    salary: 2500, availability: [], source: [], shortlistOnly: false,
  });

  // Active filter chips
  const activeChips = [];
  filters.skills.forEach((s) => activeChips.push({ key: `s-${s}`, label: s, onRemove: () => toggleArr('skills', s) }));
  filters.languages.forEach((s) => activeChips.push({ key: `l-${s}`, label: s, onRemove: () => toggleArr('languages', s) }));
  filters.availability.forEach((s) => activeChips.push({ key: `a-${s}`, label: s, onRemove: () => toggleArr('availability', s) }));
  filters.source.forEach((s) => activeChips.push({ key: `o-${s}`, label: s, onRemove: () => toggleArr('source', s) }));
  if (filters.location !== 'Todas') activeChips.push({ key: 'city', label: filters.location, onRemove: () => setFilters({ ...filters, location: 'Todas' }) });
  if (filters.salary !== 2500) activeChips.push({ key: 'sal', label: `≤ $${filters.salary}`, onRemove: () => setFilters({ ...filters, salary: 2500 }) });
  if (filters.experience[0] !== 0 || filters.experience[1] !== 10) activeChips.push({ key: 'exp', label: `${filters.experience[0]}–${filters.experience[1]} años`, onRemove: () => setFilters({ ...filters, experience: [0, 10] }) });
  if (filters.shortlistOnly) activeChips.push({ key: 'sl', label: 'Shortlist', onRemove: () => setFilters({ ...filters, shortlistOnly: false }) });

  return (
    <Card className="self-start sticky top-[76px] max-h-[calc(100vh-100px)] flex flex-col overflow-hidden">
      {/* Header */}
      <div className="px-5 py-4 border-b border-line flex items-center justify-between">
        <div className="flex items-center gap-2">
          <span className="h-7 w-7 rounded-md bg-brand-50 border border-brand-100 flex items-center justify-center text-brand-600">
            <Icon.Sliders size={14} />
          </span>
          <div>
            <div className="text-sm font-semibold text-ink-900 leading-tight">Filtros</div>
            <div className="text-[10px] text-ink-500">
              {activeCount > 0 ? `${activeCount} activo${activeCount !== 1 ? 's' : ''}` : 'Ninguno aplicado'}
            </div>
          </div>
        </div>
        {activeCount > 0 && (
          <button onClick={reset} className="text-[11px] text-brand-600 hover:text-brand-700 font-semibold flex items-center gap-1">
            <Icon.X size={11} /> Limpiar
          </button>
        )}
      </div>

      {/* Active chips */}
      {activeChips.length > 0 && (
        <div className="px-5 py-3 border-b border-line bg-sub flex flex-wrap gap-1.5">
          {activeChips.map((chip) => (
            <button key={chip.key} onClick={chip.onRemove}
              className="inline-flex items-center gap-1 h-6 pl-2 pr-1.5 rounded-full bg-brand-50 border border-brand-100 text-[11px] text-brand-700 font-medium hover:bg-brand-100">
              {chip.label}
              <Icon.X size={10} />
            </button>
          ))}
        </div>
      )}

      {/* Scrollable groups */}
      <div className="flex-1 overflow-y-auto px-5">
        <FilterGroup title="Habilidades" badge={filters.skills.length}>
          <div className="flex flex-wrap gap-1.5">
            {allSkills.map((s) => {
              const on = filters.skills.includes(s);
              return (
                <button key={s} onClick={() => toggleArr('skills', s)}
                  className={`text-[11px] h-7 px-2.5 rounded-full border transition-colors inline-flex items-center gap-1 ${
                    on ? 'bg-brand-50 text-brand-700 border-brand-200' : 'bg-white text-ink-700 border-line hover:border-ink-200'
                  }`}>
                  {on && <Icon.Check size={10} strokeWidth={3} />}
                  {s}
                </button>
              );
            })}
          </div>
        </FilterGroup>

        <FilterGroup title="Experiencia" badge={(filters.experience[0] !== 0 || filters.experience[1] !== 10) ? 1 : 0}>
          <RangeDual
            min={0} max={10} unit="años"
            value={filters.experience}
            onChange={(v) => setFilters({ ...filters, experience: v })}
          />
        </FilterGroup>

        <FilterGroup title="Salario esperado" badge={filters.salary !== 2500 ? 1 : 0}>
          <div className="flex items-center justify-between text-[11px] mb-2">
            <span className="text-ink-500">Hasta</span>
            <span className="tabular text-ink-900 font-semibold">USD ${filters.salary.toLocaleString()}</span>
          </div>
          <input type="range" min="500" max="2500" step="50" value={filters.salary}
            onChange={(e) => setFilters({ ...filters, salary: +e.target.value })}
            className="w-full h-1.5 accent-brand-500" />
          <div className="flex justify-between text-[10px] text-ink-400 mt-1 tabular">
            <span>$500</span><span>$2,500</span>
          </div>
        </FilterGroup>

        <FilterGroup title="Ubicación" badge={filters.location !== 'Todas' ? 1 : 0}>
          <select value={filters.location} onChange={(e) => setFilters({ ...filters, location: e.target.value })}
                  className="w-full h-9 bg-white border border-line rounded-lg px-2.5 text-xs text-ink-900 focus-ring hover:border-ink-200">
            {allCities.map((c) => <option key={c}>{c}</option>)}
          </select>
        </FilterGroup>

        <FilterGroup title="Idiomas" badge={filters.languages.length}>
          <div className="space-y-1.5">
            {allLangs.map((l) => (
              <CheckRow key={l} checked={filters.languages.includes(l)} onChange={() => toggleArr('languages', l)} label={l} />
            ))}
          </div>
        </FilterGroup>

        <FilterGroup title="Disponibilidad" badge={filters.availability.length}>
          <div className="space-y-1.5">
            {allAvail.map((a) => (
              <CheckRow key={a} checked={filters.availability.includes(a)} onChange={() => toggleArr('availability', a)} label={a} />
            ))}
          </div>
        </FilterGroup>

        <FilterGroup title="Canal de origen" badge={filters.source.length} defaultOpen={false}>
          <div className="space-y-1.5">
            {allSources.map((s) => (
              <CheckRow key={s} checked={filters.source.includes(s)} onChange={() => toggleArr('source', s)} label={s} />
            ))}
          </div>
        </FilterGroup>
      </div>

      {/* Footer toggle */}
      <div className="px-5 py-3 border-t border-line bg-sub">
        <label className="flex items-center justify-between cursor-pointer">
          <div className="flex items-center gap-2">
            <Icon.Star size={12} className="text-ai-600" />
            <span className="text-xs text-ink-800 font-medium">Solo en shortlist</span>
          </div>
          <Toggle checked={filters.shortlistOnly} onChange={(v) => setFilters({ ...filters, shortlistOnly: v })} />
        </label>
      </div>
    </Card>
  );
}

// ---------- Helpers ----------
function CheckRow({ checked, onChange, label }) {
  return (
    <label className="flex items-center gap-2.5 cursor-pointer select-none group h-7 px-2 -mx-2 rounded-md hover:bg-ink-50">
      <span
        onClick={() => onChange?.(!checked)}
        className={`h-4 w-4 rounded border flex items-center justify-center transition-colors shrink-0 ${
          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>
      <span className={`text-xs ${checked ? 'text-ink-900 font-medium' : 'text-ink-700'}`}>{label}</span>
    </label>
  );
}

function Toggle({ checked, onChange }) {
  return (
    <button
      onClick={() => onChange?.(!checked)}
      className={`relative h-5 w-9 rounded-full transition-colors ${checked ? 'bg-brand-500' : 'bg-ink-200'}`}
    >
      <span className={`absolute top-0.5 h-4 w-4 rounded-full bg-white shadow-sm transition-all ${checked ? 'left-[18px]' : 'left-0.5'}`} />
    </button>
  );
}

function RangeDual({ min, max, value, unit, onChange }) {
  const [lo, hi] = value;
  const span = max - min;
  const leftPct  = ((lo - min) / span) * 100;
  const rightPct = ((hi - min) / span) * 100;
  return (
    <div>
      <div className="flex items-center justify-between text-[11px] mb-2">
        <span className="text-ink-500">Rango</span>
        <span className="tabular text-ink-900 font-semibold">{lo}–{hi} {unit}</span>
      </div>
      <div className="relative h-5">
        <div className="absolute inset-x-0 top-1/2 -translate-y-1/2 h-1.5 rounded-full bg-ink-100" />
        <div className="absolute top-1/2 -translate-y-1/2 h-1.5 rounded-full bg-brand-500"
             style={{ left: `${leftPct}%`, right: `${100 - rightPct}%` }} />
        <input type="range" min={min} max={max} value={lo}
               onChange={(e) => onChange([Math.min(+e.target.value, hi), hi])}
               className="absolute inset-0 w-full opacity-0 cursor-pointer pointer-events-auto"
               style={{ zIndex: lo > max - 1 ? 5 : 3 }} />
        <input type="range" min={min} max={max} value={hi}
               onChange={(e) => onChange([lo, Math.max(+e.target.value, lo)])}
               className="absolute inset-0 w-full opacity-0 cursor-pointer pointer-events-auto z-[4]" />
        <span className="absolute top-1/2 -translate-y-1/2 h-4 w-4 rounded-full bg-white border-2 border-brand-500 shadow-sm pointer-events-none"
              style={{ left: `calc(${leftPct}% - 8px)` }} />
        <span className="absolute top-1/2 -translate-y-1/2 h-4 w-4 rounded-full bg-white border-2 border-brand-500 shadow-sm pointer-events-none"
              style={{ left: `calc(${rightPct}% - 8px)` }} />
      </div>
      <div className="flex justify-between text-[10px] text-ink-400 mt-1 tabular">
        <span>{min}</span><span>{max}+</span>
      </div>
    </div>
  );
}

function CandidateCard({ c, onOpen, onChat, onCall }) {
  return (
    <div className="bg-white border border-line hover:border-brand-200 rounded-xl p-4 hover-lift transition-all">
      <div className="flex items-start gap-3 mb-3">
        <Avatar name={c.name} initials={c.initials} color={c.avatarColor} size={44} online={c.availability === 'Inmediata'} />
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <button onClick={onOpen} className="text-sm font-semibold text-ink-900 hover:text-brand-700 truncate">{c.name}</button>
            {c.shortlistedFor && <Icon.Star size={11} className="text-ai-600 shrink-0" />}
          </div>
          <div className="text-[11px] text-ink-500 truncate">{c.role}</div>
          <div className="text-[11px] text-ink-500 flex items-center gap-2 mt-1">
            <span className="flex items-center gap-1"><Icon.MapPin size={10} /> {c.city}, {c.country}</span>
            <span>·</span>
            <span className="flex items-center gap-1"><Icon.Clock size={10} /> {c.yearsExperience}y</span>
          </div>
        </div>
        <div className="text-right shrink-0">
          <div className="gradient-text text-xl font-semibold tabular leading-none">{c.matchScore}</div>
          <div className="text-[9px] text-ink-500 uppercase tracking-wider mt-1">Match</div>
        </div>
      </div>

      <div className="flex flex-wrap gap-1 mb-3">
        {c.skills.slice(0, 3).map((s) => <Pill key={s} tone="slate" size="sm">{s}</Pill>)}
      </div>

      <div className="grid grid-cols-3 gap-2 mb-3 text-[11px]">
        <Mini label="Idiomas" value={c.languages.join(', ')} />
        <Mini label="Disp." value={c.availability} />
        <Mini label="Salario" value={c.salaryExpected} />
      </div>

      <div className="flex items-center justify-between gap-2">
        <div className="flex gap-1">
          <Button size="sm" variant="whatsapp" icon={<Icon.WhatsApp size={11} />} onClick={onChat}>Chat</Button>
          <Button size="sm" variant="call" icon={<Icon.PhoneCall size={11} />} onClick={onCall}>Call</Button>
        </div>
        <div className="flex gap-1">
          <IconButton size="sm" variant="default" icon={<Icon.BookmarkPlus size={12} />} title="Shortlist" />
          <Button size="sm" variant="ghost" onClick={onOpen} iconRight={<Icon.ArrowRight size={11} />}>Ver perfil</Button>
        </div>
      </div>
    </div>
  );
}

function Mini({ label, value }) {
  return (
    <div className="bg-ink-50 border border-line rounded-md px-2 py-1.5">
      <div className="text-[9px] uppercase tracking-wider text-ink-500 font-medium">{label}</div>
      <div className="text-[11px] text-ink-800 truncate">{value}</div>
    </div>
  );
}

// ----------------- Candidate Detail (slide-over) -----------------
function CandidateDetail({ candidate, open, onClose, onOpenChat, onOpenCall, onOpenSchedule, onOpenKit, onOpenSubmit }) {
  const [tab, setTab] = usC('summary');
  if (!candidate || !open) return null;

  const radarAxes = ['Inglés', 'Negociación', 'CRM', 'Atención', 'Liderazgo', 'POS'];
  const radarData = {
    candidate: [88, 84, 76, 92, 68, 60],
    requirement: [85, 80, 70, 80, 60, 55],
  };

  const timeline = [
    { icon: 'CheckCircle', tone: 'emerald', t: 'Hoy · 10:23', title: 'Screening completado por SOFIA Call', body: 'Recomendación: Advance · 92% conf.' },
    { icon: 'WhatsApp',    tone: 'emerald', t: 'Hoy · 10:42', title: 'WhatsApp recibido', body: '"Perfecto, confirmo la entrevista para el jueves a las 3pm"' },
    { icon: 'Bot',         tone: 'brand',   t: 'Hoy · 09:30', title: 'SOFIA generó kit de entrevista', body: 'Caso role-play + validación inglés C1' },
    { icon: 'WhatsApp',    tone: 'emerald', t: 'Ayer · 18:14', title: 'Invitación enviada vía SOFIA Chat', body: 'Template "Invitación a entrevista"' },
    { icon: 'UserPlus',    tone: 'sky',     t: 'Hace 4 días', title: 'Aplicación recibida', body: 'Portal SOFIA · referido por Camila A.' },
  ];

  return (
    <div className="fixed inset-0 z-[90]">
      <div className="absolute inset-0 bg-ink-900/30 backdrop-blur-sm animate-fade-in" onClick={onClose} />
      <aside className="absolute right-0 top-0 bottom-0 w-[920px] max-w-[96vw] bg-white border-l border-line flex flex-col animate-slide-in-right shadow-pop overflow-hidden">
        <div className="relative px-6 py-5 border-b border-line bg-gradient-to-br from-sub to-white">
          <div className="flex items-start gap-4">
            <Avatar name={candidate.name} initials={candidate.initials} color={candidate.avatarColor} size={64} ring />
            <div className="flex-1 min-w-0">
              <div className="text-[11px] text-ink-500 mb-0.5 tracking-wider font-medium">CANDIDATE-{candidate.id.slice(-4).toUpperCase()}</div>
              <div className="text-2xl font-semibold text-ink-900">{candidate.name}</div>
              <div className="text-sm text-ink-500 mt-0.5">{candidate.role} · {candidate.yearsExperience} años de experiencia</div>
              <div className="flex items-center gap-2 mt-3 flex-wrap">
                <Pill tone="slate" icon={<Icon.MapPin size={10} />}>{candidate.city}, {candidate.country}</Pill>
                <Pill tone="slate" icon={<Icon.GraduationCap size={10} />}>{candidate.education}</Pill>
                <Pill tone="slate" icon={<Icon.Languages size={10} />}>{candidate.languages.join(' · ')}</Pill>
                <Pill tone="slate" icon={<Icon.Clock size={10} />}>{candidate.availability}</Pill>
                <Pill tone="slate" icon={<Icon.Wallet size={10} />}>{candidate.salaryExpected}</Pill>
                <StageBadge stage={candidate.stage} />
              </div>
            </div>
            <div className="text-right shrink-0">
              <div className="gradient-text text-4xl font-semibold tabular leading-none">{candidate.matchScore}%</div>
              <div className="text-[10px] uppercase tracking-wider text-ink-500 mt-1 font-medium">SOFIA Match</div>
              <button onClick={onClose} className="absolute top-4 right-4 h-9 w-9 rounded-lg bg-white border border-line hover:border-ink-200 flex items-center justify-center">
                <Icon.X size={14} className="text-ink-700" />
              </button>
            </div>
          </div>
        </div>

        {/* Action bar */}
        <div className="px-6 py-3 border-b border-line bg-white flex items-center gap-2 flex-wrap">
          <Button variant="whatsapp" icon={<Icon.WhatsApp size={14} />} onClick={() => onOpenChat(candidate)}>SOFIA Chat</Button>
          <Button variant="call" icon={<Icon.PhoneCall size={14} />} onClick={() => onOpenSchedule(candidate)}>Agendar SOFIA Call</Button>
          <Button variant="amber" icon={<Icon.Notebook size={14} />} onClick={() => onOpenKit(candidate)}>Generar kit</Button>
          <Button variant="primary" icon={<Icon.Send size={14} />} onClick={() => onOpenSubmit(candidate)}>Submitir a cliente</Button>
          <div className="ml-auto flex gap-1.5">
            <IconButton icon={<Icon.BookmarkPlus size={14} />} title="Shortlist" />
            <IconButton icon={<Icon.More size={14} />} />
          </div>
        </div>

        <div className="px-6 pt-4">
          <Tabs
            value={tab} onChange={setTab}
            tabs={[
              { id: 'summary',  label: 'SOFIA Summary', icon: <Icon.Sparkles size={11} /> },
              { id: 'cv',       label: 'CV',            icon: <Icon.File size={11} /> },
              { id: 'fit',      label: 'Skills fit',    icon: <Icon.Crosshair size={11} /> },
              { id: 'timeline', label: 'Touchpoints',   icon: <Icon.Activity size={11} /> },
            ]}
          />
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-5 bg-sub">
          {tab === 'summary' && <SummaryTab c={candidate} />}
          {tab === 'cv' && <CVTab c={candidate} />}
          {tab === 'fit' && <FitTab c={candidate} radarAxes={radarAxes} radarData={radarData} />}
          {tab === 'timeline' && <TimelineTab events={timeline} />}
        </div>
      </aside>
    </div>
  );
}

function SummaryTab({ c }) {
  return (
    <div className="grid grid-cols-12 gap-5">
      <div className="col-span-8 space-y-5">
        <Card className="p-5 border-ai-200 ai-soft">
          <div className="flex items-center gap-2 mb-3">
            <Icon.Sparkles size={14} className="text-ai-600" />
            <span className="text-[11px] uppercase tracking-[0.18em] text-ai-700 font-semibold">SOFIA · La toma</span>
          </div>
          <p className="text-sm text-ink-900 leading-relaxed">
            <b>{c.name.split(' ')[0]}</b> es un fuerte fit del {c.matchScore}% para roles bilingües de cobranza outbound. Demuestra
            <b className="text-emerald-700"> manejo de objeciones avanzado</b> y un patrón consistente de superar cuotas mensuales (~115%). El screening de SOFIA Call mostró
            <b className="text-emerald-700"> tono cálido y firmeza al mismo tiempo</b>, sin lapsus de inglés.
          </p>
          <div className="grid grid-cols-2 gap-4 mt-5">
            <div>
              <div className="text-[10px] uppercase tracking-[0.18em] text-emerald-700 mb-2 flex items-center gap-1.5 font-semibold">
                <Icon.ThumbsUp size={10} /> Fortalezas
              </div>
              <ul className="space-y-1.5 text-xs text-ink-800">
                <li className="flex gap-2"><span className="text-emerald-600 mt-1">▪</span>Inglés C1 verificado en vivo</li>
                <li className="flex gap-2"><span className="text-emerald-600 mt-1">▪</span>4 años de experiencia outbound · cartera US</li>
                <li className="flex gap-2"><span className="text-emerald-600 mt-1">▪</span>Cuota cumplida 9 de últimos 12 meses</li>
                <li className="flex gap-2"><span className="text-emerald-600 mt-1">▪</span>Manejo de CRM (Salesforce + Zoho)</li>
              </ul>
            </div>
            <div>
              <div className="text-[10px] uppercase tracking-[0.18em] text-ai-700 mb-2 flex items-center gap-1.5 font-semibold">
                <Icon.AlertCircle size={10} /> Brechas / a validar
              </div>
              <ul className="space-y-1.5 text-xs text-ink-800">
                <li className="flex gap-2"><span className="text-ai-600 mt-1">▪</span>Sin experiencia en finanzas — entrenamiento de producto requerido</li>
                <li className="flex gap-2"><span className="text-ai-600 mt-1">▪</span>Expectativa salarial ligeramente arriba del rango</li>
                <li className="flex gap-2"><span className="text-ai-600 mt-1">▪</span>Modalidad: prefiere híbrido (vacante es on-site)</li>
              </ul>
            </div>
          </div>
        </Card>

        <Card className="p-5">
          <div className="text-[11px] uppercase tracking-[0.18em] text-ink-500 mb-3 flex items-center gap-1.5 font-medium">
            <Icon.Notebook size={11} /> Preguntas sugeridas para entrevista
          </div>
          <ul className="space-y-2.5 text-sm">
            <SuggestQ n="1" q='Cuéntame un caso donde un cliente moroso te ofreció una excusa elaborada — ¿cómo desarmaste la objeción?' />
            <SuggestQ n="2" q='En tu cartera anterior, ¿qué patrón usabas para identificar a los clientes que sí pagarían vs. los que no?' />
            <SuggestQ n="3" q='Has trabajado en cartera prime y subprime. ¿En cuál sentís que aportas más valor y por qué?' />
          </ul>
        </Card>
      </div>
      <div className="col-span-4 space-y-3">
        <Card className="p-4">
          <div className="text-[11px] uppercase tracking-[0.18em] text-ink-500 mb-3 font-medium">Skills declaradas</div>
          <div className="flex flex-wrap gap-1.5">
            {c.skills.map((s) => <Pill key={s} tone="brand" size="sm">{s}</Pill>)}
          </div>
        </Card>
        <Card className="p-4">
          <div className="text-[11px] uppercase tracking-[0.18em] text-ink-500 mb-3 font-medium">Métricas clave</div>
          <KV k="Aplicó" v={c.appliedAt} />
          <KV k="Fuente" v={c.source} />
          <KV k="Sentimiento" v={c.sentiment} />
          <KV k="Última actividad" v="hace 12 min" last />
        </Card>
        <Card className="p-4 border-brand-200 bg-brand-50/40">
          <div className="flex items-center gap-2 mb-2">
            <Icon.SofiaMark size={16} />
            <span className="text-xs font-semibold text-ink-900">SOFIA confianza</span>
          </div>
          <div className="text-3xl font-semibold gradient-text tabular leading-none">{Math.min(99, c.matchScore + 5)}%</div>
          <div className="text-[11px] text-ink-500 mt-1">Basado en 1,240 contrataciones históricas con perfiles análogos.</div>
        </Card>
      </div>
    </div>
  );
}

function SuggestQ({ n, q }) {
  return (
    <li className="flex gap-3 p-3 rounded-lg bg-ink-50 border border-line">
      <span className="h-6 w-6 rounded-md bg-brand-50 text-brand-600 text-xs flex items-center justify-center font-semibold tabular shrink-0">{n}</span>
      <span className="text-ink-800">{q}</span>
    </li>
  );
}

function KV({ k, v, last }) {
  return (
    <div className={`flex justify-between text-xs py-1.5 ${last ? '' : 'border-b border-line2'}`}>
      <span className="text-ink-500">{k}</span>
      <span className="text-ink-900 font-medium">{v}</span>
    </div>
  );
}

function CVTab({ c }) {
  return (
    <div className="grid grid-cols-12 gap-5">
      <Card className="col-span-8 p-6">
        <div className="border-b border-line pb-4 mb-4">
          <div className="text-xl font-semibold text-ink-900">{c.name}</div>
          <div className="text-sm text-ink-500 mt-0.5">{c.role} · {c.city}, {c.country}</div>
          <div className="text-xs text-ink-500 mt-1">{c.languages.join(' · ')} · {c.education}</div>
        </div>
        <CvSection title="Experiencia">
          <CvJob role={c.role} company="BPO Centroamericano" range="2024 — Presente · 14 meses" bullets={[
            'Manejo de cartera US prime de USD $2.4M con 78% de recuperación promedio.',
            'Top performer Q1 2026 con 117% de cumplimiento de cuota.',
            'Capacitación a 8 agentes nuevos en manejo de objeciones avanzadas.',
          ]} />
          <CvJob role="Asesor de Cobranza" company="Contact Center Internacional" range="2022 — 2024 · 22 meses" bullets={[
            'Cartera bilingüe (Español/Inglés) outbound y back-office.',
            'Promedio 60+ llamadas/día con CSAT 4.6/5.',
          ]} />
          <CvJob role="Agente Customer Support" company="Service Center Global" range="2020 — 2022" bullets={[
            'Soporte técnico nivel 1 para clientes US.',
            'Certificación interna en manejo de quejas.',
          ]} />
        </CvSection>
        <CvSection title="Educación">
          <div className="text-sm text-ink-900 font-medium">{c.education}</div>
          <div className="text-xs text-ink-500">Universidad Centroamericana · 2018 – 2022</div>
        </CvSection>
        <CvSection title="Certificaciones">
          <div className="flex flex-wrap gap-1.5">
            <Pill tone="slate" size="sm">TOEFL iBT 102/120</Pill>
            <Pill tone="slate" size="sm">Salesforce Trailhead</Pill>
            <Pill tone="slate" size="sm">Six Sigma White Belt</Pill>
          </div>
        </CvSection>
      </Card>
      <div className="col-span-4">
        <Card className="p-4">
          <div className="text-[11px] uppercase tracking-[0.18em] text-ink-500 mb-3 font-medium">Documento</div>
          <div className="rounded-lg bg-ink-50 border border-line p-4 text-center">
            <Icon.File size={28} className="text-brand-500 mx-auto mb-2" />
            <div className="text-sm font-medium text-ink-900 truncate">{c.name}_CV.pdf</div>
            <div className="text-[11px] text-ink-500 mt-0.5">2.4 MB · sub. {c.appliedAt}</div>
            <div className="flex gap-2 mt-3">
              <Button size="sm" variant="default" icon={<Icon.Download size={11} />} className="flex-1">Descargar</Button>
              <Button size="sm" variant="ghost" icon={<Icon.Eye size={11} />}>Abrir</Button>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
}

function CvSection({ title, children }) {
  return (
    <div className="mb-5">
      <div className="text-[10px] uppercase tracking-[0.18em] text-brand-600 mb-2 font-semibold">{title}</div>
      <div className="space-y-4">{children}</div>
    </div>
  );
}

function CvJob({ role, company, range, bullets }) {
  return (
    <div>
      <div className="text-sm font-medium text-ink-900">{role} · <span className="text-ink-500 font-normal">{company}</span></div>
      <div className="text-[11px] text-ink-500 mb-1">{range}</div>
      <ul className="space-y-1 mt-1">
        {bullets.map((b, i) => (
          <li key={i} className="text-xs text-ink-700 flex gap-2"><span className="text-brand-400 mt-1">▪</span>{b}</li>
        ))}
      </ul>
    </div>
  );
}

function FitTab({ c, radarAxes, radarData }) {
  return (
    <div className="grid grid-cols-12 gap-5">
      <Card className="col-span-7 p-5">
        <div className="flex items-center justify-between mb-2">
          <div>
            <div className="text-[10px] uppercase tracking-[0.18em] text-ink-500 font-medium">SOFIA Skills Fit</div>
            <div className="text-sm font-semibold text-ink-900">Candidato vs. perfil ideal</div>
          </div>
          <div className="flex items-center gap-3 text-[11px]">
            <div className="flex items-center gap-1.5 text-ink-700"><span className="h-2 w-2 rounded-full bg-brand-500" /> Candidato</div>
            <div className="flex items-center gap-1.5 text-ink-700"><span className="h-2 w-2 rounded-full bg-ai-600" /> Requerido</div>
          </div>
        </div>
        <div className="flex justify-center">
          <Radar axes={radarAxes} data={radarData} size={300} />
        </div>
      </Card>
      <div className="col-span-5 space-y-2">
        {radarAxes.map((a, i) => {
          const v = radarData.candidate[i], r = radarData.requirement[i];
          const delta = v - r;
          return (
            <Card key={a} className="p-3 flex items-center gap-3">
              <div className="text-xs text-ink-800 w-20 shrink-0 font-medium">{a}</div>
              <div className="flex-1"><MatchBar value={v} size="sm" /></div>
              <div className={`tabular text-xs font-semibold w-10 text-right ${
                delta >= 0 ? 'text-emerald-600' : 'text-ai-700'
              }`}>
                {delta >= 0 ? '+' : ''}{delta}
              </div>
            </Card>
          );
        })}
      </div>
    </div>
  );
}

function TimelineTab({ events }) {
  return (
    <div className="max-w-2xl space-y-1">
      {events.map((e, i) => {
        const I = Icon[e.icon] || Icon.Dot;
        const tones = {
          emerald: 'bg-emerald-50 text-emerald-700 border-emerald-100',
          brand:   'bg-brand-50 text-brand-600 border-brand-100',
          sky:     'bg-sky-50 text-sky-700 border-sky-100',
          amber:   'bg-ai-50 text-ai-700 border-ai-100',
        };
        return (
          <div key={i} className="flex gap-4 relative pl-8 pb-5">
            {i < events.length - 1 && <div className="absolute left-[14px] top-7 bottom-0 w-px bg-line" />}
            <div className={`absolute left-0 top-1 h-7 w-7 rounded-full flex items-center justify-center border ${tones[e.tone]}`}>
              <I size={13} />
            </div>
            <div className="flex-1">
              <div className="flex items-center gap-2 text-xs text-ink-500">{e.t}</div>
              <div className="text-sm font-medium text-ink-900 mt-0.5">{e.title}</div>
              <div className="text-xs text-ink-600 mt-0.5">{e.body}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { CandidatesScreen, CandidateDetail });
