// sections.jsx — "The Reel" landing page, in six chapters

// ──────────────────── Chapter marker ────────────────────
function Slate({ n, total = '06', title }) {
  return (
    <div className="slate">
      <span className="slate-num">{n} / {total}</span>
      <span className="slate-bullet">●</span>
      <span className="slate-title">{title}</span>
      <span className="slate-rule" />
    </div>
  );
}

// ──────────────────── Nav ────────────────────
function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const on = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', on, { passive: true });
    on();
    return () => window.removeEventListener('scroll', on);
  }, []);
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="wrap nav-inner">
        <a href="#top" className="nav-logo">
          <img src="assets/logo.png" alt="Twilight Media Production" />
        </a>
        <div className="nav-links">
          <a href="#disciplines">Services</a>
          <a href="#reel">Portfolio</a>
          <a href="#voices">Reviews</a>
          <a href="#reserve">Contact</a>
        </div>
        <a href="#reserve" className="nav-cta">Book Now</a>
      </div>
    </nav>
  );
}

// ──────────────────── Hero — Title Card with key art ────────────────────
function Hero({ layout }) {
  return (
    <header className="hero" data-layout={layout} id="top" data-screen-label="01 Hero">
      <div className="hero-bg" />
      <div className="hero-veil" />
      <div className="hero-inner">
        <div className="wrap">
          <div className="hero-main">
            <div className="hero-stamp">
              <span>Wedding Photography &amp; Cinema</span>
              <span className="hero-stamp-dot">/</span>
              <span>New Jersey · Since 2013</span>
            </div>

            <h1 className="hero-title display">
              The days<br/>
              that <em>matter most.</em>
            </h1>

            <p className="hero-sub">
              Photography, cinema and livestreaming for weddings and the
              gatherings you'll come back to forever.
            </p>

            <div className="hero-actions">
              <a href="#reserve" className="btn btn-primary">
                Reserve a Date <span className="arrow">→</span>
              </a>
              <a href="#reel" className="btn btn-ghost">
                View Our Work
              </a>
            </div>
          </div>
        </div>
      </div>
    </header>
  );
}

// ──────────────────── Chapter 02 — Disciplines ────────────────────
const DISCIPLINES = [
  { n: '01', title: 'Photography',    spec: 'Documentary + portrait coverage' },
  { n: '02', title: 'Videography',    spec: 'Multi cam wedding films' },
  { n: '03', title: 'Livestream',     spec: 'Broadcast to anywhere' },
  { n: '04', title: 'Aerial / Drone', spec: 'FAA Part 107 certified' },
  { n: '05', title: 'Same Day Edit',  spec: '60–90 sec highlight reel' },
];

function Services() {
  return (
    <section className="section disciplines" id="disciplines" data-screen-label="02 Disciplines">
      <div className="wrap">
        <Slate n="02" total="05" title="Disciplines" />
        <div className="disc-head reveal">
          <h2 className="display">
            Five disciplines.<br/>
            <em>One crew on the day.</em>
          </h2>
          <p>
            Every event is staffed by a single tight team so the photograph, the film
            and the livestream tell one story, not three. Mix what you need.
          </p>
        </div>

        <ol className="disc-list reveal">
          {DISCIPLINES.map((d) => (
            <li className="disc-row" key={d.n}>
              <span className="disc-n">/{d.n}</span>
              <h3 className="disc-title display">{d.title}</h3>
              <span className="disc-spec">{d.spec}</span>
            </li>
          ))}
        </ol>
      </div>
    </section>
  );
}

// ──────────────────── Chapter 03 — The Reel (collage) ────────────────────
// Columns of photos — varied single / stacked arrangements, scrolls sideways
const COLLAGE_COLS = [
  ['w1'],
  ['e1', 'p1'],
  ['n1'],
  ['n3', 'n2'],
  ['w2'],
  ['e2', 'p2'],
  ['n5'],
  ['n4', 'n7'],
  ['w3', 'p3'],
  ['e3'],
  ['n6'],
  ['n8'],
  ['n12'],
  ['n9'],
  ['n10'],
  ['n11'],
  ['n13'],
  ['w5', 'p4'],
  ['w4', 'p5'],
];
const COLLAGE = COLLAGE_COLS.flat().map((k) => `assets/portfolio/${k}.jpg`);

function Portfolio() {
  const [open, setOpen] = React.useState(null); // index into COLLAGE or null
  const stripRef = React.useRef(null);
  const close = () => setOpen(null);
  const go = (dir) => setOpen((i) => (i + dir + COLLAGE.length) % COLLAGE.length);

  React.useEffect(() => {
    if (open === null) return;
    const onKey = (e) => {
      if (e.key === 'Escape') close();
      else if (e.key === 'ArrowRight') go(1);
      else if (e.key === 'ArrowLeft') go(-1);
    };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [open]);

  // drag-to-scroll
  React.useEffect(() => {
    const el = stripRef.current; if (!el) return;
    let down = false, startX = 0, startScroll = 0, moved = 0;
    const onDown = (e) => {
      down = true; moved = 0;
      startX = e.pageX; startScroll = el.scrollLeft;
      el.classList.add('dragging');
    };
    const onMove = (e) => {
      if (!down) return;
      const dx = e.pageX - startX;
      moved = Math.max(moved, Math.abs(dx));
      el.scrollLeft = startScroll - dx;
    };
    const onUp = () => { down = false; el.classList.remove('dragging'); };
    el.addEventListener('pointerdown', onDown);
    window.addEventListener('pointermove', onMove);
    window.addEventListener('pointerup', onUp);
    el._getMoved = () => moved;
    return () => {
      el.removeEventListener('pointerdown', onDown);
      window.removeEventListener('pointermove', onMove);
      window.removeEventListener('pointerup', onUp);
    };
  }, []);

  const openIfNotDragged = (idx) => () => {
    const el = stripRef.current;
    if (el && el._getMoved && el._getMoved() > 6) return; // was a drag
    setOpen(idx);
  };

  let flatIdx = -1;
  return (
    <section className="section reel" id="reel" data-screen-label="03 The Reel">
      <div className="wrap">
        <Slate n="03" total="05" title="The Reel" />
        <div className="reel-head reveal">
          <h2 className="display">
            240+ events.<br/>
            <em>A few favorites.</em>
          </h2>
          <p>
            A working contact sheet of moments from weddings, ceremonies, and
            the quiet in between. Drag to scroll, click any frame to enlarge.
          </p>
        </div>

        <div className="wrap collage-hint reveal">
          <window.I.Arrow />
          <span>Drag or scroll sideways</span>
        </div>
      </div>

      <div className="collage reveal" ref={stripRef}>
        {COLLAGE_COLS.map((col, ci) => (
          <div className={`collage-col ${col.length > 1 ? 'stack' : 'single'}`} key={ci}>
            {col.map((key) => {
              flatIdx += 1;
              const idx = flatIdx;
              return (
                <button className="collage-tile" key={key} onClick={openIfNotDragged(idx)} aria-label="Open photo">
                  <img src={`assets/portfolio/${key}.jpg`} alt="" draggable="false" />
                  <span className="collage-tile-zoom" aria-hidden="true">
                    <window.I.Expand />
                  </span>
                </button>
              );
            })}
          </div>
        ))}
      </div>

      <div className="wrap reel-foot reveal">
        <span className="reel-foot-stat"><strong>240+</strong> events shot</span>
        <span className="reel-foot-stat"><strong>13</strong> years working</span>
        <span className="reel-foot-stat"><strong>NJ · NY · PA</strong> · and beyond</span>
      </div>

      {open !== null && (
        <div className="lightbox" onClick={close}>
          <button className="lightbox-close" onClick={close} aria-label="Close">
            <window.I.Close />
          </button>
          <button className="lightbox-nav prev" onClick={(e) => { e.stopPropagation(); go(-1); }} aria-label="Previous">
            <window.I.ArrowLeft />
          </button>
          <img
            className="lightbox-img"
            src={COLLAGE[open]}
            alt=""
            onClick={(e) => e.stopPropagation()}
          />
          <button className="lightbox-nav next" onClick={(e) => { e.stopPropagation(); go(1); }} aria-label="Next">
            <window.I.Arrow />
          </button>
          <div className="lightbox-count">{String(open + 1).padStart(2, '0')} / {String(COLLAGE.length).padStart(2, '0')}</div>
        </div>
      )}
    </section>
  );
}

// ──────────────────── Chapter 04 — Voices ────────────────────
const VOICES = [
  { q: 'Very professional media company with great quality work and excellent customer service. I highly recommend them to anyone in New Jersey and New Milford. Reliable, respectful, and easy to work with.', by: 'Luis Guaman', meta: 'Google Review · New Milford NJ', stars: 5 },
  { q: 'Professional, good quality, excellent photographic skills, unique capture of moments, highly recommend.', by: 'Lexy Maria Alappat', meta: 'Google Review', stars: 5 },
  { q: 'They made my grandfather\'s memorial feel like a love letter, not a funeral. We will watch the film they made for our family for the rest of our lives.',           by: 'Marisol Reyes', meta: 'Memorial · Princeton NJ', stars: 5 },
];

function Testimonials() {
  return (
    <section className="section voices" id="voices" data-screen-label="04 Voices">
      <div className="wrap">
        <Slate n="04" total="05" title="Voices" />
        <div className="voices-head reveal">
          <h2 className="display">
            What couples<br/>
            <em>say after.</em>
          </h2>
          <p>
            A handful of the things we hear most often — drawn from the cards and emails
            and the messages people send us months later, on their anniversaries.
          </p>
        </div>

        <div className="voices-grid reveal">
          {VOICES.map((v, i) => (
            <figure className="voice-card" key={i}>
              <div className="voice-head">
                <span className="voice-no">/0{i + 1}</span>
                <span className="voice-stars">
                  {Array.from({ length: v.stars }).map((_, k) => <span key={k}>★</span>)}
                </span>
              </div>
              <blockquote className="voice-q display">"{v.q}"</blockquote>
              <figcaption className="voice-by">
                <strong>{v.by}</strong>
                <span>{v.meta}</span>
              </figcaption>
            </figure>
          ))}
        </div>
      </div>
    </section>
  );
}

// ──────────────────── Chapter 06 — Reserve ────────────────────
// ⬇⬇⬇  PASTE YOUR WEB3FORMS ACCESS KEY HERE  ⬇⬇⬇
// Get a free key in 30 seconds at https://web3forms.com (enter twilightmediausa@gmail.com,
// they email you a key). Submissions then arrive in that inbox automatically.
const WEB3FORMS_ACCESS_KEY = '9c5ad4ca-b1e1-4644-acc7-60b913e141f8';

function Booking() {
  const [form, setForm] = React.useState({
    name: '', email: '', phone: '', date: '',
    eventType: 'Wedding', guests: '', notes: '',
    services: ['Photography'],
  });
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState('');
  const update = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const toggleSvc = (s) => () => {
    setForm(f => ({ ...f, services: f.services.includes(s) ? f.services.filter(x => x !== s) : [...f.services, s] }));
  };
  const submit = async (e) => {
    e.preventDefault();
    setError('');
    setSending(true);
    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          access_key: WEB3FORMS_ACCESS_KEY,
          subject: `New booking request — ${form.name || 'Website'}`,
          from_name: 'Twilight Media Website',
          name: form.name,
          email: form.email,
          phone: form.phone,
          event_date: form.date,
          event_type: form.eventType,
          approx_guests: form.guests,
          services: form.services.join(', '),
          message: form.notes,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setSent(true);
      } else {
        setError(data.message || 'Something went wrong. Please email us directly.');
      }
    } catch (err) {
      setError('Network error. Please email us directly at twilightmediausa@gmail.com.');
    } finally {
      setSending(false);
    }
  };

  return (
    <section className="section reserve" id="reserve" data-screen-label="05 Reserve">
      <div className="wrap">
        <Slate n="05" total="05" title="Reserve" />
        <div className="reserve-inner reveal">
          <aside className="reserve-side">
            <h2 className="display">
              Tell us about<br/>
              <em>your day.</em>
            </h2>
            <p>
              Share a few details and we'll send back availability, sample work matched
              to your event, and a custom package, usually within 24 hours.
            </p>

            <div className="reserve-contact">
              <div className="bc-row">
                <span className="bc-k">Tel</span>
                <a href="tel:2012389654">(201) 238-9654</a>
              </div>
              <div className="bc-row">
                <span className="bc-k">Email</span>
                <a href="mailto:twilightmediausa@gmail.com">twilightmediausa@gmail.com</a>
              </div>
              <div className="bc-row">
                <span className="bc-k">Studio</span>
                <span>New Jersey · tri state</span>
              </div>
              <div className="bc-row">
                <span className="bc-k">Hours</span>
                <span>Mon to Fri · 10a to 6p ET</span>
              </div>
            </div>

            <div className="reserve-tag">
              <span>Currently booking</span>
              <strong>Spring & Summer 2026</strong>
            </div>
          </aside>

          <div className="reserve-form-wrap">
            {sent ? (
              <div className="form-success">
                <div className="check"><window.I.Check /></div>
                <h3 className="display">Thank you, {form.name || 'friend'}.</h3>
                <p>We've received your request and will be in touch within 24 hours at <strong>{form.email || 'the email you provided'}</strong>.</p>
              </div>
            ) : (
              <form className="form-grid" onSubmit={submit}>
                <div className="form-field">
                  <label>/01 Your Name</label>
                  <input type="text" required value={form.name} onChange={update('name')} placeholder="Full name" />
                </div>
                <div className="form-field">
                  <label>/02 Email</label>
                  <input type="email" required value={form.email} onChange={update('email')} placeholder="you@example.com" />
                </div>
                <div className="form-field">
                  <label>/03 Phone</label>
                  <input type="tel" value={form.phone} onChange={update('phone')} placeholder="(555) 555-5555" />
                </div>
                <div className="form-field">
                  <label>/04 Event Date</label>
                  <input type="date" value={form.date} onChange={update('date')} />
                </div>
                <div className="form-field">
                  <label>/05 Event Type</label>
                  <select value={form.eventType} onChange={update('eventType')}>
                    <option>Wedding</option>
                    <option>Engagement</option>
                    <option>Reception</option>
                    <option>Baptism / Religious</option>
                    <option>Sweet 16</option>
                    <option>Birthday / Private Party</option>
                    <option>Memorial Service</option>
                    <option>Corporate / Other</option>
                  </select>
                </div>
                <div className="form-field">
                  <label>/06 Approx. Guests</label>
                  <input type="text" value={form.guests} onChange={update('guests')} placeholder="e.g. 200" />
                </div>
                <div className="form-field full">
                  <label>/07 Services</label>
                  <div className="chip-group">
                    {['Photography', 'Videography', 'Livestream', 'Drone', 'Same Day Edit'].map(s => (
                      <button type="button" key={s}
                        className={`chip ${form.services.includes(s) ? 'on' : ''}`}
                        onClick={toggleSvc(s)}>
                        {s}
                      </button>
                    ))}
                  </div>
                </div>
                <div className="form-field full">
                  <label>/08 Anything else?</label>
                  <textarea value={form.notes} onChange={update('notes')}
                    placeholder="Venue, vision, references, family traditions, anything that helps us prepare." />
                </div>
                <div className="form-submit">
                  <p className="form-note">
                    {error ? error : 'Usually answered within 24 hrs.'}
                  </p>
                  <button type="submit" className="btn btn-primary" disabled={sending}>
                    {sending ? 'Sending…' : <>Send Request <span className="arrow">→</span></>}
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

// ──────────────────── Footer ────────────────────
function Footer() {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div className="ft-logo">
            <img src="assets/logo.png" alt="Twilight Media Production" />
            <div className="ft-tag">
              Cinematic photography, videography and livestreaming for the gatherings
              you'll come back to forever.
            </div>
          </div>
          <div className="ft-col">
            <h4>Chapters</h4>
            <a href="#disciplines">01 Disciplines</a>
            <a href="#reel">02 The Reel</a>
            <a href="#voices">03 Voices</a>
            <a href="#reserve">04 Reserve</a>
          </div>
          <div className="ft-col">
            <h4>Contact</h4>
            <a href="tel:2012389654">(201) 238-9654</a>
            <a href="mailto:twilightmediausa@gmail.com">twilightmediausa@gmail.com</a>
            <div>New Jersey, USA</div>
          </div>
          <div className="ft-col">
            <h4>Follow</h4>
            <a href="https://www.instagram.com/twilightmediausa/" target="_blank" rel="noopener" aria-label="Instagram">Instagram</a>
          </div>
        </div>
        <div className="ft-bot">
          <div>© {new Date().getFullYear()} Twilight Media Production · End of Reel</div>
          <div className="ft-bot-r">Vol. 12 · Pressed in New Jersey</div>
        </div>
        <p className="visually-hidden">
          Twilight Media Production is a New Jersey wedding photography and videography
          studio serving the tri state area, New York, and the Jersey Shore. Services
          include documentary wedding photography, cinematic wedding films, multi camera
          ceremony livestreaming, drone aerial coverage, engagement sessions, and same day
          highlight edits. Keywords: New Jersey wedding photographer, NJ wedding videographer,
          North Jersey wedding film, Jersey Shore wedding, NYC wedding cinematographer,
          South Asian wedding photographer NJ, micro wedding, elopement photographer.
          #NJWedding #NewJerseyWeddingPhotographer #NJWeddingVideographer #WeddingPhotography
          #WeddingFilm #WeddingCinematography #TwilightMediaProduction #JerseyShoreWedding
          #NYCWeddingPhotographer #TriStateWeddings #WeddingLivestream #DroneWedding
          #EngagementSession #SameDayEdit #BrideToBe #NJBride #WeddingInspo
        </p>
      </div>
    </footer>
  );
}

// Unused but kept for backwards compat with old refs
function About() { return null; }
function Marquee() { return null; }
function FAQ() { return null; }

Object.assign(window, { Nav, Hero, Services, Marquee, Portfolio, About, Testimonials, Booking, FAQ, Footer });
