/* crm-contracts.jsx — Contracts list with filters + bulk actions */

function ContractsList({onOpenContract}) {
  const [filter, setFilter] = React.useState('all');
  const [selected, setSelected] = React.useState(new Set());
  const [search, setSearch] = React.useState('');
  const [sortKey, setSortKey] = React.useState('next');
  const [sortDir, setSortDir] = React.useState('asc');

  const filterCounts = React.useMemo(() => {
    const c = { all: CRM_CONTRACTS.length };
    STATE_OPTIONS.forEach(s => { c[s.k] = CRM_CONTRACTS.filter(x => x.state === s.k).length; });
    return c;
  }, []);

  let list = CRM_CONTRACTS;
  if (filter !== 'all') list = list.filter(c => c.state === filter);
  if (search) {
    const q = search.toLowerCase();
    list = list.filter(c => {
      const cust = CRM_BY_ID[c.id];
      return c.id.toLowerCase().includes(q) || (cust && (cust.name.toLowerCase().includes(q) || cust.loc.toLowerCase().includes(q)));
    });
  }
  // Sort
  list = [...list].sort((a, b) => {
    let av, bv;
    if (sortKey === 'next') { av = a.nextDate; bv = b.nextDate; }
    else if (sortKey === 'value') { av = a.value; bv = b.value; }
    else if (sortKey === 'cycle') { av = a.current; bv = b.current; }
    else if (sortKey === 'customer') { av = CRM_BY_ID[a.id]?.name || ''; bv = CRM_BY_ID[b.id]?.name || ''; }
    else { av = a.id; bv = b.id; }
    if (av < bv) return sortDir === 'asc' ? -1 : 1;
    if (av > bv) return sortDir === 'asc' ? 1 : -1;
    return 0;
  });

  const toggle = (id) => {
    const n = new Set(selected);
    n.has(id) ? n.delete(id) : n.add(id);
    setSelected(n);
  };
  const toggleAll = () => {
    if (selected.size === list.length) setSelected(new Set());
    else setSelected(new Set(list.map(c => c.id)));
  };

  const sortBy = (k) => {
    if (sortKey === k) setSortDir(sortDir === 'asc' ? 'desc' : 'asc');
    else { setSortKey(k); setSortDir('asc'); }
  };

  const SortIcon = ({k}) => {
    if (sortKey !== k) return null;
    return <Icon k={sortDir === 'asc' ? 'arrow-up' : 'arrow-dn'} size={10} />;
  };

  const total = list.reduce((s, c) => s + c.value, 0);

  return (
    <div className="content stack gap-5">
      <div className="flex between items-c" style={{alignItems:'flex-end'}}>
        <div>
          <h1 className="page-title">Contratos</h1>
          <div className="page-sub">{list.length} de {CRM_CONTRACTS.length} contratos · valor agregado trimestral {CRM_FMT_EUR(total)}</div>
        </div>
        <div className="row gap-2">
          <button className="btn outline sm"><Icon k="download" size={13}/> Exportar CSV</button>
          <button className="btn primary sm"><Icon k="plus" size={13}/> Novo contrato</button>
        </div>
      </div>

      {/* Filter pills + search */}
      <div className="flex items-c between gap-4" style={{flexWrap:'wrap'}}>
        <div className="row gap-2" style={{flexWrap:'wrap'}}>
          <div className={'pill ' + (filter==='all' ? 'active' : '')} onClick={() => setFilter('all')}>
            Todos <span className="count">{filterCounts.all}</span>
          </div>
          {STATE_OPTIONS.map(s => (
            <div key={s.k} className={'pill ' + (filter===s.k ? 'active' : '')} onClick={() => setFilter(s.k)}>
              {s.label} <span className="count">{filterCounts[s.k] || 0}</span>
            </div>
          ))}
        </div>
        <div className="row gap-2">
          <div style={{position:'relative', width:240}}>
            <input
              type="text"
              placeholder="ID, cliente, localidade…"
              value={search}
              onChange={e => setSearch(e.target.value)}
              className="input"
              style={{height:30, paddingLeft:30, fontSize:12.5}}
            />
            <div style={{position:'absolute', left:9, top:9, pointerEvents:'none'}}>
              <Icon k="search" size={12} color="var(--ink-3)" />
            </div>
          </div>
          <button className="btn outline sm"><Icon k="filter" size={13}/> Mais filtros</button>
        </div>
      </div>

      {/* Selection bar (sticky when items selected) */}
      {selected.size > 0 && (
        <div className="flex items-c between" style={{
          padding:'10px 14px', background:'var(--tobacco)', color:'var(--bone)',
          borderRadius:5,
        }}>
          <div className="row gap-3">
            <span style={{fontSize:13}}>{selected.size} contratos selecionados</span>
            <button className="btn ghost sm" style={{color:'var(--bone)'}} onClick={() => setSelected(new Set())}>Limpar</button>
          </div>
          <div className="row gap-2">
            <button className="btn sm" style={{background:'rgba(242,233,210,0.12)', color:'var(--bone)'}}>Renovar em massa</button>
            <button className="btn sm" style={{background:'rgba(242,233,210,0.12)', color:'var(--bone)'}}>Exportar selecionados</button>
            <button className="btn clay sm">Cobrar agora</button>
          </div>
        </div>
      )}

      {/* Table */}
      <div style={{border:'0.5px solid var(--rule)', borderRadius:6, overflow:'hidden', background:'var(--bone)'}}>
        <table className="t">
          <thead>
            <tr>
              <th style={{width:36}}>
                <input type="checkbox" checked={selected.size === list.length && list.length>0} onChange={toggleAll} style={{margin:0}}/>
              </th>
              <th style={{width:120, cursor:'pointer'}} onClick={() => sortBy('id')}>
                <span className="row gap-1">Contrato <SortIcon k="id"/></span>
              </th>
              <th style={{cursor:'pointer'}} onClick={() => sortBy('customer')}>
                <span className="row gap-1">Cliente <SortIcon k="customer"/></span>
              </th>
              <th style={{width:90}}>Tipo</th>
              <th style={{width:90, cursor:'pointer'}} onClick={() => sortBy('cycle')}>
                <span className="row gap-1">Ciclo <SortIcon k="cycle"/></span>
              </th>
              <th style={{width:130}}>Estado</th>
              <th style={{width:110, cursor:'pointer'}} onClick={() => sortBy('next')}>
                <span className="row gap-1">Próx. cobrança <SortIcon k="next"/></span>
              </th>
              <th className="num" style={{width:110, cursor:'pointer'}} onClick={() => sortBy('value')}>
                <span className="row gap-1" style={{justifyContent:'flex-end'}}>Valor trim. <SortIcon k="value"/></span>
              </th>
              <th style={{width:40}}/>
            </tr>
          </thead>
          <tbody>
            {list.map(c => {
              const cust = CRM_BY_ID[c.id];
              const sel = selected.has(c.id);
              return (
                <tr key={c.id} className="clickable" onClick={() => onOpenContract(c.id)} style={{background: sel ? 'var(--surface-2)' : undefined}}>
                  <td onClick={e => { e.stopPropagation(); toggle(c.id); }}>
                    <input type="checkbox" checked={sel} onChange={() => {}} style={{margin:0}}/>
                  </td>
                  <td className="id">{c.id}</td>
                  <td>
                    <div style={{fontSize:13, fontWeight:500}}>{cust?.name}</div>
                    <div className="ink-3" style={{fontSize:11}}>{cust?.loc}</div>
                  </td>
                  <td className="ink-3">{cust?.kind}</td>
                  <td className="mono tab">{c.current ? `${c.current} / 8` : '—'}</td>
                  <td><StateBadge state={c.state}/></td>
                  <td className="mono tab" style={{fontSize:11.5}}>{c.nextDate}</td>
                  <td className="num" style={{fontWeight:600, fontSize:13}}>{CRM_FMT_EUR(c.value)}</td>
                  <td onClick={e => e.stopPropagation()}>
                    <button className="btn ghost sm" style={{padding:'0 4px'}} title="Mais">
                      <Icon k="more" size={14}/>
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>

        {list.length === 0 && (
          <div style={{padding:'48px 24px', textAlign:'center'}}>
            <div className="display ink-3" style={{fontSize:22, fontStyle:'italic'}}>Nenhum contrato corresponde.</div>
            <div className="ink-3" style={{fontSize:13, marginTop:8}}>Limpa os filtros ou cria um novo contrato.</div>
          </div>
        )}
      </div>

      {/* Pagination */}
      <div className="flex between items-c" style={{padding:'4px 4px 24px'}}>
        <div className="mono ink-3" style={{fontSize:11}}>página 1 / 1 · {list.length} resultados</div>
        <div className="row gap-2">
          <button className="btn outline sm" disabled style={{opacity:0.4}}>← anterior</button>
          <button className="btn outline sm" disabled style={{opacity:0.4}}>seguinte →</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ContractsList });
