/* APEX CLIPS — Explore Library (access-gated), ClipCard, FilterBar, Clip Detail */

function ClipCard({ clip, onOpen }) {
  return (
    <Link to={"/clip/" + clip.id} className="clip-card" onClick={onOpen}>
      <Thumb clip={clip} className={"clip-thumb clip-thumb--" + clip.or}>
        <span className="pill pill--solid clip-dur"><span style={{ marginRight: 2 }}>▷</span>{clip.dur}</span>
        <span className="pill pill--solid clip-or">{ORIENT[clip.or]}</span>
        <div className="clip-rights"><RightsPill rights={clip.rights} solid /></div>
      </Thumb>
      <div className="clip-meta">
        <h3 className="clip-title">{clip.title}</h3>
        <div className="clip-sub">
          <span className="mono">{clip.loc}</span>
          <span className="clip-dot">·</span>
          <span className="mono">{CAT_BY_KEY[clip.cat].name}</span>
        </div>
        <div className="clip-foot">
          <span className="mono clip-id">{clip.id.toUpperCase()}</span>
          <span className="clip-req">Request License →</span>
        </div>
      </div>
    </Link>
  );
}

function Dropdown({ label, value, options, onChange, disabled }) {
  return (
    <label className="filter-field">
      <span className="filter-label mono">{label}</span>
      <select className="select filter-select" value={value} disabled={disabled}
              onChange={(e) => onChange(e.target.value)}>
        {options.map((o) => <option key={o.v} value={o.v}>{o.t}</option>)}
      </select>
    </label>
  );
}

// The catalogue search/controls. With `locked` the controls are visual only —
// the public catalogue is access-gated — and any interaction routes to the buyer
// access request. (Full filtering returns once buyers are behind access.)
function FilterBar({ state, set, compact, locked }) {
  const { go } = useContext(RouteCtx);
  const s = state || {};
  const upd = locked ? () => {} : (set || (() => {}));
  const catOpts = [{ v: "all", t: "All categories" }, ...CATEGORIES.map((c) => ({ v: c.key, t: c.name }))];
  const orOpts = [{ v: "all", t: "Any orientation" }, { v: "h", t: "Horizontal 16:9" }, { v: "v", t: "Vertical 9:16" }, { v: "s", t: "Square 1:1" }];
  const rightsOpts = [{ v: "all", t: "Any rights status" }, { v: "cleared", t: "Rights cleared" }, { v: "editorial", t: "Editorial only" }, { v: "exclusive", t: "Exclusive" }, { v: "pending", t: "Clearing" }];
  const usageOpts = [{ v: "all", t: "Any usage" }, ...USAGE_TYPES.map((u) => ({ v: u, t: u }))];
  const locOpts = [{ v: "all", t: "Any location" }, { v: "Europe", t: "Europe" }, { v: "Asia", t: "Asia" }, { v: "Oceania", t: "Oceania" }, { v: "Africa", t: "Africa" }, { v: "Americas", t: "Americas" }];
  return (
    <div className={"filter-bar" + (compact ? " filter-bar--compact" : "") + (locked ? " filter-bar--locked" : "")}
         onClick={locked ? () => go("/license") : undefined}>
      <div className="filter-search">
        <span className="filter-search-ic">⌕</span>
        <input className="input" readOnly={locked}
               placeholder={locked ? "Search the full verified library…" : "Search clips, e.g. drone barrel Bali"}
               value={s.q || ""} onChange={(e) => upd("q", e.target.value)} />
      </div>
      <div className="filter-fields">
        <Dropdown label="Category" value={s.cat || "all"} options={catOpts} onChange={(v) => upd("cat", v)} disabled={locked} />
        <Dropdown label="Location" value={s.loc || "all"} options={locOpts} onChange={(v) => upd("loc", v)} disabled={locked} />
        <Dropdown label="Orientation" value={s.or || "all"} options={orOpts} onChange={(v) => upd("or", v)} disabled={locked} />
        {!compact && <Dropdown label="Usage type" value={s.usage || "all"} options={usageOpts} onChange={(v) => upd("usage", v)} disabled={locked} />}
        <Dropdown label="Rights status" value={s.rights || "all"} options={rightsOpts} onChange={(v) => upd("rights", v)} disabled={locked} />
      </div>
      {locked && <span className="filter-lock mono">🔒 Access on request</span>}
    </div>
  );
}

// A locked, anonymous catalogue preview tile — looks like inventory, reveals no
// specific clip, and routes to the buyer access request on click.
function LockedTile({ cat, seed }) {
  const { go } = useContext(RouteCtx);
  return (
    <button type="button" className="locked-tile" onClick={() => go("/license")}
            aria-label="Request access to the library">
      <Thumb cat={cat} seed={seed} className="locked-tile-thumb" />
      <span className="pill pill--solid locked-tile-cat">{CAT_BY_KEY[cat] ? CAT_BY_KEY[cat].tag : ""}</span>
      <span className="locked-tile-lock" aria-hidden="true">🔒</span>
    </button>
  );
}

// Reusable teaser wall of locked tiles (fades out at the bottom to imply depth).
function LibraryWall({ count = 12 }) {
  const tiles = Array.from({ length: count }, (_, i) => ({ cat: CATEGORIES[i % CATEGORIES.length].key, seed: i + 3 }));
  return (
    <div className="library-wall">
      <div className="clip-grid">
        {tiles.map((t, i) => <LockedTile key={i} cat={t.cat} seed={t.seed} />)}
      </div>
      <div className="library-wall-fade" aria-hidden="true"></div>
    </div>
  );
}

// Shared buyer-access gate (library + homepage preview).
function LibraryGate({ compact }) {
  return (
    <div className={"card library-gate" + (compact ? " library-gate--compact" : "")}>
      <span className="mono library-gate-tag"><span className="dot" style={{ background: "var(--accent)" }}></span>Buyer access</span>
      <h3 className="display library-gate-h">License the full verified library.</h3>
      <p className="library-gate-p">Access to the full catalogue is opened on request. Tell us what you're after and our content desk opens the library and returns matched, rights-cleared options, usually within one business day.</p>
      <div className="library-gate-cta">
        <Link to="/license" className="btn btn--accent btn--lg">Request access →</Link>
        <Link to="/rights" className="btn btn--line btn--lg">How verification works</Link>
      </div>
    </div>
  );
}

function Library() {
  return (
    <Page>
      <section className="lib-head section--tight" style={{ paddingTop: 56 }}>
        <div className="wrap">
          <Eyebrow>Explore library</Eyebrow>
          <div className="lib-head-row">
            <h1 className="display" style={{ fontSize: "clamp(40px,6vw,82px)", marginTop: 14 }}>The verified feed.</h1>
            <p className="lib-head-sub">Rights-cleared travel, sport and adventure clips, creator-verified and ready to license. Buyer access is opened on request.</p>
          </div>
        </div>
      </section>
      <div className="lib-sticky">
        <div className="wrap"><FilterBar locked /></div>
      </div>
      <section className="section--tight" style={{ paddingTop: 28 }}>
        <div className="wrap">
          <div className="lib-toolbar">
            <span className="mono lib-count">A glimpse of the library · access on request</span>
            <Link to="/license" className="arrow-link">Request access →</Link>
          </div>
          <LibraryWall count={12} />
          <LibraryGate />
        </div>
      </section>
      <BespokeMini />
    </Page>
  );
}

function BespokeMini() {
  return (
    <section className="section--tight" style={{ paddingBottom: 88 }}>
      <div className="wrap">
        <div className="card bespoke-mini">
          <div>
            <h3 className="display" style={{ fontSize: 30 }}>Can't find the exact shot?</h3>
            <p style={{ color: "var(--ink-3)", margin: "6px 0 0" }}>Our content desk sources, verifies and clears footage to brief, usually within 48 hours.</p>
          </div>
          <Link to="/license" className="btn btn--accent btn--lg">Send a Brief →</Link>
        </div>
      </div>
    </section>
  );
}

/* ---------------- CLIP DETAIL ----------------
   A single watermarked preview listing — reachable for credibility, but routes
   to an enquiry (never a checkout). Public catalogue browsing stays gated. */
function ClipDetail() {
  const { path } = useContext(RouteCtx);
  const id = path.split("/clip/")[1];
  const clip = CLIPS.find((c) => c.id === id) || CLIPS[4];
  const cat = CAT_BY_KEY[clip.cat];
  const similar = CLIPS.filter((c) => c.cat === clip.cat && c.id !== clip.id);
  const sim2 = [...similar, ...CLIPS.filter((c) => c.id !== clip.id)]
    .filter((c, i, arr) => arr.findIndex((x) => x.id === c.id) === i)
    .slice(0, 6);
  const formats = [
    { f: clip.or === "v" ? "9:16 Vertical" : "16:9 Horizontal", res: "4K · ProRes / H.264" },
    { f: "1:1 Square", res: "1080p · social master" },
    { f: clip.or === "v" ? "4:5 Feed" : "9:16 Vertical cut", res: "1080p · platform-ready" },
  ];

  return (
    <Page>
      <section className="section--tight" style={{ paddingTop: 32, paddingBottom: 0 }}>
        <div className="wrap">
          <div className="mono detail-crumb">
            <Link to="/library" style={{ color: "var(--ink-3)" }}>Library</Link> / <Link to={"/library?cat=" + clip.cat} style={{ color: "var(--ink-3)" }}>{cat.name}</Link> / <span style={{ color: "var(--ink)" }}>{clip.id.toUpperCase()}</span>
          </div>
          <div className="detail-grid">
            <div>
              <div className="detail-player">
                <Thumb clip={clip} className="detail-thumb" kenBurns>
                  <div className="detail-wm">APEX · PREVIEW · {clip.id.toUpperCase()} · APEX · PREVIEW · {clip.id.toUpperCase()} · </div>
                  <div className="detail-play"><span></span></div>
                  <div className="detail-scrub"><div className="detail-scrub-fill"></div></div>
                </Thumb>
                <div className="detail-player-bar">
                  <span className="pill pill--solid">▷ {clip.dur}</span>
                  <span className="pill pill--solid">{ORIENT[clip.or]} · {clip.or === "v" ? "Vertical" : clip.or === "s" ? "Square" : "Horizontal"}</span>
                  <span className="pill pill--solid">4K source</span>
                  <span style={{ marginLeft: "auto" }} className="mono detail-wm-note">Watermarked preview · clean master on license</span>
                </div>
              </div>

              <div className="detail-section">
                <h3 className="detail-h">Description</h3>
                <p className="detail-desc">Captured handheld and finished in-camera, this {cat.name.toLowerCase()} moment from {clip.loc} runs {clip.dur}. Sourced directly from the original creator, verified for provenance, and packaged with full editorial context for newsroom and brand use.</p>
              </div>

              <div className="detail-section">
                <h3 className="detail-h">Suggested usage</h3>
                <div className="detail-chips">
                  {["Social publishing", "Editorial / news", clip.rights !== "editorial" && "Brand campaign", clip.rights !== "editorial" && "Paid social", "Documentary"].filter(Boolean).map((u) => (
                    <span key={u} className="pill">{u}</span>
                  ))}
                </div>
              </div>

              <div className="detail-section">
                <h3 className="detail-h">Available formats</h3>
                <div className="detail-formats">
                  {formats.map((f) => (
                    <div key={f.f} className="detail-format card">
                      <span className="detail-format-f">{f.f}</span>
                      <span className="mono detail-format-r">{f.res}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* sidebar */}
            <aside className="detail-aside">
              <div className="card detail-buy">
                <span className="mono detail-id">{clip.id.toUpperCase()}</span>
                <h1 className="display detail-title">{clip.title}</h1>
                <div className="detail-locline mono"><span>{clip.loc}</span><span className="clip-dot">·</span><span>Filmed 2026</span></div>
                <div className="detail-status">
                  <div className="detail-status-row"><span className="mono detail-status-k">Rights status</span><RightsPill rights={clip.rights} /></div>
                  <div className="detail-status-row"><span className="mono detail-status-k">Release status</span><span className="pill"><span className="dot" style={{ background: "var(--ink-3)" }}></span>{clip.releases}</span></div>
                  <div className="detail-status-row"><span className="mono detail-status-k">Creator</span><span style={{ fontWeight: 600 }}>{clip.creator} <span style={{ color: "var(--accent)" }}>✓</span></span></div>
                  <div className="detail-status-row"><span className="mono detail-status-k">Category</span><span style={{ fontWeight: 600 }}>{cat.name}</span></div>
                </div>
                <Link to="/license" className="btn btn--accent btn--lg btn--block" style={{ marginTop: 18 }}>Request License →</Link>
                <button className="btn btn--line btn--block" style={{ marginTop: 10 }}>Add to project ＋</button>
                <p className="mono detail-buy-note">Licensed under agreed platforms, territory &amp; term. Clean 4K master delivered on clearance.</p>
              </div>
              <div className="card detail-credit">
                <Thumb cat={clip.cat} className="detail-credit-av" />
                <div>
                  <div className="mono" style={{ fontSize: 11, color: "var(--ink-4)", letterSpacing: ".1em" }}>VERIFIED CREATOR</div>
                  <div style={{ fontWeight: 700, fontSize: 17 }}>{clip.creator}</div>
                  <div style={{ color: "var(--ink-3)", fontSize: 13 }}>Retains copyright · earns on every license</div>
                </div>
              </div>
            </aside>
          </div>
        </div>
      </section>

      <section className="section">
        <div className="wrap">
          <div className="kicker-row"><h2 className="display" style={{ fontSize: 34 }}>Similar clips</h2><Link to="/license" className="arrow-link">Request access →</Link></div>
          <div className="detail-carousel">
            {sim2.map((c) => <div key={c.id} className="detail-carousel-item"><ClipCard clip={c} /></div>)}
          </div>
        </div>
      </section>
    </Page>
  );
}

Object.assign(window, { ClipCard, FilterBar, LockedTile, LibraryWall, LibraryGate, Library, ClipDetail, BespokeMini });
