const { useState, useEffect, useRef } = React;

// ============================================================
// CONTACT FORM CONFIG — both keys below are PUBLIC by design.
// They are meant to live in client HTML. No .env needed.
//   1. Sign up at https://web3forms.com → grab your Access Key.
//   2. Sign up at https://www.cloudflare.com/products/turnstile/
//      → grab your SITE key. The Turnstile SECRET key is pasted
//      into the Web3Forms dashboard, NEVER into this file.
// ============================================================
const WEB3FORMS_ACCESS_KEY = "a7fd0840-9127-4d12-af5f-adce819461b6";
const TURNSTILE_SITE_KEY   = "0x4AAAAAADQa3hPUHPSEZOIg";

// ============ icons ============
const CIcon = {
  Arrow: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M5 12 H19 M13 6 L19 12 L13 18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="square" strokeLinejoin="miter"/>
    </svg>
  ),
  Menu: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <line x1="4" y1="6" x2="20" y2="6" stroke="currentColor" strokeWidth="1.8"/>
      <line x1="4" y1="12" x2="20" y2="12" stroke="currentColor" strokeWidth="1.8"/>
      <line x1="4" y1="18" x2="20" y2="18" stroke="currentColor" strokeWidth="1.8"/>
    </svg>
  ),
};

// ============ NAV ============
function Nav({ scrolled }) {
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);
  const closeMenu = () => setMenuOpen(false);
  const scrollTop = (e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: 'smooth' }); closeMenu(); };
  return (
    <header className={`nav ${scrolled ? 'nav--solid' : 'nav--floating'}`}>
      <div className="nav__inner">
        <a href="/" className="nav__logo" aria-label="Ages Productions home">
          <img src="assets/logo-primary.png" alt="Ages Productions"/>
        </a>
        <nav className="nav__links">
          <a href="/" className="nav__link">Home</a>
          <a href="Ages Productions Media Workflow.html" className="nav__link">Media Workflow</a>
          <a href="Ages Productions Self-Shoot.html" className="nav__link">Self-Shoot Systems</a>
          <a href="Ages Productions About.html" className="nav__link">About</a>
          <a href="Ages Productions Use Cases.html" className="nav__link">Use Cases</a>
          <a href="#" className="nav__link nav__link--active" onClick={(e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: 'smooth' }); }}>Contact</a>
        </nav>
        <div className="nav__cta"></div>
        <button className="nav__menu" aria-label={menuOpen ? "Close menu" : "Open menu"} aria-expanded={menuOpen} onClick={() => setMenuOpen(o => !o)}>
          {menuOpen
            ? <svg viewBox="0 0 24 24" width="22" height="22" fill="none"><line x1="6" y1="6" x2="18" y2="18" stroke="currentColor" strokeWidth="1.8"/><line x1="18" y1="6" x2="6" y2="18" stroke="currentColor" strokeWidth="1.8"/></svg>
            : <CIcon.Menu width="22" height="22"/>}
        </button>
      </div>
      <div className={`nav__drawer ${menuOpen ? 'nav__drawer--open' : ''}`} aria-hidden={!menuOpen}>
        <div className="nav__drawer-inner">
            <a href="/" className="nav__drawer-link" onClick={closeMenu}>Home</a>
            <a href="Ages Productions Media Workflow.html" className="nav__drawer-link" onClick={closeMenu}>Media Workflow</a>
            <a href="Ages Productions Self-Shoot.html" className="nav__drawer-link" onClick={closeMenu}>Self-Shoot Systems</a>
            <a href="Ages Productions About.html" className="nav__drawer-link" onClick={closeMenu}>About</a>
            <a href="Ages Productions Use Cases.html" className="nav__drawer-link" onClick={closeMenu}>Use Cases</a>
            <a href="#" className={`nav__drawer-link nav__drawer-link--active`} onClick={scrollTop}>Contact</a>
        </div>
      </div>
    </header>
  );
}

// ============ FOOTER ============
function Footer() {
  return (
    <footer className="footer">
      <div className="container footer__inner">
        <div className="footer__brand">
          <img src="assets/logo-primary.png" alt="Ages Productions" className="footer__logo"/>
          <p className="footer__tag">Field-to-post media workflow management for high-volume Reality TV productions.</p>
        </div>
        <div className="footer__cols">
          <div>
            <h6>SERVICES</h6>
            <a href="Ages Productions Media Workflow.html">Media Workflow</a>
            <a href="Ages Productions Self-Shoot.html">Self-Shoot Systems</a>
            <a href="Ages Productions Media Workflow.html#remote-cloud">Remote Delivery</a>
          </div>
          <div>
            <h6>COMPANY</h6>
            <a href="Ages Productions About.html">About</a>
            <a href="Ages Productions Use Cases.html">Use Cases</a>
            <a href="#" onClick={(e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: 'smooth' }); }}>Contact</a>
          </div>
          <div>
            <h6>CONTACT</h6>
            <a href="#" onClick={(e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: 'smooth' }); }}>Build a Media Plan</a>
            <span className="footer__loc">Miami · Worldwide</span>
          </div>
        </div>
      </div>
      <div className="footer__bar">
        <span>© 2026 Ages Productions. All rights reserved.</span>
        <span>v1.0 · Field → Post</span>
      </div>
    </footer>
  );
}

// ============ CONTACT FORM ============
function ContactForm() {
  const [status, setStatus] = useState('idle');
  const [errorMsg, setErrorMsg] = useState('');
  const formRef = useRef(null);

  const keysConfigured =
    WEB3FORMS_ACCESS_KEY && !WEB3FORMS_ACCESS_KEY.startsWith('YOUR_') &&
    TURNSTILE_SITE_KEY && !TURNSTILE_SITE_KEY.startsWith('YOUR_');

  useEffect(() => {
    if (!keysConfigured) return;
    if (document.querySelector('script[data-turnstile]')) return;
    const s = document.createElement('script');
    s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js';
    s.async = true;
    s.defer = true;
    s.dataset.turnstile = 'true';
    document.head.appendChild(s);
  }, [keysConfigured]);

  async function onSubmit(e) {
    e.preventDefault();
    if (status === 'sending') return;
    setStatus('sending');
    setErrorMsg('');

    const form = formRef.current;
    const data = new FormData(form);

    if (data.get('botcheck')) {
      setStatus('success');
      form.reset();
      return;
    }

    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Accept': 'application/json' },
        body: data,
      });
      const json = await res.json();
      if (json.success) {
        setStatus('success');
        form.reset();
        if (window.turnstile) window.turnstile.reset();
      } else {
        setStatus('error');
        setErrorMsg(json.message || 'Something went wrong. Please try again.');
      }
    } catch (err) {
      setStatus('error');
      setErrorMsg('Network error. Please try again.');
    }
  }

  if (status === 'success') {
    return (
      <div className="contact-card contact-card--success">
        <div className="contact-card__head">
          <span className="contact-card__tag">// INQUIRY · RECEIVED</span>
          <span className="contact-card__time">REPLY WITHIN 24H</span>
        </div>
        <div className="contact-success">
          <div className="contact-success__icon" aria-hidden="true">
            <svg viewBox="0 0 48 48" fill="none" width="42" height="42">
              <circle cx="24" cy="24" r="22" stroke="currentColor" strokeWidth="1.5"/>
              <path d="M14 24 L21 31 L34 17" stroke="currentColor" strokeWidth="2.5" strokeLinecap="square" strokeLinejoin="miter"/>
            </svg>
          </div>
          <h3 className="contact-success__title">Thanks — your inquiry is in.</h3>
          <p className="contact-success__body">
            I read every message personally. Expect a direct reply within 24 hours,
            usually sooner. Talk soon.
          </p>
          <p className="contact-success__sig">— Ages Productions</p>
        </div>
      </div>
    );
  }

  return (
    <form ref={formRef} className="contact-card" onSubmit={onSubmit} noValidate>
      <div className="contact-card__head">
        <span className="contact-card__tag">// PRODUCTION INQUIRY</span>
        <span className="contact-card__time">REPLY WITHIN 24H</span>
      </div>

      <input type="hidden" name="access_key" value={WEB3FORMS_ACCESS_KEY}/>
      <input type="hidden" name="subject" value="New inquiry — Ages Productions"/>
      <input type="hidden" name="from_name" value="Ages Productions Site"/>
      <input
        type="checkbox"
        name="botcheck"
        className="contact-form__hp"
        tabIndex="-1"
        autoComplete="off"
        aria-hidden="true"
      />

      <div className="contact-form__grid">
        <label className="contact-field">
          <span className="contact-field__label">Name</span>
          <input type="text" name="name" required autoComplete="name" placeholder="Full name"/>
        </label>
        <label className="contact-field">
          <span className="contact-field__label">Production company</span>
          <input type="text" name="company" required autoComplete="organization" placeholder="Company or production co."/>
        </label>
        <label className="contact-field">
          <span className="contact-field__label">Project / show name</span>
          <input type="text" name="project" required placeholder="Working title or codename is fine"/>
        </label>
        <label className="contact-field">
          <span className="contact-field__label">Production type</span>
          <select name="production_type" required defaultValue="">
            <option value="" disabled>Select one…</option>
            <option>Reality / Unscripted</option>
            <option>Documentary</option>
            <option>Live Event</option>
            <option>Sports</option>
            <option>Broadcast</option>
            <option>Other</option>
          </select>
        </label>
        <label className="contact-field contact-field--full">
          <span className="contact-field__label">What do you need support with?</span>
          <textarea
            name="message"
            required
            rows="6"
            placeholder="Shoot dates, locations, camera count, daily media volume, biggest workflow concern — whatever you have so far. Rough is fine."
          ></textarea>
        </label>
        <label className="contact-field contact-field--full">
          <span className="contact-field__label">Email</span>
          <input type="email" name="email" required autoComplete="email" placeholder="you@productioncompany.com"/>
        </label>
      </div>

      <div className="contact-form__foot">
        {keysConfigured ? (
          <div className="cf-turnstile" data-sitekey={TURNSTILE_SITE_KEY} data-theme="dark"></div>
        ) : (
          <div className="contact-form__placeholder" aria-hidden="true">
            <span>⚙</span>
            <span>Turnstile + Web3Forms keys not configured yet — form is preview-only.</span>
          </div>
        )}

        <button
          type="submit"
          className="btn btn--primary btn--lg contact-form__submit"
          disabled={status === 'sending' || !keysConfigured}
        >
          <span>{status === 'sending' ? 'Sending…' : 'Send Inquiry'}</span>
          {status !== 'sending' && <CIcon.Arrow width="18" height="18"/>}
        </button>
      </div>

      {status === 'error' && (
        <div className="contact-form__error" role="alert">
          <strong>Couldn't send:</strong> {errorMsg}
        </div>
      )}

      <div className="contact-form__fine">
        Your information is used only to respond to your inquiry. No mailing list.
        No file uploads — a secure upload link will be provided after initial contact if needed.
      </div>
    </form>
  );
}

// ============ PAGE ============
function App() {
  const [scrolled, setScrolled] = useState(false);

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

  return (
    <div className="app accent-balanced contact-page">
      <Nav scrolled={scrolled}/>

      <section className="ct-hero">
        <div className="ct-hero__bg" aria-hidden="true"></div>
        <svg className="ct-hero__glyph" viewBox="0 0 200 140" fill="none" aria-hidden="true">
          <rect x="6" y="6" width="188" height="128" stroke="currentColor" strokeWidth="1.5"/>
          <path d="M6 6 L100 84 L194 6" stroke="currentColor" strokeWidth="1.5"/>
          <path d="M6 134 L78 70" stroke="currentColor" strokeWidth="1.5"/>
          <path d="M194 134 L122 70" stroke="currentColor" strokeWidth="1.5"/>
        </svg>
        <div className="ct-hero__inner">
          <div>
            <div className="ct-hero__eyebrow">
              <span className="dot"></span>
              <span>CONTACT</span>
              <span style={{borderLeft:'1px solid rgba(255,255,255,0.2)', paddingLeft:'14px', color:'rgba(255,255,255,0.6)'}}>Direct line to Ages Productions</span>
            </div>
            <h1 className="ct-hero__title">
              Tell me about<br/>
              <span className="ct-hero__title-accent">your production.</span>
            </h1>
            <p className="ct-hero__lede">
              Reality TV, documentary, live event, sports — whatever the shape of the show,
              the conversation starts the same way. Send a few details about what you're shooting
              and I'll come back with a media plan that fits.
            </p>
          </div>
          <div className="ct-hero__meta">
            <div className="ct-hero__status" aria-label="Open for inquiries">
              <span className="ct-hero__status-pulse" aria-hidden="true"></span>
              <span className="ct-hero__status-label">OPEN FOR INQUIRIES</span>
            </div>
            <div className="ct-hero__meta-row">
              <span className="ct-hero__meta-k">REPLY WINDOW</span>
              <span className="ct-hero__meta-v"><span className="num">&lt; 24<span>h</span></span></span>
            </div>
            <div className="ct-hero__meta-row">
              <span className="ct-hero__meta-k">BASED IN</span>
              <span className="ct-hero__meta-v">MIAMI · WORLDWIDE</span>
            </div>
          </div>
        </div>
      </section>

      <section className="ct-body">
        <div className="ct-body__inner">
          <aside className="ct-side">
            <span className="section-label">[ WHAT TO INCLUDE ]</span>
            <h2 className="ct-side__title">A great first message answers a few things.</h2>
            <p className="ct-side__lede">
              You don't need all of these — but the more you can share up front, the faster
              I can come back with something useful instead of a list of follow-up questions.
            </p>
            <ul className="ct-side__list">
              <li>
                <span className="ct-side__num">01</span>
                <div>
                  <strong>Shoot dates &amp; locations</strong>
                  <span>Rough is fine — even just "summer in three cities" helps.</span>
                </div>
              </li>
              <li>
                <span className="ct-side__num">02</span>
                <div>
                  <strong>Camera &amp; audio package</strong>
                  <span>Counts and brands if known. Single units or rigs, mains and B-cams, GoPros, PTZ, cast phones, ISO recorders, mixers.</span>
                </div>
              </li>
              <li>
                <span className="ct-side__num">03</span>
                <div>
                  <strong>Estimated daily media volume</strong>
                  <span>A ballpark TB-per-day estimate, or just "a lot, we don't actually know."</span>
                </div>
              </li>
              <li>
                <span className="ct-side__num">04</span>
                <div>
                  <strong>Where post lives</strong>
                  <span>In-house, remote, cloud-based, somewhere offshore — and how fast they need footage.</span>
                </div>
              </li>
              <li>
                <span className="ct-side__num">05</span>
                <div>
                  <strong>The thing that's actually worrying you</strong>
                  <span>Bottleneck, deadline, travel constraint, post handoff, cast workflow — name the problem.</span>
                </div>
              </li>
            </ul>
            <div className="ct-side__note">
              <span className="ct-side__note-tag">NDA-FRIENDLY</span>
              <span>Working titles, codenames, and "untitled project" are fine. Specifics can come once we're on a call.</span>
            </div>
          </aside>
          <div className="ct-form-wrap">
            <ContactForm/>
          </div>
        </div>
      </section>

      <Footer/>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);
