// Prodz — Production discovery:
//   · AllProductions  — vertical overview opened from "Vedi tutte"
//   · DetailProduction — full-screen, reel-style. Horizontal carousel of the
//     production's media followed by its related Set Moments (framed in gold to
//     stand apart). Scroll down anywhere → next production. A persistent bottom
//     bar (Crew · Gear · Commenti · Set Moment) opens a pull-up sheet; "Set
//     Moment" scrolls the carousel to where the moments begin. A translucent
//     search + filters bar floats on top.

// ---------- "Vedi tutte" → vertical overview of every production ----------
function AllProductions() {
  const { L } = useL();
  const nav = useNav();
  const { Tag } = window.ProdzDesignSystem_d0b87b;
  return (
    <div className="pz-screen-enter" style={{ paddingBottom: 28 }}>
      <TopBar title={L('Produzioni', 'Productions')} onBack={nav.pop} showLang={false} />
      <div style={{ padding: '16px 16px 4px' }}>
        <h1 style={pageTitle}>{L('Tutte le produzioni', 'All productions')}</h1>
        <p style={pageSub}>{L('Tocca una produzione per aprirla a tutto schermo.', 'Tap a production to open it full-screen.')}</p>
      </div>
      <div style={{ padding: '14px 16px 0', display: 'flex', flexDirection: 'column', gap: 14 }}>
        {PRODUCTIONS.concat(PRODUCTIONS).map((p, i) => {
          const pm = PRODUCTION_MEDIA[p.id] || {};
          const crew = (pm.crew || []).length;
          const moments = (pm.moments || []).length;
          return (
            <button key={p.id + '-' + i} onClick={() => nav.openProduction(p.id)} style={{
              position: 'relative', width: '100%', height: 220, padding: 0, border: 'none', cursor: 'pointer',
              borderRadius: 'var(--radius-lg)', overflow: 'hidden', textAlign: 'left',
              background: `var(--surface-card) url(${p.image}) center/cover`, boxShadow: 'var(--ring-inset-hairline)',
            }}>
              <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(15,15,17,0) 36%, rgba(15,15,17,0.9) 100%)' }} />
              {p.trending && <span style={{ position: 'absolute', top: 12, left: 12 }}><Tag tone="solid">{L('Di tendenza', 'Trending')}</Tag></span>}
              <div style={{ position: 'absolute', left: 14, right: 14, bottom: 13 }}>
                <div style={{ fontSize: 18, fontWeight: 800, letterSpacing: '-0.01em', color: '#fff' }}>{p.title}</div>
                <div style={{ fontSize: 12, color: 'var(--gray-200)', marginTop: 3 }}>{tr(L, p.meta)}</div>
                <div style={{ display: 'flex', gap: 14, marginTop: 9 }}>
                  <span style={prodMetaPill}><Ic n="Users" s={13} color="var(--prodz-teal)" />{crew} {L('crew', 'crew')}</span>
                  <span style={prodMetaPill}><Ic n="Sparkles" s={13} color="var(--prodz-gold)" />{moments} {L('moment', 'moments')}</span>
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ---------- Full-screen reel-style detail ----------
function DetailProduction({ id }) {
  const { L } = useL();
  const nav = useNav();
  const startIdx = Math.max(0, PRODUCTIONS.findIndex((p) => p.id === id));
  const list = PRODUCTIONS;
  const vRef = useRefS(null);
  const hRefs = useRefS([]);
  const [active, setActive] = useStateS(startIdx);
  const [sheet, setSheet] = useStateS(null);

  useEffectS(() => { const v = vRef.current; if (v) v.scrollTop = startIdx * v.clientHeight; }, []);

  const onVScroll = () => {
    const v = vRef.current; if (!v) return;
    const i = Math.round(v.scrollTop / v.clientHeight);
    if (i !== active) { setActive(i); setSheet(null); }
  };

  const scrollToMoments = () => {
    const h = hRefs.current[active]; const p = list[active];
    const media = (PRODUCTION_MEDIA[p.id] || {}).media || [];
    if (h) h.scrollTo({ left: h.clientWidth * media.length, behavior: 'smooth' });
  };

  return (
    <div style={{ position: 'relative', height: '100%', background: '#000', overflow: 'hidden' }}>
      {/* translucent top: back · search · filters */}
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, zIndex: 20, padding: '12px 12px 22px', display: 'flex', alignItems: 'center', gap: 10,
        background: 'linear-gradient(180deg, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0) 100%)' }}>
        <button onClick={nav.pop} aria-label="Back" style={reelGlassBtn}><Ic n="ChevronLeft" s={22} color="#fff" /></button>
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8, height: 38, padding: '0 14px', borderRadius: 'var(--radius-pill)',
          background: 'rgba(255,255,255,0.14)', backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)' }}>
          <Ic n="Search" s={16} color="rgba(255,255,255,0.85)" />
          <span style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)' }}>{L('Cerca produzioni…', 'Search productions…')}</span>
        </div>
        <button aria-label="Filters" style={reelGlassBtn}><Ic n="SlidersHorizontal" s={18} color="#fff" /></button>
      </div>

      {/* vertical pager — one panel per production */}
      <div ref={vRef} onScroll={onVScroll} style={{ height: '100%', overflowY: 'auto', overflowX: 'hidden', scrollSnapType: 'y mandatory', WebkitOverflowScrolling: 'touch', scrollbarWidth: 'none' }}>
        {list.map((p, idx) => (
          <ProductionPanel key={p.id + idx} p={p} L={L} nav={nav}
            registerRef={(el) => { hRefs.current[idx] = el; }} />
        ))}
      </div>

      {/* persistent bottom bar */}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 20, display: 'flex',
        padding: '12px 10px calc(14px + env(safe-area-inset-bottom))',
        background: 'linear-gradient(0deg, rgba(0,0,0,0.78) 10%, rgba(0,0,0,0) 100%)' }}>
        <ReelTab icon="Users" label={L('Crew', 'Crew')} onClick={() => setSheet('crew')} />
        <ReelTab icon="Camera" label="Gear" onClick={() => setSheet('gear')} />
        <ReelTab icon="MessageCircle" label={L('Commenti', 'Comments')} onClick={() => setSheet('comments')} />
        <ReelTab icon="Sparkles" label="Set Moment" tint="var(--prodz-gold)" onClick={scrollToMoments} />
      </div>

      <Sheet open={!!sheet} onClose={() => setSheet(null)}>
        {sheet && <ReelSheet kind={sheet} p={list[active]} L={L} nav={nav} />}
      </Sheet>
    </div>
  );
}

function ProductionPanel({ p, L, nav, registerRef }) {
  const { Avatar } = window.ProdzDesignSystem_d0b87b;
  const pm = PRODUCTION_MEDIA[p.id] || { media: [], moments: [] };
  const moments = (pm.moments || []).map((mid) => MOMENTS.find((m) => m.id === mid)).filter(Boolean);
  const director = (pm.crew || []).find((c) => c.id !== 'me') || (pm.crew || [])[0];
  const dp = director ? PEOPLE[director.id] : null;

  return (
    <section style={{ position: 'relative', height: '100%', scrollSnapAlign: 'start', scrollSnapStop: 'always', background: '#000' }}>
      {/* horizontal carousel: media frames, then set-moment frames */}
      <div ref={registerRef} className="reel-h" style={{ position: 'absolute', inset: 0, display: 'flex', overflowX: 'auto', overflowY: 'hidden', scrollSnapType: 'x mandatory', WebkitOverflowScrolling: 'touch' }}>
        {pm.media.map((m, i) => (
          <div key={'md' + i} style={reelSlide}>
            <div style={{ position: 'absolute', inset: 0, background: `#111 url(${m.src}) center/cover` }} />
            {m.type === 'video' && (
              <>
                <span style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', width: 64, height: 64, borderRadius: '50%', background: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Ic n="Play" s={26} color="#fff" fill="#fff" />
                </span>
                <span style={{ position: 'absolute', top: 64, right: 14, padding: '3px 8px', borderRadius: 'var(--radius-pill)', background: 'rgba(0,0,0,0.5)', fontSize: 11, fontWeight: 700, color: '#fff' }}>{m.dur}</span>
              </>
            )}
            <span style={{ position: 'absolute', top: 66, left: 14, fontSize: 10.5, fontWeight: 700, letterSpacing: '0.08em', color: 'rgba(255,255,255,0.85)' }}>{i + 1} / {pm.media.length + moments.length}</span>
          </div>
        ))}
        {moments.map((m, i) => (
          <div key={'mo' + i} style={reelSlide}>
            {/* set moments wear a distinct gold frame */}
            <div style={{ position: 'absolute', inset: 10, borderRadius: 18, border: '3px solid var(--prodz-gold)', boxShadow: '0 0 0 1px rgba(0,0,0,0.4), inset 0 0 40px rgba(0,0,0,0.4)', background: `#111 url(${m.image}) center/cover`, overflow: 'hidden' }} />
            <span style={{ position: 'absolute', top: 26, left: 26, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 11px', borderRadius: 'var(--radius-pill)', background: 'var(--prodz-gold)', color: 'var(--text-on-accent)', fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
              <Ic n="Sparkles" s={12} color="currentColor" />Set Moment
            </span>
            <span style={{ position: 'absolute', bottom: 150, left: 26, fontSize: 13, fontWeight: 600, color: '#fff' }}>{tr(L, m.label)}</span>
          </div>
        ))}
      </div>

      {/* caption — production identity, bottom-left, above the bar */}
      <div style={{ position: 'absolute', left: 16, right: 70, bottom: 88, zIndex: 10, pointerEvents: 'none' }}>
        <button onClick={() => dp && nav.openProfile(director.id)} style={{ pointerEvents: 'auto', display: 'inline-flex', alignItems: 'center', gap: 8, background: 'none', border: 'none', cursor: 'pointer', padding: 0, marginBottom: 10 }}>
          <Avatar src={dp ? dp.avatar : null} alt={dp ? dp.name : ''} size={32} ring="gold" />
          <span style={{ fontSize: 13.5, fontWeight: 700, color: '#fff' }}>{dp ? dp.name : ''}</span>
        </button>
        <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em', color: '#fff', textShadow: '0 2px 18px rgba(0,0,0,0.6)' }}>{p.title}</div>
        <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.82)', marginTop: 3, textShadow: '0 2px 12px rgba(0,0,0,0.6)' }}>{tr(L, p.meta)}</div>
      </div>

      {/* right rail — quick engage */}
      <div style={{ position: 'absolute', right: 12, bottom: 96, zIndex: 10, display: 'flex', flexDirection: 'column', gap: 16, alignItems: 'center' }}>
        <ReelEngage icon="Heart" n="1.2k" />
        <ReelEngage icon="Bookmark" n={L('Salva', 'Save')} />
        <ReelEngage icon="Share2" n={L('Invia', 'Share')} />
      </div>
    </section>
  );
}

function ReelEngage({ icon, n }) {
  return (
    <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
      <span style={{ width: 46, height: 46, borderRadius: '50%', background: 'rgba(255,255,255,0.14)', backdropFilter: 'blur(8px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Ic n={icon} s={21} color="#fff" />
      </span>
      <span style={{ fontSize: 10.5, fontWeight: 600, color: '#fff', textShadow: '0 1px 4px rgba(0,0,0,0.6)' }}>{n}</span>
    </span>
  );
}

function ReelTab({ icon, label, onClick, tint }) {
  return (
    <button onClick={onClick} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, background: 'none', border: 'none', cursor: 'pointer', padding: '4px 0' }}>
      <Ic n={icon} s={21} color={tint || '#fff'} />
      <span style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: '0.02em', color: tint || 'rgba(255,255,255,0.92)' }}>{label}</span>
    </button>
  );
}

function ReelSheet({ kind, p, L, nav }) {
  const { Avatar, Tag, StatusDot } = window.ProdzDesignSystem_d0b87b;
  const pm = PRODUCTION_MEDIA[p.id] || {};
  const title = kind === 'crew' ? L('Crew', 'Crew') : kind === 'gear' ? 'Gear' : L('Commenti', 'Comments');
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <Eyebrow color="var(--prodz-teal)">{p.title}</Eyebrow>
      </div>
      <div style={{ fontSize: 17, fontWeight: 700, color: 'var(--text-primary)', marginBottom: 12 }}>{title}</div>
      <div style={{ maxHeight: 360, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {kind === 'crew' && (pm.crew || []).map((c) => {
          const person = PEOPLE[c.id];
          return (
            <button key={c.id} onClick={() => nav.openProfile(c.id)} style={reelRow}>
              <Avatar src={person.avatar} alt={person.name} size={42} ring={person.ring} status={person.online ? 'online' : null} />
              <div style={{ flex: 1, textAlign: 'left' }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-primary)' }}>{person.name}{c.id === 'me' && L(' · Tu', ' · You')}</div>
                <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{tr(L, c.role)}</div>
              </div>
              <Ic n="ChevronRight" s={18} color="var(--text-subtle)" />
            </button>
          );
        })}
        {kind === 'gear' && (pm.gear || []).map((gid) => {
          const g = GEAR.find((x) => x.id === gid); if (!g) return null;
          return (
            <div key={gid} style={reelRow}>
              <span style={{ width: 44, height: 44, borderRadius: 10, flexShrink: 0, background: g.img ? `url(${g.img}) center/cover` : 'var(--surface-raised)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--ring-inset-hairline)' }}>
                {!g.img && <Ic n={g.icon} s={20} color="var(--text-muted)" />}
              </span>
              <div style={{ flex: 1, textAlign: 'left' }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-primary)' }}>{g.name}</div>
                <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{tr(L, g.kind)} · {tr(L, g.price)}</div>
              </div>
              <StatusDot label={g.ready ? L('Disp.', 'Avail.') : L('In uso', 'In use')} color={g.ready ? 'var(--green)' : 'var(--yellow)'} glow={g.ready} />
            </div>
          );
        })}
        {kind === 'comments' && (pm.comments || []).map((c, i) => {
          const person = PEOPLE[c.author];
          return (
            <div key={i} style={{ display: 'flex', gap: 11, padding: '4px 2px' }}>
              <Avatar src={person.avatar} alt={person.name} size={34} ring={person.ring} />
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-primary)' }}>{person.name}</span>
                  <span style={{ fontSize: 11, color: 'var(--text-subtle)' }}>{tr(L, c.time)}</span>
                </div>
                <p style={{ fontSize: 13.5, lineHeight: 1.5, color: 'var(--text-body)', margin: '3px 0 0' }}>{tr(L, c.text)}</p>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

const reelGlassBtn = { width: 38, height: 38, borderRadius: '50%', border: 'none', cursor: 'pointer', flexShrink: 0, background: 'rgba(255,255,255,0.14)', backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)', display: 'flex', alignItems: 'center', justifyContent: 'center' };
const reelSlide = { position: 'relative', width: '100%', height: '100%', flexShrink: 0, scrollSnapAlign: 'start' };
const reelRow = { display: 'flex', alignItems: 'center', gap: 12, width: '100%', padding: 10, background: 'var(--surface-raised)', border: 'none', cursor: 'pointer', borderRadius: 'var(--radius-md)' };
const prodMetaPill = { display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 600, color: '#fff' };

Object.assign(window, { AllProductions, DetailProduction });
