// Interviews & Outreach — SOFIA Chat (WhatsApp) inbox. LIGHT enterprise.

const { useState: usI, useEffect: ueI, useRef: urI } = React;

function InterviewsScreen({ onOpenCampaign }) {
  const [tab, setTab] = usI('all');
  const [search, setSearch] = usI('');
  const [selectedId, setSelectedId] = usI(DATA.THREADS[0].id);
  const [draft, setDraft] = usI('');
  const [railOpen, setRailOpen] = usI(true);
  const [userToggledRail, setUserToggledRail] = usI(false);
  const containerRef = urI(null);
  const toast = useToast();
  const endRef = urI(null);

  ueI(() => { setDraft(''); }, [selectedId]);
  ueI(() => { endRef.current?.scrollIntoView?.({ block: 'end' }); }, [selectedId]);

  // Auto-collapse right rail at narrow widths (only if user hasn't manually toggled)
  ueI(() => {
    if (!containerRef.current) return;
    const ro = new ResizeObserver(([entry]) => {
      if (userToggledRail) return;
      const w = entry.contentRect.width;
      setRailOpen(w >= 980);
    });
    ro.observe(containerRef.current);
    return () => ro.disconnect();
  }, [userToggledRail]);

  const handleRailToggle = (open) => { setUserToggledRail(true); setRailOpen(open); };

  const thread = DATA.THREADS.find((t) => t.id === selectedId);
  const candidate = thread ? DATA.CANDIDATES.find((x) => x.id === thread.candidateId) : null;
  const clientName = thread?.role.split('·')[1]?.trim() || 'el cliente';
  const roleName = thread?.role.split('·')[0]?.trim() || '';

  const filtered = DATA.THREADS.filter((t) => {
    if (tab === 'unread' && !t.unread) return false;
    if (tab === 'pinned' && !t.pinned) return false;
    if (search && !t.candidateName.toLowerCase().includes(search.toLowerCase()) &&
        !t.snippet.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  const aiSuggestion = thread?.id === 'thr-004'
    ? '¡Claro Valeria! Te propongo el miércoles 21 a las 11am o el jueves 22 a las 3pm, ambas opciones por videollamada. ¿Cuál te funciona mejor?'
    : thread?.id === 'thr-002'
    ? 'Gracias Karla. Adjunto el calendar invite con los detalles de la entrevista final. Cualquier duda estoy en línea.'
    : 'Gracias por tu mensaje. ¿Te parece si avanzamos con el siguiente paso esta semana? Tengo disponibilidad jueves y viernes.';

  const sendDraft = () => {
    if (!draft.trim()) return;
    toast?.push({ title: 'Mensaje enviado vía SOFIA Chat', body: `Entregado a ${thread.candidateName}.`, tone: 'success' });
    setDraft('');
  };

  const fillTemplate = (t) => {
    if (!candidate || !thread) return;
    setDraft(
      t.body
        .replace('{{nombre}}', candidate.name.split(' ')[0])
        .replace('{{rol}}', roleName || candidate.role)
        .replace('{{cliente}}', clientName)
        .replace('{{salario}}', 'USD $950')
        .replace('{{modalidad}}', 'Híbrido')
        .replace('{{fecha}}', 'mañana 10:00 am')
    );
  };

  return (
    <Page id="interviews">
      <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.Message size={12} /> Entrevistas & Outreach · powered by <span className="gradient-text font-semibold">SOFIA Chat</span>
          </div>
          <h1 className="text-2xl font-semibold tracking-tight text-ink-900">Inbox de candidatos</h1>
          <p className="text-sm text-ink-500 mt-1">
            Conversaciones WhatsApp orquestadas por SOFIA Chat · <b className="text-ink-900">38 activas</b>, <b className="text-ink-900">9 sin leer</b>.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="default" icon={<Icon.Filter size={14} />}>Filtros</Button>
          <Button variant="primary" icon={<Icon.Megaphone size={14} />} onClick={onOpenCampaign}>Campaña masiva</Button>
        </div>
      </div>

      <Card className="overflow-hidden">
        <div
          ref={containerRef}
          className="grid h-[calc(100vh-220px)] min-h-[640px] max-h-[820px]"
          style={{
            gridTemplateColumns: railOpen
              ? '280px minmax(0,1fr) 296px'
              : '280px minmax(0,1fr) 56px',
          }}
        >
          {/* ============ Threads ============ */}
          <ThreadList
            search={search} setSearch={setSearch}
            tab={tab} setTab={setTab}
            threads={filtered}
            selectedId={selectedId} setSelectedId={setSelectedId}
          />

          {/* ============ Conversation ============ */}
          <div className="flex flex-col min-w-0 overflow-hidden">
            {thread && candidate ? (
              <ConversationPane
                thread={thread} candidate={candidate}
                draft={draft} setDraft={setDraft} sendDraft={sendDraft}
                aiSuggestion={aiSuggestion} endRef={endRef}
                railOpen={railOpen} setRailOpen={handleRailToggle}
              />
            ) : (
              <div className="flex-1 flex items-center justify-center text-ink-500 text-sm">Selecciona una conversación</div>
            )}
          </div>

          {/* ============ Right rail ============ */}
          {railOpen ? (
            <RightRail
              candidate={candidate}
              thread={thread}
              onFillTemplate={fillTemplate}
              onCollapse={() => handleRailToggle(false)}
            />
          ) : (
            <CollapsedRail onExpand={() => handleRailToggle(true)} />
          )}
        </div>
      </Card>
    </Page>
  );
}

// ============================================================
// Thread list
// ============================================================
function ThreadList({ search, setSearch, tab, setTab, threads, selectedId, setSelectedId }) {
  return (
    <div className="border-r border-line flex flex-col min-h-0 bg-white">
      <div className="px-3 pt-3 pb-2 border-b border-line bg-sub space-y-2 shrink-0">
        <Input value={search} onChange={setSearch} placeholder="Buscar conversación…" icon={<Icon.Search size={13} />} size="sm" />
        <Tabs
          value={tab} onChange={setTab}
          tabs={[
            { id: 'all',    label: 'Todas',    count: DATA.THREADS.length },
            { id: 'unread', label: 'Sin leer', count: DATA.THREADS.filter(t=>t.unread).length },
            { id: 'pinned', label: 'Pin',      count: DATA.THREADS.filter(t=>t.pinned).length },
          ]}
        />
      </div>
      <div className="flex-1 min-h-0 overflow-y-auto">
        {threads.map((t) => {
          const c = DATA.CANDIDATES.find((x) => x.id === t.candidateId);
          const active = selectedId === t.id;
          return (
            <button
              key={t.id}
              onClick={() => setSelectedId(t.id)}
              className={`w-full flex items-start gap-3 px-3 py-3 text-left border-b border-line2 transition-colors relative ${
                active ? 'bg-brand-50/50' : 'hover:bg-ink-50'
              }`}
            >
              {active && <span className="absolute left-0 top-2 bottom-2 w-0.5 rounded-r bg-brand-500" />}
              <Avatar name={t.candidateName} color={c?.avatarColor} size={40} online={t.online} />
              <div className="flex-1 min-w-0">
                <div className="flex items-center justify-between gap-2">
                  <span className="text-sm font-semibold text-ink-900 truncate">{t.candidateName}</span>
                  <span className="text-[10px] text-ink-500 shrink-0 tabular">{t.lastTime}</span>
                </div>
                <div className="text-[11px] text-ink-500 truncate">{t.role}</div>
                <div className="flex items-center gap-1.5 mt-1.5">
                  <Icon.WhatsApp size={10} className="text-emerald-600 shrink-0" />
                  <span className={`text-[11px] truncate flex-1 ${t.unread ? 'text-ink-900 font-medium' : 'text-ink-600'}`}>{t.snippet}</span>
                  {t.unread > 0 && (
                    <span className="tabular text-[10px] h-4 px-1.5 inline-flex items-center rounded-full bg-emerald-600 text-white font-semibold shrink-0">{t.unread}</span>
                  )}
                  {t.pinned && <Icon.Pin size={9} className="text-ai-600 shrink-0" />}
                </div>
              </div>
            </button>
          );
        })}
        {threads.length === 0 && (
          <div className="px-6 py-12 text-center text-sm text-ink-500">Sin conversaciones</div>
        )}
      </div>
    </div>
  );
}

// ============================================================
// Conversation
// ============================================================
function ConversationPane({ thread, candidate, draft, setDraft, sendDraft, aiSuggestion, endRef, railOpen, setRailOpen }) {
  const clientLabel = thread.role.split('·')[1]?.trim() || '';
  const roleLabel = thread.role.split('·')[0]?.trim() || '';

  return (
    <>
      {/* Header */}
      <div className="px-5 py-3 border-b border-line flex items-center gap-3 bg-white shrink-0">
        <Avatar name={thread.candidateName} color={candidate.avatarColor} size={38} online={thread.online} />
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 min-w-0">
            <span className="text-sm font-semibold text-ink-900 truncate">{thread.candidateName}</span>
            <Pill tone="emerald" size="sm" icon={<Icon.WhatsApp size={9} />}>WhatsApp</Pill>
          </div>
          <div className="flex items-center gap-1.5 text-[11px] text-ink-500 mt-0.5 truncate">
            <span className={`h-1.5 w-1.5 rounded-full ${thread.online ? 'bg-emerald-500' : 'bg-ink-300'}`} />
            {thread.online ? 'en línea' : 'visto hace 2h'}
            {roleLabel && <><span className="text-ink-300">·</span><span className="truncate">{roleLabel}</span></>}
            {clientLabel && <><span className="text-ink-300">·</span><span className="truncate font-medium text-ink-700">{clientLabel}</span></>}
          </div>
        </div>
        <div className="flex items-center gap-1 shrink-0">
          <IconButton variant="ghost" size="sm" icon={<Icon.Phone size={14} />} title="Llamar" />
          <IconButton variant="ghost" size="sm" icon={<Icon.Search size={14} />} title="Buscar" />
          <IconButton variant="ghost" size="sm" icon={<Icon.More size={14} />} title="Más" />
          {!railOpen && (
            <IconButton variant="ghost" size="sm" icon={<Icon.PanelLeft size={14} className="rotate-180" />} title="Mostrar panel" onClick={() => setRailOpen(true)} />
          )}
        </div>
      </div>

      {/* Messages */}
      <div className="flex-1 min-h-0 overflow-y-auto px-6 py-5 space-y-3 wa-pattern">
        <div className="flex justify-center">
          <span className="text-[10px] uppercase tracking-wider text-ink-500 bg-white/80 border border-line rounded-full px-2.5 py-0.5">
            {thread.messages[0]?.t?.split('·')[0]?.trim() || 'hoy'}
          </span>
        </div>
        {thread.messages.map((m, i) => (
          <div key={i} className={`flex ${m.from === 'op' ? 'justify-end' : 'justify-start'}`}>
            <div className="max-w-[68%]">
              <div className={`relative px-3 py-2 rounded-2xl text-sm shadow-sm ${
                m.from === 'op'
                  ? 'bg-emerald-600 text-white rounded-tr-sm'
                  : 'bg-white border border-line text-ink-900 rounded-tl-sm'
              }`}>
                <div className="leading-relaxed">{m.text}</div>
                <div className={`text-[10px] mt-1 flex items-center justify-end gap-1 ${
                  m.from === 'op' ? 'text-emerald-100' : 'text-ink-500'
                }`}>
                  <span>{m.t.split('·')[1]?.trim() || m.t}</span>
                  {m.from === 'op' && <Icon.CheckCheck size={11} />}
                </div>
              </div>
            </div>
          </div>
        ))}
        <div ref={endRef} />
      </div>

      {/* SOFIA suggestion */}
      <div className="px-4 py-2.5 border-t border-line bg-ai-50/50 flex items-start gap-2.5 shrink-0">
        <span className="h-6 w-6 rounded-md bg-ai-100 text-ai-700 flex items-center justify-center shrink-0 mt-0.5">
          <Icon.Sparkles size={12} />
        </span>
        <div className="flex-1 min-w-0">
          <div className="text-[10px] uppercase tracking-[0.16em] text-ai-700 font-semibold mb-0.5">SOFIA sugiere</div>
          <div className="text-xs text-ink-800 leading-relaxed">{aiSuggestion}</div>
        </div>
        <div className="flex items-center gap-1 shrink-0">
          <Button size="sm" variant="amber" icon={<Icon.Check size={12} />} onClick={() => setDraft(aiSuggestion)}>Usar</Button>
          <IconButton size="sm" variant="ghost" icon={<Icon.X size={12} />} title="Descartar" />
        </div>
      </div>

      {/* Composer */}
      <div className="border-t border-line bg-white shrink-0">
        <div className="p-3 flex items-end gap-2">
          <div className="flex gap-0.5">
            <IconButton size="sm" variant="ghost" icon={<Icon.Paperclip size={14} />} title="Adjuntar" />
            <IconButton size="sm" variant="ghost" icon={<Icon.Smile size={14} />} title="Emoji" />
          </div>
          <div className="flex-1 min-w-0 bg-ink-50 border border-line focus-within:border-brand-400 focus-within:ring-4 focus-within:ring-brand-100 rounded-lg px-3 py-1.5 transition">
            <textarea
              value={draft}
              onChange={(e) => setDraft(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendDraft(); } }}
              placeholder="Escribe un mensaje…"
              rows={1}
              className="w-full bg-transparent text-sm text-ink-900 outline-none resize-none placeholder:text-ink-400 max-h-24"
            />
          </div>
          <Button variant="primary" icon={<Icon.Send size={14} />} onClick={sendDraft} disabled={!draft.trim()}>Enviar</Button>
        </div>
        <div className="px-3 pb-2 flex items-center gap-3 text-[10px] text-ink-500">
          <span className="flex items-center gap-1"><Icon.Shield size={9} /> Cifrado E2E</span>
          <span className="flex items-center gap-1"><Icon.WhatsApp size={9} className="text-emerald-600" /> Vía SOFIA Chat · WhatsApp Business</span>
          <span className="ml-auto">⏎ enviar · Shift+⏎ salto</span>
        </div>
      </div>
    </>
  );
}

// ============================================================
// Right rail
// ============================================================
function RightRail({ candidate, thread, onFillTemplate, onCollapse }) {
  if (!candidate || !thread) return null;
  return (
    <div className="border-l border-line flex flex-col min-h-0 bg-white">
      {/* Header */}
      <div className="px-4 py-3 border-b border-line flex items-center justify-between shrink-0">
        <div className="text-[10px] uppercase tracking-[0.18em] text-ink-500 font-semibold">Panel del candidato</div>
        <IconButton size="sm" variant="ghost" icon={<Icon.X size={12} />} title="Ocultar panel" onClick={onCollapse} />
      </div>

      {/* Scrollable */}
      <div className="flex-1 min-h-0 overflow-y-auto">
        {/* Candidate card */}
        <div className="px-4 py-4 border-b border-line">
          <div className="flex items-center gap-3 mb-3">
            <Avatar name={candidate.name} color={candidate.avatarColor} size={44} ring />
            <div className="flex-1 min-w-0">
              <div className="text-sm font-semibold text-ink-900 truncate">{candidate.name}</div>
              <div className="text-[11px] text-ink-500 truncate">{candidate.role}</div>
            </div>
          </div>
          <div className="rounded-lg border border-line bg-sub px-3 py-2.5 flex items-center justify-between mb-3">
            <div className="text-[10px] uppercase tracking-wider text-ink-500 font-medium">SOFIA Match</div>
            <div className="flex items-center gap-2">
              <div className="w-20"><MatchBar value={candidate.matchScore} size="sm" showLabel={false} /></div>
              <span className="tabular text-sm font-semibold gradient-text">{candidate.matchScore}%</span>
            </div>
          </div>
          <div className="space-y-1.5 text-xs">
            <KVRow icon={<Icon.MapPin size={11} />} k="Ubicación" v={`${candidate.city}, ${candidate.country}`} />
            <KVRow icon={<Icon.Clock size={11} />} k="Disponibilidad" v={candidate.availability} />
            <KVRow icon={<Icon.Wallet size={11} />} k="Salario" v={candidate.salaryExpected} />
            <KVRow icon={<Icon.Languages size={11} />} k="Idiomas" v={candidate.languages.join(' · ')} />
            <KVRow icon={<Icon.Tag size={11} />} k="Fuente" v={candidate.source} />
          </div>
        </div>

        {/* Templates */}
        <div className="px-4 py-4 border-b border-line">
          <div className="flex items-center justify-between mb-2.5">
            <div className="text-[10px] uppercase tracking-[0.18em] text-ink-500 font-semibold">Plantillas rápidas</div>
            <button className="text-[11px] text-brand-600 hover:text-brand-700 font-semibold">+ Nueva</button>
          </div>
          <div className="space-y-1.5">
            {DATA.TEMPLATES.slice(0, 5).map((t) => (
              <button key={t.id} onClick={() => onFillTemplate(t)}
                className="w-full text-left p-2.5 rounded-lg border border-line hover:border-brand-300 hover:bg-brand-50/30 transition flex items-start gap-2">
                <span className="h-6 w-6 rounded-md bg-brand-50 text-brand-600 flex items-center justify-center shrink-0">
                  <Icon.File size={11} />
                </span>
                <div className="min-w-0 flex-1">
                  <div className="text-xs font-medium text-ink-900 truncate">{t.name}</div>
                  <div className="text-[10px] text-ink-500 line-clamp-1 mt-0.5">{t.body}</div>
                </div>
                <Icon.ArrowRight size={11} className="text-ink-400 mt-1.5 shrink-0" />
              </button>
            ))}
          </div>
        </div>

        {/* AI Insight (per thread) */}
        <div className="px-4 py-4 border-b border-line">
          <div className="rounded-lg border border-ai-200 ai-soft p-3">
            <div className="flex items-center gap-1.5 mb-1.5">
              <Icon.Sparkles size={11} className="text-ai-600" />
              <div className="text-[10px] uppercase tracking-[0.18em] text-ai-700 font-semibold">Contexto SOFIA</div>
            </div>
            <p className="text-xs text-ink-800 leading-relaxed">
              Última actividad: WhatsApp <b>hace 8 min</b>. Sentimiento del candidato: <b className="text-emerald-700">positivo</b>. SOFIA Call previo recomendó <b className="text-emerald-700">Advance</b>.
            </p>
          </div>
        </div>
      </div>

      {/* Footer actions (sticky) */}
      <div className="px-4 py-3 border-t border-line bg-sub shrink-0 space-y-1.5">
        <div className="text-[10px] uppercase tracking-[0.18em] text-ink-500 font-semibold mb-1.5">Acciones rápidas</div>
        <Button variant="default" size="sm" icon={<Icon.CalendarClock size={12} />} className="w-full justify-start">Agendar entrevista</Button>
        <div className="grid grid-cols-2 gap-1.5">
          <Button variant="default" size="sm" icon={<Icon.Notebook size={12} />}>Kit</Button>
          <Button variant="primary" size="sm" icon={<Icon.Send size={12} />}>Submitir</Button>
        </div>
      </div>
    </div>
  );
}

function CollapsedRail({ onExpand }) {
  return (
    <div className="border-l border-line bg-white flex flex-col items-center py-3 gap-2">
      <IconButton size="sm" variant="ghost" icon={<Icon.PanelLeft size={14} />} title="Mostrar panel" onClick={onExpand} />
      <div className="w-px h-4 bg-line my-1" />
      <IconButton size="sm" variant="ghost" icon={<Icon.User size={14} />} title="Candidato" onClick={onExpand} />
      <IconButton size="sm" variant="ghost" icon={<Icon.File size={14} />} title="Plantillas" onClick={onExpand} />
      <IconButton size="sm" variant="ghost" icon={<Icon.Sparkles size={14} />} title="SOFIA insights" onClick={onExpand} />
    </div>
  );
}

function KVRow({ icon, k, v }) {
  return (
    <div className="flex items-center gap-2">
      <span className="text-ink-400 shrink-0">{icon}</span>
      <span className="text-ink-500 flex-1">{k}</span>
      <span className="text-ink-900 font-medium text-right truncate max-w-[60%]">{v}</span>
    </div>
  );
}

window.InterviewsScreen = InterviewsScreen;
