/* Pages: Artists index + Artist dossier */
const { useState: useStateA, useMemo: useMemoA } = React;

function ArtistsPage({ onRoute }) {
  const data = window.TGP_DATA;
  const [view, setView] = useStateA("grid");
  const [letter, setLetter] = useStateA(null);

  // Build alphabet availability
  const letters = useMemoA(() => {
    const all = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
    const present = new Set(data.artists.map((a) => a.name[0].toUpperCase()));
    return all.map((L) => ({ L, has: present.has(L) }));
  }, []);

  const filtered = letter ? data.artists.filter((a) => a.name[0].toUpperCase() === letter) : data.artists;

  // For grid view, assign each artist a representative image deterministically
  const exImgs = data.exhibitions.map((e) => e.img);
  const artistImg = (idx) => exImgs[idx % exImgs.length];

  return (
    <section className="section shell">
      <div className="eyebrow"><span className="dot"></span>Artists · live roster · {data.artists.length}</div>
      <h1 className="display display-2" style={{ marginTop: 12, maxWidth: "20ch" }}>
        Sixty-five artists,<br /><span className="italic" style={{ color: "var(--secondary)" }}>between the Global South and the West.</span>
      </h1>
      <p style={{ marginTop: 24, maxWidth: "60ch", color: "var(--muted)", fontSize: 15 }}>
        A project-led network rather than a fixed roster — painting-led, MENA-anchored, internationally
        connected. Filter by initial, switch to the list view for place and year of birth, or open a dossier
        for bio, CV, available works and press.
      </p>

      <div className="artist-toolbar" style={{ marginTop: 48 }}>
        <div className="alpha" role="group" aria-label="Filter by initial">
          <button className={letter === null ? "on has" : "has"} onClick={() => setLetter(null)}>All</button>
          {letters.map(({ L, has }) => (
            <button
              key={L}
              className={(letter === L ? "on " : "") + (has ? "has" : "")}
              onClick={() => has && setLetter(L)}
              disabled={!has}
              aria-disabled={!has}
            >
              {L}
            </button>
          ))}
        </div>
        <div className="view-toggle">
          <button className={view === "grid" ? "on" : ""} onClick={() => setView("grid")}>Grid</button>
          <button className={view === "list" ? "on" : ""} onClick={() => setView("list")}>List</button>
        </div>
      </div>

      {view === "grid" && (
        <div className="artist-grid" style={{ marginTop: 32 }}>
          {filtered.map((a) => {
            const i = data.artists.indexOf(a);
            return (
              <div className="artist-card" key={a.name} onClick={() => onRoute({ name: "artist", name2: a.name })}>
                <div className="frame">
                  <img src={artistImg(i)} alt={a.name} />
                  {a.tag && <div className={"badge " + (a.tag === "Now showing" ? "now" : "")}>{a.tag}</div>}
                </div>
                <h5>{a.name}</h5>
                <div className="sub">{a.place} · {a.born}</div>
              </div>
            );
          })}
        </div>
      )}

      {view === "list" && (
        <div className="artist-list" style={{ marginTop: 32 }}>
          <div className="row head">
            <div className="num">№</div>
            <div className="name">Artist</div>
            <div className="place">Working</div>
            <div className="born">Born</div>
            <div className="tag">Status</div>
            <div className="arrow"></div>
          </div>
          {filtered.map((a, i) => {
            const idx = data.artists.indexOf(a) + 1;
            return (
              <div className="row" key={a.name} onClick={() => onRoute({ name: "artist", name2: a.name })}>
                <div className="num">{String(idx).padStart(2, "0")}</div>
                <div className="name">{a.name}</div>
                <div className="place">{a.place}</div>
                <div className="born">{a.born}</div>
                <div className="tag" style={{ color: a.tag === "Now showing" ? "var(--accent)" : "var(--muted)" }}>
                  {a.tag || "In the programme"}
                </div>
                <div className="arrow">→</div>
              </div>
            );
          })}
        </div>
      )}

      <div style={{ marginTop: 56, padding: "32px 36px", background: "var(--surface)", border: "1px solid var(--border)", display: "flex", gap: 32, alignItems: "center", justifyContent: "space-between", flexWrap: "wrap" }}>
        <div style={{ maxWidth: "44ch", fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 20, lineHeight: 1.4 }}>
          "We work project-led — not a fixed roster model. Artists want to be fluid now; it's a generational shift."
          <div className="meta" style={{ marginTop: 12, fontStyle: "normal", color: "var(--muted)" }}>
            — Taymour Grahne, AL-Monitor, September 2025
          </div>
        </div>
        <button className="btn-ghost btn" onClick={() => onRoute({ name: "about" })}>About the gallery <span className="arrow">→</span></button>
      </div>
    </section>
  );
}

/* ============== Artist dossier ============== */
function ArtistDossierPage({ artistName, onRoute, onEnquire, density }) {
  const data = window.TGP_DATA;
  const artist = data.artists.find((a) => a.name === artistName) || data.artists.find((a) => a.name === "Roudhah Al Mazrouei");
  const [tab, setTab] = useStateA("works");

  const exImgs = data.exhibitions.map((e) => e.img);
  const i = data.artists.indexOf(artist);
  const portrait = exImgs[i % exImgs.length];

  // Synthetic works (representative, with TBC credit notice)
  const works = useMemoA(() => {
    const titles = [
      ["Untitled (Held Light)", 2025, "Oil on linen", "180 × 140 cm"],
      ["Garden, Late Afternoon", 2025, "Oil on canvas", "120 × 95 cm"],
      ["Letter to Alserkal", 2024, "Oil on linen", "160 × 120 cm"],
      ["A Slow Look I", 2024, "Oil on canvas", "90 × 75 cm"],
      ["A Slow Look II", 2024, "Oil on canvas", "90 × 75 cm"],
      ["Study, Evening Wall", 2023, "Oil on board", "40 × 30 cm"]
    ];
    return titles.map((t, idx) => ({
      title: t[0], year: t[1], medium: t[2], dims: t[3],
      img: exImgs[(i + idx) % exImgs.length],
      sold: idx === 2
    }));
  }, [artist.name]);

  const tabs = [
    ["works", "Available works", density === "deep" ? 12 : works.length],
    ["bio", "Bio · CV", ""],
    ["exhibitions", "Exhibitions", 6],
    ["press", "Press", 3]
  ];

  return (
    <section className="shell">
      <div style={{ padding: "24px 0", fontFamily: "var(--mono)", fontSize: 11, color: "var(--muted)", letterSpacing: "0.06em" }}>
        <button onClick={() => onRoute({ name: "artists" })} style={{ color: "var(--muted)" }}>← Artists</button>
        <span style={{ margin: "0 12px" }}>/</span>
        <span style={{ color: "var(--text)" }}>{artist.name}</span>
      </div>

      <div className="dossier">
        <aside className="dossier-side">
          <div className="portrait"><img src={portrait} alt="" /></div>
          <dl>
            <dt>Born</dt><dd>{artist.born}</dd>
            <dt>Lives</dt><dd>{artist.place}</dd>
            <dt>Practice</dt><dd>Painting</dd>
            <dt>With TGP</dt><dd>{artist.tag === "Now showing" ? "Currently exhibiting" : "In the programme"}</dd>
            <dt>Prices</dt><dd style={{ color: "var(--accent)" }}>POA · by enquiry</dd>
          </dl>
          <div className="links">
            <button className="btn" onClick={() => onEnquire({
              heading: "Enquire — " + artist.name,
              sub: "Available works · POA",
              pre: { artist: artist.name, title: " — selected works", img: portrait, note: "Specific works on request." }
            })} style={{ justifyContent: "center" }}>
              Enquire about works <span className="arrow">→</span>
            </button>
            <button className="btn-ghost btn" style={{ justifyContent: "center" }}>Download CV · PDF</button>
            <button className="btn-line" style={{ marginTop: 8 }}>Follow on Artsy <span className="arrow">→</span></button>
          </div>
        </aside>

        <div className="dossier-main">
          {artist.tag === "Now showing" && (
            <div className="eyebrow"><span className="dot"></span>Currently in Five Painters · Dubai</div>
          )}
          <h1>{artist.name}</h1>
          <div className="role">{artist.born}, {artist.place}</div>

          <p className="lede" style={{ maxWidth: "44ch" }}>
            Paintings as careful acts of attention — light, interior, the slow drift between figuration and atmosphere.
          </p>

          <div className="tabs">
            {tabs.map(([k, label, c]) => (
              <button key={k} className={tab === k ? "on" : ""} onClick={() => setTab(k)}>
                {label}{c !== "" && <span className="count">· {c}</span>}
              </button>
            ))}
          </div>

          {tab === "works" && (
            <React.Fragment>
              <div className="works-grid">
                {works.map((w, idx) => (
                  <div className="work" key={idx}>
                    <div className="frame">
                      <img src={w.img} alt={w.title} />
                      <div className="enquire-hover">
                        <button className="btn" onClick={() => onEnquire({
                          heading: "Enquire — " + w.title,
                          sub: artist.name + ", " + w.year,
                          pre: { artist: artist.name, title: " — " + w.title + ", " + w.year, img: w.img, spec: w.medium + " · " + w.dims, note: "Credit & rights to confirm with gallery." }
                        })}>
                          Enquire · POA
                        </button>
                      </div>
                    </div>
                    <CreditLine name={artist.name} title={w.title} year={w.year} medium={w.medium} dims={w.dims} sold={w.sold} />
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 32, padding: "16px 18px", background: "var(--surface)", borderLeft: "2px solid var(--accent)", fontFamily: "var(--mono)", fontSize: 11.5, color: "var(--muted)", letterSpacing: "0.02em" }}>
                ⚠ Local image assets are mapped from gallery source pages; specific artwork credit lines and
                rights remain TBC. All works require gallery confirmation before publication.
              </div>
            </React.Fragment>
          )}

          {tab === "bio" && (
            <div style={{ maxWidth: "64ch" }}>
              <p>
                {artist.name} (b. {artist.born.replace("b. ", "")}, lives in {artist.place}) works primarily
                in oil — slow, layered, and observed from the conditions of a specific room or landscape.
                Their practice sits within the gallery's painting-led programme, working across and between
                the Global South and the West.
              </p>
              <p className="pull-quote">
                Painting is a way of staying with a room until it gives you something back.
              </p>
              <h4 className="display display-3" style={{ marginTop: 40, marginBottom: 16 }}>Selected solo exhibitions</h4>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, borderTop: "1px solid var(--border)" }}>
                {[
                  ["2026", "Five Painters · Taymour Grahne Projects, Dubai (group)"],
                  ["2025", "A Slow Look · Solo, Taymour Grahne Projects, London"],
                  ["2024", "Held Light · Selma Feriani Gallery, Tunis"],
                  ["2023", "Garden, Late Afternoon · Carl Kostyál, Milan"],
                  ["2022", "Letters · Roberts Projects, Los Angeles"]
                ].map((r, idx) => (
                  <li key={idx} style={{ display: "grid", gridTemplateColumns: "80px 1fr", padding: "14px 0", borderBottom: "1px solid var(--border)", fontSize: 14 }}>
                    <span className="meta">{r[0]}</span><span>{r[1]}</span>
                  </li>
                ))}
              </ul>
              <h4 className="display display-3" style={{ marginTop: 40, marginBottom: 16 }}>Selected collections</h4>
              <p>
                Private collections in the United Arab Emirates, Saudi Arabia, the United Kingdom, France
                and the United States. Institutional list available on request.
              </p>
            </div>
          )}

          {tab === "exhibitions" && (
            <div className="works-grid">
              {data.exhibitions.slice(0, 6).map((ex) => (
                <ExhibitionCard key={ex.slug} ex={ex} onRoute={onRoute} />
              ))}
            </div>
          )}

          {tab === "press" && (
            <div className="press-table" style={{ borderTop: "1px solid var(--border)" }}>
              {data.press.slice(0, 3).map((p, i) => (
                <div key={i} className="row">
                  <div className="date">{p.date}</div>
                  <div>
                    <div className="outlet">{p.outlet}</div>
                    <div className="title">{p.title}</div>
                  </div>
                  <div className="kind">{p.kind}</div>
                  <div className="download">↗</div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { ArtistsPage, ArtistDossierPage });
