// One row in the review queue: cover, metadata, mini player, vote tally,
// vote buttons, optional admin force-accept / force-reject, expandable
// vote breakdown.

function voteBtnStyle(active, accent, dark) {
  return {
    display: 'flex', alignItems: 'center', gap: 6,
    padding: '8px 16px', borderRadius: 10,
    background: active ? accent : (dark ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.7)'),
    color: active ? '#0a0a14' : 'inherit',
    border: active ? `1px solid ${accent}` : (dark ? '1px solid rgba(255,255,255,0.1)' : '1px solid rgba(0,0,0,0.08)'),
    fontSize: 13, fontWeight: 700, cursor: 'pointer',
  };
}

function SubmissionCard({ sub, me, onVote, onForceAccept, onForceReject, onBlockUser, onPlay, onSeek, refresh, isPlaying, audioPos, dark, expanded, onToggle }) {
  const submitter = playerByIdent(sub.identifier);
  const t = tally(sub);
  const myVote = sub.votes.find(v => v.identifier === me.identifier)?.vote;
  const isAdmin = canForceAccept(me);
  // Admins can also vote on their own submissions (the server allows it);
  // for everyone else, the self-vote ban stays.
  const eligible = canVote(me) && (me.identifier !== sub.identifier || isAdmin) && sub.status === 'pending';

  return (
    <ApGlass dark={dark} radius={20} padding={0} style={{ marginBottom: 14, overflow: 'hidden' }}>
      <div style={{ display: 'flex', gap: 18, padding: 18, alignItems: 'center' }}>
        <ApCover colors={sub.cover} src={sub.coverUrl} size={84} radius={14}/>

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
            <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: -0.3 }}>{sub.title}</div>
            <ApStatusPill status={sub.status}/>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, opacity: 0.7, marginBottom: 8 }}>
            <span>{sub.artist}</span>
            <span style={{ opacity: 0.4 }}>·</span>
            <span>{fmt(sub.duration)}</span>
            <span style={{ opacity: 0.4 }}>·</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <ApIcon name="clock" size={12}/> {timeAgo(sub.submittedAt)}
            </span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, opacity: 0.55 }}>
            Hochgeladen von <ApPlayerName player={submitter} size={11.5} opacity={1}/>
          </div>
        </div>

        <button onClick={() => onPlay(sub.id)} style={{
          width: 52, height: 52, borderRadius: '50%', flexShrink: 0,
          background: isPlaying ? '#ff4d8d' : (dark ? 'rgba(255,255,255,0.1)' : 'rgba(255,255,255,0.7)'),
          border: dark ? '1px solid rgba(255,255,255,0.15)' : '1px solid rgba(255,255,255,0.9)',
          color: isPlaying ? '#fff' : 'inherit',
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: isPlaying ? '0 8px 24px rgba(255,77,141,0.45)' : 'none',
          transition: 'all 0.15s',
        }}>
          <ApIcon name={isPlaying ? 'pause' : 'play'} size={20}/>
        </button>

        <div style={{
          display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6,
          minWidth: 96, fontSize: 12,
        }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontVariantNumeric: 'tabular-nums', fontWeight: 700 }}>
            <span style={{ color: '#34d399' }}>{t.accepts}</span>
            <span style={{ opacity: 0.3 }}>/</span>
            <span style={{ color: '#f87171' }}>{t.rejects}</span>
            <span style={{ opacity: 0.4, fontWeight: 500 }}>· {t.total}/{REQUIRED_VOTES}</span>
          </div>
          <div style={{ width: 96, height: 5, borderRadius: 3, background: dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)', overflow: 'hidden' }}>
            <div style={{
              height: '100%', width: `${Math.round(t.ratio * 100)}%`,
              background: t.ratio >= ACCEPT_THRESHOLD ? '#34d399' : '#fbbf24',
              transition: 'width 0.3s',
            }}/>
          </div>
          <div style={{ fontSize: 10.5, opacity: 0.55, fontVariantNumeric: 'tabular-nums' }}>
            {Math.round(t.ratio * 100)}% Zustimmung · {Math.round(ACCEPT_THRESHOLD * 100)}% nötig
          </div>
        </div>

        {isAdmin && refresh && <AdminMenu sub={sub} refresh={refresh} dark={dark}/>}

        <button onClick={onToggle} style={{
          background: 'none', border: 'none', cursor: 'pointer', color: 'inherit', opacity: 0.5,
          padding: 6, transform: expanded ? 'rotate(180deg)' : 'none', transition: 'transform 0.2s',
        }}>
          <ApIcon name="caret" size={20}/>
        </button>
      </div>

      {isPlaying && (
        <div style={{ padding: '0 18px 14px', display: 'flex', alignItems: 'center', gap: 10 }}>
          <ApIcon name="wave" size={14} color="#ff4d8d"/>
          <div
            onClick={(e) => {
              const rect = e.currentTarget.getBoundingClientRect();
              const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
              onSeek?.(sub.id, ratio * sub.duration);
            }}
            style={{
              flex: 1, height: 8, borderRadius: 4, padding: '2px 0',
              background: dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)',
              overflow: 'hidden', cursor: 'pointer', position: 'relative',
            }}
            title="Klicken zum Springen"
          >
            <div style={{
              height: 4, marginTop: 2, width: `${(audioPos / sub.duration) * 100}%`,
              background: 'linear-gradient(90deg, #ff4d8d, #7c3aed)',
              transition: 'width 0.2s linear', borderRadius: 2,
            }}/>
          </div>
          <div style={{ fontSize: 11, opacity: 0.6, fontVariantNumeric: 'tabular-nums', minWidth: 70, textAlign: 'right' }}>
            {fmt(audioPos)} / {fmt(sub.duration)}
          </div>
        </div>
      )}

      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, padding: '12px 18px',
        background: dark ? 'rgba(0,0,0,0.2)' : 'rgba(0,0,0,0.03)',
        borderTop: dark ? '1px solid rgba(255,255,255,0.06)' : '1px solid rgba(0,0,0,0.05)',
      }}>
        {sub.status !== 'pending' ? (
          <div style={{ flex: 1, fontSize: 12.5, opacity: 0.65, display: 'flex', alignItems: 'center', gap: 6 }}>
            {sub.status === 'accepted' && (
              <>
                <ApIcon name="check" size={14} color="#34d399"/>
                {sub.decidedBy === 'auto' ? 'Automatisch durch Community-Vote veröffentlicht' :
                  <>Veröffentlicht von <ApPlayerName player={playerByIdent(sub.decidedBy)} size={12.5} opacity={1}/></>}
              </>
            )}
            {sub.status === 'rejected' && <><ApIcon name="x" size={14} color="#f87171"/>Abgelehnt</>}
          </div>
        ) : !canVote(me) ? (
          <div style={{ flex: 1, fontSize: 12.5, opacity: 0.55 }}>
            Abstimmen ist verifizierten Künstlern und Whitelist-Rollen vorbehalten.
          </div>
        ) : me.identifier === sub.identifier && !isAdmin ? (
          <div style={{ flex: 1, fontSize: 12.5, opacity: 0.55 }}>
            Du kannst nicht über deinen eigenen Track abstimmen.
          </div>
        ) : (
          <>
            <button onClick={() => onVote(sub.id, 'accept')} disabled={!eligible} style={voteBtnStyle(myVote === 'accept', '#34d399', dark)}>
              <ApIcon name="thumb-up" size={15}/> Dafür
            </button>
            <button onClick={() => onVote(sub.id, 'reject')} disabled={!eligible} style={voteBtnStyle(myVote === 'reject', '#f87171', dark)}>
              <ApIcon name="thumb-down" size={15}/> Dagegen
            </button>
            {myVote && <span style={{ fontSize: 11.5, opacity: 0.6 }}>Deine Stimme: <b style={{ color: myVote === 'accept' ? '#34d399' : '#f87171' }}>{myVote === 'accept' ? 'dafür' : 'dagegen'}</b></span>}
            <div style={{ flex: 1 }}/>
            {isAdmin && (
              <>
                <button onClick={() => onBlockUser(sub.id)} title="Creator sperren + Track ablehnen" style={{
                  display: 'flex', alignItems: 'center', gap: 6,
                  padding: '8px 14px', borderRadius: 10,
                  background: 'rgba(127,29,29,0.25)', color: '#fca5a5',
                  border: '1px solid rgba(220,38,38,0.5)', cursor: 'pointer',
                  fontSize: 12.5, fontWeight: 700,
                }}>
                  <ApIcon name="shield" size={14}/> User sperren
                </button>
                <button onClick={() => onForceReject(sub.id)} style={{
                  display: 'flex', alignItems: 'center', gap: 6,
                  padding: '8px 14px', 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={14}/> Ablehnen
                </button>
                <button onClick={() => onForceAccept(sub.id)} style={{
                  display: 'flex', alignItems: 'center', gap: 6,
                  padding: '8px 14px', borderRadius: 10,
                  background: 'linear-gradient(135deg, #fbbf24, #f97316)', color: '#1a0d2e',
                  border: 'none', cursor: 'pointer',
                  fontSize: 12.5, fontWeight: 700,
                  boxShadow: '0 6px 18px rgba(251,191,36,0.35)',
                }}>
                  <ApIcon name="bolt" size={14}/> Veröffentlichen
                </button>
              </>
            )}
          </>
        )}
      </div>

      {expanded && sub.votes.length > 0 && (
        <div style={{
          padding: '14px 18px', borderTop: dark ? '1px solid rgba(255,255,255,0.06)' : '1px solid rgba(0,0,0,0.05)',
          background: dark ? 'rgba(0,0,0,0.15)' : 'rgba(255,255,255,0.4)',
        }}>
          <div style={{ fontSize: 11, opacity: 0.55, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 10 }}>
            Stimmen ({sub.votes.length})
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 8 }}>
            {sub.votes.map((v, i) => {
              const voter = v.identifier ? playerByIdent(v.identifier) : null;
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
                  {voter && <ApAvatar player={voter} size={22}/>}
                  <ApPlayerName player={voter || { name: 'Anonym', identifier: '', group: 'user' }} size={12} opacity={0.85}/>
                  <span style={{ marginLeft: 'auto', color: v.vote === 'accept' ? '#34d399' : '#f87171', fontWeight: 700 }}>
                    {v.vote === 'accept' ? '✓' : '✕'}
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </ApGlass>
  );
}

window.SubmissionCard = SubmissionCard;
