// ResultsPage.jsx
function ResultsPage({ store, updateStore, precincts, tweaks, onPrecinctClick, flash }) {
  const visibleCands = window.CANDIDATES.filter(c => tweaks.showCandidates.includes(c.id));

  // Aggregate countywide totals
  const totals = React.useMemo(() => {
    const t = {};
    visibleCands.forEach(c => t[c.id] = 0);
    let totalBallots = 0;
    let totalEnteredVotes = 0;
    let reported = 0;
    for (const p of precincts) {
      const r = store.results[p.id];
      if (!r) continue;
      reported++;
      totalBallots += r.totalBallots || 0;
      visibleCands.forEach(c => {
        const v = r[c.id] || 0;
        t[c.id] += v;
        totalEnteredVotes += v;
      });
    }
    return { byCand: t, totalBallots, totalEnteredVotes, reported };
  }, [store.results, precincts, visibleCands]);

  const ranked = visibleCands
    .map(c => ({ ...c, votes: totals.byCand[c.id] }))
    .sort((a, b) => b.votes - a.votes);
  const topVotes = ranked[0]?.votes || 0;

  // Lowery threshold
  const loweryVotes = totals.byCand.lowery || 0;
  const denomForPct = totals.totalBallots || totals.totalEnteredVotes;
  const loweryPct = denomForPct ? loweryVotes / denomForPct : 0;
  const winThreshold = tweaks.winThreshold / 100;
  const onPace = loweryPct >= winThreshold;

  const reportingPct = precincts.length ? totals.reported / precincts.length : 0;

  return (
    <div>
      <div className="kpi-row">
        <div className="kpi lowery">
          <div className="kpi-label">Lowery · Live</div>
          <div className="kpi-value">{fmtPct(loweryPct, 1)}</div>
          <div className={'kpi-sub ' + (onPace ? 'up' : 'down')}>
            {fmtNum(loweryVotes)} votes · target {tweaks.winThreshold}%
          </div>
        </div>
        <div className="kpi accent">
          <div className="kpi-label">Precincts Reporting</div>
          <div className="kpi-value">{totals.reported} / {precincts.length}</div>
          <div className="kpi-sub">{fmtPct(reportingPct, 0)} reported</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Total Ballots Cast</div>
          <div className="kpi-value">{fmtNum(totals.totalBallots)}</div>
          <div className="kpi-sub">Sum of entered totals</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Outstanding Precincts</div>
          <div className="kpi-value">{precincts.length - totals.reported}</div>
          <div className="kpi-sub">Click 'Enter Results' on Turnout cells</div>
        </div>
      </div>

      <div className="section">
        <div className="section-head">
          <h2 className="section-title">Live Countywide Tally</h2>
          <div className="section-spacer"></div>
          <span className="muted" style={{fontSize:12}}>{totals.reported} of {precincts.length} precincts</span>
        </div>
        <div className="section-body">
          {ranked.map((c, i) => {
            const pct = denomForPct ? c.votes / denomForPct : 0;
            const widthPct = topVotes ? (c.votes / topVotes) * 100 : 0;
            return (
              <div key={c.id} className="cand-row">
                <div className="cand-rank">{i + 1}</div>
                <div>
                  <div className={'cand-name ' + (c.isClient ? 'lowery' : '')}>
                    {c.name}{c.isClient ? ' ★' : ''}
                  </div>
                  <div className="cand-bar-wrap">
                    <div className={'cand-bar-fill ' + (c.isClient ? 'lowery' : '')} style={{width: widthPct + '%'}}></div>
                  </div>
                </div>
                <div className="cand-num">{fmtNum(c.votes)}</div>
                <div className="cand-pct" style={c.isClient ? {color: 'var(--vs-teal)'} : {}}>{fmtPct(pct, 1)}</div>
              </div>
            );
          })}
          {totals.reported === 0 && (
            <p className="muted" style={{textAlign:'center', padding:'20px 0'}}>
              No results entered yet. Open a precinct from the Turnout grid to enter results.
            </p>
          )}
        </div>
      </div>

      <ResultsTable
        store={store}
        precincts={precincts}
        visibleCands={visibleCands}
        onPrecinctClick={onPrecinctClick}
      />
    </div>
  );
}

function ResultsTable({ store, precincts, visibleCands, onPrecinctClick }) {
  const [filter, setFilter] = React.useState('');
  const [onlyReported, setOnlyReported] = React.useState(false);

  const rows = precincts
    .filter(p => {
      if (onlyReported && !store.results[p.id]) return false;
      const q = filter.trim().toLowerCase();
      if (!q) return true;
      return p.id.toLowerCase().includes(q) || p.location.toLowerCase().includes(q);
    });

  return (
    <div className="section">
      <div className="section-head">
        <h2 className="section-title">By Precinct</h2>
        <div className="section-spacer"></div>
        <div className="row">
          <input className="input" placeholder="Filter" value={filter} onChange={e=>setFilter(e.target.value)} style={{width:200}} />
          <button className={'btn ' + (onlyReported ? '' : 'ghost')} onClick={()=>setOnlyReported(v=>!v)}>
            {onlyReported ? 'Showing reported' : 'All precincts'}
          </button>
        </div>
      </div>
      <div className="section-body" style={{padding:0}}>
        <div style={{overflowX:'auto', maxHeight: 600}}>
          <table className="tbl">
            <thead>
              <tr>
                <th>PCT</th>
                <th>Location</th>
                {visibleCands.map(c => (
                  <th key={c.id} className="num">{c.short}</th>
                ))}
                <th className="num">Total</th>
                <th className="num">Lowery %</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {rows.map(p => {
                const r = store.results[p.id];
                const totalEntered = r ? visibleCands.reduce((s, c) => s + (r[c.id] || 0), 0) : 0;
                const denom = r ? (r.totalBallots || totalEntered) : 0;
                const lowPct = denom && r ? (r.lowery || 0) / denom : null;
                return (
                  <tr key={p.id} onClick={()=>onPrecinctClick(p)} style={{cursor:'pointer'}}>
                    <td><b>{p.id}</b></td>
                    <td>{p.location}</td>
                    {visibleCands.map(c => (
                      <td key={c.id} className={'num ' + (c.isClient ? 'delta-pos' : '')}>
                        {r && r[c.id] != null ? fmtNum(r[c.id]) : '—'}
                      </td>
                    ))}
                    <td className="num"><b>{r && r.totalBallots ? fmtNum(r.totalBallots) : '—'}</b></td>
                    <td className="num">{lowPct != null ? fmtPct(lowPct, 1) : '—'}</td>
                    <td><button className="btn sm ghost">{r ? 'Edit' : 'Enter'}</button></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ResultsPage });
