// Main content sections — About, Gallery, Roadmap, Download, Footer.
// Nav lives here too.

function Nav({ onToggleMembers }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [auth, setAuth] = React.useState(null);

  React.useEffect(() => {
    const h = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', h); h();
    return () => window.removeEventListener('scroll', h);
  }, []);

  React.useEffect(() => {
    fetch('/api/auth/me').then(r => r.json()).then(d => setAuth(d.authenticated ? d : false)).catch(() => setAuth(false));
  }, []);

  const handleLogout = async () => {
    await fetch('/api/auth/logout');
    setAuth(false);
    window.location.reload();
  };

  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="nav-brand">
        <img src="/assets/ui/logo.png" alt="PPL" className="nav-brand-mark" style={{ objectFit: 'cover', padding: 0 }} />
        <div>
          <div className="nav-brand-name">Pirate Privates Loot</div>
          <div className="nav-brand-sub">Wicked Tales Interactive · v0.1.5</div>
        </div>
      </div>
      <div className="nav-links">
        <a href="#about">About</a>
        <a href="#gallery">Gallery</a>
        <a href="#roadmap">Chapters</a>
        <a href="#members">Members</a>
        <a href="#download">Play</a>
      </div>
      <div className="nav-cta">
        <a className="btn btn-ghost" href="https://www.wickedtalesinteractive.com" target="_blank" rel="noreferrer" style={{ fontSize: 10, padding: '8px 14px', opacity: .7 }}>
          ← Studio
        </a>
        {auth ? (
          <button className="btn btn-ghost" onClick={handleLogout} style={{ fontSize: 11 }}>
            Log out
          </button>
        ) : (
          <button className="btn btn-gold" onClick={onToggleMembers}>
            <Icon.Patreon /> Log in
          </button>
        )}
      </div>
    </nav>
  );
}

/* ---------- About ---------- */
function About() {
  const features = [
    { icon: Icon.Map,      title: 'Choices With Consequence',  body: 'A handful of decisions carry real weight. Who you protect, what you say when the moment arrives. The story doesn\'t branch wildly — but the choices that matter arrive with clarity, and some doors close.' },
    { icon: Icon.Heart,    title: 'Earned Intimacy',           body: 'Nami and Kaya don\'t give you anything automatically. What they offer, when they offer it, is shaped by who you\'ve been. The private scenes are not unlocks — they are consequences.' },
    { icon: Icon.Book,     title: 'Adult Narrative',           body: 'Explicit content written as part of the story, not appended to it. Mature themes, mature treatment. All characters depicted are fictional adults, 18+.' },
    { icon: Icon.Dice,     title: 'Light Interactive Moments', body: 'A dice game. A confrontation that plays out in action rather than text. Small sequences that break the reading without breaking the immersion.' },
    { icon: Icon.Globe,    title: 'Five Languages',            body: 'Localised in English, Spanish, French, Italian, and Portuguese — translated with attention to register, not just syntax.' },
    { icon: Icon.Sparkle,  title: 'Illustrated Environments',  body: 'Full-resolution art across Shellstown, Syrup Village, and the sea between them. Built to match the atmosphere of each scene — not generic, not rushed.' },
  ];
  return (
    <section id="about">
      <div className="wrap">
        <div className="eyebrow">✦  Ch. I · The Setting</div>
        <h2 className="section-title">A story written in salt, silence, and the space between <em>choices</em>.</h2>
        <p style={{ fontFamily: 'var(--f-serif)', fontSize: 20, fontStyle: 'italic', color: 'var(--beige)', maxWidth: 780, lineHeight: 1.55, marginBottom: 64 }}>
          Two chapters are out. A third is in production. The writing takes
          the world seriously — the tension, the characters, the weight of
          what happens behind closed doors. The art follows.
        </p>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 20 }}>
          {features.map((f, i) => {
            const IconComp = f.icon;
            return (
              <div key={i} className="card" style={{ padding: 28 }}>
                <div style={{ color: 'var(--gold)', marginBottom: 18 }}>
                  <IconComp style={{ width: 32, height: 32 }} />
                </div>
                <h3 style={{ fontFamily: 'var(--f-display)', fontSize: 26, fontWeight: 500, fontStyle: 'italic', color: 'var(--cream)', marginBottom: 10 }}>
                  {f.title}
                </h3>
                <p style={{ fontFamily: 'var(--f-serif)', fontSize: 15, lineHeight: 1.55, color: 'var(--beige)', opacity: .85 }}>
                  {f.body}
                </p>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ---------- Gallery ---------- */
function Gallery() {
  // Editorial gallery — one hero, two wide atmospheric strips, three character moments.
  // Numbers refer to the source image files 1.png / 2-6.webp.
  const shots = [
    { n: 1, src: 'assets/gallery/1.png',  title: "Nami's Reward",           kicker: 'Ch. 01 · The Hoist',         role: 'hero',    caption: 'What she chooses to give, after the fight is over.' },
    { n: 2, src: 'assets/gallery/2.webp', title: 'Dusk Over Shellstown',    kicker: 'Setting · Marine Coast',     role: 'wide',    caption: 'The coastline where it begins.' },
    { n: 3, src: 'assets/gallery/3.webp', title: 'First Drink with Nami',   kicker: 'Ch. 01 · The Tavern',        role: 'mid',     caption: 'Before anyone knows what this is going to become.' },
    { n: 4, src: 'assets/gallery/4.webp', title: "Kaya's Farewell",         kicker: 'Ch. 02 · Syrup Village',     role: 'mid',     caption: 'Quiet, decided, hers alone.' },
    { n: 5, src: 'assets/gallery/5.webp', title: 'Stars Above the Merry',   kicker: 'Between Chapters',           role: 'wide',    caption: 'Night watch, nothing to do but listen.' },
    { n: 6, src: 'assets/gallery/6.webp', title: 'Dinner After Dark',       kicker: 'Dating System · Early Access', role: 'mid',   caption: 'A table for two, and a reason to stay.' },
  ];
  const [lightbox, setLightbox] = React.useState(null);

  return (
    <section id="gallery" style={{ background: 'linear-gradient(180deg, transparent, rgba(0,34,84,.15), transparent)' }}>
      <div className="wrap">
        <div style={{ marginBottom: 48 }}>
          <div className="eyebrow">✦  Ch. II · The Log</div>
          <h2 className="section-title">Scenes from the <em>voyage</em>.</h2>
          <p style={{ fontFamily: 'var(--f-serif)', fontStyle: 'italic', fontSize: 17, color: 'var(--beige)', maxWidth: 620, lineHeight: 1.5, opacity: .85 }}>
            Six pieces. One hero, two horizons, three quiet moments between them.
          </p>
        </div>

        {/* Editorial grid */}
        <div className="gallery-grid">
          {/* Row 1 — hero + mid */}
          <GalleryTile shot={shots[0]} className="g-hero"   big onClick={() => setLightbox(shots[0])} />
          <GalleryTile shot={shots[2]} className="g-mid-a"      onClick={() => setLightbox(shots[2])} />
          {/* Row 2 — full-width cinematic strip */}
          <GalleryTile shot={shots[1]} className="g-wide-a"     onClick={() => setLightbox(shots[1])} />
          {/* Row 3 — three */}
          <GalleryTile shot={shots[3]} className="g-mid-b"      onClick={() => setLightbox(shots[3])} />
          <GalleryTile shot={shots[5]} className="g-mid-c"      onClick={() => setLightbox(shots[5])} />
          {/* Row 4 — second wide atmospheric pause */}
          <GalleryTile shot={shots[4]} className="g-wide-b"     onClick={() => setLightbox(shots[4])} />
        </div>
      </div>

      {lightbox && <GalleryLightbox shot={lightbox} onClose={() => setLightbox(null)} />}
    </section>
  );
}

function GalleryTile({ shot, className = '', big = false, onClick }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={onClick}
      className={`card ${className}`}
      style={{
        padding: 0, overflow: 'hidden', position: 'relative',
        cursor: 'pointer', color: 'var(--cream)', border: 'none',
        background: '#05122E',
      }}
    >
      <img
        src={shot.src}
        alt={shot.title}
        style={{
          position: 'absolute', inset: 0,
          width: '100%', height: '100%',
          objectFit: 'cover',
          transform: hover ? 'scale(1.04)' : 'scale(1)',
          transition: 'transform .8s cubic-bezier(.2,.8,.2,1)',
        }}
      />
      {/* Bottom gradient for legibility */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(180deg, transparent 40%, rgba(11,11,20,.85) 100%)',
      }} />
      {/* Top-left chip (role indicator for hero only) */}
      {big && (
        <div style={{
          position: 'absolute', top: 20, left: 20,
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '6px 12px', border: '1px solid rgba(212,175,55,.4)',
          background: 'rgba(11,11,20,.6)', backdropFilter: 'blur(4px)',
          fontFamily: 'var(--f-caps)', fontSize: 10, letterSpacing: '.25em',
          color: 'var(--gold)', textTransform: 'uppercase',
        }}>
          <Icon.Sparkle style={{ width: 10, height: 10 }} /> Featured Scene
        </div>
      )}
      {/* Caption */}
      <div style={{
        position: 'absolute', left: big ? 32 : 20, right: big ? 32 : 20, bottom: big ? 28 : 20,
        display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16,
      }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--f-caps)', fontSize: 10, letterSpacing: '.3em', color: 'var(--gold)', marginBottom: 6 }}>
            ✦ {shot.kicker}
          </div>
          <div style={{
            fontFamily: 'var(--f-display)', fontWeight: 500, fontStyle: 'italic',
            fontSize: big ? 34 : 20, color: 'var(--cream)', lineHeight: 1.15,
            textShadow: '0 2px 12px rgba(0,0,0,.6)',
          }}>
            {shot.title}
          </div>
          {big && (
            <div style={{
              fontFamily: 'var(--f-serif)', fontStyle: 'italic', fontSize: 14,
              color: 'var(--beige)', opacity: .9, marginTop: 8, maxWidth: 460,
            }}>
              {shot.caption}
            </div>
          )}
        </div>
        <div style={{
          flexShrink: 0,
          width: big ? 44 : 36, height: big ? 44 : 36, border: '1px solid var(--gold)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--gold)', transition: 'all .2s',
          background: hover ? 'var(--gold)' : 'rgba(11,11,20,.4)',
        }}>
          <Icon.Arrow style={{ width: 14, height: 14, color: hover ? 'var(--navy-deep)' : 'var(--gold)' }} />
        </div>
      </div>
    </button>
  );
}

function GalleryLightbox({ shot, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onClose]);
  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(7,7,16,.92)', backdropFilter: 'blur(8px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 40, cursor: 'zoom-out',
      }}
    >
      <div onClick={(e) => e.stopPropagation()} style={{
        position: 'relative', maxWidth: '92vw', maxHeight: '88vh',
        display: 'flex', flexDirection: 'column', gap: 14,
      }}>
        <img src={shot.src} alt={shot.title} style={{
          maxWidth: '100%', maxHeight: '74vh',
          objectFit: 'contain', border: '1px solid rgba(212,175,55,.25)',
        }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 20, color: 'var(--cream)' }}>
          <div>
            <div style={{ fontFamily: 'var(--f-caps)', fontSize: 10, letterSpacing: '.3em', color: 'var(--gold)' }}>
              ✦ {shot.kicker}
            </div>
            <div style={{ fontFamily: 'var(--f-display)', fontWeight: 500, fontStyle: 'italic', fontSize: 26, marginTop: 4 }}>
              {shot.title}
            </div>
            <div style={{ fontFamily: 'var(--f-serif)', fontStyle: 'italic', fontSize: 14, color: 'var(--beige)', opacity: .85, marginTop: 6, maxWidth: 560 }}>
              {shot.caption}
            </div>
          </div>
          <button onClick={onClose} className="btn btn-ghost" style={{ padding: '10px 16px', fontSize: 10 }}>
            Close · Esc
          </button>
        </div>
      </div>
    </div>
  );
}

/* ---------- Roadmap ---------- */
function Roadmap() {
  const chapters = [
    {
      num: 'I', title: 'Shellstown',
      status: 'live', access: 'Public Demo · Free',
      summary: 'You wash up in a Marine port with no money and a thief who has no reason to trust you. Nami wants a chart stolen from the barracks. The plan falls apart — she gets caught, and you get one choice: walk away clean, or fight for someone you barely know. How it ends depends on what kind of person you are, and what she does with you afterward, alone in the back of a bar, is your reward for finding out.',
    },
    {
      num: 'II', title: 'Syrup Village',
      status: 'live', access: 'Public · Released April 24',
      summary: 'A rich girl dying slowly in a mansion full of lies. A sniper who cannot shoot straight but will not stop protecting her. A butler whose smile never reaches his eyes. You and Nami arrive as strangers and leave with a ship and a debt you did not ask for. Before you go, Kaya finds a moment alone with you — what she offers is not gratitude. She decided it on her own, quietly, while no one was watching.',
    },
    {
      num: 'III', title: 'Baratie · Cocoyashi · Arlong Park',
      status: 'dev', access: 'Patreon · In Development',
      summary: 'The night before the Baratie, Nami cries alone on the ship thinking no one can hear her. You do. You do not say anything — and that silence costs more than any fight. She takes the ship while you are still in the kitchen. No note. You follow her to a village that stopped being a village years ago — red lights, Fishmen at the corners, women working jobs they did not choose. The thing she has been carrying since before she met you is finally about to break open.',
    },
    {
      num: 'IV', title: 'Loguetown',
      status: 'planned', access: 'Planned · The Real Voyage Begins',
      summary: 'The town of beginnings and endings. Everything up to now was shore leave — in Loguetown, the Grand Line opens, and the choices you made start writing who you are.',
    },
  ];
  return (
    <section id="roadmap">
      <div className="wrap">
        <div className="eyebrow">✦  Ch. III · The Log Book</div>
        <h2 className="section-title">Chapters & <em>roadmap</em>.</h2>
        <p style={{ fontFamily: 'var(--f-serif)', fontStyle: 'italic', fontSize: 17, color: 'var(--beige)', maxWidth: 680, lineHeight: 1.5, marginBottom: 56 }}>
          New chapters land on Patreon first, then roll into the free public build
          as the next one enters production.
        </p>

        <div style={{ display: 'grid', gap: 18 }}>
          {chapters.map((c, i) => <ChapterRow key={i} c={c} />)}
        </div>
      </div>
    </section>
  );
}

function ChapterRow({ c }) {
  const statusChip = c.status === 'live'
    ? <span className="chip chip-live"><Icon.Check style={{ width: 10, height: 10 }} /> Live · Free</span>
    : c.status === 'dev'
      ? <span className="chip chip-dev"><Icon.Lock style={{ width: 10, height: 10 }} /> In Development</span>
      : <span className="chip"><Icon.Sparkle style={{ width: 10, height: 10 }} /> Planned</span>;
  return (
    <div className="card" style={{
      display: 'grid', gridTemplateColumns: '120px 1fr', gap: 32, padding: 32, alignItems: 'center',
    }}>
      <div style={{
        fontFamily: 'var(--f-display)', fontWeight: 500, fontStyle: 'italic', fontSize: 96,
        color: c.status === 'live' ? 'var(--gold)' : 'rgba(212,175,55,.3)',
        lineHeight: 1, textAlign: 'center',
      }}>
        {c.num}
      </div>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12, flexWrap: 'wrap' }}>
          {statusChip}
          <span style={{ fontFamily: 'var(--f-caps)', fontSize: 10, letterSpacing: '.25em', color: 'var(--beige)', opacity: .7, textTransform: 'uppercase' }}>
            {c.access}
          </span>
        </div>
        <h3 style={{ fontFamily: 'var(--f-display)', fontWeight: 500, fontStyle: 'italic', fontSize: 30, color: 'var(--cream)', marginBottom: 10 }}>
          Chapter {c.num} — {c.title}
        </h3>
        <p style={{ fontFamily: 'var(--f-serif)', fontStyle: 'italic', fontSize: 16, color: 'var(--beige)', opacity: .9, lineHeight: 1.55, maxWidth: 720 }}>
          {c.summary}
        </p>
      </div>
    </div>
  );
}

/* ---------- Download ---------- */
function Download() {
  return (
    <section id="download" style={{ background: 'linear-gradient(180deg, transparent, rgba(11,11,20,.6))' }}>
      <div className="wrap" style={{ textAlign: 'center' }}>
        <div className="eyebrow">✦  Ch. IV · The Hoist</div>
        <h2 className="section-title">Play the free <em>demo</em>.</h2>
        <p style={{ fontFamily: 'var(--f-serif)', fontStyle: 'italic', fontSize: 18, color: 'var(--beige)', maxWidth: 640, margin: '0 auto 48px', lineHeight: 1.5 }}>
          The public demo is hosted on itch.io — Windows, macOS, Linux, and a playable web build, all from one page.
        </p>
        <a className="btn btn-primary" href="https://wicked2509.itch.io/pirate-private-loot" target="_blank" rel="noreferrer"
           style={{ padding: '20px 36px', fontSize: 14 }}>
          <Icon.Play /> Play on itch.io
        </a>
        <div style={{ marginTop: 20, fontFamily: 'var(--f-caps)', fontSize: 10, letterSpacing: '.25em', color: 'var(--beige)', opacity: .6, textTransform: 'uppercase' }}>
          ↗ wicked2509.itch.io/pirate-private-loot
        </div>
      </div>
    </section>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  const cols = [
    { t: 'Game', l: [
      { x: 'Play the Demo', h: '#download' },
      { x: 'Roadmap', h: '#roadmap' },
      { x: 'Gallery', h: '#gallery' },
      { x: 'About the Story', h: '#about' },
    ]},
    { t: 'Community', l: [
      { x: 'Patreon', h: 'https://www.patreon.com/c/PiratePrivateLoot', ext: true },
      { x: 'itch.io', h: 'https://wicked2509.itch.io/pirate-private-loot', ext: true },
      { x: 'Members Area', h: 'members.html' },
    ]},
    { t: 'Legal', l: [
      { x: 'Terms of Service', h: '#' },
      { x: 'Privacy Policy', h: '#' },
      { x: 'DMCA', h: '#' },
      { x: 'Content Notice · 18+', h: '#' },
    ]},
  ];
  return (
    <footer style={{ padding: '72px 48px 32px', borderTop: '1px solid rgba(212,175,55,.2)', background: '#070710' }}>
      <div className="wrap" style={{
        display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 40, marginBottom: 48,
      }}>
        <div>
          <div style={{ fontFamily: 'var(--f-display)', fontWeight: 500, fontStyle: 'italic', fontSize: 28, color: 'var(--cream)', marginBottom: 10 }}>
            Pirate Privates Loot
          </div>
          <div style={{ fontFamily: 'var(--f-serif)', fontStyle: 'italic', fontSize: 14, color: 'var(--beige)', opacity: .7, maxWidth: 340, lineHeight: 1.55, marginBottom: 20 }}>
            An adult visual novel from Wicked Tales Interactive.
            Built in Ren'Py. All characters depicted are fictional adults 18+.
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            {[
              { label: 'Patreon', href: 'https://www.patreon.com/c/PiratePrivateLoot' },
              { label: 'itch.io',  href: 'https://wicked2509.itch.io/pirate-private-loot' },
            ].map(s => (
              <a key={s.label} href={s.href} target="_blank" rel="noreferrer"
                 style={{
                   fontFamily: 'var(--f-caps)', fontSize: 10, letterSpacing: '.2em',
                   padding: '8px 12px', border: '1px solid rgba(212,175,55,.3)',
                   color: 'var(--gold)', textDecoration: 'none', textTransform: 'uppercase',
                 }}>
                {s.label}
              </a>
            ))}
          </div>
        </div>
        {cols.map(col => (
          <div key={col.t}>
            <div style={{ fontFamily: 'var(--f-caps)', letterSpacing: '.2em', fontSize: 11, color: 'var(--gold)', marginBottom: 16 }}>
              {col.t}
            </div>
            <div style={{ display: 'grid', gap: 10 }}>
              {col.l.map(item => (
                <a key={item.x} href={item.h}
                   {...(item.ext ? { target: '_blank', rel: 'noreferrer' } : {})}
                   style={{
                     fontFamily: 'var(--f-sans)', fontSize: 13, color: 'var(--cream)',
                     opacity: .7, textDecoration: 'none', transition: 'opacity .15s, color .15s',
                   }}
                   onMouseEnter={e => { e.currentTarget.style.opacity = 1; e.currentTarget.style.color = 'var(--gold)'; }}
                   onMouseLeave={e => { e.currentTarget.style.opacity = .7; e.currentTarget.style.color = 'var(--cream)'; }}>
                  {item.x}{item.ext ? ' ↗' : ''}
                </a>
              ))}
            </div>
          </div>
        ))}
      </div>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12,
        paddingTop: 24, borderTop: '1px solid rgba(212,175,55,.1)',
        fontFamily: 'var(--f-sans)', fontSize: 12, color: 'rgba(245,240,232,.4)',
      }}>
        <div>© 2026 Wicked Tales Interactive · Fan-made. Not affiliated with or endorsed by the original rights holders.</div>
        <div>v0.1.5 · Shellstown</div>
      </div>
    </footer>
  );
}

Object.assign(window, { Nav, About, Gallery, Roadmap, Download, Footer });
