const { useState: useStateH } = React;

function HistoryPage() {
  const [filter, setFilter] = useStateH("all");

  const list = DB.matches.filter(m => {
    if (filter === "all") return true;
    if (filter === "tarneeb") return m.game === "طرنيب";
    if (filter === "trix")    return m.game === "تركس";
    return true;
  });

  return (
    <div className="screen" data-screen-label="history">
      <header className="app-header">
        <div>
          <div className="app-title">سجل المباريات</div>
          <div className="app-sub">كل مباراة، كل ضحية</div>
        </div>
      </header>

      <div className="filter-row">
        {[{ id: "all", label: "الكل" }, { id: "tarneeb", label: "طرنيب" }, { id: "trix", label: "تركس" }].map(f => (
          <span key={f.id} className={`chip ${filter === f.id ? "active" : ""}`} onClick={() => setFilter(f.id)}>{f.label}</span>
        ))}
      </div>

      {list.length === 0 && (
        <div style={{ textAlign: "center", opacity: 0.5, marginTop: 60, fontFamily: "Lalezar,serif", fontSize: 22 }}>
          {DB.loading ? "جاري التحميل…" : "لا توجد مباريات بعد"}
        </div>
      )}

      {list.map((m, i) => {
        const aWon = m.winner === "A";
        return (
          <div key={m.id} className={`match-card d${Math.min(i, 9)}`}>
            <span className="game-chip">{m.game}</span>
            <span className="date-chip">{arabicDateLabel(m.date)}</span>
            <div className="teams-vs">
              <div className={`team ${aWon ? "winner" : ""}`}>
                <div className="players">
                  {m.teamA.map(id => {
                    const p = byId(id);
                    return p ? (
                      <span key={id} className="ph"><MiniAvatar player={p} />{p.name}</span>
                    ) : null;
                  })}
                </div>
              </div>
              <div className="vs-blob">VS</div>
              <div className={`team ${!aWon ? "winner" : ""}`}>
                <div className="players">
                  {m.teamB.map(id => {
                    const p = byId(id);
                    return p ? (
                      <span key={id} className="ph"><MiniAvatar player={p} />{p.name}</span>
                    ) : null;
                  })}
                </div>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { HistoryPage });