// Conversaciones — vista multicanal con transcripción + sandbox de Agente
// Static demo: 4 tabs (WhatsApp / Email / Tel. / Agente), all clickable, no backend.

const channelLabel = (c) => c==='whatsapp' ? 'WhatsApp' : c==='phone' ? 'Telefonía' : c==='email' ? 'Email' : 'Agente';
const channelCls   = (c) => c==='whatsapp' ? 'wa'       : c==='phone' ? 'ph'        : c==='email' ? 'em'    : 'ai';

const stateMap = {
  open:        { cls: 'amber',  label: 'Abierto'        },
  scheduled:   { cls: 'teal',   label: 'Programado'     },
  in_progress: { cls: 'blue',   label: 'En curso'       },
  resolved:    { cls: 'green',  label: 'Resuelto'       },
  follow_up:   { cls: 'violet', label: 'Seguimiento'    },
  escalated:   { cls: 'red',    label: 'Escalado'       },
};

const priorityColor = {
  high:   { bg: 'var(--color-danger-light)',  fg: 'var(--color-danger)'  },
  medium: { bg: 'var(--color-warning-light)', fg: 'var(--color-warning)' },
  low:    { bg: 'var(--color-surface-2)',     fg: 'var(--color-text-secondary)' },
};

// Sample Agente sandbox conversations (purely client-side)
const SEED_AGENTE = [
  {
    id: 'A-001',
    title: 'Prueba · Triaje incidencia HVAC',
    agent: 'AG-WA-INB-01',
    created: 'Hoy 09:14',
    msgs: [
      { who: 'user',  t: '09:14', text: 'Hola, tengo el aire averiado en el salón. ¿Qué necesitas para abrir incidencia?' },
      { who: 'ai',    t: '09:14', text: '¡Hola! Para abrir la incidencia necesito tres datos: 1) Dirección o referencia del inmueble, 2) Descripción breve del fallo (no enfría / no enciende / ruidos / goteo), y 3) Si hay urgencia (personas vulnerables, daños materiales).' },
      { who: 'user',  t: '09:15', text: 'Apt 4B Chamberí, no enfría, tenemos un bebé en casa.' },
      { who: 'ai',    t: '09:15', text: 'Marcado como prioridad alta. Genero la orden #PM-1042 y consulto disponibilidad de Climatec y ServiClima. ¿Te paso opciones de hoy con coste extra o de mañana sin coste?' },
    ],
  },
  {
    id: 'A-002',
    title: 'Prueba · Email de programación de visita',
    agent: 'AG-MAIL-OUT-01',
    created: 'Hoy 08:02',
    msgs: [
      { who: 'user', t: '08:02', text: 'Redacta un email para confirmar la visita del técnico de fontanería al inquilino James Carter, mañana 10:00-11:00. Tono profesional pero cercano, en inglés.' },
      { who: 'ai',   t: '08:02', text: 'Subject: Confirming tomorrow\u2019s plumbing visit · Loft 2 Malasaña\n\nHi James,\n\nQuick note to confirm the plumber from Fontanería Madrid Centro will arrive tomorrow between 10:00 and 11:00 to fix the leak under the bathroom sink. The technician\u2019s name and photo will be shared 30 min before arrival for your reference.\n\nIf anything changes on your end, just reply to this email or message us on WhatsApp.\n\nKind regards,\nEmentil Property Care' },
    ],
  },
];

const Conversations = ({ onNav }) => {
  const D = window.BW_DATA;
  const [tab, setTab] = useState('whatsapp');
  const [selectedId, setSelectedId] = useState('PM-1042');
  const [humanMode, setHumanMode] = useState(false);
  const [draft, setDraft] = useState('');
  const [emailMode, setEmailMode] = useState('ai'); // 'ai' | 'manual'
  const [agenteList, setAgenteList] = useState(SEED_AGENTE);
  const [agenteSelectedId, setAgenteSelectedId] = useState('A-001');
  const [agenteAgent, setAgenteAgent] = useState('AG-WA-INB-01');

  const isAgente = tab === 'agente';

  // ── Conversation list per tab ──
  const list = isAgente
    ? agenteList
    : D.PM_TICKETS.filter(t => t.channel === tab);

  const selected = isAgente
    ? agenteList.find(c => c.id === agenteSelectedId) || agenteList[0]
    : D.PM_TICKETS.find(t => t.id === selectedId) || list[0];

  // When tab changes, pick first item of that tab
  useEffect(() => {
    if (isAgente) return;
    const first = D.PM_TICKETS.find(t => t.channel === tab);
    if (first) setSelectedId(first.id);
  }, [tab]);

  // Transcript fallback per ticket
  const transcript = (selected && !isAgente)
    ? (D.PM_TRANSCRIPTS[selected.id] || D.PM_TRANSCRIPTS['PM-1042'])
    : [];

  const counts = {
    whatsapp: D.PM_TICKETS.filter(t=>t.channel==='whatsapp').length,
    email:    D.PM_TICKETS.filter(t=>t.channel==='email').length,
    phone:    D.PM_TICKETS.filter(t=>t.channel==='phone').length,
    agente:   agenteList.length,
  };

  const handleNewSandbox = () => {
    const id = 'A-' + Math.random().toString(36).slice(2, 6).toUpperCase();
    const conv = {
      id,
      title: 'Nueva conversación de prueba',
      agent: agenteAgent,
      created: 'Ahora',
      msgs: [],
    };
    setAgenteList(prev => [conv, ...prev]);
    setAgenteSelectedId(id);
  };

  const handleSend = () => {
    if (!draft.trim()) return;
    if (isAgente && selected) {
      const msg = { who: 'user', t: 'Ahora', text: draft };
      const reply = { who: 'ai', t: 'Ahora', text: 'Recibido. (Respuesta simulada — conecta el agente real para probarlo.)' };
      setAgenteList(prev => prev.map(c =>
        c.id === selected.id ? { ...c, msgs: [...c.msgs, msg, reply] } : c
      ));
    }
    setDraft('');
  };

  return (
    <div className="page-enter" style={{ display:'grid', gridTemplateColumns: '320px 1fr 320px', height: 'calc(100vh - var(--header-h))' }}>

      {/* ── Left column: list ── */}
      <div style={{ borderRight:'1px solid var(--color-border)', background:'white', display:'flex', flexDirection:'column', minHeight: 0 }}>
        <div style={{ padding: '14px 16px', borderBottom:'1px solid var(--color-border)' }}>
          <div className="brand-eyebrow" style={{ marginBottom: 10 }}>Bandeja · Multi-canal</div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap: 6, marginBottom: 12 }}>
            {[
              ['whatsapp','WhatsApp', I.WhatsApp, 'wa'],
              ['email',   'Email',    I.Mail,     'em'],
              ['phone',   'Tel.',     I.Phone,    'ph'],
              ['agente',  'Agente',   I.Sparkle,  'ai'],
            ].map(([id, l, Ic, cls]) => {
              const active = tab === id;
              const accent = id==='agente' ? '#7C3AED' : 'var(--color-accent)';
              return (
                <button key={id} onClick={() => setTab(id)} style={{
                  padding: '8px 4px',
                  border: active ? `1px solid ${accent}` : '1px solid var(--color-border)',
                  borderRadius: 8,
                  background: active ? (id==='agente' ? 'rgba(124,58,237,.08)' : 'var(--color-accent-light)') : 'white',
                  color: active ? accent : 'var(--color-text-secondary)',
                  display:'flex', flexDirection:'column', alignItems:'center', gap: 4,
                  fontSize: 11.5, fontWeight: 600, cursor: 'pointer', position:'relative',
                }}>
                  <Ic size={15}/>
                  <span>{l}</span>
                  <span style={{
                    position:'absolute', top: 4, right: 6,
                    fontSize: 9.5, fontFamily:'var(--font-mono)',
                    color: active ? accent : 'var(--color-text-muted)',
                  }}>{counts[id]}</span>
                </button>
              );
            })}
          </div>

          {isAgente ? (
            <button
              onClick={handleNewSandbox}
              style={{
                width:'100%', justifyContent:'center', gap: 6,
                padding:'8px 12px', borderRadius: 8,
                border:'1px solid #C4B5FD',
                background:'linear-gradient(135deg,#EDE9FE,#DDD6FE)',
                color:'#7C3AED', fontSize: 13, fontWeight: 600, cursor:'pointer',
                display:'flex', alignItems:'center',
              }}
            >
              <I.Plus size={14}/> Nueva conversación de prueba
            </button>
          ) : (
            <div style={{ position:'relative' }}>
              <I.Search size={14} style={{ position:'absolute', left: 12, top: '50%', transform:'translateY(-50%)', color:'var(--color-text-muted)' }} />
              <input className="input input-sm" placeholder="Buscar inquilino, unidad, referencia…" style={{ paddingLeft: 36 }} />
            </div>
          )}
        </div>

        <div style={{ overflow:'auto', flex: 1 }}>
          {list.length === 0 && (
            <div style={{ padding:'40px 20px', textAlign:'center', color:'var(--color-text-muted)', fontSize: 13 }}>
              No hay conversaciones en {channelLabel(tab)}.
            </div>
          )}

          {isAgente && list.map(conv => {
            const isSel = selected && conv.id === selected.id;
            return (
              <div key={conv.id} onClick={()=>setAgenteSelectedId(conv.id)} style={{
                padding:'12px 16px', borderBottom:'1px solid var(--color-border)',
                display:'flex', gap: 10, cursor:'pointer',
                background: isSel ? 'rgba(124,58,237,.08)' : 'white',
                borderLeft: isSel ? '3px solid #7C3AED' : '3px solid transparent',
              }}>
                <div style={{ width: 36, height: 36, borderRadius: 8, background:'linear-gradient(135deg,#A78BFA,#7C3AED)', color:'white', display:'grid', placeItems:'center', flex:'0 0 36px' }}>
                  <I.Sparkle size={16}/>
                </div>
                <div style={{ flex:1, minWidth: 0 }}>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', gap: 6 }}>
                    <span style={{ fontWeight: 600, fontSize: 13.5 }} className="truncate">{conv.title}</span>
                    <span style={{ fontSize: 11, color:'var(--color-text-muted)', whiteSpace:'nowrap' }}>{conv.created}</span>
                  </div>
                  <div style={{ fontSize: 12, color:'var(--color-text-secondary)', marginTop: 2, fontFamily:'var(--font-mono)' }} className="truncate">{conv.agent}</div>
                  <div style={{ fontSize: 12.5, color:'var(--color-text-muted)', marginTop: 4 }} className="truncate">
                    {conv.msgs.length > 0 ? conv.msgs[conv.msgs.length - 1].text : 'Sin mensajes'}
                  </div>
                </div>
              </div>
            );
          })}

          {!isAgente && list.map(t => {
            const isSel = selected && t.id === selected.id;
            const st = stateMap[t.state] || stateMap.open;
            const cat = D.PM_CATEGORIES[t.category] || { color:'var(--color-text-muted)', bg:'var(--color-surface-2)', icon:'Sparkle' };
            const CatIc = I[cat.icon] || I.Sparkle;
            return (
              <div key={t.id} onClick={()=>setSelectedId(t.id)} style={{
                padding:'12px 16px', borderBottom:'1px solid var(--color-border)',
                display:'flex', gap: 10, cursor:'pointer',
                background: isSel ? 'var(--color-accent-light)' : 'white',
                borderLeft: isSel ? '3px solid var(--color-accent)' : '3px solid transparent',
              }}>
                <div style={{
                  width: 28, height: 28, borderRadius: 8, flex:'0 0 28px',
                  background: cat.bg, color: cat.color,
                  display:'grid', placeItems:'center',
                  marginTop: 2,
                }} title={t.category}>
                  <CatIc size={14}/>
                </div>
                <div style={{ flex:1, minWidth: 0 }}>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', gap: 6 }}>
                    <span style={{ fontWeight: 600, fontSize: 13.5 }} className="truncate">{t.tenant}</span>
                    <span style={{ fontSize: 11, color:'var(--color-text-muted)', whiteSpace:'nowrap' }}>{t.last}</span>
                  </div>
                  <div style={{ fontSize: 12, color:'var(--color-text-secondary)', marginTop: 1 }} className="truncate">{t.unit}</div>
                  <div style={{ fontSize: 13, color:'var(--color-text-primary)', marginTop: 4 }} className="truncate">{t.issue}</div>
                  <div style={{ display:'flex', gap: 4, marginTop: 6, alignItems:'center' }}>
                    <span className={'badge ' + st.cls + ' dot'} style={{ fontSize: 10, padding:'0 6px' }}>{st.label}</span>
                    <span style={{
                      fontSize: 9.5, fontWeight: 700, letterSpacing:'0.08em', textTransform:'uppercase',
                      padding:'2px 6px', borderRadius: 4,
                      background: priorityColor[t.priority].bg, color: priorityColor[t.priority].fg,
                    }}>{t.priority}</span>
                    <span className={'ch ' + channelCls(t.channel)} style={{ marginLeft:'auto', fontSize: 10, padding:'0 6px' }}>
                      {t.channel==='whatsapp' ? <I.WhatsApp size={10}/> : t.channel==='phone' ? <I.Phone size={10}/> : <I.Mail size={10}/>}
                    </span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* ── Center column: thread ── */}
      <div style={{ display:'flex', flexDirection:'column', minHeight: 0, background:'var(--color-surface)' }}>
        {!selected ? (
          <div style={{ flex:1, display:'grid', placeItems:'center', color:'var(--color-text-muted)', fontSize:14 }}>
            Selecciona una conversación.
          </div>
        ) : (
          <>
            {/* Header */}
            <div style={{ padding:'14px 24px', borderBottom:'1px solid var(--color-border)', background:'white', display:'flex', alignItems:'center', gap: 12 }}>
              {isAgente ? (
                <>
                  <div style={{ width: 40, height: 40, borderRadius: 10, background:'linear-gradient(135deg,#A78BFA,#7C3AED)', color:'white', display:'grid', placeItems:'center' }}>
                    <I.Sparkle size={18}/>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display:'flex', alignItems:'center', gap: 8 }}>
                      <span style={{ fontWeight: 600, fontSize: 15 }}>{selected.title}</span>
                      <span className="badge" style={{ background:'rgba(124,58,237,.12)', color:'#7C3AED', fontSize: 11 }}>Sandbox</span>
                    </div>
                    <div style={{ fontSize: 12, color:'var(--color-text-secondary)', marginTop: 2, fontFamily:'var(--font-mono)' }}>{selected.agent} · {selected.created}</div>
                  </div>
                </>
              ) : (
                <>
                  <div style={{ flex:1, minWidth: 0 }}>
                    <div style={{ display:'flex', alignItems:'center', gap: 8 }}>
                      <span style={{ fontWeight: 600, fontSize: 16 }}>{selected.tenant}</span>
                      <span style={{ fontSize: 12, color:'var(--color-text-secondary)' }}>· {selected.unit}</span>
                      <span style={{
                        fontSize: 9.5, fontWeight: 700, letterSpacing:'0.08em', textTransform:'uppercase',
                        padding:'2px 6px', borderRadius: 4,
                        background: priorityColor[selected.priority].bg, color: priorityColor[selected.priority].fg,
                      }}>{selected.priority}</span>
                    </div>
                    <div style={{ display:'flex', gap:6, marginTop: 4, alignItems:'center', flexWrap:'wrap' }}>
                      <span className={'ch ' + channelCls(selected.channel)}>
                        {selected.channel==='whatsapp' ? <I.WhatsApp size={11}/> : selected.channel==='phone' ? <I.Phone size={11}/> : <I.Mail size={11}/>}
                        {channelLabel(selected.channel)}
                      </span>
                      <span className="badge" style={{ fontFamily:'var(--font-mono)', fontSize: 11 }}>{selected.agent}</span>
                      <span style={{ fontSize: 12, color:'var(--color-text-secondary)' }}>· #{selected.id}</span>
                    </div>
                  </div>
                  <button className="btn btn-sm" onClick={() => { window.BW_OPEN_TICKET = selected.id; onNav && onNav('ticket_detail'); }}>
                    <I.Doc size={13}/> Ver ticket
                  </button>
                  <button className="icon-btn"><I.Dots size={16}/></button>
                </>
              )}
            </div>

            {/* Identificación IA — extracted problem details (Step 2) */}
            {!isAgente && (() => {
              const cat = D.PM_CATEGORIES[selected.category] || { icon:'Sparkle', color:'var(--color-accent)', bg:'var(--color-accent-light)' };
              const CatIc = I[cat.icon] || I.Sparkle;
              return (
                <div style={{
                  margin: '14px 24px 0',
                  background: 'white',
                  border: '1px solid var(--color-border)',
                  borderRadius: 12,
                  overflow: 'hidden',
                }}>
                  {/* Header strip */}
                  <div style={{
                    display:'flex', alignItems:'center', gap: 12,
                    padding:'12px 16px',
                    borderBottom:'1px solid var(--color-border)',
                    background:'var(--color-surface)',
                  }}>
                    <div style={{
                      width: 32, height: 32, borderRadius: 8, flex:'0 0 32px',
                      background: cat.bg, color: cat.color,
                      display:'grid', placeItems:'center',
                    }}>
                      <CatIc size={16}/>
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing:'0.12em', textTransform:'uppercase', color:'var(--color-accent)', marginBottom: 2 }}>
                        Identificación IA · {selected.category}
                      </div>
                      <div style={{ fontSize: 14, fontWeight: 600, color:'var(--color-text-primary)' }} className="truncate">{selected.issue}</div>
                    </div>
                    <div style={{ display:'flex', flexDirection:'column', alignItems:'flex-end', gap: 2 }}>
                      <div style={{ fontSize: 10.5, color:'var(--color-text-muted)', textTransform:'uppercase', letterSpacing:'0.08em' }}>Confianza</div>
                      <div style={{ fontFamily:'var(--font-mono)', fontSize: 13, fontWeight: 600, color: selected.confidence >= 0.9 ? 'var(--color-success)' : 'var(--color-warning)' }}>
                        {Math.round(selected.confidence * 100)}%
                      </div>
                    </div>
                    <button className="btn btn-sm btn-ghost" title="Reanalizar"><I.Refresh size={13}/></button>
                  </div>

                  {/* Body grid */}
                  <div style={{ padding:'14px 16px', display:'grid', gridTemplateColumns:'1fr 1fr', gap: '14px 24px' }}>
                    <IdField label="Subcategoría"   value={selected.subcategory}/>
                    <IdField label="Componente"     value={selected.component}/>
                    <div style={{ gridColumn:'1 / -1' }}>
                      <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--color-text-muted)', marginBottom: 6 }}>Síntomas detectados</div>
                      <div style={{ display:'flex', gap: 6, flexWrap:'wrap' }}>
                        {selected.symptoms.map((s, i) => (
                          <span key={i} style={{
                            fontSize: 11.5, fontWeight: 500,
                            padding:'3px 9px', borderRadius: 999,
                            background:'var(--color-surface-2)', color:'var(--color-text-primary)',
                            border:'1px solid var(--color-border)',
                          }}>{s}</span>
                        ))}
                      </div>
                    </div>
                    <div style={{ gridColumn:'1 / -1', display:'flex', gap: 12, alignItems:'flex-start', padding:'10px 12px', background:'var(--color-surface)', borderRadius: 8, border:'1px dashed var(--color-border)' }}>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--color-text-muted)', marginBottom: 4 }}>Urgencia</div>
                        <div style={{ display:'flex', alignItems:'center', gap: 8 }}>
                          <span style={{
                            fontSize: 9.5, fontWeight: 700, letterSpacing:'0.08em', textTransform:'uppercase',
                            padding:'2px 6px', borderRadius: 4,
                            background: priorityColor[selected.priority].bg, color: priorityColor[selected.priority].fg,
                          }}>{selected.priority}</span>
                          <span style={{ fontSize: 12.5, color:'var(--color-text-secondary)' }}>{selected.urgencyReason}</span>
                        </div>
                      </div>
                    </div>
                    <div style={{ gridColumn:'1 / -1', display:'flex', alignItems:'center', gap: 12, paddingTop: 6, borderTop:'1px solid var(--color-border)' }}>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--color-text-muted)', marginBottom: 2 }}>Recomendado</div>
                        <div style={{ fontSize: 13.5, fontWeight: 500, color:'var(--color-text-primary)' }}>
                          {selected.recommendedSpecialty} <span style={{ color:'var(--color-text-muted)', fontWeight: 400 }}>· {selected.compatibleTeams} equipos compatibles</span>
                        </div>
                      </div>
                      <button className="btn btn-primary btn-sm">
                        <I.Send size={13}/> Asignar técnico
                      </button>
                    </div>
                  </div>
                </div>
              );
            })()}

            {humanMode && !isAgente && (
              <div style={{ margin:'8px 24px 0', padding:'8px 14px', background:'var(--color-warning-light)', color:'var(--color-warning)', borderRadius: 8, fontSize: 13, display:'flex', alignItems:'center', gap: 8 }}>
                <I.Hand size={14}/> Modo humano activo — el agente IA está pausado.
                <button className="btn-ghost btn btn-sm" onClick={()=>setHumanMode(false)} style={{ marginLeft:'auto', color:'var(--color-warning)', fontWeight:500 }}>Devolver a IA</button>
              </div>
            )}

            {/* Phone playback for phone channel */}
            {!isAgente && selected.channel === 'phone' && (
              <div style={{ margin:'12px 24px 0', background:'white', border:'1px solid var(--color-border)', borderRadius: 12, padding: 14, display:'flex', alignItems:'center', gap: 14 }}>
                <button className="btn btn-primary" style={{ width: 40, height: 40, borderRadius:'50%', padding: 0 }}><I.Play size={14}/></button>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500, marginBottom: 4 }}>Grabación · 04:32 · ElevenLabs</div>
                  <svg viewBox="0 0 400 24" style={{ width:'100%', height: 22 }} preserveAspectRatio="none">
                    {Array.from({length:80}).map((_,i)=>{
                      const h = 4 + Math.abs(Math.sin(i*0.6))*16;
                      return <rect key={i} x={i*5} y={(24-h)/2} width="2.5" height={h} fill={i<30?'var(--color-accent)':'var(--color-border-strong)'} />;
                    })}
                  </svg>
                </div>
                <span className="mono" style={{ fontSize: 12, color:'var(--color-text-secondary)' }}>01:43 / 04:32</span>
              </div>
            )}

            {/* Messages */}
            <div style={{ flex:1, overflow:'auto', padding:'20px 24px' }}>
              <div style={{ display:'flex', flexDirection:'column', gap: 10 }}>
                {isAgente && selected.msgs.length === 0 && (
                  <div style={{ alignSelf:'center', fontSize:13, color:'var(--color-text-muted)', padding: 24, textAlign:'center', maxWidth: 360 }}>
                    Escribe un mensaje para empezar a probar al agente.
                  </div>
                )}

                {(isAgente ? selected.msgs : transcript).map((m, i) => {
                  const isAi = isAgente ? m.who === 'ai' : m.who === 'agent';
                  const bubble = isAi
                    ? (isAgente
                        ? { background:'linear-gradient(135deg,#EDE9FE,#DDD6FE)', border:'none' }
                        : { background:'var(--color-accent-light)', border:'none' })
                    : { background:'white', border:'1px solid var(--color-border)' };
                  return (
                    <div key={i} style={{ display:'flex', justifyContent: isAi ? 'flex-end' : 'flex-start' }}>
                      <div style={{
                        maxWidth: '74%',
                        padding:'10px 14px',
                        borderRadius: isAi ? '12px 12px 4px 12px' : '12px 12px 12px 4px',
                        fontSize: 14, lineHeight: 1.5,
                        whiteSpace: 'pre-wrap',
                        ...bubble,
                      }}>
                        {m.text}
                        <div style={{ fontSize: 11, color:'var(--color-text-muted)', marginTop: 6, fontFamily:'var(--font-mono)' }}>
                          {isAi ? (isAgente ? 'Agente IA' : 'IA') : (isAgente ? 'Tú' : selected.tenant.split(' ')[0])} · {m.t}
                        </div>
                      </div>
                    </div>
                  );
                })}

                {!isAgente && (
                  <div style={{ alignSelf:'center', fontSize: 12, padding:'4px 12px', background:'var(--color-success-light)', color:'var(--color-success)', borderRadius: 999, display:'flex', alignItems:'center', gap: 6 }}>
                    <I.Check size={12}/> Incidencia registrada · #{selected.id}
                  </div>
                )}
              </div>
            </div>

            {/* Compose area */}
            <div style={{ padding:'14px 24px', background:'white', borderTop:'1px solid var(--color-border)' }}>
              {/* Email mode toggle */}
              {!isAgente && selected.channel === 'email' && (
                <div style={{ display:'flex', gap: 8, marginBottom: 12, alignItems:'center', flexWrap:'wrap' }}>
                  <span style={{ fontSize: 12, color:'var(--color-text-muted)', fontWeight: 500 }}>Responder con:</span>
                  <div style={{ display:'flex', gap: 6 }}>
                    {[['ai','IA',I.Sparkle], ['manual','Manual',I.Hand]].map(([id, l, Ic]) => (
                      <button key={id} onClick={()=>setEmailMode(id)} style={{
                        padding:'6px 12px', borderRadius: 6,
                        border: emailMode===id ? '1px solid var(--color-accent)' : '1px solid var(--color-border)',
                        background: emailMode===id ? 'var(--color-accent-light)' : 'white',
                        color: emailMode===id ? 'var(--color-accent)' : 'var(--color-text-secondary)',
                        fontSize: 12, fontWeight: 500, cursor:'pointer',
                        display:'flex', alignItems:'center', gap: 6,
                      }}>
                        <Ic size={13}/> {l}
                      </button>
                    ))}
                  </div>
                  <button style={{
                    marginLeft:'auto', padding:'6px 14px', borderRadius: 6,
                    border:'1px solid #C4B5FD',
                    background:'linear-gradient(135deg,#EDE9FE,#DDD6FE)',
                    color:'#7C3AED', fontSize: 12, fontWeight: 600, cursor:'pointer',
                    display:'flex', alignItems:'center', gap: 6,
                  }}>
                    <I.Sparkle size={13}/> Respuesta rápida IA
                  </button>
                </div>
              )}

              <div style={{ display:'flex', gap: 8, alignItems:'flex-end' }}>
                <div style={{ flex: 1, border:'1px solid var(--color-border-strong)', borderRadius: 10, padding:'10px 12px', background: (isAgente || humanMode || selected.channel==='email') ? 'white' : 'var(--color-surface)' }}>
                  <textarea
                    value={draft}
                    onChange={e=>setDraft(e.target.value)}
                    onKeyDown={e=>{ if (e.key==='Enter' && (e.ctrlKey||e.metaKey)) handleSend(); }}
                    placeholder={
                      isAgente ? 'Escribe un mensaje al agente… (Ctrl+Enter para enviar)' :
                      selected.channel==='email' ? `Responder por email (${emailMode==='ai' ? 'IA' : 'Manual'})…` :
                      humanMode ? 'Escribe como humano…' :
                      'Toma el control para escribir manualmente'
                    }
                    disabled={!isAgente && !humanMode && selected.channel !== 'email'}
                    rows={2}
                    style={{ width:'100%', border: 0, outline:'none', resize:'none', background:'transparent', fontFamily:'inherit', fontSize: 14, color:'var(--color-text-primary)' }}
                  />
                  {!isAgente && (
                    <div style={{ display:'flex', gap: 4, marginTop: 4 }}>
                      <button className="icon-btn" style={{ width: 26, height: 26 }}><I.Tag size={14}/></button>
                      <button className="icon-btn" style={{ width: 26, height: 26 }}><I.Sparkle size={14}/></button>
                    </div>
                  )}
                </div>
                <div style={{ display:'flex', flexDirection:'column', gap: 8 }}>
                  {isAgente ? (
                    <button onClick={handleSend} disabled={!draft.trim()} style={{
                      height: 40, padding:'0 18px', borderRadius: 8,
                      background:'linear-gradient(135deg,#7C3AED,#6D28D9)',
                      color:'white', border:'none',
                      fontSize: 14, fontWeight: 600, cursor: draft.trim() ? 'pointer' : 'default',
                      opacity: draft.trim() ? 1 : 0.5,
                      display:'inline-flex', alignItems:'center', gap: 6,
                    }}>
                      <I.Sparkle size={14}/> Enviar al agente
                    </button>
                  ) : (selected.channel === 'email' || humanMode) ? (
                    <button className="btn btn-primary btn-md" onClick={handleSend}>
                      <I.Send size={14}/> Enviar
                    </button>
                  ) : (
                    <button className="btn btn-warn btn-md" onClick={()=>setHumanMode(true)}><I.Hand size={14}/> Tomar el control</button>
                  )}
                  {!isAgente && (
                    <button className="btn btn-md" style={{ color:'var(--color-danger)', borderColor:'var(--color-border)' }}>
                      <I.ArrowRight size={14}/> Escalar
                    </button>
                  )}
                </div>
              </div>
            </div>
          </>
        )}
      </div>

      {/* ── Right column: context card ── */}
      <div style={{ borderLeft:'1px solid var(--color-border)', background:'white', overflow:'auto', minHeight: 0 }}>
        {!selected ? (
          <div style={{ padding: 40, textAlign:'center', color:'var(--color-text-muted)', fontSize: 13 }}>—</div>
        ) : isAgente ? (
          <>
            <div style={{ padding: 20, borderBottom:'1px solid var(--color-border)', background:'linear-gradient(135deg,#F5F3FF,#EDE9FE)' }}>
              <div style={{ width: 44, height: 44, borderRadius: 10, background:'linear-gradient(135deg,#A78BFA,#7C3AED)', display:'grid', placeItems:'center', marginBottom: 12 }}>
                <I.Sparkle size={20} style={{ color:'white' }}/>
              </div>
              <div className="brand-eyebrow" style={{ color:'#7C3AED', marginBottom: 4 }}>Sandbox de agente</div>
              <div style={{ fontFamily:'var(--font-ui)', fontSize: 22, letterSpacing:'-0.02em', color:'var(--brand-navy)' }}>Probar respuestas</div>
              <div style={{ fontSize: 12.5, color:'var(--color-text-secondary)', marginTop: 6, lineHeight: 1.5 }}>
                Las conversaciones se guardan localmente. No se envían WhatsApp ni emails reales.
              </div>
            </div>
            <CvSection title="Agente seleccionado">
              <div style={{ display:'flex', flexDirection:'column', gap: 6 }}>
                {D.AGENTS.map(a => {
                  const active = agenteAgent === a.id;
                  return (
                    <button key={a.id} onClick={()=>setAgenteAgent(a.id)} style={{
                      display:'flex', alignItems:'center', gap: 10,
                      padding:'8px 10px', borderRadius: 8,
                      border: active ? '1px solid #7C3AED' : '1px solid var(--color-border)',
                      background: active ? 'rgba(124,58,237,.06)' : 'white',
                      cursor:'pointer', textAlign:'left',
                    }}>
                      <div style={{ width: 24, height: 24, borderRadius: 6, background:'var(--color-surface-2)', color:'var(--color-text-secondary)', display:'grid', placeItems:'center', flex:'0 0 24px' }}>
                        {a.channel === 'whatsapp' ? <I.WhatsApp size={12}/> : a.channel === 'phone' ? <I.Phone size={12}/> : <I.Mail size={12}/>}
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 12.5, fontWeight: 500, color:'var(--color-text-primary)' }} className="truncate">{a.name}</div>
                        <div style={{ fontSize: 11, color:'var(--color-text-muted)', fontFamily:'var(--font-mono)' }}>{a.id}</div>
                      </div>
                      {active && <I.Check size={14} style={{ color:'#7C3AED' }}/>}
                    </button>
                  );
                })}
              </div>
            </CvSection>
            <CvSection title="Notas" no>
              <div style={{ fontSize: 12.5, color:'var(--color-text-secondary)', lineHeight: 1.6 }}>
                Usa este sandbox para validar prompts, scripts y respuestas antes de activar el agente en producción.
              </div>
            </CvSection>
          </>
        ) : (
          <>
            <div style={{ padding: 20, borderBottom:'1px solid var(--color-border)' }}>
              <div className="brand-eyebrow mist" style={{ marginBottom: 4 }}>Ficha de incidencia</div>
              <div style={{ fontFamily:'var(--font-ui)', fontSize: 22, letterSpacing:'-0.02em', color:'var(--brand-navy)' }}>{selected.tenant}</div>
              <div style={{ fontSize: 12.5, color:'var(--color-text-secondary)', marginTop: 4 }}>{selected.unit}</div>
              <div style={{ display:'flex', gap: 6, marginTop: 10, flexWrap:'wrap' }}>
                <span className={'badge ' + stateMap[selected.state].cls + ' dot'}>{stateMap[selected.state].label}</span>
                <span className="badge dark">{selected.category}</span>
              </div>
            </div>
            <CvSection title="Contacto">
              <CvField icon="Phone" label="Teléfono" value={selected.phone}/>
              <CvField icon="Mail"  label="Email"    value={selected.tenant.toLowerCase().replace(/\s+/g,'.') + '@tenant.es'}/>
              <CvField icon="Tag"   label="Referencia" value={selected.property} mono/>
            </CvSection>
            <CvSection title="Identificación">
              <CvField icon="AlertTriangle" label="Tipo"         value={selected.category}/>
              <CvField icon="Tag"           label="Subcategoría" value={selected.subcategory}/>
              <CvField icon="Settings"      label="Componente"   value={selected.component}/>
              <CvField icon="Sparkle"       label="Recomendado"  value={selected.recommendedSpecialty}/>
              <div style={{ marginTop: 4 }}>
                <div style={{ fontSize: 11, color:'var(--color-text-muted)', marginBottom: 4 }}>Confianza</div>
                <div style={{ display:'flex', alignItems:'center', gap: 8 }}>
                  <div style={{ flex: 1, height: 4, borderRadius: 2, background:'var(--color-border)', overflow:'hidden' }}>
                    <div style={{ width: `${Math.round(selected.confidence*100)}%`, height:'100%', background: selected.confidence >= 0.9 ? 'var(--color-success)' : 'var(--color-warning)' }}/>
                  </div>
                  <span style={{ fontSize: 12, fontWeight: 600, fontFamily:'var(--font-mono)', color: selected.confidence >= 0.9 ? 'var(--color-success)' : 'var(--color-warning)' }}>
                    {Math.round(selected.confidence*100)}%
                  </span>
                </div>
              </div>
            </CvSection>
            {D.PM_FOLLOWUPS && D.PM_FOLLOWUPS[selected.id] && (
              <FollowupTimeline ticket={selected} D={D}/>
            )}
            <CvSection title="Próximos pasos" no>
              <div style={{ display:'flex', flexDirection:'column', gap: 8 }}>
                <button className="btn btn-primary btn-sm" style={{ justifyContent:'center' }}>
                  <I.Send size={13}/> Avisar al técnico
                </button>
                <button className="btn btn-sm" style={{ justifyContent:'center' }} onClick={() => { window.BW_OPEN_TICKET = selected.id; onNav && onNav('ticket_detail'); }}>
                  <I.Doc size={13}/> Ver ticket completo
                </button>
                <button className="btn btn-sm" style={{ justifyContent:'center' }}>
                  <I.ArrowRight size={13}/> Escalar a supervisor
                </button>
              </div>
            </CvSection>
          </>
        )}
      </div>
    </div>
  );
};

const CvSection = ({ title, children, no }) => (
  <div style={{ padding:'16px 20px', borderBottom: no ? 'none' : '1px solid var(--color-border)' }}>
    <div style={{ fontSize: 11, fontWeight: 600, color:'var(--color-text-muted)', textTransform:'uppercase', letterSpacing:'0.12em', marginBottom: 10 }}>{title}</div>
    <div style={{ display:'flex', flexDirection:'column', gap: 8 }}>{children}</div>
  </div>
);

const CvField = ({ icon, label, value, mono }) => {
  const Ic = I[icon];
  return (
    <div style={{ display:'flex', alignItems:'flex-start', gap: 10 }}>
      {Ic && <Ic size={14} style={{ color:'var(--color-text-muted)', marginTop: 2, flex:'0 0 14px' }}/>}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 11, color:'var(--color-text-muted)' }}>{label}</div>
        <div style={{ fontSize: 13, color:'var(--color-text-primary)', fontFamily: mono ? 'var(--font-mono)' : 'inherit', wordBreak:'break-word' }}>{value}</div>
      </div>
    </div>
  );
};

const IdField = ({ label, value }) => (
  <div>
    <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--color-text-muted)', marginBottom: 3 }}>{label}</div>
    <div style={{ fontSize: 13.5, color:'var(--color-text-primary)' }}>{value}</div>
  </div>
);

// ── Follow-up timeline (Step 4) — 3-step visit lifecycle in the right panel
const FollowupTimeline = ({ ticket, D }) => {
  const fu = D.PM_FOLLOWUPS && D.PM_FOLLOWUPS[ticket.id];
  if (!fu) return null;

  const stateStyle = {
    sent:      { bg: 'var(--color-accent-light)',   fg: 'var(--color-accent)',   label: 'Enviado' },
    pending:   { bg: 'var(--color-warning-light)',  fg: 'var(--color-warning)',  label: 'Pendiente' },
    scheduled: { bg: 'var(--color-surface-2)',      fg: 'var(--color-text-secondary)', label: 'Programado' },
    responded: { bg: 'var(--color-success-light)',  fg: 'var(--color-success)',  label: 'Respondido' },
    skipped:   { bg: 'var(--color-surface-2)',      fg: 'var(--color-text-muted)', label: 'Omitido' },
  };

  return (
    <CvSection title="Seguimiento de visita">
      {/* Visit summary */}
      <div style={{
        padding:'10px 12px',
        background:'var(--color-surface)',
        borderRadius: 8,
        border:'1px solid var(--color-border)',
        marginBottom: 6,
      }}>
        <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--color-text-muted)', marginBottom: 4 }}>Visita</div>
        <div style={{ fontSize: 13.5, fontWeight: 600, color:'var(--color-text-primary)' }}>{fu.visitDate}</div>
        {fu.technicianAssigned && (
          <div style={{ fontSize: 12, color:'var(--color-text-secondary)', marginTop: 4, display:'flex', alignItems:'center', gap: 6 }}>
            <I.Wrench size={12}/>{fu.technicianAssigned.name} · {fu.technicianAssigned.company}
          </div>
        )}
      </div>

      {/* Steps */}
      <div style={{ position:'relative', paddingLeft: 8 }}>
        {fu.steps.map((s, i) => {
          const isLast = i === fu.steps.length - 1;
          const ss = stateStyle[s.state] || stateStyle.scheduled;
          const isSatisfaction = s.stage === 'T+1';
          return (
            <div key={i} style={{ position:'relative', paddingLeft: 24, paddingBottom: isLast ? 0 : 16 }}>
              {/* Connector line */}
              {!isLast && (
                <div style={{
                  position:'absolute', left: 8, top: 18, bottom: -2, width: 2,
                  background: 'var(--color-border)',
                }}/>
              )}
              {/* Dot */}
              <div style={{
                position:'absolute', left: 0, top: 2,
                width: 18, height: 18, borderRadius:'50%',
                background: ss.bg, color: ss.fg,
                display:'grid', placeItems:'center',
                border: '2px solid white', boxShadow: '0 0 0 1px ' + ss.fg,
              }}>
                {s.state === 'sent' || s.state === 'responded' ? <I.Check size={9}/> :
                 s.state === 'pending' ? <I.Clock size={9}/> :
                 s.state === 'skipped' ? <I.X size={9}/> : null}
              </div>

              <div style={{ display:'flex', alignItems:'baseline', gap: 6, marginBottom: 4 }}>
                <span className="mono" style={{ fontSize: 11, fontWeight: 600, color:'var(--color-text-secondary)' }}>{s.stage}</span>
                <span style={{ fontSize: 13, fontWeight: 600, color:'var(--color-text-primary)' }}>{s.label}</span>
              </div>

              <div style={{ display:'flex', gap: 6, marginBottom: 6, alignItems:'center', flexWrap:'wrap' }}>
                <span style={{
                  fontSize: 10, fontWeight: 700, letterSpacing:'0.08em', textTransform:'uppercase',
                  padding:'1px 6px', borderRadius: 4,
                  background: ss.bg, color: ss.fg,
                }}>{ss.label}</span>
                <span style={{ fontSize: 11, color:'var(--color-text-muted)' }}>{s.when}</span>
                {s.channel && s.state !== 'skipped' && (
                  <span style={{ fontSize: 11, color:'var(--color-text-muted)', display:'inline-flex', alignItems:'center', gap: 3 }}>
                    · {s.channel === 'whatsapp' ? <I.WhatsApp size={10}/> : s.channel === 'phone' ? <I.Phone size={10}/> : <I.Mail size={10}/>} {s.channel === 'whatsapp' ? 'WhatsApp' : s.channel === 'email' ? 'Email' : 'SMS'}
                  </span>
                )}
              </div>

              {/* Message preview */}
              {s.state !== 'skipped' && s.message && (
                <div style={{
                  fontSize: 12, lineHeight: 1.5, color:'var(--color-text-secondary)',
                  padding:'8px 10px', borderRadius: 6,
                  background: 'var(--color-surface)',
                  border:'1px solid var(--color-border)',
                  marginBottom: s.response || isSatisfaction ? 6 : 0,
                }}>
                  {s.message}
                </div>
              )}

              {/* Tenant response */}
              {s.response && (
                <div style={{
                  fontSize: 12, lineHeight: 1.5, color:'var(--color-text-primary)',
                  padding:'8px 10px', borderRadius: 6,
                  background:'white',
                  border:'1px solid var(--color-border)',
                  display:'flex', alignItems:'flex-start', gap: 8,
                }}>
                  <I.ArrowR size={11} style={{ color:'var(--color-text-muted)', marginTop: 4, flex:'0 0 11px' }}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 10.5, fontWeight: 600, color:'var(--color-text-muted)', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom: 2 }}>Respuesta inquilino</div>
                    {s.response}
                  </div>
                </div>
              )}

              {/* Star rating for T+1 */}
              {isSatisfaction && s.state === 'responded' && s.rating != null && (
                <div style={{ display:'flex', alignItems:'center', gap: 6, marginTop: 6 }}>
                  {[1,2,3,4,5].map(n => (
                    <I.Star key={n} size={14} style={{
                      color: n <= s.rating ? 'var(--color-warning)' : 'var(--color-border-strong)',
                      fill:  n <= s.rating ? 'var(--color-warning)' : 'transparent',
                    }}/>
                  ))}
                  <span style={{ fontSize: 12.5, fontWeight: 600, color:'var(--color-warning)', marginLeft: 4 }}>{s.rating}/5</span>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </CvSection>
  );
};

window.ConversationsPage = Conversations;
