/* Inbox / cases dashboard */

const InboxView = ({ data, onOpen, onNew }) => {
  const [filter, setFilter] = React.useState("all");
  const [query, setQuery] = React.useState("");
  const [selected, setSelected] = React.useState(new Set());

  const counts = React.useMemo(() => {
    const c = { all: data.cases.length, processing: 0, review: 0, approved: 0, error: 0 };
    data.cases.forEach((x) => (c[x.status] = (c[x.status] || 0) + 1));
    return c;
  }, [data]);

  const rows = data.cases.filter(
    (c) =>
      (filter === "all" || c.status === filter) &&
      (query === "" ||
        c.ref.toLowerCase().includes(query.toLowerCase()) ||
        c.sender.toLowerCase().includes(query.toLowerCase()) ||
        c.consignee.toLowerCase().includes(query.toLowerCase()))
  );

  const toggle = (id) => {
    const n = new Set(selected);
    n.has(id) ? n.delete(id) : n.add(id);
    setSelected(n);
  };

  return (
    <div className="page">
      <header>
        <div>
          <h1>Boîte de réception</h1>
          <div className="sub">{data.cases.length} expéditions · {counts.review} à vérifier</div>
        </div>
        <div style={{marginLeft:"auto", display:"flex", gap:8}}>
          <button className="btn"><Icon name="download" size={14}/>Exporter</button>
          <button className="btn accent" onClick={onNew}><Icon name="plus" size={14}/>Nouveau dossier</button>
        </div>
      </header>

      <div className="filterbar">
        <div className="segctl">
          {[
            ["all","Tous"],
            ["processing","En traitement"],
            ["review","À vérifier"],
            ["approved","Validés"],
            ["error","Erreur"],
          ].map(([k,l]) => (
            <button key={k} className={filter===k?"active":""} onClick={() => setFilter(k)}>
              {l}<span className="count">{counts[k] ?? 0}</span>
            </button>
          ))}
        </div>
        <div className="search">
          <Icon name="search" size={14}/>
          <input placeholder="Rechercher par référence, expéditeur, destinataire…" value={query} onChange={(e)=>setQuery(e.target.value)}/>
          <span className="kbd">⌘ K</span>
        </div>
        <button className="btn"><Icon name="filter" size={14}/>Filtres</button>
        <button className="btn"><Icon name="calendar" size={14}/>22 mai 2026</button>
      </div>

      {selected.size > 0 && (
        <div style={{
          display:"flex", alignItems:"center", gap:10,
          background:"var(--ink)", color:"#fff",
          padding:"8px 14px", borderRadius:8, marginBottom:10,
          fontSize:13,
        }}>
          <b>{selected.size}</b> sélectionné{selected.size>1?"s":""}
          <button className="btn sm" style={{background:"transparent", border:"1px solid #444", color:"#fff"}}>Valider en lot</button>
          <button className="btn sm" style={{background:"transparent", border:"1px solid #444", color:"#fff"}}>Affecter…</button>
          <button className="btn sm" style={{background:"transparent", border:"1px solid #444", color:"#fff"}}>Archiver</button>
          <button className="btn sm" style={{background:"transparent", border:"0", color:"#bbb", marginLeft:"auto"}} onClick={()=>setSelected(new Set())}>Désélectionner</button>
        </div>
      )}

      <div className="card" style={{overflow:"hidden"}}>
        <table className="table">
          <thead>
            <tr>
              <th style={{width:32}}>
                <input type="checkbox"
                  checked={selected.size === rows.length && rows.length>0}
                  onChange={() => setSelected(selected.size===rows.length?new Set():new Set(rows.map(r=>r.id)))}
                />
              </th>
              <th style={{width:160}}>Référence</th>
              <th>Expéditeur → Destinataire</th>
              <th>Itinéraire</th>
              <th style={{width:60}}>Source</th>
              <th style={{width:130}}>Statut</th>
              <th style={{width:120}}>À vérifier</th>
              <th style={{width:110}}>Reçu</th>
              <th style={{width:40}}></th>
            </tr>
          </thead>
          <tbody>
            {rows.map((c) => (
              <tr key={c.id} className={c.hero ? "selected" : ""} onClick={() => onOpen(c.id)} style={{cursor:"pointer"}}>
                <td onClick={(e)=>{e.stopPropagation(); toggle(c.id);}}>
                  <input type="checkbox" checked={selected.has(c.id)} readOnly />
                </td>
                <td>
                  <div className="ref">{c.ref}</div>
                  <div style={{fontSize:11, color:"var(--muted)", marginTop:1}}>{c.weight} · {c.value}</div>
                </td>
                <td>
                  <div style={{fontWeight:500}}>{c.sender}</div>
                  <div style={{fontSize:12, color:"var(--muted)"}}>→ {c.consignee}</div>
                </td>
                <td>
                  <div className="route">
                    {c.route.split(" → ").map((p, i, a) => (
                      <React.Fragment key={i}>
                        <span>{p}</span>
                        {i < a.length - 1 && <span className="arr">→</span>}
                      </React.Fragment>
                    ))}
                  </div>
                </td>
                <td><SourceIcon source={c.source}/></td>
                <td><StatusBadge status={c.status}/></td>
                <td>
                  {c.status === "review" ? (
                    <span style={{display:"inline-flex", alignItems:"center", gap:6, color:"var(--med-ink)", fontSize:12, fontWeight:500}}>
                      <Icon name="alert" size={12}/>
                      {c.needsReview} champ{c.needsReview>1?"s":""}
                    </span>
                  ) : c.status === "error" ? (
                    <span style={{fontSize:11.5, color:"var(--lo-ink)"}}>{c.errorMsg}</span>
                  ) : c.status === "processing" ? (
                    <span style={{display:"inline-flex", gap:8, alignItems:"center"}}>
                      <span className="sk" style={{width:60, height:8}}></span>
                    </span>
                  ) : (
                    <span style={{color:"var(--muted-2)", fontSize:12}}>—</span>
                  )}
                </td>
                <td style={{fontSize:12, color:"var(--muted)"}}>{c.received}</td>
                <td><Icon name="chev" size={14} style={{color:"var(--muted-2)"}}/></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div style={{marginTop:14, display:"flex", justifyContent:"space-between", alignItems:"center", color:"var(--muted)", fontSize:12}}>
        <div>Affichage 1–{rows.length} sur {data.cases.length}</div>
        <div style={{display:"flex", gap:6}}>
          <button className="btn sm" disabled>←</button>
          <button className="btn sm">→</button>
        </div>
      </div>
    </div>
  );
};

window.InboxView = InboxView;
