// Source Quality View — compares SportsNet/CultureNet vs MC handle accuracy

const SQ_PLATFORM_NAMES = Object.fromEntries(
  (typeof PLATFORMS !== 'undefined' ? PLATFORMS : []).map(p => [p.id, p.name])
);

const fmtBreakdownName = (tab, value) => {
  if (tab === 'platform') return SQ_PLATFORM_NAMES[value] || value;
  return value;
};

function SourceQualityView({ makeAuthenticatedRequest }) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [qcOnly, setQcOnly] = useState(true);
  const [tab, setTab] = useState('country');
  const [sortKey, setSortKey] = useState('name');
  const [sortDir, setSortDir] = useState('asc');
  const [search, setSearch] = useState('');

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError(null);
    setData(null);
    makeAuthenticatedRequest(
      `${API_URL}/people/source-quality/stats?qc_only=${qcOnly}`
    )
      .then(res => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      })
      .then(d => { if (!cancelled) setData(d); })
      .catch(err => { if (!cancelled) setError(err.message); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [qcOnly]);

  const qualColor = (p) => {
    if (p == null) return 'var(--border-2)';
    if (p >= 95) return 'var(--ok)';
    if (p >= 75) return 'var(--warn)';
    return 'var(--err)';
  };

  const fmtPct = (n) => (typeof n === 'number' ? n.toFixed(1) : '—');

  // Resolve the row-name key for the current tab
  const nameKey = useMemo(() => {
    if (tab === 'country') return 'country';
    if (tab === 'platform') return 'platform';
    // For type breakdown we don't know the key name upfront; detect from first row
    const rows = data?.type_breakdown || [];
    if (rows.length === 0) return 'type';
    const first = rows[0];
    return Object.keys(first).find(k => k !== 'sportsnet_culturenet' && k !== 'mc') || 'type';
  }, [tab, data]);

  const rawRows = useMemo(() => {
    if (!data) return [];
    if (tab === 'country') return data.country_breakdown || [];
    if (tab === 'platform') return data.platform_breakdown || [];
    return data.type_breakdown || [];
  }, [data, tab]);

  const breakdownData = useMemo(() => {
    let rows = rawRows;
    if (search) {
      const q = search.toLowerCase();
      rows = rows.filter(r => (r[nameKey] || '').toLowerCase().includes(q));
    }
    return [...rows].sort((a, b) => {
      let av, bv;
      if (sortKey === 'name') {
        av = (a[nameKey] || '').toLowerCase();
        bv = (b[nameKey] || '').toLowerCase();
      } else if (sortKey === 'sn') {
        av = a.sportsnet_culturenet?.quality_percentage ?? -1;
        bv = b.sportsnet_culturenet?.quality_percentage ?? -1;
      } else if (sortKey === 'mc') {
        av = a.mc?.quality_percentage ?? -1;
        bv = b.mc?.quality_percentage ?? -1;
      } else {
        // delta
        av = (a.mc?.quality_percentage ?? 0) - (a.sportsnet_culturenet?.quality_percentage ?? 0);
        bv = (b.mc?.quality_percentage ?? 0) - (b.sportsnet_culturenet?.quality_percentage ?? 0);
      }
      if (av < bv) return sortDir === 'asc' ? -1 : 1;
      if (av > bv) return sortDir === 'asc' ? 1 : -1;
      return 0;
    });
  }, [rawRows, nameKey, search, sortKey, sortDir]);

  const toggleSort = (key) => {
    if (sortKey === key) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortKey(key); setSortDir('asc'); }
  };

  const SortArrow = ({ col }) => (
    <span style={{opacity: sortKey === col ? 1 : 0.3, marginLeft: 3}}>
      {sortKey === col ? (sortDir === 'asc' ? '↑' : '↓') : '↕'}
    </span>
  );

  const snSummary = data?.summary?.['SportsNet/CultureNet'];
  const mcSummary = data?.summary?.['MC'];
  const delta = (mcSummary && snSummary)
    ? mcSummary.quality_percentage - snSummary.quality_percentage
    : null;

  return (
    <>
      {/* Toolbar */}
      <div className="report-scope">
        <span style={{fontSize: 12, color: 'var(--muted)'}}>Count:</span>
        <button
          onClick={() => setQcOnly(false)}
          className={`chip ${!qcOnly ? 'active' : ''}`}
          style={{fontSize: 12}}
        >
          Verified + QC
        </button>
        <button
          onClick={() => setQcOnly(true)}
          className={`chip ${qcOnly ? 'active' : ''}`}
          style={{fontSize: 12}}
        >
          QC only
        </button>
        {data && (
          <span style={{fontSize: 12, color: 'var(--muted)', marginLeft: 4}}>
            · {data.total_handles_counted?.toLocaleString()} handles counted
          </span>
        )}
        <div className="spacer"/>
        {loading && (
          <span style={{fontSize: 12, color: 'var(--muted)', display: 'flex', alignItems: 'center', gap: 6}}>
            <Icon name="loader" size={12}/> Refreshing…
          </span>
        )}
      </div>

      <div className="scroll">
        {/* Loading skeleton */}
        {loading && !data && (
          <div style={{padding: '80px 20px', textAlign: 'center', color: 'var(--muted)', fontSize: 14}}>
            Loading source quality data…
          </div>
        )}

        {/* Error state */}
        {error && (
          <div style={{padding: '60px 20px', textAlign: 'center'}}>
            <div style={{color: 'var(--err)', fontWeight: 600, marginBottom: 8}}>Failed to load</div>
            <div style={{fontSize: 13, color: 'var(--muted)'}}>{error}</div>
          </div>
        )}

        {data && (
          <>
            {/* ── Hero comparison ─────────────────────────────── */}
            <div style={{padding: '20px 16px 0'}}>
              <div style={{
                display: 'grid',
                gridTemplateColumns: '1fr 72px 1fr',
                gap: 0,
                alignItems: 'stretch',
              }}>
                {/* SN/CN card */}
                <SQSourceCard
                  label="SportsNet / CultureNet"
                  stats={snSummary}
                  qualColor={qualColor}
                  fmtPct={fmtPct}
                  side="left"
                />

                {/* VS divider */}
                <div style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: 8,
                  padding: '0 4px',
                }}>
                  <span style={{
                    fontSize: 11, fontWeight: 700, letterSpacing: '0.1em',
                    color: 'var(--muted)', textTransform: 'uppercase',
                  }}>VS</span>
                  {delta != null && (
                    <span style={{
                      fontSize: 12, fontWeight: 700,
                      color: delta > 0 ? 'var(--ok)' : delta < 0 ? 'var(--err)' : 'var(--muted)',
                      padding: '3px 8px',
                      borderRadius: 99,
                      background: delta > 0 ? 'var(--ok-2)' : delta < 0 ? 'var(--err-2)' : 'var(--surface-2)',
                      textAlign: 'center',
                      fontVariantNumeric: 'tabular-nums',
                    }}>
                      {delta > 0 ? '+' : ''}{delta.toFixed(1)}pp
                    </span>
                  )}
                </div>

                {/* MC card */}
                <SQSourceCard
                  label="MC"
                  stats={mcSummary}
                  qualColor={qualColor}
                  fmtPct={fmtPct}
                  side="right"
                />
              </div>
            </div>

            {/* ── Breakdown tabs ───────────────────────────────── */}
            <div style={{
              display: 'flex', gap: 4, alignItems: 'center',
              padding: '16px 16px 0',
              borderBottom: '1px solid var(--border)',
            }}>
              {[
                { id: 'country',  label: 'By Country',  count: (data.country_breakdown || []).length },
                { id: 'platform', label: 'By Platform', count: (data.platform_breakdown || []).length },
                { id: 'type',     label: 'By Type',     count: (data.type_breakdown || []).length },
              ].map(t => (
                <button
                  key={t.id}
                  className={`chip ${tab === t.id ? 'active' : ''}`}
                  onClick={() => {
                    setTab(t.id);
                    setSortKey('name');
                    setSortDir('asc');
                    setSearch('');
                  }}
                >
                  {t.label}
                  {t.count > 0 && <span className="count">{t.count}</span>}
                </button>
              ))}
              <div className="spacer"/>
              {tab === 'country' && (
                <div className="search" style={{width: 200}}>
                  <Icon name="search" size={14} stroke="var(--muted)"/>
                  <input
                    placeholder="Filter countries…"
                    value={search}
                    onChange={e => setSearch(e.target.value)}
                  />
                </div>
              )}
            </div>

            {/* ── Breakdown table ──────────────────────────────── */}
            <div style={{padding: '0 16px 32px'}}>
              <table className="data" style={{marginTop: 12}}>
                <thead>
                  <tr>
                    <th
                      style={{cursor: 'pointer', userSelect: 'none'}}
                      onClick={() => toggleSort('name')}
                    >
                      {tab === 'country' ? 'Country' : tab === 'platform' ? 'Platform' : 'Type'}
                      <SortArrow col="name"/>
                    </th>
                    <th
                      style={{cursor: 'pointer', userSelect: 'none', width: '34%'}}
                      onClick={() => toggleSort('sn')}
                    >
                      SportsNet / CultureNet <SortArrow col="sn"/>
                    </th>
                    <th
                      style={{cursor: 'pointer', userSelect: 'none', width: '34%'}}
                      onClick={() => toggleSort('mc')}
                    >
                      MC <SortArrow col="mc"/>
                    </th>
                    <th
                      style={{cursor: 'pointer', userSelect: 'none', width: 72, textAlign: 'right'}}
                      onClick={() => toggleSort('delta')}
                    >
                      Δ MC−SN <SortArrow col="delta"/>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {breakdownData.length === 0 && (
                    <tr>
                      <td colSpan={4} style={{
                        textAlign: 'center', color: 'var(--muted)',
                        padding: '40px 0', fontSize: 13,
                      }}>
                        {search ? 'No matches' : 'No data available'}
                      </td>
                    </tr>
                  )}
                  {breakdownData.map((row, i) => {
                    const name = fmtBreakdownName(tab, row[nameKey] || '—');
                    const sn = row.sportsnet_culturenet;
                    const mc = row.mc;
                    const rowDelta = (mc?.quality_percentage != null && sn?.quality_percentage != null)
                      ? mc.quality_percentage - sn.quality_percentage
                      : null;
                    return (
                      <tr key={i}>
                        <td style={{fontWeight: 500}}>{name}</td>
                        <td><SQQualCell stats={sn} qualColor={qualColor} fmtPct={fmtPct}/></td>
                        <td><SQQualCell stats={mc} qualColor={qualColor} fmtPct={fmtPct}/></td>
                        <td style={{textAlign: 'right', fontSize: 12, fontWeight: 600, fontVariantNumeric: 'tabular-nums'}}>
                          {rowDelta != null ? (
                            <span style={{
                              color: Math.abs(rowDelta) < 0.1 ? 'var(--muted)' :
                                     rowDelta > 0 ? 'var(--ok)' : 'var(--err)',
                            }}>
                              {rowDelta > 0 ? '+' : ''}{rowDelta.toFixed(1)}pp
                            </span>
                          ) : '—'}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </>
        )}
      </div>
    </>
  );
}

// Hero card showing overall quality for one source
function SQSourceCard({ label, stats, qualColor, fmtPct, side }) {
  if (!stats) return <div/>;
  const q = stats.quality_percentage;
  const color = qualColor(q);

  return (
    <div style={{
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      borderRadius: side === 'left' ? 'var(--radius-lg) 0 0 var(--radius-lg)' : '0 var(--radius-lg) var(--radius-lg) 0',
      padding: '22px 24px',
      display: 'flex',
      flexDirection: 'column',
      gap: 10,
      borderLeft: side === 'left' ? `4px solid ${color}` : '1px solid var(--border)',
      borderRight: side === 'right' ? `4px solid ${color}` : '1px solid var(--border)',
    }}>
      <div style={{
        fontSize: 11, fontWeight: 600, textTransform: 'uppercase',
        letterSpacing: '0.07em', color: 'var(--muted)',
      }}>
        {label}
      </div>

      <div style={{display: 'flex', alignItems: 'baseline', gap: 8}}>
        <span style={{
          fontSize: 48, fontWeight: 700, letterSpacing: '-0.03em',
          color, fontVariantNumeric: 'tabular-nums', lineHeight: 1,
        }}>
          {fmtPct(q)}%
        </span>
        <span style={{fontSize: 13, color: 'var(--muted)'}}>quality score</span>
      </div>

      {/* Big progress bar */}
      <div style={{height: 10, background: 'var(--surface-2)', borderRadius: 99, overflow: 'hidden'}}>
        <div style={{
          height: '100%',
          width: `${Math.max(0, Math.min(100, q ?? 0))}%`,
          background: color,
          borderRadius: 99,
          transition: 'width 0.6s cubic-bezier(.4,0,.2,1)',
        }}/>
      </div>

      {/* Counts */}
      <div style={{display: 'flex', gap: 20, fontSize: 12}}>
        <span style={{color: 'var(--muted)'}}>
          <span style={{color: 'var(--ink)', fontWeight: 600, fontVariantNumeric: 'tabular-nums'}}>
            {stats.correct_count?.toLocaleString()}
          </span>{' '}correct
        </span>
        <span style={{color: 'var(--muted)'}}>
          <span style={{color: 'var(--ink)', fontWeight: 600, fontVariantNumeric: 'tabular-nums'}}>
            {stats.total_count?.toLocaleString()}
          </span>{' '}total
        </span>
        <span style={{color: 'var(--muted)'}}>
          <span style={{
            color: 'var(--err)', fontWeight: 600, fontVariantNumeric: 'tabular-nums',
          }}>
            {((stats.total_count ?? 0) - (stats.correct_count ?? 0)).toLocaleString()}
          </span>{' '}wrong
        </span>
      </div>
    </div>
  );
}

// Inline quality cell for the breakdown table
function SQQualCell({ stats, qualColor, fmtPct }) {
  if (!stats) return <span style={{color: 'var(--muted)', fontSize: 12}}>—</span>;
  const q = stats.quality_percentage;
  const color = qualColor(q);
  return (
    <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
      <div style={{
        flex: 1, height: 6, background: 'var(--surface-2)',
        borderRadius: 99, overflow: 'hidden', minWidth: 48,
      }}>
        <div style={{
          height: '100%',
          width: `${Math.max(0, Math.min(100, q ?? 0))}%`,
          background: color,
          borderRadius: 99,
        }}/>
      </div>
      <span style={{
        fontSize: 12, fontWeight: 700, color,
        fontVariantNumeric: 'tabular-nums', minWidth: 42, textAlign: 'right',
      }}>
        {fmtPct(q)}%
      </span>
      <span style={{
        fontSize: 11, color: 'var(--muted-2)',
        fontVariantNumeric: 'tabular-nums', minWidth: 64, textAlign: 'right',
      }}>
        {stats.correct_count?.toLocaleString()}/{stats.total_count?.toLocaleString()}
      </span>
    </div>
  );
}
