// Job Requisitions — list + detail panel. LIGHT.

const { useState: usR } = React;

function RequisitionsScreen({ onOpenCandidate }) {
  const [selectedId, setSelectedId] = usR(DATA.REQUISITIONS[0].id);
  const [filterStatus, setFilterStatus] = usR('Active');
  const [search, setSearch] = usR('');
  const [view, setView] = usR('list');

  const filtered = DATA.REQUISITIONS.filter((r) => {
    if (filterStatus !== 'All' && r.status !== filterStatus) return false;
    if (search && !(`${r.title} ${r.client}`.toLowerCase().includes(search.toLowerCase()))) return false;
    return true;
  });

  const selected = DATA.REQUISITIONS.find((r) => r.id === selectedId) || filtered[0];
  const client = selected ? DATA.CLIENTS.find((c) => c.id === selected.clientId) : null;
  const matchedCandidates = selected
    ? DATA.CANDIDATES.filter((c) => c.matchedReq === selected.id || c.matchScore >= 80).slice(0, 6)
    : [];

  return (
    <Page id="requisitions">
      <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.Briefcase size={12} /> Vacantes
          </div>
          <h1 className="text-2xl font-semibold tracking-tight text-ink-900">Requisiciones abiertas</h1>
          <p className="text-sm text-ink-500 mt-1">7 activas · 1 borrador · 0 en pausa · 142 nuevos matches generados por SOFIA esta semana.</p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="default" icon={<Icon.Download size={14} />}>Exportar</Button>
          <Button variant="primary" icon={<Icon.Plus size={14} />}>Nueva requisición</Button>
        </div>
      </div>

      <div className="flex items-center gap-3 mb-4">
        <div className="flex-1 max-w-md">
          <Input value={search} onChange={setSearch} placeholder="Buscar por rol, cliente o ciudad…" icon={<Icon.Search size={13} />} />
        </div>
        <Tabs
          value={filterStatus} onChange={setFilterStatus}
          tabs={[
            { id: 'All',    label: 'Todas',      count: DATA.REQUISITIONS.length },
            { id: 'Active', label: 'Activas',    count: DATA.REQUISITIONS.filter(r=>r.status==='Active').length },
            { id: 'Draft',  label: 'Borradores', count: DATA.REQUISITIONS.filter(r=>r.status==='Draft').length },
          ]}
        />
        <div className="ml-auto flex items-center gap-1 bg-ink-100 border border-line2 rounded-lg p-1">
          <IconButton size="sm" variant={view==='list'?'soft':'ghost'} icon={<Icon.List size={13} />} onClick={() => setView('list')} />
          <IconButton size="sm" variant={view==='grid'?'soft':'ghost'} icon={<Icon.Grid size={13} />} onClick={() => setView('grid')} />
        </div>
      </div>

      <div className="grid grid-cols-12 gap-5">
        {/* Table */}
        <Card className="col-span-7 overflow-hidden">
          <div className="grid grid-cols-[1fr_120px_90px_90px_90px] text-[10px] uppercase tracking-[0.18em] text-ink-500 px-4 py-2.5 border-b border-line bg-ink-50 font-medium">
            <div>Vacante · Cliente</div>
            <div>Match AI</div>
            <div className="text-right">Matches</div>
            <div className="text-right">Plazas</div>
            <div className="text-right">Deadline</div>
          </div>
          <div className="divide-y divide-line2 max-h-[640px] overflow-y-auto">
            {filtered.map((r) => {
              const c = DATA.CLIENTS.find((x) => x.id === r.clientId);
              const active = selected?.id === r.id;
              return (
                <button
                  key={r.id}
                  onClick={() => setSelectedId(r.id)}
                  className={`w-full grid grid-cols-[1fr_120px_90px_90px_90px] items-center text-sm px-4 py-3.5 text-left transition-colors ${
                    active ? 'bg-brand-50/50' : 'hover:bg-ink-50'
                  }`}
                >
                  <div className="flex items-center gap-3 min-w-0">
                    <div className={`h-9 w-9 rounded-lg bg-gradient-to-br ${c.logoBg} flex items-center justify-center text-white text-[11px] font-bold shrink-0`}>
                      {c.monogram}
                    </div>
                    <div className="min-w-0">
                      <div className="text-ink-900 font-medium truncate flex items-center gap-1.5">
                        {r.title}
                        {r.priority === 'High' && <Icon.Flame size={11} className="text-rose-600" />}
                      </div>
                      <div className="text-[11px] text-ink-500 truncate flex items-center gap-1.5">
                        <span>{r.client}</span>
                        <span className="h-0.5 w-0.5 rounded-full bg-ink-300" />
                        <span>{r.location}</span>
                        <span className="h-0.5 w-0.5 rounded-full bg-ink-300" />
                        <span>{r.modality}</span>
                      </div>
                    </div>
                  </div>
                  <div className="pr-3"><MatchBar value={r.aiQuality} size="sm" /></div>
                  <div className="tabular text-right text-ink-900 font-semibold">{r.matched}</div>
                  <div className="tabular text-right text-ink-700">{r.openings}</div>
                  <div className="tabular text-right text-[11px] text-ink-500">
                    {r.deadline.split('-').slice(1).reverse().join('/')}
                  </div>
                </button>
              );
            })}
          </div>
        </Card>

        {/* Detail */}
        <div className="col-span-5 space-y-4">
          {selected && client && (
            <>
              <Card className="p-5">
                <div className="flex items-start gap-3 mb-4">
                  <div className={`h-12 w-12 rounded-xl bg-gradient-to-br ${client.logoBg} flex items-center justify-center text-white text-sm font-bold shrink-0`}>
                    {client.monogram}
                  </div>
                  <div className="flex-1">
                    <div className="text-[11px] text-ink-500">{client.name} · {client.city}</div>
                    <div className="text-lg font-semibold text-ink-900">{selected.title}</div>
                    <div className="flex items-center gap-2 mt-2 flex-wrap">
                      <Pill tone="emerald" size="sm" icon={<Icon.Dot size={10} />}>{selected.status}</Pill>
                      <PriorityBadge value={selected.priority} />
                      <Pill tone="slate" size="sm" icon={<Icon.MapPin size={10} />}>{selected.location}</Pill>
                      <Pill tone="slate" size="sm" icon={<Icon.Building size={10} />}>{selected.modality}</Pill>
                    </div>
                  </div>
                </div>

                <div className="grid grid-cols-3 gap-2 mb-4">
                  <Stat label="Plazas" value={selected.openings} />
                  <Stat label="Matches" value={selected.matched} accent />
                  <Stat label="Deadline" value={selected.deadline.split('-').slice(1).reverse().join('/')} />
                </div>

                <div className="text-xs uppercase tracking-[0.16em] text-ink-500 mb-1.5 font-medium">Descripción</div>
                <p className="text-sm text-ink-800 leading-relaxed mb-4">{selected.description}</p>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <div className="text-xs uppercase tracking-[0.16em] text-ink-500 mb-2 font-medium">Must-have</div>
                    <div className="flex flex-wrap gap-1.5">
                      {selected.mustHave.map((s) => <Pill key={s} tone="brand" size="sm">{s}</Pill>)}
                    </div>
                  </div>
                  <div>
                    <div className="text-xs uppercase tracking-[0.16em] text-ink-500 mb-2 font-medium">Nice-to-have</div>
                    <div className="flex flex-wrap gap-1.5">
                      {selected.niceHave.map((s) => <Pill key={s} tone="slate" size="sm">{s}</Pill>)}
                    </div>
                  </div>
                </div>

                <Divider className="my-4" />

                <div className="flex items-center justify-between text-sm">
                  <div className="flex items-center gap-1.5 text-ink-800">
                    <Icon.Wallet size={13} className="text-ink-500" /> {selected.salary}
                  </div>
                  <div className="flex items-center gap-1.5 text-ink-500 text-xs">
                    <Icon.Calendar size={12} /> Abierta {selected.opened}
                  </div>
                </div>
              </Card>

              <Card className="p-5 border-ai-200 ai-soft">
                <div className="flex items-center gap-2 mb-2">
                  <Icon.Sparkles size={13} className="text-ai-600" />
                  <span className="text-[10px] uppercase tracking-[0.18em] text-ai-700 font-semibold">SOFIA · Perfil ideal extraído</span>
                </div>
                <p className="text-sm text-ink-800 leading-relaxed">{selected.profile}</p>
                <div className="flex flex-wrap gap-1.5 mt-3">
                  {selected.soft.map((s) => <Pill key={s} tone="amber" size="sm">{s}</Pill>)}
                </div>
              </Card>

              <Card className="p-5">
                <div className="flex items-center justify-between mb-3">
                  <div>
                    <div className="text-[10px] uppercase tracking-[0.18em] text-ink-500 font-medium">Candidatos rankeados por SOFIA</div>
                    <div className="text-sm font-semibold text-ink-900">Top {matchedCandidates.length} · de {selected.matched} matches</div>
                  </div>
                  <button className="text-[11px] text-brand-600 hover:text-brand-700 flex items-center gap-1 font-medium">
                    Ver todos <Icon.ArrowRight size={11} />
                  </button>
                </div>
                <div className="space-y-2">
                  {matchedCandidates.map((c) => (
                    <button key={c.id} onClick={() => onOpenCandidate(c)}
                      className="w-full flex items-center gap-3 p-2.5 rounded-lg border border-line hover:border-brand-300 hover:bg-brand-50/30 hover-lift bg-white text-left">
                      <Avatar name={c.name} color={c.avatarColor} size={32} />
                      <div className="flex-1 min-w-0">
                        <div className="text-sm font-medium text-ink-900 truncate">{c.name}</div>
                        <div className="text-[11px] text-ink-500 truncate">{c.role} · {c.yearsExperience}y · {c.city}</div>
                      </div>
                      <div className="w-24 shrink-0"><MatchBar value={c.matchScore} size="sm" /></div>
                    </button>
                  ))}
                </div>
              </Card>
            </>
          )}
        </div>
      </div>
    </Page>
  );
}

function Stat({ label, value, accent }) {
  return (
    <div className={`p-3 rounded-lg border ${accent ? 'border-brand-200 bg-brand-50/40' : 'border-line bg-ink-50'}`}>
      <div className="text-[10px] uppercase tracking-[0.16em] text-ink-500 font-medium">{label}</div>
      <div className={`text-xl font-semibold tabular ${accent ? 'gradient-text' : 'text-ink-900'}`}>{value}</div>
    </div>
  );
}

window.RequisitionsScreen = RequisitionsScreen;
