// ═══════════════════════════════════════════════════════════════
// RINTANA — APP SHELL
// 4 secciones: vv (Vamos Viendo), ib (Inmenso Bastardo),
//              ed (EdiBarak), about (Detrás de Escenas)
// Navegación: SOLO hamburger.
// Hash format:
//   #/vv             → Vamos Viendo (feed)
//   #/vv/<slug>      → Vamos Viendo, abrir crítica directa
//   #/ib             → Inmenso Bastardo
//   #/ib/<slug>      → IB, capítulo directo
//   #/ed             → EdiBarak (editoriales)
//   #/ed/<slug>      → Editorial directo
//   #/about          → Detrás de Escenas
//   #/                → Home
// ═══════════════════════════════════════════════════════════════

const SECTIONS = [
  { id:'vv',    name:'Vamos Viendo',     italicName:'Viendo',
    kicker:'Crítica con foto',
    desc:'Feed full-bleed. Una crítica por vez. La imagen manda.',
    accent:'#d92b2b' },
  { id:'ib',    name:'Inmenso Bastardo', italicName:'Bastardo',
    kicker:'Cuadernos de épicas',
    desc:'Capítulos sobre épicas. Márgenes anchos, anotaciones al margen.',
    accent:'#8b5e3c' },
  { id:'ed',    name:'EdiBarak',         italicName:'Barak',
    kicker:'Editoriales',
    desc:'Textos de opinión. Tipografía gritada, reglas gruesas, grid partido.',
    accent:'#d92b2b' },
  { id:'about', name:'Detrás de Escenas',italicName:'Escenas',
    kicker:'Quién, cómo, por qué',
    desc:'El proyecto, el autor. Carpa de teatro, bombillas encendidas.',
    accent:'#c8960a' },
];
window.RT_SECTIONS = SECTIONS;

// ─── Hash helpers ──────────────────────────────────────────────
function parseHash() {
  const h = (window.location.hash || '').replace(/^#/, '');
  if (!h || h === '/') return { section: null, slug: null };
  const parts = h.replace(/^\//, '').split('/');
  return { section: parts[0] || null, slug: parts[1] || null };
}
function setHash(section, slug) {
  const path = slug ? `#/${section}/${slug}` : (section ? `#/${section}` : '#/');
  if (window.location.hash !== path) {
    history.pushState(null, '', path);
    window.dispatchEvent(new HashChangeEvent('hashchange'));
  }
}

// ─── Main app ──────────────────────────────────────────────────
function RintanaApp() {
  const TW = window.__RINTANA_TWEAKS__ || {};
  const [showHomeOnLand] = React.useState(TW.startOnHome !== false);

  // Desktop detection — DesktopShell.jsx debe cargarse ANTES que este archivo
  // para que window.useIsDesktop exista. Ver orden de scripts en index.astro.
  const isDesktop = window.useIsDesktop(1024);

  const initialHash = React.useMemo(parseHash, []);
  const [section, setSection] = React.useState(() => {
    if (initialHash.section) return initialHash.section;
    return showHomeOnLand ? null : 'vv';
  });
  const [deepSlug, setDeepSlug] = React.useState(initialHash.slug);
  const [chrome, setChrome] = React.useState({ accent:'#d92b2b', dark:'#0a0807', light:'#f0e6d0' });

  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const [tweaksOpen, setTweaksOpen] = React.useState(false);

  // URL → state
  React.useEffect(() => {
    const onPop = () => {
      const { section: s, slug } = parseHash();
      setSection(s || null);
      setDeepSlug(slug);
      setDrawerOpen(false);
    };
    window.addEventListener('hashchange', onPop);
    return () => window.removeEventListener('hashchange', onPop);
  }, []);

  // state → URL
  React.useEffect(() => {
    setHash(section, deepSlug);
  }, [section, deepSlug]);

  // Tweak edit-mode plumbing
  React.useEffect(() => {
    const onMsg = (e) => {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({type:'__edit_mode_available'}, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const updateTweak = (key, value) => {
    window.parent.postMessage({type:'__edit_mode_set_keys', edits:{[key]: value}}, '*');
  };

  const goSection = (sec, slug=null) => {
    setSection(sec);
    setDeepSlug(slug);
    setDrawerOpen(false);
  };
  const goHome = () => {
    setSection(null);
    setDeepSlug(null);
    setDrawerOpen(false);
  };

  // Hide burger on home (home has its own entry points)
  const showBurger = section !== null;

  // ── DESKTOP BRANCH ─────────────────────────────────────────
  // Cuando isDesktop, se reemplaza TODO el chrome por DesktopShell
  // (header + sidebar + frame). Los componentes de sección se
  // renderizan igual que en mobile para no duplicar código.
  // Mobile NO se toca — queda el return de abajo.
  if (isDesktop) {
    // Decidimos el tamaño de frame según la sección y si hay slug:
    //   VV siempre phone (440px) — su layout está tuneado ahí.
    //   IB/ED sin slug → freeform (grid desktop propio).
    //   IB/ED con slug → reader (~720px, lectura cómoda sin look de celu).
    //   Detrás → reader también (no tiene variant de listado).
    //   Home → freeform.
    let desktopFrame = 'freeform';
    if (section === 'vv') desktopFrame = 'phone';
    else if ((section === 'ib' || section === 'ed') && deepSlug) desktopFrame = 'reader';
    else if (section === 'about') desktopFrame = 'reader';

    const sectionEl = (
      <>
        {section === 'vv' && (
          <TrailerApp initialSlug={deepSlug} onSlugChange={(s) => setDeepSlug(s)} onHome={goHome}/>
        )}
        {section === 'ib' && (
          deepSlug
            ? <IBSection initialSlug={deepSlug} onSlugChange={setDeepSlug} onChrome={setChrome}/>
            : <DesktopIBIndex onOpen={(slug) => setDeepSlug(slug)}/>
        )}
        {section === 'ed' && (
          deepSlug
            ? <EDSection initialSlug={deepSlug} onSlugChange={setDeepSlug} onChrome={setChrome}/>
            : <DesktopEDIndex onOpen={(slug) => setDeepSlug(slug)}/>
        )}
        {section === 'about' && (
          <DBSection
            onPickFilm={(slug) => goSection('vv', slug)}
            onPickSection={(id) => goSection(id)}
            onChrome={setChrome}/>
        )}
      </>
    );

    return (
      <div className="rt-app rt-app--desktop" data-mode="desktop">
        <DesktopShell
          section={section}
          onPick={(id) => goSection(id)}
          onHome={goHome}
          frame={desktopFrame}>
          {section === null
            ? <DesktopHome onPick={(id) => goSection(id)}/>
            : sectionEl}
        </DesktopShell>

        {/* TWEAKS PANEL — sigue disponible en desktop */}
        {tweaksOpen && (
          <div className="rt-tweaks">
            <div className="rt-tweaks-title">Tweaks</div>
            <div className="rt-tweaks-row">
              <div className="rt-tweaks-label">Sección</div>
              <div className="rt-tweaks-opts" style={{ gridTemplateColumns:'1fr 1fr' }}>
                {SECTIONS.map(s => (
                  <button
                    key={s.id}
                    className="rt-tweaks-opt"
                    aria-pressed={section === s.id}
                    onClick={() => goSection(s.id)}>
                    {s.id === 'about' ? 'Detrás' : s.name.split(' ')[0]}
                  </button>
                ))}
              </div>
            </div>
            <div className="rt-tweaks-row">
              <div className="rt-tweaks-label">Ir a home</div>
              <div className="rt-tweaks-opts" style={{ gridTemplateColumns:'1fr' }}>
                <button className="rt-tweaks-opt" onClick={goHome}>Home</button>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  }

  // ── MOBILE BRANCH ──────────────────────────────────────────
  // Árbol mobile original — no se toca.
  return (
    <div className="rt-app" data-nav="hamburger">

      {/* ───────────── BODY ───────────── */}
      {section === null && (
        // Home v2 is the new portal layout (3 stylised section entries +
        // detrás-de-escenas). The legacy collage/list variants are kept
        // available behind the `homeStyle` tweak for debug only.
        (TW.homeStyle === 'collage')
          ? <RTHomeCollage onPick={(id) => goSection(id)}/>
          : <RTHome onPick={(id) => goSection(id)}/>
      )}

      {section === 'vv' && (
        <div className="rt-section">
          <TrailerApp initialSlug={deepSlug} onSlugChange={(s) => setDeepSlug(s)} onHome={goHome}/>
        </div>
      )}
      {section === 'ib' && (
        <div className="rt-section">
          <IBSection initialSlug={deepSlug} onSlugChange={setDeepSlug} onChrome={setChrome}/>
        </div>
      )}
      {section === 'ed' && (
        <div className="rt-section">
          <EDSection initialSlug={deepSlug} onSlugChange={setDeepSlug} onChrome={setChrome}/>
        </div>
      )}
      {section === 'about' && (
        <div className="rt-section">
          <DBSection
            onPickFilm={(slug) => goSection('vv', slug)}
            onPickSection={(id) => goSection(id)}
            onChrome={setChrome}/>
        </div>
      )}

      {/* ───────────── NAV — HAMBURGER ───────────── */}
      {showBurger && (
        <button
          className={`rt-burger-trigger ${drawerOpen ? 'is-open' : ''}`}
          onClick={() => setDrawerOpen(o => !o)}
          aria-label="Menú">
          <span/><span/><span/>
        </button>
      )}
      {drawerOpen && (
        <BurgerDrawer
          current={section}
          onPick={goSection}
          onHome={goHome}
          onClose={() => setDrawerOpen(false)}/>
      )}

      {/* ───────────── TWEAKS PANEL ───────────── */}
      {tweaksOpen && (
        <div className="rt-tweaks">
          <div className="rt-tweaks-title">Tweaks</div>
          <div className="rt-tweaks-row">
            <div className="rt-tweaks-label">Sección</div>
            <div className="rt-tweaks-opts" style={{ gridTemplateColumns:'1fr 1fr' }}>
              {SECTIONS.map(s => (
                <button
                  key={s.id}
                  className="rt-tweaks-opt"
                  aria-pressed={section === s.id}
                  onClick={() => goSection(s.id)}>
                  {s.id === 'about' ? 'Detrás' : s.name.split(' ')[0]}
                </button>
              ))}
            </div>
          </div>
          <div className="rt-tweaks-row">
            <div className="rt-tweaks-label">Ir a home</div>
            <div className="rt-tweaks-opts" style={{ gridTemplateColumns:'1fr' }}>
              <button
                className="rt-tweaks-opt"
                onClick={goHome}>Home</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── HOME ─────────────────────────────────────────────────────
// Home = portal to the 3 main sections. No movie photos — each portal
// has its own typographic identity built from SVG/CSS primitives so
// the three styles clearly clash/dialogue.
function RTHome({ onPick }) {
  return (
    <div className="rt-home rt-home-v2">
      <div className="rt-home-v2-head">
        <div className="rt-home-v2-wordmark">
          <span>RINTANA</span>
          <span className="rt-home-v2-wordmark-dot"/>
        </div>
        <div className="rt-home-v2-tag">POR NICO BARAK</div>
      </div>

      <button
        className="rt-portal rt-portal-vv"
        onClick={() => onPick('vv')}
        aria-label="Vamos Viendo">
        <span className="rt-portal-kicker"><span className="rt-portal-rec"/> EN CARTEL</span>
        <span className="rt-portal-num">01</span>
        <span className="rt-portal-title">
          Vamos<br/><em>Viendo</em>
        </span>
        <span className="rt-portal-desc">Críticas sueltas. Una película, un análisis, una opinión. A veces, todo eso mezclado.</span>
        <span className="rt-portal-cta">Entrar al feed →</span>
        <svg className="rt-portal-perf" viewBox="0 0 400 40" preserveAspectRatio="none" aria-hidden="true">
          {Array.from({length: 20}).map((_, i) => (
            <rect key={i} x={i * 20 + 4} y={10} width={12} height={20} fill="currentColor"/>
          ))}
        </svg>
      </button>

      <button
        className="rt-portal rt-portal-ib"
        onClick={() => onPick('ib')}
        aria-label="Inmenso Bastardo">
        <span className="rt-portal-stamp">CUADERNOS · VOL II</span>
        <span className="rt-portal-num">02</span>
        <span className="rt-portal-title">
          Inmenso<br/><em>Bastardo.</em>
        </span>
        <span className="rt-portal-desc">
          Historia de lo épico en el séptimo arte.
        </span>
        <span className="rt-portal-cta">Abrir cuaderno →</span>
        <span className="rt-portal-tape rt-portal-tape-tl" aria-hidden="true"/>
        <span className="rt-portal-tape rt-portal-tape-br" aria-hidden="true"/>
        <span className="rt-portal-scribble" aria-hidden="true">✎ Leer en orden, si&nbsp;querés</span>
      </button>

      <button
        className="rt-portal rt-portal-ed"
        onClick={() => onPick('ed')}
        aria-label="EdiBarak">
        <span className="rt-portal-masthead">EDI · BARAK</span>
        <span className="rt-portal-num">03</span>
        <span className="rt-portal-title">
          Edi<em>Barak</em>
        </span>
        <span className="rt-portal-desc">Columnas de opinión.</span>
        <span className="rt-portal-cta">Leer columnas →</span>
        <span className="rt-portal-rule" aria-hidden="true"/>
        <span className="rt-portal-columns" aria-hidden="true">
          <span/><span/><span/>
        </span>
      </button>

      <button
        className="rt-home-v2-about"
        onClick={() => onPick('about')}>
        <span className="rt-home-v2-about-kick">· 04 ·</span>
        <span className="rt-home-v2-about-name">Detrás de escenas</span>
        <span className="rt-home-v2-about-desc">quién escribe, cómo, por qué.</span>
        <span className="rt-home-v2-about-arrow">→</span>
      </button>

      <div className="rt-home-v2-foot">
        <span>RINTANA · CINE · 2026</span>
        <span>☰ menú abajo a la derecha</span>
      </div>
    </div>
  );
}

// ─── NAV — HAMBURGER DRAWER ───────────────────────────────────
function BurgerDrawer({ current, onPick, onHome, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  return (
    <div className="rt-burger-drawer" role="dialog">
      <div className="rt-burger-head">
        <div className="rt-burger-kicker">
          <span style={{
            fontFamily:"'Bebas Neue', 'Anton', Impact, sans-serif",
            fontWeight: 400,
            fontSize: '1.35em',
            letterSpacing: '0.12em',
            color: '#f0ece4',
            textShadow: '2px 2px 0 #2b5dd9',
            verticalAlign: 'middle',
          }}>RINTANA</span>
          <span aria-hidden="true" style={{
            display:'inline-block',
            width: '0.35em', height: '0.35em',
            borderRadius: '50%',
            background: '#d92b2b',
            marginLeft: '0.35em',
            verticalAlign: 'middle',
            transform: 'translateY(-0.2em)',
          }}/>
        </div>
        <h2 className="rt-burger-title">Distintas<br/>maneras de<br/>ver lo mismo.</h2>
      </div>
      <div className="rt-burger-list">
        <button className="rt-burger-item" onClick={onHome}>
          <span className="rt-burger-item-num">00</span>
          <span className="rt-burger-item-name" style={{ color:'#8a7d6b' }}>Inicio</span>
          <span className="rt-burger-item-arrow">↩</span>
        </button>
        {SECTIONS.map((s, i) => (
          <button
            key={s.id}
            className="rt-burger-item"
            style={{ '--cellAccent': s.accent }}
            aria-current={current === s.id ? 'page' : undefined}
            onClick={() => onPick(s.id)}>
            <span className="rt-burger-item-num">{String(i+1).padStart(2,'0')}</span>
            <span className="rt-burger-item-name">
              {s.id === 'vv' && (<>Vamos <em>Viendo</em></>)}
              {s.id === 'ib' && (<>Inmenso <em>Bastardo</em></>)}
              {s.id === 'ed' && (<>Edi<em>Barak</em></>)}
              {s.id === 'about' && (<><em>Detrás</em> de escenas</>)}
            </span>
            <span className="rt-burger-item-arrow">→</span>
          </button>
        ))}
      </div>
    </div>
  );
}

window.RintanaApp = RintanaApp;

// ═══════════════════════════════════════════════════════════════
// HOME — COLLAGE (rupturista, cruza las 4 estéticas)
// ═══════════════════════════════════════════════════════════════
function RTHomeCollage({ onPick }) {
  return (
    <div className="rt-home-col">
      {/* Paper grain overlay on everything */}
      <div className="rt-col-grain" aria-hidden="true"/>

      {/* ─── PAGE HEADER — newsprint masthead ─── */}
      <div className="rt-col-masthead">
        <div className="rt-col-mast-rule"/>
        <div className="rt-col-mast-row">
          <span className="rt-col-mast-l">№1 · AÑO XI</span>
          <div className="rt-col-mast-logo">
            <img src="src/rintana/rintana-wordmark.svg" alt="Rintana"/>
          </div>
          <span className="rt-col-mast-r">2026 · BA</span>
        </div>
        <div className="rt-col-mast-rule"/>
        <div className="rt-col-mast-tag">
          <span>Cine · Crítica · Manía</span>
          <span className="rt-col-mast-dot">●</span>
          <span>Tres formas de seguir mirando</span>
        </div>
      </div>

      {/* ─── CROSSING HEADLINE — compacto ─── */}
      <div className="rt-col-headline">
        <span className="rt-col-head-line1">HACE RATO</span>
        <span className="rt-col-head-line2">
          <span className="rt-col-head-strike">QUE</span>
          <em>vamos</em>
          <span className="rt-col-head-line2-tail"> viendo.</span>
        </span>
        <span className="rt-col-head-note">↙ elegí por dónde entrar</span>
      </div>

      {/* ─── TABLEAU — 3 secciones ─── */}
      <div className="rt-col-grid">

        {/* VV — cinematic black / still of the week */}
        <button
          className="rt-col-tile rt-col-vv"
          onClick={() => onPick('vv')}
          aria-label="Vamos Viendo">
          <div className="rt-col-vv-still">
            <div className="rt-col-vv-lbl">
              <span>STILL №47</span>
              <span>·</span>
              <span>CHUNGKING EXPRESS</span>
            </div>
            <div className="rt-col-vv-frame"/>
            <div className="rt-col-vv-scratch"/>
            <div className="rt-col-vv-grain"/>
          </div>
          <div className="rt-col-vv-meta">
            <span className="rt-col-vv-num">01</span>
            <span className="rt-col-vv-name">Vamos <em>Viendo</em></span>
            <span className="rt-col-vv-sub">→ 142 críticas · una por semana</span>
          </div>
          <div className="rt-col-tape rt-col-tape--tl"/>
        </button>

        {/* IB — paper, handwritten, ink blots */}
        <button
          className="rt-col-tile rt-col-ib"
          onClick={() => onPick('ib')}
          aria-label="Inmenso Bastardo">
          <div className="rt-col-ib-paper">
            <div className="rt-col-ib-stain rt-col-ib-stain--a"/>
            <div className="rt-col-ib-stain rt-col-ib-stain--b"/>
            <div className="rt-col-ib-blot rt-col-ib-blot--a"/>
            <div className="rt-col-ib-blot rt-col-ib-blot--b"/>
            <div className="rt-col-ib-paperclip">📎</div>

            <div className="rt-col-ib-meta">CUAD. №04 · ÉPICAS</div>
            <div className="rt-col-ib-title">
              <span>Inmenso</span>
              <em>Bastardo</em>
            </div>
            <div className="rt-col-ib-hand">
              «una épica
              <span className="rt-col-ib-cross"> sin piedad</span>
              <span className="rt-col-ib-add"> con piedad.»</span>
            </div>
            <div className="rt-col-ib-stamp">URGENTE</div>
          </div>
          <div className="rt-col-tape rt-col-tape--tr"/>
        </button>

        {/* ED — Swiss editorial RED block */}
        <button
          className="rt-col-tile rt-col-ed"
          onClick={() => onPick('ed')}
          aria-label="EdiBarak">
          <div className="rt-col-ed-bg">
            <div className="rt-col-ed-num">03</div>
            <div className="rt-col-ed-kicker">
              <span className="rt-col-ed-square"/>
              EDITORIAL №002
            </div>
            <div className="rt-col-ed-title">
              EDI<br/>BARAK
            </div>
            <div className="rt-col-ed-rot">OPINIÓN · MANIFIESTO · FURIA</div>
            <div className="rt-col-ed-foot">
              <span>↳ Último:</span>
              <span>"El cine ya no se ve, se consume"</span>
            </div>
          </div>
          <div className="rt-col-tape rt-col-tape--bl"/>
        </button>

      </div>

      {/* ─── FOOTER — typewriter meta ─── */}
      <div className="rt-col-foot">
        <div className="rt-col-foot-row">
          <span>EST. 2015</span>
          <span className="rt-col-foot-sep">——————</span>
          <span>350 pel/año</span>
          <span className="rt-col-foot-sep">——————</span>
          <span>∞</span>
        </div>
        <div className="rt-col-foot-sig">
          <span>menú ☰ arriba a la derecha</span>
        </div>
      </div>
    </div>
  );
}
