// Tickets — incidencias de gestión inmobiliaria por estado (kanban + lista)
// Stages: open · scheduled · in_progress · follow_up · resolved · escalated

const TicketStages = [
  { id: 'open',        label: 'Abierto',       cls: 'amber',  desc: 'Recibido · pendiente de asignar' },
  { id: 'scheduled',   label: 'Programado',    cls: 'teal',   desc: 'Técnico confirmado' },
  { id: 'in_progress', label: 'En curso',      cls: 'blue',   desc: 'Técnico en sitio' },
  { id: 'follow_up',   label: 'Seguimiento',   cls: 'violet', desc: 'Encuesta · postservicio' },
  { id: 'resolved',    label: 'Resuelto',      cls: 'green',  desc: 'Cerrado positivo' },
  { id: 'escalated',   label: 'Escalado',      cls: 'red',    desc: 'Requiere supervisor' },
];

const TicketsPage = ({ onNav }) => {
  const D = window.BW_DATA;
  const tickets = D.PM_TICKETS;
  const [view, setView]           = useState('board'); // 'board' | 'list'
  const [priority, setPriority]   = useState('all');
  const [channel, setChannel]     = useState('all');
  const [category, setCategory]   = useState('all');

  // Pre-filter tickets
  const filtered = tickets.filter(t =>
    (priority === 'all' || t.priority === priority) &&
    (channel  === 'all' || t.channel  === channel) &&
    (category === 'all' || t.category === category)
  );

  // Group by stage
  const byStage = TicketStages.reduce((acc, s) => {
    acc[s.id] = filtered.filter(t => t.state === s.id);
    return acc;
  }, {});

  // Counts for totals row
  const stageCount = (id) => tickets.filter(t => t.state === id).length;
  const total = tickets.length;
  const openTotal = stageCount('open') + stageCount('escalated');

  // Distinct categories present in data
  const categories = ['all', ...Array.from(new Set(tickets.map(t => t.category)))];
  const priorities = ['all','high','medium','low'];
  const channels   = ['all','whatsapp','email','phone'];

  return (
    <div className="page-enter" style={{ padding: '24px 32px 40px' }}>
      {/* Page header */}
      <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', marginBottom: 20, gap: 24 }}>
        <div>
          <div className="brand-eyebrow" style={{ marginBottom: 10 }}>
            Operaciones · Incidencias
          </div>
          <h1 style={{ fontFamily:'var(--font-ui)', fontWeight: 600, fontSize: 28, margin: 0, letterSpacing:'-0.02em', color:'var(--brand-navy)', lineHeight: 1.1 }}>
            Tickets
          </h1>
          <div className="accent-line" style={{ marginTop: 14 }}/>
          <div style={{ fontSize: 13, color:'var(--color-text-secondary)', marginTop: 14 }}>
            {total} tickets activos · {openTotal} sin asignar técnico
          </div>
        </div>
        <div style={{ display:'flex', gap: 8, alignItems:'center' }}>
          <div className="seg">
            {[['board','Tablero'],['list','Lista']].map(([id, l]) => (
              <button key={id} className={view === id ? 'active' : ''} onClick={() => setView(id)}>{l}</button>
            ))}
          </div>
          <button className="btn btn-primary btn-md"><I.Plus size={14}/> Nuevo ticket</button>
        </div>
      </div>

      {/* Stage totals row — clickable summary */}
      <div style={{ display:'grid', gridTemplateColumns:`repeat(${TicketStages.length}, 1fr)`, gap: 10, marginBottom: 20 }}>
        {TicketStages.map(s => {
          const n = stageCount(s.id);
          const pct = total > 0 ? Math.round((n/total)*100) : 0;
          return (
            <div key={s.id} style={{
              padding:'14px 16px',
              background:'white',
              border:'1px solid var(--color-border)',
              borderRadius: 10,
            }}>
              <span className={'badge ' + s.cls + ' dot'} style={{ fontSize: 10.5 }}>{s.label}</span>
              <div style={{ fontFamily:'var(--font-ui)', fontWeight: 600, fontSize: 26, color:'var(--brand-navy)', marginTop: 10, letterSpacing:'-0.015em', lineHeight: 1 }}>{n}</div>
              <div style={{ fontSize: 11, color:'var(--color-text-muted)', marginTop: 6 }}>{pct}% del total</div>
            </div>
          );
        })}
      </div>

      {/* Filters */}
      <div style={{ display:'flex', gap: 10, marginBottom: 16, alignItems:'center', flexWrap:'wrap' }}>
        <div style={{ position:'relative', flex:'0 1 280px' }}>
          <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 style={{ width: 1, height: 24, background:'var(--color-border)' }} />
        <FilterPill icon="AlertTriangle" label="Prioridad" value={priority} setValue={setPriority} options={priorities} labels={{ all:'Todas', high:'Alta', medium:'Media', low:'Baja' }} />
        <FilterPill icon="Plug"          label="Canal"     value={channel}  setValue={setChannel}  options={channels}   labels={{ all:'Todos', whatsapp:'WhatsApp', email:'Email', phone:'Teléfono' }} />
        <FilterPill icon="Tag"           label="Categoría" value={category} setValue={setCategory} options={categories} labels={Object.fromEntries(categories.map(c => [c, c==='all' ? 'Todas' : c]))} />
      </div>

      {/* Board view */}
      {view === 'board' && (
        <div style={{
          display:'grid',
          gridTemplateColumns:`repeat(${TicketStages.length}, minmax(240px, 1fr))`,
          gap: 12,
          overflowX:'auto',
          paddingBottom: 12,
        }}>
          {TicketStages.map(s => (
            <BoardColumn key={s.id} stage={s} tickets={byStage[s.id]} onNav={onNav}/>
          ))}
        </div>
      )}

      {/* List view */}
      {view === 'list' && (
        <div className="card" style={{ overflow:'hidden' }}>
          <table className="tbl">
            <thead>
              <tr>
                <th style={{ width: 92 }}>Ticket</th>
                <th style={{ width: 32 }}></th>
                <th>Inquilino · Unidad</th>
                <th>Incidencia</th>
                <th style={{ width: 130 }}>Categoría</th>
                <th style={{ width: 110 }}>Estado</th>
                <th style={{ width: 90 }}>Prioridad</th>
                <th style={{ width: 70 }}>Canal</th>
                <th style={{ width: 90 }}>Actualizado</th>
                <th style={{ width: 60 }}></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(t => {
                const stage = TicketStages.find(s => s.id === t.state) || TicketStages[0];
                const cat = (D.PM_CATEGORIES && 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 (
                  <tr key={t.id} onClick={() => { window.BW_OPEN_TICKET = t.id; onNav && onNav('ticket_detail'); }}>
                    <td><span className="mono" style={{ fontSize: 12, color:'var(--color-text-secondary)' }}>{t.id}</span></td>
                    <td>
                      <span style={{ width: 26, height: 26, borderRadius: 6, background: cat.bg, color: cat.color, display:'inline-grid', placeItems:'center' }}>
                        <CatIc size={13}/>
                      </span>
                    </td>
                    <td>
                      <div style={{ fontWeight: 500, color:'var(--color-text-primary)' }}>{t.tenant}</div>
                      <div style={{ fontSize: 12, color:'var(--color-text-muted)' }}>{t.unit}</div>
                    </td>
                    <td>
                      <div style={{ color:'var(--color-text-primary)' }} className="truncate">{t.issue}</div>
                      <div style={{ fontSize: 11.5, color:'var(--color-text-muted)' }} className="truncate">{t.subcategory}</div>
                    </td>
                    <td><span style={{ fontSize: 12.5, color:'var(--color-text-secondary)' }}>{t.category}</span></td>
                    <td><span className={'badge ' + stage.cls + ' dot'} style={{ fontSize: 11 }}>{stage.label}</span></td>
                    <td>
                      <span style={{
                        fontSize: 10, fontWeight: 700, letterSpacing:'0.08em', textTransform:'uppercase',
                        padding:'2px 6px', borderRadius: 4,
                        background: t.priority==='high'?'var(--color-danger-light)':t.priority==='medium'?'var(--color-warning-light)':'var(--color-surface-2)',
                        color:     t.priority==='high'?'var(--color-danger)':     t.priority==='medium'?'var(--color-warning)':     'var(--color-text-secondary)',
                      }}>{t.priority}</span>
                    </td>
                    <td>
                      <span className={'ch ' + (t.channel==='whatsapp'?'wa':t.channel==='phone'?'ph':'em')} style={{ padding:'2px 8px' }}>
                        {t.channel==='whatsapp' ? <I.WhatsApp size={11}/> : t.channel==='phone' ? <I.Phone size={11}/> : <I.Mail size={11}/>}
                      </span>
                    </td>
                    <td><span className="num">{t.last}</span></td>
                    <td><button className="btn btn-sm" onClick={(e)=>{ e.stopPropagation(); window.BW_OPEN_TICKET = t.id; onNav && onNav('ticket_detail'); }}>Abrir</button></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {filtered.length === 0 && (
            <div style={{ padding:'40px 20px', textAlign:'center', color:'var(--color-text-muted)', fontSize: 13 }}>
              No hay tickets con esos filtros.
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// ─────────────────────── helpers ───────────────────────

const FilterPill = ({ icon, label, value, setValue, options, labels }) => {
  const [open, setOpen] = useState(false);
  const Ic = I[icon];
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open]);
  return (
    <div ref={ref} style={{ position:'relative' }}>
      <button className={'chip' + (value !== 'all' ? ' active' : '')} onClick={()=>setOpen(o => !o)} style={{ height: 32 }}>
        {Ic && <Ic size={12}/>}
        {label}: {labels[value] || value}
        <I.ChevD size={12}/>
      </button>
      {open && (
        <div style={{
          position:'absolute', top:'calc(100% + 6px)', left: 0, zIndex: 30,
          background:'white', border:'1px solid var(--color-border)', borderRadius: 8,
          boxShadow:'0 12px 32px -8px rgba(15,23,42,.18)',
          padding: 4, minWidth: 180, maxHeight: 280, overflow:'auto',
        }}>
          {options.map(o => (
            <button key={o} onClick={() => { setValue(o); setOpen(false); }} style={{
              width:'100%', textAlign:'left', display:'flex', alignItems:'center', gap: 8,
              padding:'7px 10px', border: 0, background: value===o ? 'var(--color-accent-light)' : 'transparent',
              color: value===o ? 'var(--color-accent)' : 'var(--color-text-primary)',
              borderRadius: 6, cursor:'pointer', fontSize: 13,
            }}>
              {labels[o] || o}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

const BoardColumn = ({ stage, tickets, onNav }) => {
  const D = window.BW_DATA;
  return (
    <div style={{
      background:'var(--color-surface)',
      border:'1px solid var(--color-border)',
      borderRadius: 12,
      padding: 12,
      display:'flex', flexDirection:'column',
      minHeight: 360,
    }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap: 8, marginBottom: 10 }}>
        <span className={'badge ' + stage.cls + ' dot'} style={{ fontSize: 11 }}>{stage.label}</span>
        <span style={{
          fontSize: 11, fontFamily:'var(--font-mono)', fontWeight: 600,
          background:'white', border:'1px solid var(--color-border)',
          color:'var(--color-text-secondary)',
          padding:'1px 7px', borderRadius: 999,
        }}>{tickets.length}</span>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap: 8, flex: 1 }}>
        {tickets.length === 0 && (
          <div style={{ fontSize: 12, color:'var(--color-text-muted)', textAlign:'center', padding: '24px 12px', fontStyle:'italic' }}>
            Sin tickets
          </div>
        )}
        {tickets.map(t => {
          const cat = (D.PM_CATEGORIES && 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={() => { window.BW_OPEN_TICKET = t.id; onNav && onNav('ticket_detail'); }} style={{
              background:'white',
              border:'1px solid var(--color-border)',
              borderRadius: 8,
              padding: 10,
              cursor:'pointer',
              transition:'border-color .12s, box-shadow .12s',
            }}
              onMouseEnter={e => { e.currentTarget.style.borderColor='var(--color-border-strong)'; e.currentTarget.style.boxShadow='0 2px 8px -2px rgba(15,23,42,.08)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor='var(--color-border)'; e.currentTarget.style.boxShadow='none'; }}
            >
              <div style={{ display:'flex', alignItems:'center', gap: 6, marginBottom: 6 }}>
                <span style={{ width: 22, height: 22, borderRadius: 6, background: cat.bg, color: cat.color, display:'inline-grid', placeItems:'center', flex:'0 0 22px' }}>
                  <CatIc size={12}/>
                </span>
                <span className="mono" style={{ fontSize: 10.5, color:'var(--color-text-muted)' }}>{t.id}</span>
                <span style={{
                  marginLeft:'auto',
                  fontSize: 9, fontWeight: 700, letterSpacing:'0.08em', textTransform:'uppercase',
                  padding:'1px 5px', borderRadius: 3,
                  background: t.priority==='high'?'var(--color-danger-light)':t.priority==='medium'?'var(--color-warning-light)':'var(--color-surface-2)',
                  color:     t.priority==='high'?'var(--color-danger)':     t.priority==='medium'?'var(--color-warning)':     'var(--color-text-secondary)',
                }}>{t.priority}</span>
              </div>
              <div style={{ fontSize: 13, fontWeight: 600, color:'var(--color-text-primary)', marginBottom: 3 }} className="truncate">{t.issue}</div>
              <div style={{ fontSize: 11.5, color:'var(--color-text-muted)' }} className="truncate">{t.tenant} · {t.unit}</div>
              <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginTop: 8 }}>
                <span className={'ch ' + (t.channel==='whatsapp'?'wa':t.channel==='phone'?'ph':'em')} style={{ padding:'2px 7px', fontSize: 10.5 }}>
                  {t.channel==='whatsapp' ? <I.WhatsApp size={11}/> : t.channel==='phone' ? <I.Phone size={11}/> : <I.Mail size={11}/>}
                </span>
                <span style={{ fontSize: 11, color:'var(--color-text-muted)' }}>{t.last}</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

window.TicketsPage = TicketsPage;
