// AI Screening — SOFIA Call integration. LIGHT.

const { useState: usS } = React;

function ScreeningScreen({ onLaunchCall }) {
  const [tab, setTab] = usS('all');
  const [selectedId, setSelectedId] = usS('call-001');

  const filtered = DATA.SCREENING_CALLS.filter((c) => {
    if (tab === 'completed') return c.status === 'Completed';
    if (tab === 'scheduled') return c.status === 'Scheduled';
    return true;
  });

  const selected = DATA.SCREENING_CALLS.find((c) => c.id === selectedId) || filtered[0];
  const candidate = selected ? DATA.CANDIDATES.find((x) => x.id === selected.candidateId) : null;

  return (
    <Page id="screening">
      <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.PhoneCall size={12} /> AI Screening · powered by <span className="gradient-text font-semibold">SOFIA Call</span>
          </div>
          <h1 className="text-2xl font-semibold tracking-tight text-ink-900">Screenings con voz AI</h1>
          <p className="text-sm text-ink-500 mt-1">
            SOFIA Call entrevista, transcribe y recomienda. <b className="text-ink-900">142 screenings</b> esta semana con <b className="text-ink-900">94% de precisión</b> vs. operador humano.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="default" icon={<Icon.Wand size={14} />}>Editar script</Button>
          <Button variant="primary" icon={<Icon.PlayCircle size={14} />}>Lanzar screening</Button>
        </div>
      </div>

      {/* KPIs */}
      <div className="grid grid-cols-4 gap-4 mb-5">
        <KpiCard label="Completadas hoy" value="18" sub="meta: 24" icon={<Icon.PhoneIn size={14} />} trend={{ dir: 'up', value: '+4' }}
          accent="radial-gradient(circle, #10b981, transparent 70%)" />
        <KpiCard label="Agendadas mañana" value="22" sub="6:00 am – 8:00 pm" icon={<Icon.CalendarClock size={14} />}
          accent="radial-gradient(circle, #4f46e5, transparent 70%)" />
        <KpiCard label="Duración promedio" value="7:24" sub="−18% vs. operador" icon={<Icon.Clock size={14} />}
          trend={{ dir: 'down', value: '−1:08' }} accent="radial-gradient(circle, #a855f7, transparent 70%)" />
        <KpiCard label="Tasa Advance" value="58%" sub="filtrado de calidad" icon={<Icon.ThumbsUp size={14} />}
          trend={{ dir: 'up', value: '+6%' }} accent="radial-gradient(circle, #d97706, transparent 70%)" />
      </div>

      <div className="grid grid-cols-12 gap-5">
        {/* List */}
        <Card className="col-span-5 overflow-hidden">
          <div className="px-4 py-3 border-b border-line flex items-center justify-between">
            <Tabs
              value={tab} onChange={setTab}
              tabs={[
                { id: 'all', label: 'Todas', count: DATA.SCREENING_CALLS.length },
                { id: 'completed', label: 'Completadas', count: DATA.SCREENING_CALLS.filter(c=>c.status==='Completed').length },
                { id: 'scheduled', label: 'Agendadas', count: DATA.SCREENING_CALLS.filter(c=>c.status==='Scheduled').length },
              ]}
            />
            <IconButton size="sm" variant="ghost" icon={<Icon.Refresh size={12} />} title="Refrescar" />
          </div>
          <div className="divide-y divide-line2 max-h-[640px] overflow-y-auto">
            {filtered.map((c) => {
              const cand = DATA.CANDIDATES.find((x) => x.id === c.candidateId);
              const active = selectedId === c.id;
              return (
                <button
                  key={c.id}
                  onClick={() => setSelectedId(c.id)}
                  className={`w-full flex items-start gap-3 p-4 text-left transition-colors ${
                    active ? 'bg-brand-50/50' : 'hover:bg-ink-50'
                  }`}
                >
                  <Avatar name={c.candidateName} color={cand?.avatarColor} size={36} />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <div className="text-sm font-semibold text-ink-900 truncate">{c.candidateName}</div>
                      {c.status === 'Scheduled' && <Pill tone="sky" size="sm" icon={<Icon.Clock size={10} />}>{c.scheduled}</Pill>}
                    </div>
                    <div className="text-[11px] text-ink-500 truncate">{c.role} · {c.client}</div>
                    <div className="flex items-center gap-2 mt-2">
                      {c.status === 'Completed' ? (
                        <>
                          <Pill tone="slate" size="sm" icon={<Icon.Clock size={9} />}>{c.duration}</Pill>
                          <RecoBadge value={c.recommendation} />
                          <span className="text-[11px] text-ink-500 tabular">conf. {c.recoConfidence}%</span>
                        </>
                      ) : (
                        <Pill tone="amber" size="sm" icon={<Icon.CalendarClock size={10} />}>Pendiente</Pill>
                      )}
                    </div>
                  </div>
                </button>
              );
            })}
          </div>
        </Card>

        {/* Detail */}
        <div className="col-span-7 space-y-4">
          {selected && (
            <>
              {selected.status === 'Completed' ? (
                <CallDetail call={selected} candidate={candidate} />
              ) : (
                <ScheduledCall call={selected} candidate={candidate} onLaunch={() => candidate && onLaunchCall(candidate)} />
              )}

              {/* Live launcher */}
              <Card className="p-5 border-brand-200 bg-gradient-to-br from-white to-brand-50/30">
                <div className="flex items-center gap-4">
                  <div className="h-12 w-12 rounded-xl gradient-bg flex items-center justify-center text-white shadow-sm">
                    <Icon.PhoneCall size={20} />
                  </div>
                  <div className="flex-1">
                    <div className="text-sm font-semibold text-ink-900">Lanzar screening ahora con SOFIA Call</div>
                    <div className="text-xs text-ink-500 mt-0.5">Selecciona un candidato del pool y SOFIA marcará en menos de 8 segundos.</div>
                  </div>
                  <select className="h-9 bg-white border border-line rounded-lg px-3 text-sm text-ink-900 max-w-[200px]">
                    {DATA.CANDIDATES.slice(0, 10).map((c) => (
                      <option key={c.id} value={c.id}>{c.name}</option>
                    ))}
                  </select>
                  <Button variant="primary" icon={<Icon.PlayCircle size={14} />}
                          onClick={() => onLaunchCall(DATA.CANDIDATES[0])}>
                    Iniciar
                  </Button>
                </div>
              </Card>

              {/* Script panel */}
              <Card className="p-5">
                <div className="flex items-center justify-between mb-3">
                  <div>
                    <div className="text-[11px] uppercase tracking-[0.18em] text-ink-500 font-medium">Configurar screening</div>
                    <div className="text-sm font-semibold text-ink-900">Script de 5 preguntas · ES/EN</div>
                  </div>
                  <Button size="sm" variant="default" icon={<Icon.Wand size={12} />}>Generar con SOFIA</Button>
                </div>
                <div className="space-y-2">
                  {DATA.SCREENING_QUESTIONS.map((q, i) => (
                    <div key={i} className="flex items-start gap-3 p-2.5 rounded-lg bg-ink-50 border border-line">
                      <span className="h-6 w-6 rounded-md bg-brand-50 text-brand-600 text-xs font-semibold tabular flex items-center justify-center shrink-0">{i + 1}</span>
                      <span className="text-sm text-ink-800 flex-1">{q}</span>
                      <IconButton size="sm" variant="ghost" icon={<Icon.More size={12} />} />
                    </div>
                  ))}
                </div>
                <button className="mt-2 w-full h-9 rounded-lg border border-dashed border-ink-300 text-sm text-ink-500 hover:text-ink-900 hover:border-ink-400 flex items-center justify-center gap-2 transition">
                  <Icon.Plus size={13} /> Agregar pregunta
                </button>
              </Card>
            </>
          )}
        </div>
      </div>
    </Page>
  );
}

function CallDetail({ call, candidate }) {
  const sentimentTone = call.sentiment === 'Positive' || call.sentiment === 'Enthusiastic' ? 'emerald'
                      : call.sentiment === 'Neutral' ? 'amber' : 'rose';

  return (
    <Card className="p-5">
      <div className="flex items-start gap-4 mb-4">
        <Avatar name={call.candidateName} color={candidate?.avatarColor} size={48} />
        <div className="flex-1">
          <div className="flex items-center gap-2">
            <span className="text-base font-semibold text-ink-900">{call.candidateName}</span>
            <Pill tone="emerald" size="sm" icon={<Icon.CheckCircle size={10} />}>Completada</Pill>
          </div>
          <div className="text-xs text-ink-500 mt-0.5">{call.role} · {call.client}</div>
          <div className="flex items-center gap-3 mt-2 text-[11px] text-ink-500">
            <span className="flex items-center gap-1"><Icon.Clock size={10} /> {call.duration}</span>
            <span className="flex items-center gap-1"><Icon.CalendarClock size={10} /> {call.completed}</span>
          </div>
        </div>
        <div className="text-right">
          <RecoBadge value={call.recommendation} />
          <div className="text-[11px] text-ink-500 mt-1">conf. <b className="text-ink-900">{call.recoConfidence}%</b></div>
        </div>
      </div>

      <div className="rounded-xl bg-ink-50 border border-line p-4 mb-4">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2">
            <Icon.Wave size={14} className="text-brand-500" />
            <span className="text-xs text-ink-700 font-medium">Transcripción & sentimiento</span>
          </div>
          <Pill tone={sentimentTone} size="sm" icon={
            call.sentiment === 'Positive' || call.sentiment === 'Enthusiastic' ? <Icon.Smile size={10} /> :
            call.sentiment === 'Neutral' ? <Icon.Meh size={10} /> : <Icon.Frown size={10} />
          }>
            {call.sentiment} · {call.sentimentScore}
          </Pill>
        </div>
        <div className="flex items-end gap-0.5 h-14 mb-3">
          {Array.from({ length: 80 }).map((_, i) => {
            const h = 30 + Math.abs(Math.sin(i * 0.45) * 70) + (i % 7) * 4;
            return (
              <div key={i} className="w-1 rounded-full"
                style={{ height: `${h}%`,
                  background: `linear-gradient(180deg, #4f46e5 ${30 + (i % 9)}%, #a855f7)`,
                  opacity: 0.45 + (i % 7) * 0.06 }} />
            );
          })}
        </div>
        <div className="flex items-center justify-between text-[11px] text-ink-500 tabular">
          <span>00:00</span><span>{call.duration}</span>
        </div>
        <div className="mt-3 flex items-center gap-2">
          <IconButton size="sm" icon={<Icon.Play size={12} />} variant="primary" />
          <IconButton size="sm" icon={<Icon.Volume size={12} />} variant="default" />
          <div className="ml-auto flex gap-2">
            <Button size="sm" variant="default" icon={<Icon.File size={11} />}>Transcripción</Button>
            <Button size="sm" variant="default" icon={<Icon.Download size={11} />}>Audio</Button>
          </div>
        </div>
      </div>

      <div className="text-[11px] uppercase tracking-[0.18em] text-ink-500 mb-2 flex items-center gap-1.5 font-medium">
        <Icon.Message size={11} /> Respuestas extraídas
      </div>
      <div className="space-y-2 mb-4">
        {call.answers.map((a, i) => (
          <div key={i} className="rounded-lg border border-line bg-white p-3">
            <div className="text-xs text-brand-600 font-medium mb-1">{a.q}</div>
            <div className="text-sm text-ink-800">{a.a}</div>
          </div>
        ))}
      </div>

      <div className="rounded-xl border border-ai-200 ai-soft p-4">
        <div className="flex items-center gap-2 mb-2">
          <Icon.Sparkles size={13} className="text-ai-600" />
          <span className="text-[11px] uppercase tracking-[0.18em] text-ai-700 font-semibold">SOFIA · Notas y razonamiento</span>
        </div>
        <p className="text-sm text-ink-800 leading-relaxed">{call.aiNotes}</p>
        <div className="flex gap-2 mt-3">
          <Button size="sm" variant="success" icon={<Icon.ThumbsUp size={12} />}>Avanzar</Button>
          <Button size="sm" variant="default" icon={<Icon.Hand size={12} />}>Hold</Button>
          <Button size="sm" variant="default" icon={<Icon.ThumbsDown size={12} />}>Rechazar</Button>
        </div>
      </div>
    </Card>
  );
}

function ScheduledCall({ call, candidate, onLaunch }) {
  return (
    <Card className="p-5">
      <div className="flex items-start gap-4 mb-4">
        <Avatar name={call.candidateName} color={candidate?.avatarColor} size={48} />
        <div className="flex-1">
          <div className="flex items-center gap-2">
            <span className="text-base font-semibold text-ink-900">{call.candidateName}</span>
            <Pill tone="sky" size="sm" icon={<Icon.CalendarClock size={10} />}>Agendada</Pill>
          </div>
          <div className="text-xs text-ink-500 mt-0.5">{call.role} · {call.client}</div>
        </div>
      </div>
      <div className="grid grid-cols-3 gap-3 mb-4">
        <Card className="p-3 bg-ink-50">
          <div className="text-[10px] uppercase tracking-[0.18em] text-ink-500 font-medium">Programada</div>
          <div className="text-base font-semibold text-ink-900 mt-1">{call.scheduled}</div>
        </Card>
        <Card className="p-3 bg-ink-50">
          <div className="text-[10px] uppercase tracking-[0.18em] text-ink-500 font-medium">Duración estimada</div>
          <div className="text-base font-semibold text-ink-900 mt-1">~8 min</div>
        </Card>
        <Card className="p-3 bg-ink-50">
          <div className="text-[10px] uppercase tracking-[0.18em] text-ink-500 font-medium">Script</div>
          <div className="text-base font-semibold text-ink-900 mt-1">5 preguntas · ES</div>
        </Card>
      </div>
      <div className="flex items-center justify-between p-4 rounded-xl bg-brand-50/50 border border-brand-200">
        <div className="flex items-center gap-3">
          <Icon.SofiaMark size={22} />
          <div>
            <div className="text-sm font-medium text-ink-900">SOFIA Call está lista</div>
            <div className="text-[11px] text-ink-600">Llamará automáticamente al horario agendado · o lánzala ahora.</div>
          </div>
        </div>
        <div className="flex gap-2">
          <Button variant="default" icon={<Icon.CalendarClock size={12} />}>Reagendar</Button>
          <Button variant="primary" icon={<Icon.PlayCircle size={12} />} onClick={onLaunch}>Lanzar ahora</Button>
        </div>
      </div>
    </Card>
  );
}

window.ScreeningScreen = ScreeningScreen;
