/* global React */
/* global I, useRoute */
const { useState: useUtilState } = React;

/* ─────────────────────────────────────────────────────────────────
   Shared utility page chrome
   ───────────────────────────────────────────────────────────────── */
function UtilHeader({ eyebrow, title, lede, lastUpdated }) {
  const { goto } = useRoute();
  return (
    <>
      <section className="container" style={{ padding: "56px 0 16px" }}>
        <div className="crumbs">
          <a onClick={() => goto("home")}>Home</a>
          <I name="chev" size={11} />
          <span>{title}</span>
        </div>
      </section>
      <section className="container" style={{ padding: "24px 0 56px" }}>
        <span className="eyebrow eyebrow-gold">§ {eyebrow}</span>
        <h1 className="serif" style={{ fontSize: "clamp(48px, 7vw, 96px)", lineHeight: 0.95, letterSpacing: "-0.02em", margin: "16px 0 28px", maxWidth: 1100 }}>
          {title}
        </h1>
        {lede && (
          <p className="pretty" style={{ fontSize: 17, lineHeight: 1.55, color: "var(--text-1)", maxWidth: 720, margin: 0 }}>
            {lede}
          </p>
        )}
        {lastUpdated && (
          <p className="mono" style={{ fontSize: 10, letterSpacing: "0.18em", color: "var(--text-3)", textTransform: "uppercase", margin: "32px 0 0" }}>
            Last updated · {lastUpdated}
          </p>
        )}
      </section>
      <hr className="rule" />
    </>
  );
}

/* ─────────────────────────────────────────────────────────────────
   FAQ
   ───────────────────────────────────────────────────────────────── */
function FAQPage() {
  const { goto } = useRoute();
  const [open, setOpen] = useUtilState({});
  const [q, setQ] = useUtilState("");

  const groups = window.FAQ.map(g => ({
    ...g,
    items: g.items.filter(([h, b]) => !q || (h + " " + b).toLowerCase().includes(q.toLowerCase())),
  })).filter(g => g.items.length > 0);

  function toggle(k) { setOpen(s => ({ ...s, [k]: !s[k] })); }

  return (
    <main className="page-faq">
      <UtilHeader eyebrow="Help" title="Frequently asked." lede="The questions briefs and customers send most. If yours isn't here, write the studio directly." />

      <section className="container" style={{ padding: "56px 0 32px" }}>
        <div className="faq-search">
          <I name="search" size={16} stroke="var(--text-3)" />
          <input
            type="search"
            placeholder="Search the answers…"
            value={q}
            onChange={(e) => setQ(e.target.value)}
            aria-label="Search FAQ"
          />
          {q && <button className="lk" onClick={() => setQ("")} style={{ fontSize: 12 }}>Clear</button>}
        </div>
      </section>

      <section className="container" style={{ padding: "0 0 80px" }}>
        {groups.map((g, gi) => (
          <div key={g.group} style={{ marginBottom: 56 }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 48, alignItems: "start" }}>
              <div>
                <span className="mono" style={{ fontSize: 11, letterSpacing: "0.18em", color: "var(--gold)", textTransform: "uppercase" }}>0{gi + 1}</span>
                <h2 className="serif" style={{ fontSize: 32, lineHeight: 1.05, margin: "12px 0 0", letterSpacing: "-0.01em" }}>{g.group}</h2>
              </div>
              <div className="faq-list">
                {g.items.map(([h, b], i) => {
                  const k = `${g.group}-${i}`;
                  const isOpen = open[k];
                  return (
                    <button key={k} className={`faq-item ${isOpen ? "is-open" : ""}`} onClick={() => toggle(k)} aria-expanded={isOpen}>
                      <div className="faq-q">
                        <span className="serif">{h}</span>
                        <I name={isOpen ? "minus" : "plus"} size={16} />
                      </div>
                      {isOpen && <p className="faq-a">{b}</p>}
                    </button>
                  );
                })}
              </div>
            </div>
            {gi < groups.length - 1 && <hr className="rule" style={{ margin: "56px 0 0" }} />}
          </div>
        ))}
        {groups.length === 0 && (
          <div style={{ padding: "60px 0", textAlign: "center" }}>
            <p className="serif" style={{ fontSize: 24 }}>Nothing matches "{q}".</p>
            <p style={{ color: "var(--text-2)", marginTop: 8 }}>Write the studio, we'll answer by hand.</p>
          </div>
        )}
      </section>

      <hr className="rule" />
      <section className="container" style={{ padding: "72px 0 96px" }}>
        <div className="util-cta">
          <div>
            <h3 className="serif" style={{ fontSize: 36, lineHeight: 1.1, margin: 0, letterSpacing: "-0.01em" }}>Still curious?</h3>
            <p style={{ color: "var(--text-2)", margin: "10px 0 0" }}>The studio reads every note by hand.</p>
          </div>
          <button className="btn btn-gold btn-lg" onClick={() => goto("contact")}>Write the studio <I name="arrow" size={16} /></button>
        </div>
      </section>
    </main>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Shipping & Returns
   ───────────────────────────────────────────────────────────────── */
function Shipping() {
  const { goto } = useRoute();
  return (
    <main>
      <UtilHeader eyebrow="Store policy" title="Shipping & returns." lede="Pieces leave the studio carefully. If something arrives wrong, the studio makes it right." lastUpdated="14 March 2026" />

      <section className="container" style={{ padding: "72px 0 64px" }}>
        <div className="policy-grid">
          {[
            { eb: "Domestic", t: "United States · 3–5 business days", body: "All US orders ship from the studio via UPS Ground. Free over $200. Tracked, with insurance up to $400. Apparel ships flat; music ships sleeved." },
            { eb: "International", t: "DDP across 28 countries", body: "Duties and taxes calculated at checkout, no surprise fees on arrival. Most international orders arrive within 7–12 business days, expedited 3–5." },
            { eb: "Returns", t: "30-day window · unworn", body: "Return any unworn apparel or accessory within 30 days. Music, prints, and digital goods are non-refundable. Start a return from your account or by writing the studio." },
            { eb: "Damages", t: "We make it right", body: "If something arrives damaged, send a photo within 7 days. We replace or refund without sending the original back." },
            { eb: "Exchanges", t: "Sizes within 30 days", body: "Sizes can be exchanged within 30 days at no charge, we'll send the replacement when the original is in transit." },
            { eb: "Custom & made-to-order", t: "Final sale", body: "Numbered prints, hand-sewn objects, and custom commissions are final sale. We confirm specs in writing before production begins." },
          ].map((p) => (
            <div key={p.eb} className="policy-card">
              <span className="eyebrow eyebrow-gold">§ {p.eb}</span>
              <h3 className="serif">{p.t}</h3>
              <p>{p.body}</p>
            </div>
          ))}
        </div>
      </section>

      <hr className="rule" />

      <section className="container" style={{ padding: "72px 0" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.6fr", gap: 64 }}>
          <span className="eyebrow eyebrow-gold">§ Rates</span>
          <div>
            <table className="policy-table">
              <thead>
                <tr><th>Region</th><th>Standard</th><th>Expedited</th><th>Free over</th></tr>
              </thead>
              <tbody>
                <tr><td>US Continental</td><td>$8</td><td>$22</td><td>$200</td></tr>
                <tr><td>US Hawaii / AK</td><td>$18</td><td>$48</td><td>$300</td></tr>
                <tr><td>Canada</td><td>$28 DDP</td><td>$58 DDP</td><td>$400</td></tr>
                <tr><td>Europe (28 countries)</td><td>$32 DDP</td><td>$68 DDP</td><td>$400</td></tr>
                <tr><td>Asia · Pacific</td><td>$38 DDP</td><td>$78 DDP</td><td>$500</td></tr>
              </tbody>
            </table>
          </div>
        </div>
      </section>

      <hr className="rule" />
      <section className="container" style={{ padding: "72px 0 96px" }}>
        <div className="util-cta">
          <div>
            <h3 className="serif" style={{ fontSize: 36, lineHeight: 1.1, margin: 0, letterSpacing: "-0.01em" }}>Need to start a return?</h3>
            <p style={{ color: "var(--text-2)", margin: "10px 0 0" }}>From your account, or by writing the studio.</p>
          </div>
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
            <button className="btn btn-line btn-lg" onClick={() => goto("login")}>Sign in <I name="user" size={14} /></button>
            <button className="btn btn-gold btn-lg" onClick={() => goto("contact", { topic: "support" })}>Write the studio <I name="arrow" size={16} /></button>
          </div>
        </div>
      </section>
    </main>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Privacy
   ───────────────────────────────────────────────────────────────── */
function Privacy() {
  return (
    <main>
      <UtilHeader eyebrow="Legal" title="Privacy." lede="The plain-language version: we collect what we need to ship the work, we don't sell anything to anyone, and you can ask us to delete it whenever you like." lastUpdated="14 March 2026" />
      <LegalBody sections={[
        { id: "scope", t: "What this covers", body: "This applies to elevenviews.io, store orders, project briefs, and the studio newsletter. It does not cover work shared on third-party platforms (Vimeo, Instagram) where their terms apply." },
        { id: "collect", t: "What we collect", body: "Name, email, billing and shipping address for orders. Brief details (project type, budget, dates) when you submit an inquiry. Aggregated, anonymized analytics on which pages get read. We do not collect IP-tied behavioral profiles." },
        { id: "use", t: "How we use it", body: "To answer briefs, ship orders, send the studio newsletter, and to make the work better. We do not run third-party retargeting pixels, social trackers, or ad-tech." },
        { id: "share", t: "Who we share it with", body: "Stripe (payments), Shippo (labels), our hosting provider, and a single email service. We sign DPAs with each. We do not sell, rent, or trade any customer data." },
        { id: "rights", t: "Your rights", body: "You can request a copy of everything we have on you, ask us to correct it, or ask us to delete it. We answer within seven business days. Email privacy@elevenviews.io." },
        { id: "cookies", t: "Cookies", body: "Strictly necessary cookies for cart and login. One first-party analytics cookie that respects Do-Not-Track. No third-party advertising cookies." },
        { id: "children", t: "Children", body: "The studio does not knowingly collect data from anyone under 16. If you believe a minor has submitted information, write to privacy@elevenviews.io and we'll remove it." },
        { id: "changes", t: "Changes", body: "We update this page when policy changes. The last-updated date at the top is honest. Newsletter subscribers get a heads-up before substantive changes take effect." },
      ]} />
    </main>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Terms
   ───────────────────────────────────────────────────────────────── */
function Terms() {
  return (
    <main>
      <UtilHeader eyebrow="Legal" title="Terms of service." lede={'The agreement between Eleven Views Studio ("the studio") and visitors, customers, and clients. We try to write these the way we\'d say them out loud.'} lastUpdated="14 March 2026" />
      <LegalBody sections={[
        { id: "use", t: "Use of the site", body: "Browsing the site is free and unrestricted. You agree not to scrape, mirror, or republish editorial content or imagery without written permission. The store is for personal and commercial use; resale of store goods at scale is prohibited without written consent." },
        { id: "store", t: "Store orders", body: "Prices are in US dollars. Orders are confirmed when payment is captured. Title passes to you on shipment; risk of loss passes once the carrier scans the package as delivered. See Shipping & Returns for the full policy." },
        { id: "services", t: "Studio engagements", body: "Project briefs are not contracts. A signed Statement of Work (SOW) governs every engagement. The studio reserves the right to decline any brief without disclosed cause. Deposits secure dates; see the SOW for refund schedule." },
        { id: "ip", t: "Intellectual property", body: "All site content, copy, photographs, films, and designs, is © Eleven Views Studio unless credited. Client deliverables are licensed per the SOW; the studio retains the right to publish work in portfolios, awards, and press." },
        { id: "warranty", t: "Warranty & liability", body: "The site is provided as-is. The studio is not liable for indirect, incidental, or consequential damages. Liability for any direct claim is capped at the amount paid for the relevant product or service." },
        { id: "law", t: "Governing law", body: "These terms are governed by the laws of New York. Disputes are resolved by arbitration, except where prohibited by law." },
        { id: "contact", t: "Contact", body: "Questions about these terms, legal@elevenviews.io. We answer within seven business days." },
      ]} />
    </main>
  );
}

function LegalBody({ sections }) {
  return (
    <section className="container" style={{ padding: "72px 0 96px" }}>
      <div className="legal-layout">
        <aside className="legal-toc">
          <span className="eyebrow">Sections</span>
          <ol>
            {sections.map((s, i) => (
              <li key={s.id}><a href={`#${s.id}`}><span className="mono">0{i + 1}</span> {s.t}</a></li>
            ))}
          </ol>
        </aside>
        <div className="legal-body">
          {sections.map((s, i) => (
            <article key={s.id} id={s.id} className="legal-section">
              <span className="mono" style={{ fontSize: 11, letterSpacing: "0.18em", color: "var(--gold)", textTransform: "uppercase" }}>0{i + 1}</span>
              <h2 className="serif">{s.t}</h2>
              <p>{s.body}</p>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Accessibility
   ───────────────────────────────────────────────────────────────── */
function Accessibility() {
  const { goto } = useRoute();
  return (
    <main>
      <UtilHeader eyebrow="Commitment" title="Accessibility." lede="The studio designs for people, not just users. The site, the storefront, and the booking flow should work for everyone, keyboard, screen reader, low vision, slow connection." lastUpdated="14 March 2026" />
      <section className="container" style={{ padding: "72px 0 64px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.6fr", gap: 64 }}>
          <span className="eyebrow eyebrow-gold">§ Standard</span>
          <p style={{ fontSize: 16, color: "var(--text-1)", lineHeight: 1.6, margin: 0, maxWidth: 700 }}>
            We aim for <strong>WCAG 2.2 AA</strong> across every page, and AAA where it's reasonable.
            We test with VoiceOver and NVDA on each major release. The site is fully navigable by keyboard.
            Contrast is checked across all six tone presets the design system supports.
          </p>
        </div>
      </section>
      <hr className="rule" />
      <section className="container" style={{ padding: "72px 0" }}>
        <div className="a11y-grid">
          {[
            ["Keyboard", "Every interactive element has a visible focus ring and a sensible tab order. The cart, booking flow, and store filters are entirely keyboardable."],
            ["Screen readers", "Semantic HTML, ARIA labels on icon-only buttons, descriptive alt text on every photograph, and live-region announcements for cart updates and form errors."],
            ["Motion", "Animations respect prefers-reduced-motion. The hero film and process visuals can be paused. Auto-playing video has sound off by default."],
            ["Contrast & type", "Body copy clears 4.8:1 against the studio dark canvas. Type can be scaled to 200% without horizontal scroll. The accent gold is held above 3:1 on every surface."],
            ["Forms", "Errors are announced inline and on submit. Required fields are labeled, not asterisked. The booking flow saves progress so you can step away and return."],
            ["Reporting", "If you hit something that doesn't work, write a11y@elevenviews.io. We answer within five business days, fix critical issues within ten, and publish a quarterly progress note."],
          ].map(([t, b]) => (
            <div key={t} className="a11y-card">
              <h3 className="serif">{t}</h3>
              <p>{b}</p>
            </div>
          ))}
        </div>
      </section>
      <hr className="rule" />
      <section className="container" style={{ padding: "72px 0 96px" }}>
        <div className="util-cta">
          <div>
            <h3 className="serif" style={{ fontSize: 36, lineHeight: 1.1, margin: 0, letterSpacing: "-0.01em" }}>Found a barrier?</h3>
            <p style={{ color: "var(--text-2)", margin: "10px 0 0" }}>Tell us. The studio reads every note.</p>
          </div>
          <button className="btn btn-gold btn-lg" onClick={() => goto("contact", { topic: "support" })}>Report an issue <I name="arrow" size={16} /></button>
        </div>
      </section>
    </main>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Sitemap
   ───────────────────────────────────────────────────────────────── */
function Sitemap() {
  const { goto } = useRoute();
  const groups = [
    { t: "Studio", links: [["home", "Home"], ["about", "About"], ["press", "Press"], ["journal", "Journal"], ["contact", "Contact"]] },
    { t: "Services", links: [["services", "All services"], ...Object.values(window.SERVICES).map(s => ["service", s.name, { key: s.key }])] },
    { t: "Work", links: [["work", "All work"], ...window.WORK_FILTERS.filter(f => f.key !== "all").map(f => ["work", f.label, { filter: f.key }])] },
    { t: "Store", links: [["store", "All store"], ...window.CATEGORIES.filter(c => c.key !== "all").map(c => ["store", c.label, { cat: c.key }])] },
    { t: "Booking", links: [["booking", "Submit a brief"], ["contact", "Talk first"]] },
    { t: "Account", links: [["login", "Sign in"], ["login", "Create account"]] },
    { t: "Legal", links: [["privacy", "Privacy"], ["terms", "Terms"], ["accessibility", "Accessibility"], ["shipping", "Shipping & returns"], ["faq", "FAQ"]] },
  ];
  return (
    <main>
      <UtilHeader eyebrow="Map" title="Everything, in one place." lede="The whole studio, listed plainly. Useful for the curious and the search engines." />
      <section className="container" style={{ padding: "72px 0 96px" }}>
        <div className="sitemap-grid">
          {groups.map(g => (
            <div key={g.t} className="sitemap-col">
              <h3 className="serif">{g.t}</h3>
              <ul>
                {g.links.map(([k, label, params], i) => (
                  <li key={`${k}-${i}`}><a onClick={() => goto(k, params)}>{label} <I name="arrow" size={12} /></a></li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      </section>
    </main>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Press
   ───────────────────────────────────────────────────────────────── */
function Press() {
  const { goto } = useRoute();
  // Real features get added here as they land. Empty list shows the
  // press-kit CTA only — never fake placeholder coverage.
  const features = [];
  return (
    <main>
      <UtilHeader eyebrow="Press" title="What's been written." lede="Press kit, hi-res imagery, and bios available on request. Write press@elevenviews.io." />
      {features.length > 0 && (
        <section className="container" style={{ paddingTop: "72px", paddingBottom: "64px" }}>
          <div className="press-list">
            {features.map(([pub, t, when, body]) => (
              <article key={t} className="press-row">
                <div>
                  <span className="mono" style={{ fontSize: 10, letterSpacing: "0.16em", color: "var(--text-3)", textTransform: "uppercase" }}>{when}</span>
                  <h3 className="serif">{pub}</h3>
                </div>
                <div>
                  <h4 className="serif" dangerouslySetInnerHTML={{ __html: t }} />
                  <p>{body}</p>
                </div>
                <a className="lk lk-arrow">Read <I name="ext" size={12} /></a>
              </article>
            ))}
          </div>
        </section>
      )}
      <hr className="rule" />
      <section className="container" style={{ padding: "72px 0 96px" }}>
        <div className="util-cta">
          <div>
            <h3 className="serif" style={{ fontSize: 36, lineHeight: 1.1, margin: 0, letterSpacing: "-0.01em" }}>Writing about the studio?</h3>
            <p style={{ color: "var(--text-2)", margin: "10px 0 0" }}>Press kit, hi-res, founder bios, same day.</p>
          </div>
          <button className="btn btn-gold btn-lg" onClick={() => goto("contact", { topic: "partnership" })}>Request press kit <I name="arrow" size={16} /></button>
        </div>
      </section>
    </main>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Journal, placeholder index
   ───────────────────────────────────────────────────────────────── */
function Journal() {
  const entries = [
    ["The eleven rule", "On choosing scarcity over scale", "Mar 2026", "warm"],
    ["Shooting on a single 50mm", "What constraint earns you", "Feb 2026", "deep"],
    ["The Marfa cycle, in writing", "Behind the film for A24", "Dec 2025", "cool"],
    ["A year on tape", "Field recordings, Vol. I notes", "Oct 2025", "warm"],
  ];
  const { goto } = useRoute();
  return (
    <main>
      <UtilHeader eyebrow="Journal" title="Letters from the studio." lede="The view from the studio. Process notes, occasional essays, the work in progress." />
      <section className="container" style={{ padding: "72px 0 96px" }}>
        <div className="journal-grid">
          {entries.map(([t, sub, when, v]) => (
            <article key={t} className="journal-entry">
              <Placeholder label={t.toLowerCase()} variant={v} code="EV-J" style={{ aspectRatio: "5/3", marginBottom: 22 }} />
              <span className="mono" style={{ fontSize: 10, letterSpacing: "0.16em", color: "var(--text-3)", textTransform: "uppercase" }}>{when}</span>
              <h3 className="serif" style={{ fontSize: 30, lineHeight: 1.1, letterSpacing: "-0.01em", margin: "12px 0 8px" }}>{t}</h3>
              <p style={{ fontSize: 14, color: "var(--text-2)", lineHeight: 1.6, margin: "0 0 16px" }}>{sub}</p>
              <a className="lk lk-arrow">Read the entry <I name="arrow" size={12} /></a>
            </article>
          ))}
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { FAQPage, Shipping, Privacy, Terms, Accessibility, Sitemap, Press, Journal });
