/* =========================================================
   RENFECHT — FAQ, Sponsors, Contact, Gallery
   ========================================================= */

/* ---------- FAQ ---------- */

function FaqPage({ onNavigate }) {
  useReveal();
  const v = useValues();
  const [open, setOpen] = React.useState(() => new Set(["0-0"]));
  const toggle = (key) => {
    setOpen(s => { const next = new Set(s); next.has(key) ? next.delete(key) : next.add(key); return next; });
  };

  return (
    <main>
      <PageBanner
        eyebrow="ENQUIRIES"
        title="Frequently Asked"
        lead="If yours isn't here, write to us. We answer every letter within two days."
      />

      <section className="section-tight">
        <div className="wrap faq-grid" style={{ display: "grid", gridTemplateColumns: "240px 1fr", gap: "var(--space-7)", alignItems: "start" }}>
          <aside style={{ position: "sticky", top: 96 }}>
            <div className="eyebrow" style={{ marginBottom: 12 }}>JUMP TO</div>
            <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
              {v.faq.map((g, i) => (
                <li key={g.label} style={{ borderBottom: "1px dashed var(--rule)" }}>
                  <a href={"#faq-" + i} style={{ display: "block", padding: "10px 0", borderBottom: 0, color: "var(--ink)" }}>
                    <span className="mono" style={{ fontSize: "0.75rem", color: "var(--accent)", letterSpacing: "0.2em" }}>{String(i + 1).padStart(2, "0")} ·</span>{" "}
                    <span style={{ fontFamily: "var(--font-display)", letterSpacing: "0.04em" }}>{g.label}</span>
                  </a>
                </li>
              ))}
            </ul>
            <div className="frame" style={{ marginTop: 28 }}>
              <CornerDots />
              <div className="eyebrow" style={{ color: "var(--accent)" }}>STILL STUCK?</div>
              <p style={{ marginTop: 8, fontSize: "0.95rem", color: "var(--ink-soft)" }}>Write to us directly — a human reads every message.</p>
              <a href="#contact" className="btn btn-ghost" onClick={(e) => { e.preventDefault(); onNavigate("contact"); }} style={{ marginTop: 8 }}>Contact →</a>
            </div>
          </aside>

          <div className="stack-lg">
            {v.faq.map((g, i) => (
              <div key={g.label} id={"faq-" + i} className="reveal">
                <div style={{ display: "flex", alignItems: "baseline", gap: 18, marginBottom: 18 }}>
                  <span style={{ fontFamily: "var(--font-display)", color: "var(--accent)", letterSpacing: "0.06em", fontSize: "var(--scale-7)" }}></span>
                  <h2 style={{ fontSize: "var(--scale-6)", textTransform: "none", letterSpacing: "0.02em" }}>{g.label}</h2>
                </div>
                {g.items.map((it, j) => {
                  const key = `${i}-${j}`;
                  const isOpen = open.has(key);
                  return (
                    <div key={key} style={{ borderBottom: "1px solid var(--rule)" }}>
                      <button onClick={() => toggle(key)} className="faq-q" aria-expanded={isOpen}>
                        <span>{it.q}</span>
                        <span className="faq-mark">{isOpen ? "−" : "+"}</span>
                      </button>
                      <div className={"faq-a " + (isOpen ? "is-open" : "")}>
                        <p className={isOpen ? "dropcap" : ""} style={{ margin: 0, paddingBottom: 22, color: "var(--ink-soft)" }}>{it.a}</p>
                      </div>
                    </div>
                  );
                })}
              </div>
            ))}
          </div>
        </div>
        <style>{`
          .faq-q { width: 100%; background: none; border: 0; padding: 22px 0; cursor: pointer; display: flex; justify-content: space-between; align-items: center; gap: 24px; text-align: left; font-family: var(--font-display); font-size: var(--scale-4); letter-spacing: 0.02em; color: var(--ink); }
          .faq-q:hover { color: var(--accent); }
          .faq-q .faq-mark { font-family: var(--font-display); font-size: 1.8rem; line-height: 1; color: var(--accent); font-weight: 400; }
          .faq-a { max-height: 0; overflow: hidden; transition: max-height .35s ease; }
          .faq-a.is-open { max-height: 600px; }
          @media (max-width: 880px) { .faq-grid { grid-template-columns: 1fr !important; } }
        `}</style>
      </section>

      <ClosingCTA onNavigate={onNavigate} eyebrow="READY?" title="No more questions. Just steel." cta="Enter the Lists" target="register" />
    </main>
  );
}

/* ---------- SPONSORS ---------- */

function SponsorsPage({ onNavigate }) {
  useReveal();
  const v = useValues();
  return (
    <main>
      <PageBanner
        eyebrow="HOUSES & PATRONS"
        title="Those Who Stand With Us"
        lead="RenFecht is a tournament. It is also a small business — and these are the houses that keep the lists open."
      />

      <section className="section-tight">
        <div className="wrap stack-lg">
          {v.sponsors.tiers.map((tier, ti) => (
            <div key={tier.name} className="reveal" style={{ transitionDelay: `${ti * 80}ms` }}>
              <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginBottom: 24 }}>
                <span style={{ fontFamily: "var(--font-display)", color: "var(--accent)", letterSpacing: "0.06em" }}>{String(ti + 1).padStart(2, "0")}</span>
                <h2 style={{ fontSize: "var(--scale-5)", letterSpacing: "0.16em" }}>{tier.name}</h2>
                <div style={{ flex: 1, height: 1, background: "var(--rule)" }} />
              </div>
              <div className="grid" style={{ gridTemplateColumns: ti === 2 ? "repeat(auto-fit, minmax(200px, 1fr))" : "repeat(auto-fit, minmax(280px, 1fr))" }}>
                {tier.items.map(s => (
                  <div key={s.name} className={ti < 2 ? "frame" : ""} style={ti < 2 ? {} : { padding: "20px", border: "1px solid var(--rule)", background: "color-mix(in oklab, var(--paper) 95%, var(--paper-deep))" }}>
                    {ti < 2 && <CornerDots />}
                    <Placeholder label="LOGO" ratio={ti === 0 ? "16 / 7" : "16 / 9"} style={{ marginBottom: 14, background: "color-mix(in oklab, var(--paper) 80%, var(--ink) 4%)" }}>
                      <span className="ph-label">{s.name.toUpperCase()}</span>
                    </Placeholder>
                    <div style={{ fontFamily: "var(--font-display)", letterSpacing: "0.04em", fontSize: ti === 0 ? "var(--scale-5)" : "var(--scale-4)" }}>{s.name}</div>
                    {s.note && <div style={{ color: "var(--ink-mute)", fontSize: "0.9rem", fontStyle: "italic", marginTop: 4 }}>{s.note}</div>}
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Pitch */}
      <section className="section" style={{ background: "var(--ink)", color: "var(--paper)", position: "relative", overflow: "hidden" }}>
        <div aria-hidden="true" className="flourish" style={{ position: "absolute", left: -100, top: "50%", transform: "translateY(-50%)", color: "var(--paper)", opacity: 0.08, pointerEvents: "none" }}>
          <Crest size={460} withBanner={false} />
        </div>
        <div className="wrap pitch-grid" style={{ position: "relative", display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--space-7)", alignItems: "center" }}>
          <div>
            <span className="eyebrow" style={{ color: "color-mix(in oklab, var(--paper) 70%, transparent)" }}>BECOME A SPONSOR</span>
            <h2 style={{ color: "var(--paper)", marginTop: 12 }}>Put your house on the field.</h2>
            <p style={{ color: "color-mix(in oklab, var(--paper) 80%, transparent)", maxWidth: "44ch", marginTop: 18 }}>
              Sponsor a ring. Sponsor a list. Or simply hang your banner at the gate. Three tiers, plain pricing, no surprises.
            </p>
            <a href="#contact" className="btn btn-accent" style={{ marginTop: 26 }} onClick={(e) => { e.preventDefault(); onNavigate("contact"); }}>Write to us →</a>
          </div>
          <div style={{ borderLeft: "1px solid color-mix(in oklab, var(--paper) 30%, transparent)", paddingLeft: "var(--space-6)" }}>
            <dl style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", gap: "12px 24px", margin: 0, alignItems: "baseline" }}>
              {v.sponsors.pricing.map(t => (
                <React.Fragment key={t.tier}>
                  <dt style={{ fontFamily: "var(--font-display)", letterSpacing: "0.1em" }}>{t.tier}</dt>
                  <dd style={{ color: "color-mix(in oklab, var(--paper) 70%, transparent)", margin: 0, fontStyle: "italic" }}>{t.blurb}</dd>
                  <dd className="mono" style={{ margin: 0, color: "var(--accent-soft)" }}>{t.price}</dd>
                </React.Fragment>
              ))}
            </dl>
          </div>
        </div>
        <style>{`@media (max-width: 740px) { .pitch-grid { grid-template-columns: 1fr !important; } }`}</style>
      </section>
    </main>
  );
}

/* ---------- CONTACT ---------- */

function ContactPage({ onNavigate }) {
  useReveal();
  const v = useValues();
  const [sent, setSent] = React.useState(false);
  const [msg, setMsg] = React.useState({ name: "", email: "", subject: v.contact.subjects[0], body: "" });

  return (
    <main>
      <PageBanner
        eyebrow="CORRESPONDENCE"
        title="Write to the Marshals"
        lead="A human reads every letter. We try to reply within two days — faster as the tournament approaches."
      />

      <section className="section-tight">
        <div className="wrap contact-grid" style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: "var(--space-7)", alignItems: "start" }}>
          <div className="reveal">
            {sent ? (
              <div className="frame frame--ornate" style={{ textAlign: "center", padding: "var(--space-8)" }}>
                <CornerDots />
                <span className="flourish" style={{ color: "var(--accent)", display: "inline-block" }}><CrossedSwordsIcon size={48} /></span>
                <h2 style={{ marginTop: 18, fontSize: "var(--scale-6)" }}>Your letter is received.</h2>
                <p style={{ color: "var(--ink-soft)", marginTop: 12 }}>Reply will arrive at <strong>{msg.email}</strong> shortly.</p>
                <button className="btn btn-ghost" style={{ marginTop: 20 }} onClick={() => { setSent(false); setMsg({ name: "", email: "", subject: v.contact.subjects[0], body: "" }); }}>Send another →</button>
              </div>
            ) : (
              <form onSubmit={(e) => { e.preventDefault(); setSent(true); }} className="frame frame--ornate" style={{ padding: "var(--space-7)" }}>
                <CornerDots />
                <div className="eyebrow" style={{ color: "var(--accent)" }}>NEW LETTER</div>
                <div className="rule" />
                <div className="row-2-contact">
                  <label className="field"><span className="field-label">Your name *</span>
                    <input className="input" required value={msg.name} onChange={e => setMsg(m => ({...m, name: e.target.value}))} />
                  </label>
                  <label className="field"><span className="field-label">Email *</span>
                    <input className="input" type="email" required value={msg.email} onChange={e => setMsg(m => ({...m, email: e.target.value}))} />
                  </label>
                </div>
                <label className="field"><span className="field-label">Subject</span>
                  <select className="select" value={msg.subject} onChange={e => setMsg(m => ({...m, subject: e.target.value}))}>
                    {v.contact.subjects.map(s => <option key={s}>{s}</option>)}
                  </select>
                </label>
                <label className="field"><span className="field-label">Message *</span>
                  <textarea className="textarea" required style={{ minHeight: 160 }} value={msg.body} onChange={e => setMsg(m => ({...m, body: e.target.value}))} />
                </label>
                <button type="submit" className="btn btn-accent">Send Letter →</button>
                <style>{`
                  .row-2-contact { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-4); }
                  @media (max-width: 540px) { .row-2-contact { grid-template-columns: 1fr; } }
                `}</style>
              </form>
            )}
          </div>

          <aside className="reveal" style={{ position: "sticky", top: 96 }}>
            <div className="eyebrow">THE MARSHALS' OFFICE</div>
            <div className="rule" />

            <ContactRow eyebrow="GENERAL"      value={v.contact.general} />
            <ContactRow eyebrow="REGISTRATION" value={v.contact.registration} />
            <ContactRow eyebrow="SPONSORS"     value={v.contact.sponsors} />
            <ContactRow eyebrow="PRESS"        value={v.contact.press} />

            <div className="rule" />

            <ContactRow eyebrow="POST" value={v.contact.post.map((l, i) => <React.Fragment key={i}>{l}<br/></React.Fragment>)} />
            <ContactRow eyebrow="TELEPHONE" value={v.contact.phone} />

            <div style={{ marginTop: 28, display: "flex", gap: 16 }}>
              {v.contact.social.map(s => (
                <a key={s} href="#" onClick={(e) => e.preventDefault()} style={{ fontFamily: "var(--font-display)", fontSize: "0.78rem", letterSpacing: "0.18em", textTransform: "uppercase", borderBottom: "1px solid var(--rule)" }}>{s}</a>
              ))}
            </div>
          </aside>
        </div>
        <style>{`@media (max-width: 880px) { .contact-grid { grid-template-columns: 1fr !important; } }`}</style>
      </section>
    </main>
  );
}

function ContactRow({ eyebrow, value }) {
  return (
    <div style={{ padding: "14px 0", borderBottom: "1px dashed var(--rule)" }}>
      <div className="eyebrow" style={{ color: "var(--accent)", fontSize: "0.7rem" }}>{eyebrow}</div>
      <div style={{ marginTop: 4, fontFamily: "var(--font-display)", letterSpacing: "0.04em", fontSize: "1rem" }}>{value}</div>
    </div>
  );
}

/* ---------- GALLERY ---------- */

/* Parse a YouTube URL or bare ID into a video ID. Returns null if unrecognized. */
function parseYouTubeId(url) {
  if (!url) return null;
  // Bare ID (11 chars, alphanumeric/-/_)
  if (/^[\w-]{11}$/.test(url)) return url;
  try {
    const u = new URL(url);
    if (u.hostname.includes("youtu.be")) return u.pathname.slice(1).split("/")[0] || null;
    if (u.hostname.includes("youtube.com")) {
      if (u.searchParams.get("v")) return u.searchParams.get("v");
      const parts = u.pathname.split("/").filter(Boolean);  // /embed/ID or /shorts/ID
      if (parts[0] === "embed" || parts[0] === "shorts") return parts[1] || null;
    }
  } catch (_) {}
  return null;
}

function GalleryPage({ onNavigate }) {
  useReveal();
  const v = useValues();
  const [filter, setFilter] = React.useState("All");
  const [lightbox, setLightbox] = React.useState(null);
  const items = filter === "All" ? v.gallery.items : v.gallery.items.filter(x => x.category === filter);

  React.useEffect(() => {
    if (!lightbox) return;
    const onKey = (e) => { if (e.key === "Escape") setLightbox(null); };
    document.body.classList.add("modal-open");
    window.addEventListener("keydown", onKey);
    return () => { document.body.classList.remove("modal-open"); window.removeEventListener("keydown", onKey); };
  }, [lightbox]);

  return (
    <main>
      <PageBanner
        eyebrow="THE ARCHIVE"
        title="Gallery"
        lead={v.gallery.intro}
      />

      <section className="section-tight">
        <div className="wrap">
          {/* Filter bar */}
          <div className="gallery-filters">
            {v.gallery.categories.map(c => {
              const count = c === "All" ? v.gallery.items.length : v.gallery.items.filter(x => x.category === c).length;
              return (
                <button key={c}
                  className={"gal-filter " + (filter === c ? "is-on" : "")}
                  onClick={() => setFilter(c)}>
                  <span>{c}</span>
                  <span className="gal-count">{count}</span>
                </button>
              );
            })}
          </div>

          {/* Grid */}
          <div className="gallery-grid">
            {items.map((it, i) => (
              <GalleryCard key={it.id} item={it} delay={i * 40} onOpen={() => setLightbox(it)} />
            ))}
          </div>
        </div>
      </section>

      {lightbox && <Lightbox item={lightbox} onClose={() => setLightbox(null)} />}

      <style>{`
        .gallery-filters { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: var(--space-7); border-bottom: 1px solid var(--rule); padding-bottom: 18px; }
        .gal-filter { background: none; border: 1px solid var(--rule); padding: 10px 18px; cursor: pointer; font-family: var(--font-display); font-size: 0.78rem; letter-spacing: 0.18em; text-transform: uppercase; color: var(--ink-soft); display: inline-flex; gap: 10px; align-items: center; transition: all .15s; }
        .gal-filter:hover { color: var(--ink); border-color: var(--ink); }
        .gal-filter.is-on { background: var(--ink); color: var(--paper); border-color: var(--ink); }
        .gal-filter.is-on .gal-count { background: var(--accent); color: var(--paper); }
        .gal-count { font-family: var(--font-mono); font-size: 0.7rem; padding: 2px 8px; background: color-mix(in oklab, var(--paper) 60%, var(--paper-deep)); border: 1px solid var(--rule); }

        .gallery-grid { columns: 3 320px; column-gap: var(--space-5); }
        .gal-item { break-inside: avoid; margin-bottom: var(--space-5); cursor: pointer; display: block; }
        .gal-item .gal-media { position: relative; overflow: hidden; border: 1px solid var(--rule); transition: transform .25s ease, box-shadow .25s ease, border-color .25s ease; }
        .gal-item .gal-media img { width: 100%; height: 100%; object-fit: cover; display: block; }
        .gal-item:hover .gal-media { transform: translateY(-4px); border-color: var(--ink); box-shadow: 0 10px 0 -4px var(--ink); }
        .gal-play { position: absolute; inset: 0; display: grid; place-items: center; pointer-events: none; }
        .gal-play span { width: 56px; height: 56px; background: var(--accent); color: var(--paper); border-radius: 50%; display: grid; place-items: center; font-size: 1.2rem; padding-left: 4px; box-shadow: 0 4px 18px rgba(0,0,0,0.4); transition: transform .2s; }
        .gal-item:hover .gal-play span { transform: scale(1.08); }
        .gal-cat { position: absolute; top: 10px; left: 10px; font-family: var(--font-mono); font-size: 0.7rem; letter-spacing: 0.2em; text-transform: uppercase; background: var(--ink); color: var(--paper); padding: 4px 10px; }
        .gal-meta { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; padding: 12px 4px 4px; }
        .gal-title { font-family: var(--font-display); font-size: 1rem; letter-spacing: 0.02em; }
        .gal-credit { font-size: 0.85rem; color: var(--ink-mute); font-style: italic; margin-top: 2px; }
        .gal-year { color: var(--accent); font-size: 0.78rem; letter-spacing: 0.16em; }

        .lightbox { position: fixed; inset: 0; background: rgba(10, 6, 2, 0.92); z-index: 200; display: grid; place-items: center; padding: 40px; animation: fade .2s ease; }
        @keyframes fade { from { opacity: 0; } to { opacity: 1; } }
        .lightbox-inner { max-width: 1100px; width: 100%; max-height: 90vh; overflow: auto; background: var(--paper); border: 1px solid var(--accent); padding: var(--space-5); position: relative; }
        .lightbox-media { position: relative; width: 100%; }
        .lightbox-media iframe, .lightbox-media img { width: 100%; display: block; border: 0; }
        .lightbox-meta { display: flex; justify-content: space-between; align-items: flex-end; gap: 18px; margin-top: var(--space-5); padding-top: var(--space-4); border-top: 1px solid var(--rule); }
        .lightbox-close { position: fixed; top: 24px; right: 24px; background: none; border: 1px solid var(--paper); color: var(--paper); width: 44px; height: 44px; font-size: 1.6rem; cursor: pointer; z-index: 210; transition: all .15s; }
        .lightbox-close:hover { background: var(--paper); color: var(--ink); }
        @media (max-width: 600px) { .lightbox { padding: 20px; } .lightbox-meta { flex-direction: column; align-items: flex-start; } }
      `}</style>
    </main>
  );
}

function GalleryCard({ item, delay, onOpen }) {
  const ytId = item.embed ? parseYouTubeId(item.embed) : null;
  // Card thumbnail logic:
  //  - YouTube video: hi-quality YT thumb + play overlay
  //  - Image URL provided: <img>
  //  - Otherwise: striped placeholder
  return (
    <article className="gal-item reveal" style={{ transitionDelay: `${delay}ms` }} onClick={onOpen}>
      <div className="gal-media" style={{ aspectRatio: item.ratio }}>
        {ytId ? (
          <img src={`https://i.ytimg.com/vi/${ytId}/hqdefault.jpg`}
               alt={item.title}
               loading="lazy"
               onError={(e) => { e.currentTarget.style.display = "none"; }} />
        ) : item.image ? (
          <img src={item.image} alt={item.title} loading="lazy" />
        ) : (
          <Placeholder
            label={`${item.category.toUpperCase()} · ${item.title.toUpperCase()}`}
            ratio={item.ratio}
            style={{ height: "100%", border: 0 }}
          />
        )}
        {item.category === "Video" && (
          <div className="gal-play" aria-hidden="true"><span>▶</span></div>
        )}
        <div className="gal-cat">{item.category}</div>
      </div>
      <div className="gal-meta">
        <div>
          <div className="gal-title">{item.title}</div>
          <div className="gal-credit">{item.credit}</div>
        </div>
        <span className="mono gal-year">{item.year}</span>
      </div>
    </article>
  );
}

function Lightbox({ item, onClose }) {
  const ytId = item.embed ? parseYouTubeId(item.embed) : null;
  return (
    <div className="lightbox" onClick={onClose}>
      <button className="lightbox-close" aria-label="Close" onClick={onClose}>×</button>
      <div className="lightbox-inner" onClick={(e) => e.stopPropagation()}>
        <div className="lightbox-media" style={{ aspectRatio: ytId ? "16 / 9" : item.ratio }}>
          {ytId ? (
            <iframe
              src={`https://www.youtube-nocookie.com/embed/${ytId}?autoplay=1&rel=0&modestbranding=1`}
              title={item.title}
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              allowFullScreen
              style={{ width: "100%", height: "100%" }}
            />
          ) : item.image ? (
            <img src={item.image} alt={item.title} />
          ) : (
            <Placeholder label={`${item.category.toUpperCase()} · ${item.title.toUpperCase()}`} ratio={item.ratio} style={{ width: "100%", height: "100%", border: 0 }} />
          )}
        </div>
        <div className="lightbox-meta">
          <div>
            <div className="eyebrow" style={{ color: "var(--accent)" }}>{item.category} · {item.year}</div>
            <h2 style={{ marginTop: 8, fontSize: "var(--scale-6)", textTransform: "none", letterSpacing: "0.02em" }}>{item.title}</h2>
          </div>
          <div className="mono" style={{ fontSize: "0.85rem", color: "var(--ink-mute)" }}>{item.credit}</div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { FaqPage, SponsorsPage, ContactPage, GalleryPage });
