// Prodz — Shoutouts: discovery of opportunities (collab + job call) as a swipe
// stack. Three actions: Salva · Salta · Rispondi. Undo + saved queue always
// visible (brief §1.5 / §2.4). "Rispondi" opens a conversation in the Inbox.
function Shoutouts() {
  const { L } = useL();
  const nav = useNav();
  const { Button, Tag, Avatar } = window.ProdzDesignSystem_d0b87b;
  const deck = SHOUTOUTS;
  const [idx, setIdx] = useStateS(0);
  const [saved, setSaved] = useStateS([]);
  const [history, setHistory] = useStateS([]);
  const [drag, setDrag] = useStateS({ dx: 0, dy: 0, active: false });
  const [leaving, setLeaving] = useStateS(null);
  const [showSaved, setShowSaved] = useStateS(false);
  const startRef = useRefS(null);

  const undo = () => {
    setHistory((h) => {
      if (!h.length) return h;
      const last = h[h.length - 1];
      setIdx((i) => Math.max(0, i - 1));
      if (last.wasSaved) setSaved((s) => s.filter((c) => c.id !== last.card.id));
      return h.slice(0, -1);
    });
  };

  const commit = (action) => {
    if (idx >= deck.length || leaving) return;
    const card = deck[idx];
    const fly = action === 'save' ? { x: 560, y: -30, rot: 20 }
      : action === 'skip' ? { x: -560, y: -30, rot: -20 }
      : { x: 0, y: -760, rot: 0 };
    setLeaving({ dir: action, ...fly });
    const wasSaved = action === 'save';
    setTimeout(() => {
      setHistory((h) => [...h, { action, card, wasSaved }]);
      if (wasSaved) setSaved((s) => (s.find((c) => c.id === card.id) ? s : [...s, card]));
      setIdx((i) => i + 1);
      setLeaving(null);
      setDrag({ dx: 0, dy: 0, active: false });
      if (action === 'reply') nav.replyShoutout(card);
      else nav.toast(action === 'save' ? L('Salvato nella coda', 'Saved to queue') : L('Saltato', 'Skipped'), L('Annulla', 'Undo'), undo);
    }, 300);
  };

  const onDown = (e) => { if (leaving) return; startRef.current = { x: e.clientX, y: e.clientY }; setDrag({ dx: 0, dy: 0, active: true }); try { e.currentTarget.setPointerCapture(e.pointerId); } catch (_) {} };
  const onMove = (e) => { if (!drag.active || !startRef.current) return; setDrag({ dx: e.clientX - startRef.current.x, dy: e.clientY - startRef.current.y, active: true }); };
  const onUp = () => {
    if (!drag.active) return;
    const { dx, dy } = drag; const TH = 105;
    if (dy < -150 && Math.abs(dx) < 100) commit('reply');
    else if (dx > TH) commit('save');
    else if (dx < -TH) commit('skip');
    else setDrag({ dx: 0, dy: 0, active: false });
    startRef.current = null;
  };

  const remaining = deck.length - idx;
  const topTransform = leaving
    ? `translate(${leaving.x}px, ${leaving.y}px) rotate(${leaving.rot}deg)`
    : `translate(${drag.dx}px, ${drag.dy}px) rotate(${drag.dx * 0.04}deg)`;
  const topTransition = (leaving || !drag.active) ? 'transform 300ms var(--ease-out)' : 'none';
  // direction hints
  const dirSave = Math.max(0, Math.min(1, drag.dx / 110));
  const dirSkip = Math.max(0, Math.min(1, -drag.dx / 110));
  const dirReply = Math.max(0, Math.min(1, -drag.dy / 150)) * (Math.abs(drag.dx) < 100 ? 1 : 0);

  return (
    <div className="pz-screen-enter" style={{ display: 'flex', flexDirection: 'column', minHeight: '100%' }}>
      <TopBar />
      <div style={{ padding: '16px 16px 0', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <h1 style={pageTitle}>Shoutouts</h1>
          <p style={pageSub}>{L('Scopri collab e job call. Scorri o usa i tasti.', 'Discover collabs & job calls. Swipe or tap.')}</p>
        </div>
        {/* saved queue — always visible */}
        <button onClick={() => setShowSaved(true)} style={savedChip}>
          <Ic n="Bookmark" s={15} color="var(--prodz-teal)" fill={saved.length ? 'var(--prodz-teal)' : 'none'} />
          <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-body)' }}>{saved.length}</span>
        </button>
      </div>

      {/* card stack */}
      <div style={{ position: 'relative', flex: 1, minHeight: 430, margin: '14px 16px 0' }}>
        {remaining <= 0 ? (
          <div style={emptyState}>
            <span style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--teal-surface)', boxShadow: 'var(--ring-teal)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}>
              <Ic n="Check" s={28} color="var(--prodz-teal)" />
            </span>
            <div style={{ fontSize: 17, fontWeight: 700, color: 'var(--text-primary)' }}>{L('Sei in pari', 'All caught up')}</div>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4, textAlign: 'center', maxWidth: 240 }}>{L('Hai visto tutte le opportunità per ora. Torna più tardi.', 'You’ve seen every opportunity for now. Check back later.')}</div>
            <div style={{ marginTop: 18 }}>
              <Button variant="secondary" leadingIcon={<Ic n="RotateCcw" s={15} />} onClick={() => { setIdx(0); setHistory([]); }}>{L('Ricomincia', 'Restart')}</Button>
            </div>
          </div>
        ) : (
          [2, 1, 0].map((depth) => {
            const i = idx + depth;
            if (i >= deck.length) return null;
            const card = deck[i];
            const isTop = depth === 0;
            const style = isTop
              ? { transform: topTransform, transition: topTransition, zIndex: 3, cursor: drag.active ? 'grabbing' : 'grab' }
              : { transform: `translateY(${depth * 12}px) scale(${1 - depth * 0.05})`, transition: 'transform 300ms var(--ease-out)', zIndex: 3 - depth, opacity: depth === 2 ? 0.55 : 0.85 };
            return (
              <div key={card.id}
                onPointerDown={isTop ? onDown : undefined}
                onPointerMove={isTop ? onMove : undefined}
                onPointerUp={isTop ? onUp : undefined}
                onPointerCancel={isTop ? onUp : undefined}
                style={{ position: 'absolute', inset: 0, touchAction: 'none', ...style }}>
                <ShoutoutCard card={card} L={L} />
                {isTop && <SwipeHints save={dirSave} skip={dirSkip} reply={dirReply} L={L} />}
              </div>
            );
          })
        )}
      </div>

      {/* actions */}
      {remaining > 0 && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 18, padding: '18px 16px 20px' }}>
          <ActionBtn icon="X" onClick={() => commit('skip')} bg="var(--surface-raised)" color="var(--text-muted)" size={56} label={L('Salta', 'Skip')} />
          <ActionBtn icon="Send" onClick={() => commit('reply')} bg="var(--prodz-gold)" color="var(--text-on-accent)" size={66} glow="var(--glow-gold)" label={L('Rispondi', 'Reply')} />
          <ActionBtn icon="Bookmark" onClick={() => commit('save')} bg="var(--teal-surface)" color="var(--prodz-teal)" size={56} ring="var(--ring-teal)" label={L('Salva', 'Save')} />
          {history.length > 0 && <ActionBtn icon="RotateCcw" onClick={undo} bg="transparent" color="var(--text-subtle)" size={44} label={L('Annulla', 'Undo')} ghost />}
        </div>
      )}

      <Sheet open={showSaved} onClose={() => setShowSaved(false)}>
        <Eyebrow style={{ marginBottom: 4 }}>{L('Coda dei salvati', 'Saved queue')} · {saved.length}</Eyebrow>
        {saved.length === 0 ? (
          <p style={{ fontSize: 13, color: 'var(--text-muted)', padding: '12px 2px 6px' }}>{L('Nessuna opportunità salvata. Scorri a destra o tocca Salva.', 'No saved opportunities yet. Swipe right or tap Save.')}</p>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 8, maxHeight: 320, overflowY: 'auto' }}>
            {saved.map((c) => (
              <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', background: 'var(--surface-raised)', borderRadius: 'var(--radius-md)' }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: c.kind === 'job' ? 'var(--prodz-gold)' : 'var(--prodz-teal)', flexShrink: 0 }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--text-primary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tr(L, c.title)}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--text-subtle)' }}>{c.author} · {c.city}</div>
                </div>
                <Button size="sm" variant="primary" onClick={() => { setShowSaved(false); nav.replyShoutout(c); }}>{L('Rispondi', 'Reply')}</Button>
              </div>
            ))}
          </div>
        )}
      </Sheet>
    </div>
  );
}

function ShoutoutCard({ card, L }) {
  const { Tag, Avatar } = window.ProdzDesignSystem_d0b87b;
  const warm = card.surface === 'cream' || card.surface === 'mint';
  const bg = card.surface === 'cream' ? 'var(--cream)' : card.surface === 'mint' ? 'var(--mint)' : 'var(--surface-card)';
  const ink = warm ? (card.surface === 'cream' ? 'var(--cream-ink)' : 'var(--mint-ink)') : 'var(--text-primary)';
  const sub = warm ? 'rgba(58,47,36,0.7)' : 'var(--text-muted)';
  const kindLabel = card.kind === 'job' ? L('Job Call', 'Job Call') : 'Collab Proposal';
  return (
    <div style={{
      position: 'absolute', inset: 0, background: bg, color: ink, borderRadius: 22, padding: 22,
      display: 'flex', flexDirection: 'column', boxShadow: '0 24px 50px -16px rgba(0,0,0,0.6), ' + (warm ? 'none' : 'var(--ring-inset-hairline)'),
      overflow: 'hidden', userSelect: 'none',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 11, fontWeight: 800, letterSpacing: '0.1em', textTransform: 'uppercase', color: card.kind === 'job' ? (warm ? 'var(--cream-ink)' : 'var(--prodz-gold)') : 'var(--prodz-teal)' }}>
          <Ic n={card.kind === 'job' ? 'Megaphone' : 'Handshake'} s={15} color="currentColor" />{kindLabel}
        </span>
        {card.paid && <Tag tone={warm ? 'onCream' : 'gold'} onDark={!warm}>{L('Retribuito', 'Paid')}</Tag>}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 20 }}>
        <Avatar src={card.person ? PEOPLE[card.person].avatar : null} alt={card.author} size={40} ring={warm ? 'none' : 'teal'} />
        <div>
          <div style={{ fontSize: 14.5, fontWeight: 700 }}>{card.author}</div>
          <div style={{ fontSize: 12, color: sub }}>{tr(L, card.role)} · {card.city}</div>
        </div>
      </div>

      <div style={{ fontSize: 23, fontWeight: 800, letterSpacing: '-0.02em', lineHeight: 1.15, marginTop: 18 }}>{tr(L, card.title)}</div>
      <div style={{ fontSize: 14, lineHeight: 1.55, color: sub, marginTop: 12, flex: 1 }}>{tr(L, card.blurb)}</div>

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 16 }}>
        {card.tags.map((t) => <Tag key={t} tone={warm ? 'onCream' : 'neutral'} onDark={!warm}>{t}</Tag>)}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 14, fontSize: 13, fontWeight: 600, color: warm ? ink : 'var(--text-body)' }}>
        <Ic n="Calendar" s={15} color="currentColor" />{tr(L, card.date)}
      </div>
    </div>
  );
}

function SwipeHints({ save, skip, reply, L }) {
  const tag = (label, color, opacity, pos) => (
    <span style={{ position: 'absolute', ...pos, opacity, transform: `scale(${0.8 + opacity * 0.2})`, transition: 'opacity 80ms linear',
      padding: '8px 16px', borderRadius: 'var(--radius-pill)', border: `2.5px solid ${color}`, color,
      fontSize: 15, fontWeight: 800, letterSpacing: '0.08em', textTransform: 'uppercase', background: 'rgba(10,10,10,0.35)', backdropFilter: 'blur(2px)', pointerEvents: 'none' }}>{label}</span>
  );
  return (
    <>
      {tag(L('Salva', 'Save'), 'var(--prodz-teal)', save, { top: 22, left: 22, transformOrigin: 'left top' })}
      {tag(L('Salta', 'Skip'), '#ff6b6b', skip, { top: 22, right: 22, transformOrigin: 'right top' })}
      {tag(L('Rispondi', 'Reply'), 'var(--prodz-gold)', reply, { bottom: 80, left: '50%', marginLeft: -54 })}
    </>
  );
}

function ActionBtn({ icon, onClick, bg, color, size, glow, ring, label, ghost }) {
  return (
    <button onClick={onClick} aria-label={label} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, background: 'none', border: 'none', cursor: 'pointer' }}>
      <span style={{ width: size, height: size, borderRadius: '50%', background: bg, color, display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: glow || ring || (ghost ? 'none' : 'var(--ring-inset-hairline)'), transition: 'transform var(--dur-fast) var(--ease-standard)' }}
        onPointerDown={(e) => { e.currentTarget.style.transform = 'scale(0.9)'; }}
        onPointerUp={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
        onPointerLeave={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}>
        <Ic n={icon} s={size * 0.42} color="currentColor" />
      </span>
      <span style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-subtle)' }}>{label}</span>
    </button>
  );
}

const savedChip = { display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 12px', background: 'var(--surface-card)', border: 'none', cursor: 'pointer', borderRadius: 'var(--radius-pill)', boxShadow: 'var(--ring-inset-hairline)' };
const emptyState = { position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center' };

Object.assign(window, { Shoutouts });
