// Statistics screen
const { useMemo: useMemo_st, useState: useState_st } = React;

function StatsScreen({ store }) {
  const { visiblePlayers: players, visibleGroups: groups, isSuper, scope: globalScope, setScope: setGlobalScope } = store;
  const [scope, setScope] = useState_st("all");
  const [tab, setTab] = useState_st("players"); // "players" | "report" | "reco"
  const [reportRange, setReportRange] = useState_st("30");

  // Date picker — for players tab
  const todayStr = new Date().toISOString().slice(0, 10);
  const [date, setDate] = useState_st(todayStr);

  const availableDates = useMemo_st(() => {
    const days = new Set();
    groups.forEach(g => {
      g.history?.forEach(h => {
        days.add(new Date(h.at).toISOString().slice(0, 10));
      });
    });
    return Array.from(days).sort().reverse();
  }, [groups]);

  const noDataOnDate = !groups.some(g =>
    g.history?.some(h => new Date(h.at).toISOString().slice(0, 10) === date)
  );
  const latestDate = availableDates[0];

  // Player stats (existing — single date)
  const data = useMemo_st(() => {
    const stats = {};
    players.forEach(p => {
      stats[p.id] = { ...p, matches: 0, wins: 0, losses: 0, partners: {} };
    });
    const scopedGroups = scope === "all" ? groups : groups.filter(g => g.id === scope);
    scopedGroups.forEach(g => {
      const filteredHistory = (g.history || []).filter(h =>
        new Date(h.at).toISOString().slice(0, 10) === date
      );
      filteredHistory.forEach(h => {
        h.players.forEach(id => {
          if (!stats[id]) return;
          stats[id].matches += 1;
          if (h.winners) {
            if (h.winners.includes(id)) stats[id].wins += 1;
            else stats[id].losses += 1;
          }
        });
        if (g.mode === "double") {
          const a = [h.players[0], h.players[1]];
          const b = [h.players[2], h.players[3]];
          [a, b].forEach(team => {
            if (team[0] && team[1] && stats[team[0]] && stats[team[1]]) {
              stats[team[0]].partners[team[1]] = (stats[team[0]].partners[team[1]] || 0) + 1;
              stats[team[1]].partners[team[0]] = (stats[team[1]].partners[team[0]] || 0) + 1;
            }
          });
        }
      });
    });
    return Object.values(stats);
  }, [players, groups, scope, date]);

  const allPlayerById = useMemo_st(() => Object.fromEntries(players.map(p => [p.id, p])), [players]);

  // Report data: grouped by date → group → match list
  const reportData = useMemo_st(() => {
    const cutoff = reportRange === "all" ? 0 : Date.now() - parseInt(reportRange) * 86400000;
    const scopedGroups = scope === "all" ? groups : groups.filter(g => g.id === scope);
    const byDate = {};
    scopedGroups.forEach(g => {
      (g.history || []).forEach(h => {
        if (h.at < cutoff) return;
        const d = new Date(h.at).toISOString().slice(0, 10);
        if (!byDate[d]) byDate[d] = {};
        if (!byDate[d][g.id]) byDate[d][g.id] = { group: g, matches: [] };
        byDate[d][g.id].matches.push(h);
      });
    });
    return Object.entries(byDate)
      .sort(([a], [b]) => b.localeCompare(a))
      .map(([dateStr, gmap]) => ({
        dateStr,
        groups: Object.values(gmap).map(({ group, matches }) => {
          const withResult = matches.filter(m => Array.isArray(m.winners) && m.winners.length > 0);
          const teamAWins = withResult.filter(m => m.winners.includes(m.players[0])).length;
          const teamBWins = withResult.length - teamAWins;
          const totalDur = matches.reduce((s, m) => s + (m.duration || 0), 0);
          const avgDur = matches.length ? Math.round(totalDur / matches.length) : 0;
          const winRate = matches.length ? Math.round(withResult.length / matches.length * 100) : 0;
          return { group, matches, withResultCount: withResult.length, teamAWins, teamBWins, totalDur, avgDur, winRate };
        }),
      }));
  }, [groups, scope, reportRange]);

  // Summary totals for report tiles
  const reportTotals = useMemo_st(() => {
    let totalMatches = 0, totalDur = 0, withResult = 0;
    reportData.forEach(({ groups }) => groups.forEach(({ matches, withResultCount }) => {
      totalMatches += matches.length;
      withResult += withResultCount;
      matches.forEach(m => { totalDur += m.duration || 0; });
    }));
    const avgDur = totalMatches ? Math.round(totalDur / totalMatches) : 0;
    const resultRate = totalMatches ? Math.round(withResult / totalMatches * 100) : 0;
    return { totalMatches, totalDur, avgDur, withResult, resultRate };
  }, [reportData]);

  const topByMatches = [...data].sort((a,b) => b.matches - a.matches).slice(0, 10);
  const topByWinRate = [...data].filter(p => p.matches > 0)
    .sort((a,b) => (b.wins/b.matches) - (a.wins/a.matches)).slice(0, 5);

  const totalMatches = data.reduce((s,p) => s + p.matches, 0);
  const totalWins = data.reduce((s,p) => s + p.wins, 0);
  const maxMatches = Math.max(...data.map(d => d.matches), 1);

  function exportPlayersCSV() {
    const rows = [["ชื่อ", "ระดับ", "เพศ", "แมตช์", "ชนะ", "แพ้", "อัตราชนะ%"]];
    [...data].sort((a,b) => b.matches - a.matches).forEach(p => {
      const wr = p.matches ? Math.round(p.wins / p.matches * 100) : 0;
      rows.push([p.name, p.level.toFixed(1), p.gender === "m" ? "ชาย" : p.gender === "f" ? "หญิง" : "ไม่ระบุ", p.matches, p.wins, p.losses, wr]);
    });
    downloadCSV(`stats-players-${date}.csv`, rows);
  }

  function exportReportCSV() {
    const rows = [["วันที่", "ก๊วน", "สนาม", "ทีม A", "ทีม B", "ผู้ชนะ", "เวลา(วิ)", "เริ่มเมื่อ"]];
    reportData.forEach(({ dateStr, groups: dayGroups }) => {
      dayGroups.forEach(({ group, matches }) => {
        matches.forEach(h => {
          const isDouble = group.mode === "double";
          const teamA = isDouble ? h.players.slice(0,2) : [h.players[0]];
          const teamB = isDouble ? h.players.slice(2,4) : [h.players[1]];
          const getName = id => allPlayerById[id]?.name || id;
          const courtName = group.courts.find(c => c.id === h.court)?.name || "";
          const hasResult = Array.isArray(h.winners) && h.winners.length > 0;
          const aWon = hasResult && h.winners.some(id => teamA.includes(id));
          const winner = !hasResult ? "" : aWon ? teamA.map(getName).join(" & ") : teamB.map(getName).join(" & ");
          rows.push([
            dateStr, group.name, courtName,
            teamA.map(getName).join(" & "), teamB.map(getName).join(" & "),
            winner, h.duration || "", new Date(h.at).toISOString().slice(0,19).replace("T"," ")
          ]);
        });
      });
    });
    const label = reportRange === "all" ? "all" : `${reportRange}d`;
    downloadCSV(`stats-report-${label}.csv`, rows);
  }

  return (
    <div className="page" data-screen-label="Stats">
      <div className="sec-head">
        <div>
          <h2 className="sec-title">สถิติ</h2>
          <div className="sec-sub">
            {tab === "players"
              ? `รายงานรายวัน · ${date === todayStr ? "วันนี้" : date}`
              : `รายงานสนาม · ${reportRange === "all" ? "ทั้งหมด" : `${reportRange} วันล่าสุด`}`}
          </div>
        </div>
        <div className="row gap-2" style={{flexWrap:"wrap"}}>
          {isSuper && (
            <Segmented value={globalScope} onChange={setGlobalScope}
              options={[{value:"mine", label:"ของฉัน"}, {value:"all", label:"ทั้งระบบ"}]} />
          )}
          <Segmented value={tab} onChange={setTab}
            options={[{value:"players", label:"สถิติผู้เล่น"}, {value:"report", label:"รายงานสนาม"}, {value:"reco", label:"คำแนะนำระดับ"}]} />
          {tab === "players" ? (
            <>
              <input type="date" value={date} onChange={e => setDate(e.target.value)} style={{width: 160}} />
              <select value={scope} onChange={e => setScope(e.target.value)} style={{maxWidth: 220}}>
                <option value="all">ทุกก๊วน</option>
                {groups.map(g => <option key={g.id} value={g.id}>{g.name}</option>)}
              </select>
              <button className="btn sm" onClick={exportPlayersCSV} title="Export CSV">
                <Icon name="download" size={13} stroke={2} /> CSV
              </button>
            </>
          ) : tab === "report" ? (
            <>
              <select value={reportRange} onChange={e => setReportRange(e.target.value)} style={{maxWidth: 160}}>
                <option value="7">7 วันล่าสุด</option>
                <option value="30">30 วันล่าสุด</option>
                <option value="all">ทั้งหมด</option>
              </select>
              <select value={scope} onChange={e => setScope(e.target.value)} style={{maxWidth: 220}}>
                <option value="all">ทุกก๊วน</option>
                {groups.map(g => <option key={g.id} value={g.id}>{g.name}</option>)}
              </select>
              <button className="btn sm" onClick={exportReportCSV} title="Export CSV">
                <Icon name="download" size={13} stroke={2} /> CSV
              </button>
            </>
          ) : null}
        </div>
      </div>

      {/* ---- PLAYERS TAB ---- */}
      {tab === "players" && <>
        {noDataOnDate && (
          <div className="card card-pad mb-2" style={{background:"var(--orange-soft)", border:"1px solid rgba(255,159,10,0.3)"}}>
            <div className="row gap-2">
              <Icon name="history" size={16} />
              <div className="grow">
                <div style={{fontWeight: 600}}>วันที่ {date} ยังไม่มีข้อมูล</div>
                <div className="small muted">
                  {latestDate ? <>ข้อมูลล่าสุดอยู่ที่ <b>{latestDate}</b></> : "ยังไม่มีข้อมูลบันทึกไว้ไปยังระบบ"}
                </div>
              </div>
              {latestDate && (
                <button className="btn sm" onClick={() => setDate(latestDate)}>
                  ไปยังวันล่าสุด
                </button>
              )}
            </div>
          </div>
        )}

        <section>
          <div className="tile-grid">
            <Tile label="แมตช์ที่ลงเล่นรวม" num={Math.round(totalMatches/2) || totalMatches} sub="หน่วย: เกม" />
            <Tile label="บันทึกผลแล้ว" num={totalWins} sub="ครั้ง" accent="green" />
            <Tile label="ผู้เล่นที่ลงสนาม" num={data.filter(d=>d.matches>0).length} sub={`จาก ${data.length} คน`} />
            <Tile label="ระดับเฉลี่ย" num={avgLevel(data)} sub="Lv ของผู้เล่นทั้งหมด" />
          </div>
        </section>

        <section>
          <h3 className="mb-1" style={{fontSize:15, fontWeight:600, color:"var(--text-3)", letterSpacing:"0.04em", textTransform:"uppercase"}}>
            จำนวนแมตช์ที่ลงเล่น (Top 10)
          </h3>
          <div className="card card-pad">
            {topByMatches.map(p => (
              <div key={p.id} className="row gap-3" style={{padding:"6px 0"}}>
                <div className="stat-bar-name" style={{width:140, fontSize:13.5, fontWeight:500, whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis"}}>
                  {p.name}
                </div>
                <div style={{flex:1, height: 22, background:"var(--bg-inset)", borderRadius: 6, position:"relative", overflow:"hidden"}}>
                  <div style={{
                    width: `${(p.matches/maxMatches)*100}%`, height:"100%",
                    background:`linear-gradient(90deg, ${hashColor(p.id)}, ${hashColor(p.id+"z")})`,
                    borderRadius: 6, transition:"width 0.4s ease"
                  }} />
                  <div style={{position:"absolute", left: 8, top: "50%", transform:"translateY(-50%)", fontSize: 12, fontWeight: 600, color:"white", mixBlendMode:"plus-lighter"}}>
                    {p.matches}
                  </div>
                </div>
                <LevelPill level={p.level} />
              </div>
            ))}
            {!topByMatches.some(p => p.matches) && <div className="empty"><div>ยังไม่มีข้อมูลแมตช์ในขอบเขตนี้</div></div>}
          </div>
        </section>

        <section>
          <div className="row gap-3" style={{flexWrap:"wrap"}}>
            <div className="card grow" style={{minWidth: 300}}>
              <div className="card-pad" style={{borderBottom:"0.5px solid var(--sep-soft)"}}>
                <div style={{fontWeight:600}}>อัตราชนะสูงสุด</div>
                <div className="small muted">เฉพาะผู้ที่ลงเล่น ≥ 1 แมตช์</div>
              </div>
              {topByWinRate.length ? topByWinRate.map((p,i) => (
                <div key={p.id} className="card-row">
                  <div style={{width:24, fontWeight:700, color:"var(--text-3)"}}>{i+1}</div>
                  <div className="grow">
                    <div style={{fontWeight:500}}>{p.name}</div>
                    <div className="small muted">{p.matches} แมตช์ · {p.wins}W / {p.losses}L</div>
                  </div>
                  <div style={{fontWeight:700, color:"var(--green)", fontSize: 16}}>
                    {Math.round(p.wins/p.matches*100)}%
                  </div>
                </div>
              )) : <div className="empty"><div>ยังไม่มีข้อมูล</div></div>}
            </div>

            <div className="card grow" style={{minWidth: 300}}>
              <div className="card-pad" style={{borderBottom:"0.5px solid var(--sep-soft)"}}>
                <div style={{fontWeight:600}}>คู่ที่จับบ่อยที่สุด</div>
                <div className="small muted">ทีมคู่ในแมตช์ประเภทคู่</div>
              </div>
              <PartnerList data={data} />
            </div>
          </div>
        </section>

        <section>
          <h3 className="mb-1" style={{fontSize:15, fontWeight:600, color:"var(--text-3)", letterSpacing:"0.04em", textTransform:"uppercase"}}>
            กระจายระดับฝีมือผู้เล่น
          </h3>
          <div className="card card-pad">
            <LevelDistribution players={players} />
          </div>
        </section>
      </>}

      {/* ---- REPORT TAB ---- */}
      {tab === "report" && <>
        <section>
          <div className="tile-grid">
            <Tile label="แมตช์ทั้งหมด" num={reportTotals.totalMatches} sub="ในช่วงเวลาที่เลือก" />
            <Tile label="เวลารวมทั้งหมด" num={fmtSecs(reportTotals.totalDur)} sub="นาที:วินาที" accent="green" />
            <Tile label="เฉลี่ยต่อแมตช์" num={fmtSecs(reportTotals.avgDur)} sub="ระยะเวลาต่อเกม" />
            <Tile label="บันทึกผลแล้ว" num={`${reportTotals.resultRate}%`} sub={`${reportTotals.withResult}/${reportTotals.totalMatches} แมตช์`} />
          </div>
        </section>

        {!reportData.length
          ? <div className="card empty"><div className="em">📊</div><div>ยังไม่มีข้อมูลในช่วงเวลาที่เลือก</div></div>
          : reportData.map(({ dateStr, groups: dayGroups }) => (
            <section key={dateStr}>
              <h3 style={{margin:"0 0 10px", fontSize:15, fontWeight:700, color:"var(--text-3)", letterSpacing:"0.04em", textTransform:"uppercase"}}>
                {fmtDateLong(dateStr)}
              </h3>
              {dayGroups.map(({ group, matches, withResultCount, teamAWins, teamBWins, totalDur, avgDur, winRate }) => (
                <div key={group.id} className="card" style={{marginBottom:14}}>
                  {/* Group summary header */}
                  <div className="card-pad" style={{borderBottom:"0.5px solid var(--sep-soft)", display:"flex", gap:12, alignItems:"center", flexWrap:"wrap"}}>
                    <div className="row gap-2">
                      <span className="dot" style={{background:group.color, width:10, height:10, flexShrink:0}} />
                      <div>
                        <div className="row gap-2">
                          <span style={{fontWeight:700, fontSize:15}}>{group.name}</span>
                          <span className="chip">{group.mode === "double" ? "คู่" : "เดี่ยว"}</span>
                        </div>
                        <div className="small muted mt-1" style={{display:"flex", gap:10, flexWrap:"wrap"}}>
                          <span>{matches.length} แมตช์</span>
                          <span>·</span>
                          <span><Icon name="clock" size={11} /> รวม {fmtSecs(totalDur)}</span>
                          <span>·</span>
                          <span>เฉลี่ย {fmtSecs(avgDur)}/แมตช์</span>
                          {withResultCount > 0 && <>
                            <span>·</span>
                            <span>ทีม A ชนะ {teamAWins} · ทีม B ชนะ {teamBWins}</span>
                          </>}
                        </div>
                      </div>
                    </div>
                    <div style={{marginLeft:"auto", textAlign:"right", flexShrink:0}}>
                      <div style={{fontWeight:800, fontSize:22, lineHeight:1, color: winRate >= 80 ? "var(--green)" : winRate >= 50 ? "var(--tint)" : "var(--text-2)"}}>
                        {winRate}%
                      </div>
                      <div className="small muted">บันทึกผล {withResultCount}/{matches.length}</div>
                    </div>
                  </div>

                  {/* Match rows */}
                  {matches.map((h, i) => {
                    const courtName = group.courts.find(c => c.id === h.court)?.name;
                    const isDouble = group.mode === "double";
                    const teamA = isDouble ? h.players.slice(0,2) : [h.players[0]];
                    const teamB = isDouble ? h.players.slice(2,4) : [h.players[1]];
                    const hasResult = Array.isArray(h.winners) && h.winners.length > 0;
                    const aWon = hasResult && h.winners.some(id => teamA.includes(id));
                    return (
                      <div key={h.id} className="card-row" style={{gap:10, flexWrap:"wrap"}}>
                        <div className="muted" style={{width:20, textAlign:"right", fontSize:12, flexShrink:0}}>
                          {i+1}
                        </div>
                        {courtName && (
                          <span className="chip" style={{fontSize:11, flexShrink:0}}>สนาม {courtName}</span>
                        )}
                        {/* Team A */}
                        <div className="row gap-1" style={{flexShrink:0}}>
                          {hasResult && (
                            <span className={`chip ${aWon ? "green" : ""}`} style={{fontSize:10, padding:"1px 5px", fontWeight:700}}>
                              {aWon ? "W" : "L"}
                            </span>
                          )}
                          <span style={{fontSize:13}}>
                            {teamA.map(id => allPlayerById[id]?.name?.split(" ")[0] || "?").join(" & ")}
                          </span>
                        </div>
                        <span className="muted small">vs</span>
                        {/* Team B */}
                        <div className="row gap-1" style={{flexShrink:0}}>
                          {hasResult && (
                            <span className={`chip ${!aWon ? "green" : ""}`} style={{fontSize:10, padding:"1px 5px", fontWeight:700}}>
                              {!aWon ? "W" : "L"}
                            </span>
                          )}
                          <span style={{fontSize:13}}>
                            {teamB.map(id => allPlayerById[id]?.name?.split(" ")[0] || "?").join(" & ")}
                          </span>
                        </div>
                        <div style={{marginLeft:"auto", display:"flex", gap:8, alignItems:"center", flexShrink:0}}>
                          {!hasResult && <span className="muted small">ไม่บันทึกผล</span>}
                          {h.duration != null
                            ? <span className="chip" style={{fontVariantNumeric:"tabular-nums", fontSize:12}}>
                                <Icon name="clock" size={11} /> {fmtSecs(h.duration)}
                              </span>
                            : <span className="muted small">—</span>}
                          <span className="muted small">{fmtTime(h.at)}</span>
                        </div>
                      </div>
                    );
                  })}
                </div>
              ))}
            </section>
          ))
        }
      </>}

      {tab === "reco" && <RecommendationsScreen store={store} embedded />}
    </div>
  );
}

function PartnerList({ data }) {
  const pairs = useMemo_st(() => {
    const seen = new Set();
    const list = [];
    data.forEach(p => {
      Object.entries(p.partners || {}).forEach(([pid, count]) => {
        const key = [p.id, pid].sort().join("-");
        if (seen.has(key)) return;
        seen.add(key);
        const partner = data.find(d => d.id === pid);
        if (!partner) return;
        list.push({ a: p, b: partner, count });
      });
    });
    return list.sort((x, y) => y.count - x.count).slice(0, 5);
  }, [data]);

  if (!pairs.length) return <div className="empty"><div>ยังไม่มีคู่ที่จับซ้ำ</div></div>;
  return pairs.map((pair, i) => (
    <div key={i} className="card-row">
      <div className="grow">
        <div style={{fontWeight:500}}>{pair.a.name} <span className="muted">&</span> {pair.b.name}</div>
        <div className="small muted">Lv {pair.a.level.toFixed(1)} + Lv {pair.b.level.toFixed(1)} = ทีมเฉลี่ย Lv {((pair.a.level+pair.b.level)/2).toFixed(1)}</div>
      </div>
      <span className="chip blue">{pair.count} ครั้ง</span>
    </div>
  ));
}

function LevelDistribution({ players }) {
  const buckets = Array(10).fill(0);
  players.forEach(p => {
    const b = Math.max(1, Math.min(10, Math.floor(p.level)));
    buckets[b - 1] += 1;
  });
  const max = Math.max(...buckets, 1);

  return (
    <div style={{display:"grid", gridTemplateColumns:"repeat(10, 1fr)", gap: 8, alignItems:"end", height: 160}}>
      {buckets.map((c, i) => (
        <div key={i} style={{display:"flex", flexDirection:"column", alignItems:"center", gap:4, height:"100%"}}>
          <div className="small muted" style={{fontFeatureSettings:'"tnum"'}}>{c}</div>
          <div style={{flex:1, display:"flex", alignItems:"flex-end", width:"100%"}}>
            <div style={{
              width:"100%",
              height: `${(c/max)*100}%`,
              minHeight: c ? 6 : 2,
              background: `var(--tint)`,
              opacity: c ? 0.85 : 0.15,
              borderRadius: "6px 6px 2px 2px",
              transition: "height 0.4s ease",
            }} />
          </div>
          <div className="small" style={{fontWeight:600}}>Lv{i+1}</div>
        </div>
      ))}
    </div>
  );
}

function downloadCSV(filename, rows) {
  const escape = v => {
    const s = String(v == null ? "" : v);
    return s.includes(",") || s.includes('"') || s.includes("\n")
      ? `"${s.replace(/"/g, '""')}"` : s;
  };
  const csv = "﻿" + rows.map(r => r.map(escape).join(",")).join("\r\n");
  const a = document.createElement("a");
  a.href = URL.createObjectURL(new Blob([csv], { type: "text/csv;charset=utf-8;" }));
  a.download = filename;
  a.click();
  URL.revokeObjectURL(a.href);
}

function fmtSecs(s) {
  if (!s) return "—";
  const m = Math.floor(s / 60), ss = s % 60;
  return `${m}:${String(ss).padStart(2, "0")}`;
}

function fmtDateLong(dateStr) {
  const d = new Date(dateStr + "T00:00:00");
  return d.toLocaleDateString("th-TH", {
    year: "numeric", month: "long", day: "numeric", weekday: "long",
  });
}

Object.assign(window, { StatsScreen });
