// Prodz — Shoutout detail. Reached by tapping a shoutout on a profile.
//   · owner === 'me'  → MINE: a summary card of the call, the people who applied
//     as tappable avatars, and the chat you had for that role opening inline at
//     the bottom (no page change).
//   · owner === other → THEIRS: view the call, Save it, or Apply & reply inline.

function statusMeta(L, st) {
  switch (st) {
    case 'shortlist': return { label: L('In shortlist', 'Shortlisted'), color: 'var(--prodz-teal)' };
    case 'hired':     return { label: L('Scelto', 'Hired'),            color: 'var(--green)' };
    case 'closed':    return { label: L('Chiusa', 'Closed'),           color: 'var(--text-subtle)' };
    default:          return { label: L('Nuova', 'New'),               color: 'var(--prodz-gold)' };
  }
}

// Shared summary card at the top of the detail.
function ShoutoutSummary({ s, owner, L }) {
  const { Avatar, Tag } = window.ProdzDesignSystem_d0b87b;
  const mine = owner === 'me';
  const open = mine ? s.status === 'open' : true;
  const prod = s.prod ? PRODUCTIONS.find((x) => x.id === s.prod) : null;
  const author = mine ? PEOPLE.me : (s.person ? PEOPLE[s.person] : null);
  const authorName = author ? author.name : s.author;
  const authorRole = author ? tr(L, author.role) : tr(L, s.role);
  const authorCity = author ? author.city : s.city;

  return (
    <div style={{ margin: '16px 16px 0', padding: 18, borderRadius: 'var(--radius-lg)', background: 'var(--surface-card)', boxShadow: 'var(--ring-inset-hairline)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 10.5, fontWeight: 800, letterSpacing: '0.08em', textTransform: 'uppercase', color: s.kind === 'job' ? 'var(--prodz-gold)' : 'var(--prodz-teal)' }}>
          <Ic n={s.kind === 'job' ? 'Megaphone' : 'Handshake'} s={13} color="currentColor" />{s.kind === 'job' ? L('Job Call', 'Job Call') : 'Collab'}
        </span>
        {s.paid && <Tag tone="gold">{L('Retribuito', 'Paid')}</Tag>}
        {mine && (
          <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, fontWeight: 700, color: open ? 'var(--green)' : 'var(--text-subtle)' }}>
            <span style={{ width: 7, height: 7, borderRadius: '50%', background: open ? 'var(--green)' : 'var(--text-subtle)' }} />{open ? L('Aperta', 'Open') : L('Chiusa', 'Closed')}
          </span>
        )}
      </div>

      <h1 style={{ margin: '12px 0 0', fontFamily: 'var(--font-display)', fontSize: 21, fontWeight: 800, letterSpacing: '-0.02em', lineHeight: 1.18, color: 'var(--text-primary)', textWrap: 'balance' }}>{tr(L, s.title)}</h1>

      {/* author line — for someone else's call, who posted it */}
      {!mine && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 13 }}>
          <Avatar src={author ? author.avatar : null} alt={authorName} size={36} ring={author ? author.ring : 'none'} status={author && author.online ? 'online' : null} />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--text-primary)' }}>{authorName}</div>
            <div style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>{authorRole}{authorCity ? ' · ' + authorCity : ''}</div>
          </div>
        </div>
      )}

      {s.blurb && <p style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--text-muted)', margin: '13px 0 0' }}>{tr(L, s.blurb)}</p>}

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 14, marginTop: 15, fontSize: 12, color: 'var(--text-muted)' }}>
        {prod && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Ic n="Clapperboard" s={14} color="var(--prodz-teal)" />{prod.title}</span>}
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Ic n="Calendar" s={14} color="var(--text-subtle)" />{tr(L, s.date)}</span>
        {mine && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Ic n="Users" s={14} color="var(--text-subtle)" />{s.applicants} {L('candidature', 'applicants')}</span>}
      </div>

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 13 }}>
        {s.tags.map((t) => <Tag key={t} tone="neutral">{t}</Tag>)}
      </div>
    </div>
  );
}

function ShoutoutDetail({ id, owner = 'me' }) {
  const { L } = useL();
  const nav = useNav();
  const { Avatar, Button, Tag } = window.ProdzDesignSystem_d0b87b;
  const mine = owner === 'me';
  const s = (mine ? MY_SHOUTOUTS : shoutoutsOf(owner)).find((x) => x.id === id);

  // ---- MINE: applicants + inline chat ----
  const applicants = (s && s.applicantList) || [];
  const [sel, setSel] = useStateS(null);            // selected applicant person id
  const [threads, setThreads] = useStateS(() => {
    const o = {}; applicants.forEach((a) => { o[a.person] = a.messages.map((m) => ({ ...m })); }); return o;
  });
  const [draft, setDraft] = useStateS('');
  const panelRef = useRefS(null);
  const selApp = applicants.find((a) => a.person === sel);

  useEffectS(() => {
    if (sel && panelRef.current) {
      const sc = panelRef.current.closest('.prodz-scroll');
      if (sc) sc.scrollTo({ top: panelRef.current.offsetTop - 64, behavior: 'smooth' });
    }
  }, [sel]);

  // ---- THEIRS: save / apply / reply ----
  const [saved, setSaved] = useStateS(false);
  const [applied, setApplied] = useStateS(false);
  const [showApply, setShowApply] = useStateS(false);
  const [reply, setReply] = useStateS('');

  if (!s) {
    return (
      <div className="pz-screen-enter">
        <TopBar title="Shoutout" onBack={nav.pop} showLang={false} />
        <p style={{ textAlign: 'center', fontSize: 13, color: 'var(--text-subtle)', padding: '40px 0' }}>{L('Shoutout non trovato.', 'Shoutout not found.')}</p>
      </div>
    );
  }

  const sendInChat = () => {
    const t = draft.trim(); if (!t || !sel) return;
    setThreads((m) => ({ ...m, [sel]: [...(m[sel] || []), { me: true, time: L('adesso', 'now'), text: { it: t, en: t } }] }));
    setDraft('');
  };

  const submitApply = () => {
    nav.applyShoutout(s, reply.trim());
    setApplied(true); setShowApply(false); setReply('');
  };

  return (
    <div className="pz-screen-enter" style={{ display: 'flex', flexDirection: 'column', minHeight: '100%', paddingBottom: 28 }}>
      <TopBar title="Shoutout" onBack={nav.pop} showLang={false} />

      <ShoutoutSummary s={s} owner={owner} L={L} />

      {/* ============ MINE: applicants + inline chat ============ */}
      {mine && (
        <>
          <div style={{ padding: '20px 16px 0' }}>
            <Eyebrow style={{ marginBottom: 12 }}>{L('Candidature', 'Applicants')} · {applicants.length}</Eyebrow>
            {applicants.length === 0 ? (
              <p style={{ fontSize: 13, color: 'var(--text-subtle)', padding: '6px 0' }}>{L('Ancora nessuna candidatura.', 'No applications yet.')}</p>
            ) : (
              <div className="hscroll" style={{ gap: 16, paddingBottom: 4 }}>
                {applicants.map((a) => {
                  const p = PEOPLE[a.person]; if (!p) return null;
                  const active = a.person === sel;
                  const st = statusMeta(L, a.status);
                  return (
                    <button key={a.person} onClick={() => setSel(active ? null : a.person)} style={{ flexShrink: 0, width: 64, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
                      <span style={{ position: 'relative', borderRadius: '50%', padding: 2.5, background: active ? 'var(--prodz-teal)' : 'transparent', transition: 'background var(--dur-base) var(--ease-standard)' }}>
                        <Avatar src={p.avatar} alt={p.name} size={54} ring={active ? 'none' : p.ring} status={p.online ? 'online' : null} />
                        <span style={{ position: 'absolute', right: 0, bottom: 2, width: 13, height: 13, borderRadius: '50%', background: st.color, border: '2px solid var(--surface-canvas)' }} />
                      </span>
                      <span style={{ fontSize: 11.5, fontWeight: 600, color: active ? 'var(--text-primary)' : 'var(--text-body)', whiteSpace: 'nowrap', maxWidth: 64, overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name.split(' ')[0]}</span>
                    </button>
                  );
                })}
              </div>
            )}
            {applicants.length > 0 && !sel && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 14, padding: '12px 14px', borderRadius: 'var(--radius-md)', background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)', fontSize: 12.5, color: 'var(--text-muted)' }}>
                <Ic n="MousePointerClick" s={16} color="var(--prodz-teal)" />{L('Tocca un candidato per leggere la chat che hai avuto per il ruolo.', 'Tap an applicant to read the chat you had for the role.')}
              </div>
            )}
          </div>

          {/* inline chat panel — opens below, page stays put */}
          {selApp && (() => {
            const p = PEOPLE[selApp.person];
            const st = statusMeta(L, selApp.status);
            const msgs = threads[selApp.person] || [];
            return (
              <div ref={panelRef} style={{ margin: '16px 16px 0', borderRadius: 'var(--radius-lg)', background: 'var(--surface-card)', boxShadow: 'var(--ring-inset-hairline)', overflow: 'hidden', animation: 'pz-fade-up 240ms var(--ease-out) both' }}>
                {/* chat header */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '13px 14px', borderBottom: '1px solid var(--border-hairline)' }}>
                  <Avatar src={p.avatar} alt={p.name} size={40} ring={p.ring} status={p.online ? 'online' : null} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--text-primary)' }}>{p.name}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>{tr(L, p.role)} · {p.city}</div>
                  </div>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 10.5, fontWeight: 700, color: st.color }}>
                    <span style={{ width: 7, height: 7, borderRadius: '50%', background: st.color }} />{st.label}
                  </span>
                  <button onClick={() => setSel(null)} aria-label={L('Chiudi', 'Close')} style={{ width: 30, height: 30, borderRadius: '50%', border: 'none', cursor: 'pointer', background: 'var(--surface-raised)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <Ic n="X" s={16} color="var(--text-muted)" />
                  </button>
                </div>

                {/* messages */}
                <div style={{ padding: '14px 14px 6px', display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {msgs.map((m, i) => (
                    <div key={i} style={{ display: 'flex', justifyContent: m.me ? 'flex-end' : 'flex-start', alignItems: 'flex-end', gap: 8 }}>
                      {!m.me && <Avatar src={p.avatar} alt={p.name} size={24} />}
                      <div style={{ maxWidth: '76%' }}>
                        <div style={{ padding: '9px 12px', borderRadius: 15, borderBottomRightRadius: m.me ? 4 : 15, borderBottomLeftRadius: m.me ? 15 : 4, background: m.me ? 'var(--prodz-gold)' : 'var(--surface-raised)', color: m.me ? 'var(--text-on-accent)' : 'var(--text-body)', boxShadow: m.me ? 'var(--glow-gold)' : 'var(--ring-inset-hairline)', fontSize: 13.5, lineHeight: 1.5 }}>{tr(L, m.text)}</div>
                        <div style={{ fontSize: 10, color: 'var(--text-subtle)', marginTop: 3, textAlign: m.me ? 'right' : 'left' }}>{m.time}</div>
                      </div>
                    </div>
                  ))}
                </div>

                {/* quick actions */}
                <div style={{ display: 'flex', gap: 8, padding: '4px 14px 12px' }}>
                  <Button variant="secondary" size="sm" leadingIcon={<Ic n="User" s={14} />} onClick={() => nav.openProfile(selApp.person)}>{L('Profilo', 'Profile')}</Button>
                  {s.status === 'open' && <Button variant="secondary" size="sm" leadingIcon={<Ic n="Star" s={14} color="var(--prodz-gold)" />} onClick={() => nav.toast(L(p.name.split(' ')[0] + ' aggiunto alla shortlist', p.name.split(' ')[0] + ' added to shortlist'), null)}>{L('Shortlist', 'Shortlist')}</Button>}
                </div>

                {/* composer */}
                {s.status === 'open' ? (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '10px 12px', borderTop: '1px solid var(--border-hairline)', background: 'var(--surface-raised)' }}>
                    <input value={draft} onChange={(e) => setDraft(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); sendInChat(); } }}
                      placeholder={L('Rispondi a ' + p.name.split(' ')[0] + '…', 'Reply to ' + p.name.split(' ')[0] + '…')}
                      style={{ flex: 1, height: 40, padding: '0 14px', borderRadius: 'var(--radius-pill)', border: 'none', outline: 'none', background: 'var(--surface-card)', boxShadow: 'var(--ring-inset-hairline)', color: 'var(--text-body)', fontSize: 13.5, fontFamily: 'var(--font-ui)' }} />
                    <button onClick={sendInChat} aria-label="Send" style={{ width: 38, height: 38, borderRadius: '50%', border: 'none', cursor: 'pointer', background: 'var(--prodz-gold)', color: 'var(--text-on-accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--glow-gold)', flexShrink: 0 }}>
                      <Ic n="Send" s={16} color="currentColor" />
                    </button>
                  </div>
                ) : (
                  <div style={{ padding: '12px 14px', borderTop: '1px solid var(--border-hairline)', fontSize: 12, color: 'var(--text-subtle)', textAlign: 'center' }}>{L('Questa call è chiusa.', 'This call is closed.')}</div>
                )}
              </div>
            );
          })()}
        </>
      )}

      {/* ============ THEIRS: save / apply / reply ============ */}
      {!mine && (
        <div style={{ padding: '18px 16px 0' }}>
          {!showApply && !applied && (
            <div style={{ display: 'flex', gap: 8 }}>
              <Button variant={saved ? 'secondary' : 'secondary'} size="md" fullWidth
                leadingIcon={<Ic n="Bookmark" s={16} color="var(--prodz-teal)" fill={saved ? 'var(--prodz-teal)' : 'none'} />}
                onClick={() => { setSaved((v) => !v); nav.toast(saved ? L('Rimosso dai salvati', 'Removed from saved') : L('Salvato nella coda', 'Saved to queue'), null); }}>
                {saved ? L('Salvato', 'Saved') : L('Salva', 'Save')}
              </Button>
              <Button variant="primary" size="md" fullWidth glow leadingIcon={<Ic n="Send" s={16} />} onClick={() => setShowApply(true)}>
                {s.kind === 'job' ? L('Candidati', 'Apply') : L('Proponi', 'Propose')}
              </Button>
            </div>
          )}

          {showApply && (
            <div style={{ borderRadius: 'var(--radius-lg)', background: 'var(--surface-card)', boxShadow: 'var(--ring-inset-hairline)', padding: 16, animation: 'pz-fade-up 220ms var(--ease-out) both' }}>
              <Eyebrow color={s.kind === 'job' ? 'var(--prodz-gold)' : 'var(--prodz-teal)'} style={{ marginBottom: 8 }}>{s.kind === 'job' ? L('La tua candidatura', 'Your application') : L('La tua proposta', 'Your proposal')}</Eyebrow>
              <textarea value={reply} onChange={(e) => setReply(e.target.value)} autoFocus
                placeholder={L('Scrivi un messaggio per ' + (s.person ? PEOPLE[s.person].name.split(' ')[0] : s.author) + '…', 'Write a message to ' + (s.person ? PEOPLE[s.person].name.split(' ')[0] : s.author) + '…')}
                style={{ width: '100%', minHeight: 92, resize: 'none', padding: '12px 14px', borderRadius: 'var(--radius-md)', border: 'none', outline: 'none', background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)', color: 'var(--text-body)', fontSize: 14, lineHeight: 1.5, fontFamily: 'var(--font-ui)' }} />
              <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
                <Button variant="secondary" size="md" onClick={() => setShowApply(false)}>{L('Annulla', 'Cancel')}</Button>
                <Button variant="primary" size="md" fullWidth glow leadingIcon={<Ic n="Send" s={16} />} onClick={submitApply}>{L('Invia', 'Send')}</Button>
              </div>
            </div>
          )}

          {applied && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 16, borderRadius: 'var(--radius-lg)', background: 'var(--teal-surface)', boxShadow: 'var(--ring-teal)' }}>
              <span style={{ width: 40, height: 40, borderRadius: '50%', flexShrink: 0, background: 'var(--surface-canvas)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Ic n="Check" s={20} color="var(--prodz-teal)" />
              </span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-primary)' }}>{L('Candidatura inviata', 'Application sent')}</div>
                <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2 }}>{L('La conversazione è nella tua Inbox.', 'The conversation is in your Inbox.')}</div>
              </div>
              <Button variant="secondary" size="sm" onClick={() => nav.openInbox()}>{L('Apri', 'Open')}</Button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ShoutoutDetail, ShoutoutSummary });
