// Gallery + Artist detail pages
const { useState: gUseState, useEffect: gUseEffect, useMemo: gUseMemo } = React;

function PriceTier({ price }) {
  if (price < 250) return "$0–250";
  if (price < 500) return "$250–500";
  if (price < 1000) return "$500–1k";
  if (price < 2500) return "$1k–2.5k";
  return "$2.5k+";
}

function Gallery() {
  const [view, setView] = gUseState("artist"); // or "artwork"
  const [search, setSearch] = gUseState("");
  const [activeCat, setActiveCat] = gUseState(null);
  const [activePrice, setActivePrice] = gUseState(null);
  const [activeMedium, setActiveMedium] = gUseState(null);
  const [sort, setSort] = gUseState("featured");
  const [mobileFiltersOpen, setMobileFiltersOpen] = gUseState(false);

  const filtered = gUseMemo(() => {
    let list = [...ARTISTS];
    if (search) {
      const q = search.toLowerCase();
      list = list.filter(a => (a.first + " " + a.last).toLowerCase().includes(q) || (a.featured || "").toLowerCase().includes(q));
    }
    if (activeCat) list = list.filter(a => a.category === activeCat);
    if (activeMedium) list = list.filter(a => a.medium === activeMedium);
    if (activePrice) {
      const ranges = {
        "0-250": [0, 250],
        "250-500": [250, 500],
        "500-1000": [500, 1000],
        "1000-2500": [1000, 2500],
        "2500-up": [2500, Infinity],
      };
      const [lo, hi] = ranges[activePrice];
      list = list.filter(a => a.price >= lo && a.price < hi);
    }
    if (sort === "alpha") list.sort((a, b) => a.last.localeCompare(b.last));
    else if (sort === "price-low") list.sort((a, b) => a.price - b.price);
    else if (sort === "price-high") list.sort((a, b) => b.price - a.price);
    return list;
  }, [search, activeCat, activePrice, activeMedium, sort]);

  const mediums = ["Oil", "Watercolor", "Mixed Media", "Acrylic", "Bronze", "Charcoal", "Giclée", "Lithograph"];
  const priceFilters = [
    { id: "0-250", label: "$0 – $250" },
    { id: "250-500", label: "$250 – $500" },
    { id: "500-1000", label: "$500 – $1,000" },
    { id: "1000-2500", label: "$1,000 – $2,500" },
    { id: "2500-up", label: "$2,500 +" },
  ];

  const clearFilters = () => {
    setActiveCat(null); setActivePrice(null); setActiveMedium(null); setSearch("");
  };

  return (
    <div data-screen-label="02 Gallery">
      {/* Page header */}
      <section style={{ paddingTop: 72, paddingBottom: 48 }}>
        <div className="container">
          <Eyebrow>Browse our collection</Eyebrow>
          <h1 className="display" style={{ fontSize: "clamp(56px, 7vw, 104px)", margin: "20px 0 0" }}>
            The <em>Gallery</em>.
          </h1>
          <p style={{ maxWidth: 620, marginTop: 24, fontSize: 17, lineHeight: 1.7 }}>
            Eighty-plus represented artists. From affordable originals under $250 to museum-quality oils and bronze. Browse by artist, or filter by category, price, and medium.
          </p>
        </div>
      </section>

      <hr className="hairline"/>

      {/* Filter toolbar */}
      <section style={{ padding: "24px 0", borderBottom: "1px solid var(--hairline)", background: "var(--bg)", position: "sticky", top: 60, zIndex: 10 }}>
        <div className="container" style={{ display: "flex", gap: 24, alignItems: "center", flexWrap: "wrap" }}>
          <div style={{ display: "flex", border: "1px solid var(--hairline)", borderRadius: 2 }}>
            <button onClick={() => setView("artist")} style={{ background: view === "artist" ? "var(--ink)" : "transparent", color: view === "artist" ? "var(--bg)" : "var(--ink)", border: 0, padding: "10px 20px", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", cursor: "pointer", fontFamily: "var(--body)" }}>By Artist</button>
            <button onClick={() => setView("artwork")} style={{ background: view === "artwork" ? "var(--ink)" : "transparent", color: view === "artwork" ? "var(--bg)" : "var(--ink)", border: 0, padding: "10px 20px", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", cursor: "pointer", fontFamily: "var(--body)" }}>By Artwork</button>
          </div>
          <div style={{ flex: 1, minWidth: 200, position: "relative" }}>
            <input type="text" placeholder="Search artists or works…" value={search} onChange={(e) => setSearch(e.target.value)} style={{ paddingLeft: 38 }} />
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", color: "var(--muted)" }}><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <label style={{ fontSize: 11 }}>Sort</label>
            <select value={sort} onChange={(e) => setSort(e.target.value)} style={{ width: "auto", padding: "10px 14px" }}>
              <option value="featured">Featured</option>
              <option value="alpha">Alphabetical</option>
              <option value="price-low">Price · Low</option>
              <option value="price-high">Price · High</option>
            </select>
          </div>
          <button onClick={() => setMobileFiltersOpen(true)} className="btn btn-ghost mobile-filter-btn" style={{ padding: "10px 18px" }}>Filters</button>
        </div>
      </section>

      {/* Body — sidebar + grid */}
      <section style={{ padding: "48px 0 96px" }}>
        <div className="container" style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 56 }} className="gallery-body">
          <aside style={{ borderRight: "1px solid var(--hairline)", paddingRight: 32 }} className="gallery-sidebar">
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 20 }}>
              <div className="eyebrow">Filter</div>
              {(activeCat || activePrice || activeMedium || search) && (
                <button onClick={clearFilters} style={{ background: "transparent", border: 0, fontSize: 11, color: "var(--wine)", cursor: "pointer", letterSpacing: "0.12em", textTransform: "uppercase" }}>Clear</button>
              )}
            </div>
            <FilterGroup label="Category">
              {ART_CATEGORIES.map(c => (
                <FilterRow key={c.slug} active={activeCat === c.slug} onClick={() => setActiveCat(activeCat === c.slug ? null : c.slug)}>
                  {c.title}<span style={{ color: "var(--muted)", fontSize: 11 }}>{c.count}</span>
                </FilterRow>
              ))}
            </FilterGroup>
            <FilterGroup label="Price">
              {priceFilters.map(p => (
                <FilterRow key={p.id} active={activePrice === p.id} onClick={() => setActivePrice(activePrice === p.id ? null : p.id)}>{p.label}</FilterRow>
              ))}
            </FilterGroup>
            <FilterGroup label="Medium">
              {mediums.map(m => (
                <FilterRow key={m} active={activeMedium === m} onClick={() => setActiveMedium(activeMedium === m ? null : m)}>{m}</FilterRow>
              ))}
            </FilterGroup>
          </aside>

          <div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 24 }}>
              <div className="eyebrow">{filtered.length} {view === "artist" ? "artists" : "works"} · showing</div>
              <div className="eyebrow">{view === "artist" ? "By artist" : "By artwork"}</div>
            </div>

            {filtered.length === 0 ? (
              <div style={{ padding: "80px 0", textAlign: "center", color: "var(--muted)" }}>
                <div className="display" style={{ fontSize: 36, fontStyle: "italic" }}>Nothing matches yet.</div>
                <p style={{ marginTop: 16 }}>Try clearing some filters.</p>
                <button onClick={clearFilters} className="btn btn-ghost-wine" style={{ marginTop: 20 }}>Clear filters</button>
              </div>
            ) : view === "artist" ? (
              <div className="artist-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 32 }}>
                {filtered.map(a => (
                  <a key={a.slug} href={"#/gallery/artists/" + a.slug} className="lift" style={{ textDecoration: "none", display: "block" }}>
                    <ArtCanvas seed={a.canvas} ratio="1 / 1" src={a.img} />
                    <div style={{ marginTop: 14 }}>
                      <div className="display" style={{ fontSize: 22, fontStyle: "italic" }}>{a.last}, {a.first}</div>
                      <div style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--muted)", marginTop: 4 }}>
                        {a.medium} · {ART_CATEGORIES.find(c => c.slug === a.category)?.title}
                      </div>
                      <div style={{ fontSize: 13, color: "var(--wine)", marginTop: 6, fontStyle: "italic", fontFamily: "var(--display)" }}>{a.featured}</div>
                    </div>
                  </a>
                ))}
              </div>
            ) : (
              <div className="artwork-grid" style={{ columnCount: 3, columnGap: 24 }}>
                {filtered.map(a => {
                  const ratios = ["3 / 4", "4 / 5", "1 / 1", "4 / 3"];
                  const r = ratios[a.canvas % ratios.length];
                  return (
                    <a key={a.slug} href={"#/gallery/artists/" + a.slug} style={{ display: "block", breakInside: "avoid", marginBottom: 24, textDecoration: "none" }} className="lift">
                      <ArtCanvas seed={a.canvas} ratio={r} src={a.img} />
                      <div style={{ marginTop: 12 }}>
                        <div className="display" style={{ fontSize: 18, fontStyle: "italic" }}>{a.featured}</div>
                        <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--muted)", marginTop: 4 }}>{a.first} {a.last}</div>
                        <div style={{ fontSize: 13, color: "var(--ink)", marginTop: 4 }}>{a.medium} · ${a.price.toLocaleString()}</div>
                      </div>
                    </a>
                  );
                })}
              </div>
            )}

            {/* CTA row */}
            <div style={{ marginTop: 80, padding: "48px 0", textAlign: "center", borderTop: "1px solid var(--hairline)" }}>
              <Eyebrow withRule={false}>Found a piece you like?</Eyebrow>
              <h3 className="display" style={{ fontSize: 40, margin: "12px 0 24px" }}>Inquire about <em>any</em> work.</h3>
              <a href="#/visit" className="btn btn-primary">Send an inquiry →</a>
            </div>
          </div>
        </div>
      </section>

      {/* Mobile filter sheet */}
      {mobileFiltersOpen && (
        <div onClick={() => setMobileFiltersOpen(false)} style={{ position: "fixed", inset: 0, background: "rgba(26,22,18,0.5)", zIndex: 200, display: "flex", alignItems: "flex-end" }}>
          <div onClick={(e) => e.stopPropagation()} style={{ background: "var(--bg)", width: "100%", maxHeight: "85vh", overflow: "auto", padding: 24, borderTopLeftRadius: 8, borderTopRightRadius: 8 }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 20 }}>
              <div className="eyebrow">Filters</div>
              <button onClick={() => setMobileFiltersOpen(false)} style={{ background: "transparent", border: 0, fontSize: 24, cursor: "pointer" }}>×</button>
            </div>
            <FilterGroup label="Category">
              {ART_CATEGORIES.map(c => (
                <FilterRow key={c.slug} active={activeCat === c.slug} onClick={() => setActiveCat(activeCat === c.slug ? null : c.slug)}>{c.title}</FilterRow>
              ))}
            </FilterGroup>
            <FilterGroup label="Price">
              {priceFilters.map(p => <FilterRow key={p.id} active={activePrice === p.id} onClick={() => setActivePrice(activePrice === p.id ? null : p.id)}>{p.label}</FilterRow>)}
            </FilterGroup>
            <button onClick={() => setMobileFiltersOpen(false)} className="btn btn-primary" style={{ width: "100%", marginTop: 20, justifyContent: "center" }}>Apply</button>
          </div>
        </div>
      )}
    </div>
  );
}

function FilterGroup({ label, children }) {
  return (
    <div style={{ marginBottom: 28 }}>
      <div className="eyebrow" style={{ marginBottom: 14, fontSize: 10 }}>{label}</div>
      <div style={{ display: "flex", flexDirection: "column" }}>{children}</div>
    </div>
  );
}
function FilterRow({ children, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      background: "transparent", border: 0, textAlign: "left", padding: "6px 0",
      fontSize: 14, color: active ? "var(--wine)" : "var(--ink-body)",
      cursor: "pointer", fontFamily: "var(--body)",
      fontWeight: active ? 500 : 400,
      display: "flex", justifyContent: "space-between", alignItems: "center",
      borderBottom: "1px solid transparent",
    }}>
      <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span style={{ width: 8, height: 8, borderRadius: "50%", border: "1px solid " + (active ? "var(--wine)" : "var(--hairline)"), background: active ? "var(--wine)" : "transparent" }} />
        {children}
      </span>
    </button>
  );
}

// ----- ARTIST DETAIL -----
function ArtistDetail({ slug }) {
  const artist = ARTISTS.find(a => a.slug === slug);
  if (!artist) {
    return (
      <div className="section container">
        <Eyebrow>404</Eyebrow>
        <h1 className="display" style={{ fontSize: 64, margin: "20px 0" }}>Artist not found.</h1>
        <a href="#/gallery" className="btn btn-ghost-wine">← Back to gallery</a>
      </div>
    );
  }
  // Generate 6 additional "works" for this artist using the canvas variations
  const works = Array.from({ length: 6 }, (_, i) => ({
    title: ["Studies", "Field Notes", "Series", "Untitled", "Composition", "Plein Air"][i] + " " + (["I", "II", "III", "IV", "V", "VI"][i]),
    seed: (artist.canvas + i + 1) % 10,
    price: artist.price + (i - 2) * 120,
    size: ["18 × 24", "24 × 30", "30 × 40", "12 × 16", "16 × 20", "20 × 24"][i],
  }));
  const ratios = ["3 / 4", "4 / 5", "1 / 1", "4 / 3", "5 / 4", "3 / 4"];

  return (
    <div data-screen-label={"03 Artist · " + artist.last}>
      <section style={{ paddingTop: 56 }}>
        <div className="container">
          <a href="#/gallery" className="btn-link" style={{ fontSize: 11 }}>← All artists</a>
          <div style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 80, marginTop: 32, alignItems: "center" }} className="hero-grid">
            <div>
              <ArtCanvas seed={artist.canvas} ratio="4 / 5" framed src={artist.img} />
            </div>
            <div>
              <Eyebrow>{ART_CATEGORIES.find(c => c.slug === artist.category)?.title} · {artist.medium}</Eyebrow>
              <h1 className="display" style={{ fontSize: "clamp(56px, 7vw, 96px)", margin: "20px 0 0" }}>
                <em>{artist.first}</em><br/>{artist.last}
              </h1>
              <div className="display" style={{ fontSize: 28, fontStyle: "italic", color: "var(--wine)", marginTop: 24 }}>{artist.featured}</div>
              <div className="eyebrow" style={{ marginTop: 8 }}>Featured work · ${artist.price.toLocaleString()}</div>
              <p style={{ marginTop: 32, fontSize: 17, lineHeight: 1.7, maxWidth: 460 }}>
                {artist.bio || `${artist.first} ${artist.last} has been part of the Dutch Art Gallery roster across many years and many shows. Working primarily in ${artist.medium.toLowerCase()}, ${artist.first}'s ${ART_CATEGORIES.find(c => c.slug === artist.category)?.title.toLowerCase()} have found homes in private and corporate collections across Texas and beyond.`}
              </p>
              <div style={{ display: "flex", gap: 14, marginTop: 36, flexWrap: "wrap" }}>
                <a href="#/visit" className="btn btn-primary">Inquire about a piece</a>
                <a href="#/gallery" className="btn btn-ghost">More artists →</a>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 40 }}>
            <SectionHead eyebrow="Selected works" title={<>In the studio<br/>this season</>} />
            <div className="eyebrow">6 works available</div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 32 }} className="works-grid">
            {works.map((w, i) => (
              <div key={i} className="lift">
                <ArtCanvas seed={w.seed} ratio={ratios[i]} />
                <div style={{ marginTop: 14 }}>
                  <div className="display" style={{ fontSize: 22, fontStyle: "italic" }}>{w.title}</div>
                  <div style={{ fontSize: 12, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--muted)", marginTop: 4 }}>{artist.medium} · {w.size}″</div>
                  <div style={{ fontSize: 14, color: "var(--ink)", marginTop: 6 }}>${w.price.toLocaleString()}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section style={{ background: "#efe5ce", padding: "80px 0", marginTop: 64 }}>
        <div className="container" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 24 }}>
          <div>
            <Eyebrow>Continue browsing</Eyebrow>
            <h3 className="display" style={{ fontSize: 40, margin: "12px 0 0" }}>80+ artists on the walls.</h3>
          </div>
          <a href="#/gallery" className="btn btn-primary">Back to gallery</a>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { Gallery, ArtistDetail });
