// Reports screen — community-flagged tracks, with admin force-delete /
// dismiss actions. Mods can view; only admins act.
//
// The list shows reports/dismissals counts + the source track inline so
// an admin can listen-before-deciding without opening another tab.

function ReportsScreen({ me, dark }) {
  const [list, setList] = React.useState(null);
  const audio = useAudio();

  const refresh = React.useCallback(async () => {
    try {
      setList(await Api.reports.list());
    } catch (e) {
      toast.error('Reports laden fehlgeschlagen: ' + e.message);
    }
  }, []);

  React.useEffect(() => { refresh(); }, [refresh]);

  // Auto-refresh every 30s so an open admin tab doesn't go stale during
  // a busy reporting period. Cheap — single GET per cycle.
  React.useEffect(() => {
    const id = setInterval(refresh, 30_000);
    return () => clearInterval(id);
  }, [refresh]);

  const isAdmin = canForceAccept(me);

  const onDismiss = async (id) => {
    if (!confirm('Alle Meldungen für diesen Track verwerfen?\n\nDer Track bleibt online, die Stimmen werden gelöscht.')) return;
    try {
      if (audio.currentId === id) AudioService.stop();
      await Api.reports.dismiss(id);
      await refresh();
      toast.success('Meldungen verworfen.');
    } catch (e) {
      toast.error('Verwerfen fehlgeschlagen: ' + e.message);
    }
  };

  const onForceDelete = async (id) => {
    if (!confirm('Track sofort delisten?\n\nStatus wird auf „Abgelehnt" gesetzt, Track verschwindet aus dem Katalog. Meldungen werden gelöscht. CDN-Dateien bleiben — falls du die auch entfernen willst, geh über den normalen Delete-Knopf.')) return;
    try {
      if (audio.currentId === id) AudioService.stop();
      await Api.reports.forceDelete(id);
      await refresh();
      toast.info('Track delistet.');
    } catch (e) {
      toast.error('Delisten fehlgeschlagen: ' + e.message);
    }
  };

  return (
    <div style={{ padding: '28px 32px', maxWidth: 1100, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 24, marginBottom: 18, flexWrap: 'wrap' }}>
        <div style={{ flex: '1 1 420px' }}>
          <div style={{ fontSize: 12, opacity: 0.55, letterSpacing: 1.4, textTransform: 'uppercase', fontWeight: 700, marginBottom: 4 }}>
            {list ? `${list.length} gemeldet` : 'lädt…'}
          </div>
          <h1 style={{ fontSize: 32, fontWeight: 800, letterSpacing: -0.7, margin: 0 }}>Meldungen</h1>
          <p style={{ fontSize: 14, opacity: 0.6, marginTop: 6, maxWidth: 620 }}>
            Tracks, die Spieler ingame gemeldet haben. Bei <b>60% Zustimmung</b> mit
            mindestens <b>6 Stimmen</b> wird automatisch delistet — Admins können sofort
            entscheiden.
          </p>
        </div>
      </div>

      {list === null ? (
        <ApGlass dark={dark} radius={20} padding={32} style={{ textAlign: 'center', opacity: 0.6 }}>
          Lädt…
        </ApGlass>
      ) : list.length === 0 ? (
        <ApGlass dark={dark} radius={20} padding={48} style={{ textAlign: 'center' }}>
          <ApIcon name="check" size={36} color="#34d399"/>
          <div style={{ fontSize: 16, fontWeight: 700, marginTop: 10 }}>Keine offenen Meldungen</div>
          <div style={{ fontSize: 13, opacity: 0.6, marginTop: 4 }}>
            Sobald Spieler einen Track ingame melden, taucht er hier auf.
          </div>
        </ApGlass>
      ) : (
        <ApGlass dark={dark} radius={20} padding={6}>
          {list.map((r, i) => {
            const total = r.reports + r.dismissals;
            const ratio = total > 0 ? r.reports / total : 0;
            const ratioPct = Math.round(ratio * 100);
            const isPlaying = audio.currentId === r.trackId;
            const submitter = playerByIdent(r.identifier);

            return (
              <div key={r.trackId} style={{
                display: 'flex', alignItems: 'center', gap: 14, padding: '12px 14px', borderRadius: 14,
                borderBottom: i < list.length - 1
                  ? (dark ? '1px solid rgba(255,255,255,0.05)' : '1px solid rgba(0,0,0,0.04)')
                  : 'none',
                background: isPlaying ? 'rgba(255,77,141,0.08)' : 'transparent',
                transition: 'background 0.15s',
              }}>
                <ApCover colors={['#7c3aed', '#ff4d8d']} src={r.coverUrl} size={48} radius={10}/>

                {r.audioUrl && (
                  <button
                    onClick={() => audio.play(r.trackId, r.audioUrl)}
                    title={isPlaying ? 'Pausieren' : 'Anhören'}
                    style={{
                      width: 36, height: 36, borderRadius: '50%',
                      background: isPlaying ? '#ff4d8d' : (dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.05)'),
                      border: dark ? '1px solid rgba(255,255,255,0.12)' : '1px solid rgba(0,0,0,0.08)',
                      color: isPlaying ? '#fff' : 'inherit',
                      cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
                      flexShrink: 0,
                    }}
                  >
                    <ApIcon name={isPlaying ? 'pause' : 'play'} size={14}/>
                  </button>
                )}

                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 700 }}>{r.title}</div>
                  <div style={{ fontSize: 12, opacity: 0.6, display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                    <span>{r.artist}</span>
                    <span style={{ opacity: 0.5 }}>·</span>
                    <span>von <ApPlayerName player={submitter} size={12} opacity={1}/></span>
                    <span style={{ opacity: 0.5 }}>·</span>
                    <span>{timeAgo(r.latest)}</span>
                  </div>
                </div>

                {/* Tally — green dismiss / red report bar with ratio. */}
                <div style={{ minWidth: 150, textAlign: 'right' }}>
                  <div style={{
                    fontSize: 11.5, fontVariantNumeric: 'tabular-nums',
                    color: ratio >= 0.6 ? '#f87171' : 'inherit',
                    fontWeight: ratio >= 0.6 ? 700 : 600,
                    marginBottom: 4,
                  }}>
                    <span style={{ color: '#f87171' }}>{r.reports}</span>
                    {' / '}
                    <span style={{ color: '#34d399' }}>{r.dismissals}</span>
                    {' '}<span style={{ opacity: 0.55 }}>({ratioPct}%)</span>
                  </div>
                  <div style={{ height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.08)', overflow: 'hidden' }}>
                    <div style={{
                      width: `${ratioPct}%`, height: '100%',
                      background: ratio >= 0.6 ? '#f87171' : '#fbbf24',
                      transition: 'width 0.2s',
                    }}/>
                  </div>
                </div>

                <ApStatusPill status={r.status}/>

                {isAdmin && (
                  <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                    <button onClick={() => onDismiss(r.trackId)} title="Meldungen verwerfen — Track bleibt" style={{
                      display: 'flex', alignItems: 'center', gap: 6,
                      padding: '8px 12px', borderRadius: 10,
                      background: 'rgba(52,211,153,0.18)', color: '#34d399',
                      border: '1px solid rgba(52,211,153,0.4)', cursor: 'pointer',
                      fontSize: 12.5, fontWeight: 700,
                    }}>
                      <ApIcon name="check" size={13}/> Passt so
                    </button>
                    <button onClick={() => onForceDelete(r.trackId)} title="Track delisten + Meldungen löschen" style={{
                      display: 'flex', alignItems: 'center', gap: 6,
                      padding: '8px 12px', borderRadius: 10,
                      background: 'rgba(239,68,68,0.18)', color: '#f87171',
                      border: '1px solid rgba(239,68,68,0.4)', cursor: 'pointer',
                      fontSize: 12.5, fontWeight: 700,
                    }}>
                      <ApIcon name="x" size={13}/> Delisten
                    </button>
                  </div>
                )}
              </div>
            );
          })}
        </ApGlass>
      )}
    </div>
  );
}

window.ReportsScreen = ReportsScreen;
