/* Ayyam Gallery — pages + App shell. */
const { GALLERY_ARTISTS: GA, EXHIBITED_ARTISTS: EA, WORKS: WK, EXHIBITIONS: EX, PUBLICATIONS: PUB, FAIRS: FR, PRESS: PR, ARTIST_BIOS: BIOS } = window.AYYAM_DATA;
const { useState: uS, useEffect: uE, useMemo: uM } = React;

/* ---------- HOME ---------- */
function HomePage({ locale, setRoute, openEnquiryFor, openDossier }) {
  const t = window.L[locale];
  const current = EX.find(e => e.state === "current");
  const featured = WK.filter(w => w.featured);
  return (
    <>
      {/* Hero */}
      <section className="shell" data-screen-label="01 Home — Hero">
        <div className="hero">
          <div className="hero-text">
            <span className="eyebrow">{t.current} — {current.dates}</span>
            <h1 style={{marginTop:18}}>
              {locale==="en"
                ? <>The Eye:<br/><em>An Aperture<br/>Into the Soul.</em></>
                : <>العين:<br/><em>منفذٌ إلى الروح.</em></>}
            </h1>
            <p className="lede">
              {locale==="en"
                ? <>A new exhibition of acrylics by <b>Safwan Dahoul</b>, continuing his decades-long Dream cycle — a sustained meditation on memory, exile and waiting.</>
                : <>معرض جديد لأعمال أكريليك للفنان <b>صفوان داحول</b>، يواصل سلسلته «حلم» الممتدة منذ عقود — تأمّل طويل في الذاكرة والمنفى والانتظار.</>}
            </p>
            <div className="hero-meta">
              <div><b>{t.workOnView}.</b> Safwan Dahoul, <em>Dream 284</em>, 2025. Acrylic on canvas, 200 × 220 cm.</div>
              <div className="credit-line" style={{marginTop:6}}>© the artist. Courtesy Ayyam Gallery. <span className="copyright-flag">[Rights pending]</span></div>
            </div>
            <div className="hero-cta">
              <button className="btn" onClick={() => openExhibition(current.id)}>
                {locale==="en"?"View exhibition":"شاهد المعرض"} →
              </button>
              <button className="btn btn-ghost" onClick={() => openEnquiryFor({kind:"viewing"})}>{t.requestViewing}</button>
            </div>
          </div>
          <div className="hero-image">
            <img src={current.cover} alt="Safwan Dahoul, Dream 284, 2025" />
            <div className="credit">
              <b style={{display:"block", fontWeight:500, marginBottom:2}}>Safwan Dahoul</b>
              <em>Dream 284</em>, 2025 · 200 × 220 cm<br/>
              <span style={{opacity:.7, fontSize:10, letterSpacing:".18em", textTransform:"uppercase"}}>© rights pending</span>
            </div>
          </div>
        </div>
      </section>

      <hr className="hairline shell" style={{margin:0}} />

      {/* Now Showing / Exhibitions teaser */}
      <section className="shell section" data-screen-label="01 Home — Programme">
        <div className="s-head">
          <div>
            <span className="eyebrow">{locale==="en"?"Programme":"البرنامج"}</span>
            <h2>{locale==="en"?<>Currently & forthcoming.</>:"المعارض الحالية والقادمة"}</h2>
          </div>
          <div className="s-action">
            <button className="btn btn-quiet" onClick={() => setRoute("exhibitions")}>
              {locale==="en"?"All exhibitions":"كل المعارض"} →
            </button>
          </div>
        </div>
        <div className="exh-grid">
          {EX.filter(e => e.state !== "past").concat(EX.filter(e=>e.state==="past").slice(0,1)).slice(0,3).map(e => (
            <ExhibitionCard key={e.id} ex={e} locale={locale} onClick={() => openExhibition(e.id)} />
          ))}
        </div>
      </section>

      {/* Gallery space band */}
      <section className="shell section" data-screen-label="01 Home — Space">
        <div className="band">
          <div className="band-img">
            <img src="media/gallery-space-alserkal.webp" alt="Ayyam Gallery — Alserkal Avenue, Dubai" />
          </div>
          <div>
            <span className="eyebrow">{locale==="en"?"The space":"المكان"}</span>
            <h3 style={{marginTop:12}}>
              {locale==="en"
                ? <>A white-cube hall<br/>in Alserkal Avenue.</>
                : "قاعة عرض في العسكر أفينيو."}
            </h3>
            <p>{locale==="en"
              ? "B11 has been our permanent home since the gallery's move to Dubai's Alserkal Avenue arts district. The hall's curved white walls were built to give long-format paintings, sculpture and video installations the slow walk they need."
              : "B11 هو مقرنا الدائم منذ انتقال الغاليري إلى حيّ الفنون في العسكر أفينيو بدبي. صُمّمت الجدران البيضاء المنحنية لإتاحة المشاهدة الهادئة للوحات الكبيرة والمنحوتات والفيديو."}</p>
            <p>{locale==="en"
              ? <>Open <b>Mon–Fri 10:00–19:00</b>, <b>Sat 12:00–18:00</b>. Closed Sunday.</>
              : <>المواعيد <b>الإثنين–الجمعة 10:00–19:00</b>، <b>السبت 12:00–18:00</b>. مغلق الأحد.</>}</p>
            <div style={{marginTop:24, display:"flex", gap:10, flexWrap:"wrap"}}>
              <button className="btn btn-ghost" onClick={() => setRoute("visit")}>{t.visit}</button>
            </div>
          </div>
        </div>
      </section>

      {/* Featured works */}
      <section className="shell section" data-screen-label="01 Home — Featured works">
        <div className="s-head">
          <div>
            <span className="eyebrow">{locale==="en"?"Selected works":"أعمال مختارة"}</span>
            <h2>{locale==="en"?<>From the programme.</>:"من البرنامج."}</h2>
          </div>
          <div className="s-action">
            <button className="btn btn-quiet" onClick={() => setRoute("artists")}>{t.nav[1]} →</button>
          </div>
        </div>
        <div className="works-strip">
          {featured.map(w => (
            <WorkCard key={w.id} work={w} locale={locale} onClick={() => openEnquiryFor({kind:"work", work:w})} />
          ))}
        </div>
      </section>

      {/* Publications teaser */}
      <section className="shell section" data-screen-label="01 Home — Publications">
        <div className="band">
          <div>
            <span className="eyebrow">{locale==="en"?"A differentiator":"السمة المميزة"}</span>
            <h3 style={{marginTop:12}}>
              {locale==="en"
                ? <>Publications.<br/><em style={{color:"var(--accent-ink)"}}>The gallery as a press.</em></>
                : <>المنشورات.<br/><em style={{color:"var(--accent-ink)"}}>الغاليري دار نشر.</em></>}
            </h3>
            <p>{locale==="en"
              ? "Since 2007 the gallery has run an active publishing programme — monographs, catalogues and essay collections for artists working under custodianship and through the wider Middle Eastern scene. Recent titles include the Dahoul, Azzam and Halaby monographs."
              : "منذ عام 2007، يدير الغاليري برنامج نشر فعّالاً يضم كتباً مخصصة، وكتالوغات، ومجموعات مقالات لفنانين من المشهد العربي الأوسع. من أحدث الإصدارات: داحول، عزّام، وحلبي."}</p>
            <div style={{marginTop:22, display:"flex", gap:10}}>
              <button className="btn btn-ghost" onClick={() => setRoute("publications")}>
                {locale==="en"?"All publications":"كل المنشورات"} →
              </button>
              <button className="btn-link" onClick={() => openEnquiryFor({kind:"catalogue"})}>{t.requestCatalogue}</button>
            </div>
          </div>
          <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:14}}>
            {PUB.slice(0,4).map((p, i) => (
              <div key={p.id} className="pub" style={{aspectRatio:"3/4", padding:18}}>
                <span className="kind">{p.kind}</span>
                <h3 style={{fontSize:18, margin:"12px 0 6px"}}>{p.title}</h3>
                <div className="pub-meta">{p.year} · {p.pages}pp</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <MailingList locale={locale} />
    </>
  );

  function openExhibition(id) { setRoute("exhibition:" + id); }
}

/* ---------- EXHIBITIONS ---------- */
function ExhibitionsPage({ locale, setRoute }) {
  const t = window.L[locale];
  const groups = [
    { state:"current", label: t.current, items: EX.filter(e=>e.state==="current") },
    { state:"upcoming", label: t.upcoming, items: EX.filter(e=>e.state==="upcoming") },
    { state:"past", label: t.past, items: EX.filter(e=>e.state==="past") },
  ];
  return (
    <section className="shell section" data-screen-label="02 Exhibitions">
      <div className="s-head">
        <div>
          <span className="eyebrow">{locale==="en"?"Programme":"البرنامج"}</span>
          <h2>{t.nav[0]}.</h2>
        </div>
      </div>
      {groups.map(g => (
        <div key={g.state} style={{marginBottom:72}}>
          <div style={{display:"flex", alignItems:"baseline", gap:14, marginBottom:24, borderBottom:"1px solid var(--hairline)", paddingBottom:10}}>
            <h3 style={{fontFamily:"var(--serif)", fontSize:24, fontWeight:400, margin:0}}>{g.label}</h3>
            <span style={{color:"var(--muted)", fontSize:13}}>{g.items.length}</span>
          </div>
          {g.items.length === 0
            ? <div style={{color:"var(--muted)", fontSize:14, padding:"24px 0"}}>{locale==="en"?"To be announced. Confirmed listings will appear here.":"سيُعلن قريباً. ستظهر القوائم المؤكدة هنا."}</div>
            : <div className="exh-grid">
                {g.items.map(e => (
                  <ExhibitionCard key={e.id} ex={e} locale={locale} onClick={() => setRoute("exhibition:" + e.id)} />
                ))}
              </div>}
        </div>
      ))}
    </section>
  );
}

/* ---------- Exhibition detail ---------- */
function ExhibitionDetailPage({ id, locale, setRoute, openEnquiryFor }) {
  const t = window.L[locale];
  const ex = EX.find(e => e.id === id);
  if (!ex) return null;
  const works = ex.works.map(wid => WK.find(w => w.id === wid)).filter(Boolean);
  const stateLabel = ex.state === "current" ? t.current : ex.state === "upcoming" ? t.upcoming : t.past;
  return (
    <section className="section" data-screen-label={`02 Exhibition — ${ex.title}`}>
      <div className="shell">
        <button className="btn-link" onClick={() => setRoute("exhibitions")}>← {locale==="en"?"All exhibitions":"كل المعارض"}</button>
        <div style={{marginTop:24}}>
          <span className="eyebrow">{stateLabel} — {ex.dates}</span>
          <h1 style={{fontFamily:"var(--serif)", fontWeight:400, fontSize:"clamp(36px,5vw,72px)", lineHeight:1.02, margin:"14px 0 8px"}}>
            {ex.title}
          </h1>
          <div style={{fontSize:18, color:"var(--muted)", marginBottom:32}}>{ex.artist}</div>
        </div>
      </div>
      <div className="shell-wide" style={{marginBottom:48}}>
        <div style={{aspectRatio:"16/9", background:"var(--surface-warm)", overflow:"hidden"}}>
          <img src={ex.cover} alt={ex.title} style={{width:"100%", height:"100%", objectFit:"cover"}} />
        </div>
      </div>
      <div className="shell">
        <div style={{display:"grid", gridTemplateColumns:"1fr 1.4fr", gap:48, marginBottom:64}} className="ex-detail-grid">
          <div>
            <span className="eyebrow">{locale==="en"?"Essay":"مقالة"}</span>
          </div>
          <div>
            <p style={{fontFamily:"var(--serif)", fontSize:"clamp(22px,2.4vw,28px)", lineHeight:1.35, margin:0, color:"var(--text)"}}>
              {ex.blurb}
            </p>
            <div style={{marginTop:32, display:"flex", gap:10, flexWrap:"wrap"}}>
              <button className="btn" onClick={() => openEnquiryFor({kind:"work", work:works[0]})}>{t.enquire}</button>
              <button className="btn btn-ghost" onClick={() => openEnquiryFor({kind:"viewing"})}>{t.requestViewing}</button>
              <button className="btn btn-ghost" onClick={() => openEnquiryFor({kind:"catalogue"})}>{t.requestCatalogue}</button>
            </div>
          </div>
        </div>

        {ex.install && ex.install.length > 0 && (
          <div style={{marginBottom:64}}>
            <span className="eyebrow">{locale==="en"?"Install views":"مشاهد التركيب"}</span>
            <div style={{display:"grid", gridTemplateColumns:"repeat(3, 1fr)", gap:14, marginTop:18}}>
              {ex.install.map((src, i) => (
                <div key={i} style={{aspectRatio:"4/3", background:"var(--surface-warm)", overflow:"hidden"}}>
                  <img src={src} alt={`Install view ${i+1}`} style={{width:"100%", height:"100%", objectFit:"cover"}} />
                </div>
              ))}
            </div>
            <div className="credit-line" style={{marginTop:10}}>
              {locale==="en"?"Install views — Ayyam Gallery, Alserkal Avenue.":"مشاهد التركيب — غاليري أيام، العسكر أفينيو."}
              <span className="copyright-flag">[Rights pending]</span>
            </div>
          </div>
        )}

        <div>
          <span className="eyebrow">{locale==="en"?"Works":"الأعمال"}</span>
          <h3 style={{fontFamily:"var(--serif)", fontWeight:400, fontSize:28, margin:"10px 0 24px"}}>{works.length} {locale==="en" ? (works.length===1?"work":"works") : "أعمال"}</h3>
          <div className="works-strip">
            {works.map(w => (
              <WorkCard key={w.id} work={w} locale={locale} onClick={() => openEnquiryFor({kind:"work", work:w})} />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- ARTISTS ---------- */
function ArtistsPage({ locale, openDossier }) {
  const t = window.L[locale];
  return (
    <section className="shell section" data-screen-label="03 Artists">
      <div className="s-head">
        <div>
          <span className="eyebrow">{locale==="en"?"Roster":"السجل"}</span>
          <h2>{t.nav[1]}.</h2>
        </div>
        <div className="s-action">
          <span className="smallcaps">{locale==="en"?"Gallery artists & artists exhibited":"فنانو الغاليري والفنانون الذين عُرضوا"}</span>
        </div>
      </div>

      <div className="artists-section">
        <div className="artists-h">
          <h3>{t.galleryArtists}</h3>
          <span className="count">{GA.length}</span>
          <span style={{flex:1}}></span>
          <span className="smallcaps">{locale==="en"?"Represented programme":"البرنامج المُمَثَّل"}</span>
        </div>
        <div className="artists-grid">
          {GA.map(name => <ArtistTile key={name} name={name} onClick={() => openDossier(name)} />)}
        </div>
      </div>

      <div className="artists-section" style={{marginTop:96}}>
        <div className="artists-h">
          <h3>{t.exhibitedArtists}</h3>
          <span className="count">{EA.length}</span>
          <span style={{flex:1}}></span>
          <span className="smallcaps">{locale==="en"?"Past exhibitions / projects":"معارض سابقة / مشاريع"}</span>
        </div>
        <div className="artists-grid">
          {EA.map(name => <ArtistTile key={name} name={name} onClick={() => openDossier(name)} />)}
        </div>
      </div>
    </section>
  );
}

/* ---------- PUBLICATIONS ---------- */
function PublicationsPage({ locale, openEnquiryFor }) {
  const t = window.L[locale];
  return (
    <section className="shell section" data-screen-label="04 Publications">
      <div className="s-head">
        <div>
          <span className="eyebrow">{locale==="en"?"A differentiator":"السمة المميزة"}</span>
          <h2>{t.nav[2]}.</h2>
        </div>
        <div className="s-action">
          <button className="btn btn-ghost" onClick={() => openEnquiryFor({kind:"catalogue"})}>{t.requestCatalogue}</button>
        </div>
      </div>

      <p style={{maxWidth:"68ch", fontSize:17, color:"var(--text)", marginBottom:48}}>
        {locale==="en"
          ? "The gallery has run an active publishing arm since 2007. Monographs, exhibition catalogues and essay collections are produced for artists in the programme and for the wider Middle Eastern scene — many under custodianship of an estate. Titles are available by request; selected publications ship internationally."
          : "يدير الغاليري ذراعاً نشطاً للنشر منذ عام 2007. تُنتَج كتب مخصّصة وكتالوغات معارض ومجموعات مقالات لفنانين من البرنامج ومن المشهد العربي الأوسع — كثير منها بإدارة عهدة الأرشيف الفني. الإصدارات متاحة عند الطلب."}
      </p>

      <div className="pubs">
        {PUB.map(p => (
          <div key={p.id} className="pub" onClick={() => openEnquiryFor({kind:"catalogue"})}>
            <div>
              <span className="kind">{p.kind}</span>
              <h3>{p.title}</h3>
              <div className="pub-meta">{p.year} · {p.pages}pp</div>
            </div>
            <div className="pub-foot">
              <span className="smallcaps">{p.notes.split(". ")[0]}.</span>
              <span className="btn-link">{locale==="en"?"Request":"اطلب"}</span>
            </div>
          </div>
        ))}
      </div>

      <div className="credit-line" style={{marginTop:36}}>
        {locale==="en"?"Cover images flagged for client supply. Production stewardship — Ayyam Gallery, Alserkal Avenue, Dubai.":"صور الأغلفة قيد الطلب من العميل. الإشراف على الإنتاج — غاليري أيام، العسكر أفينيو، دبي."}
      </div>
    </section>
  );
}

/* ---------- VIEWING ROOMS ---------- */
function ViewingRoomsPage({ locale, openEnquiryFor }) {
  const t = window.L[locale];
  const rooms = [
    { id:"dahoul", title: locale==="en"?"Safwan Dahoul — The Dream Cycle":"صفوان داحول — سلسلة الحلم", img: "media/artwork-safwan-dahoul-dream184.webp", count:6, blurb: locale==="en"?"A private selection of recent and historic Dream paintings, available for placement under POA. Includes the current exhibition's Dream 284.":"مجموعة خاصة من أعمال «حلم» الحديثة والتاريخية، متاحة للحجز بالسعر عند الطلب." },
    { id:"abstraction", title: locale==="en"?"Geometries — Halaby, Murad, Kaaf":"هندسات — حلبي، مراد، كعّاف", img:"media/artwork-samia-halaby-milk.webp", count:9, blurb: locale==="en"?"A reading of geometric abstraction across three of the gallery's longest-held painters.":"قراءة في التجريد الهندسي عبر ثلاثة من أطول رسامي الغاليري حضوراً." },
    { id:"paper", title: locale==="en"?"Paper / Place — Tammam Azzam":"ورق / مكان — تمّام عزّام", img:"media/artwork-tammam-azzam-place-paper.webp", count:5, blurb: locale==="en"?"A focused viewing room on Azzam's collaged cities — a preview of the autumn exhibition.":"غرفة عرض مركّزة على مدن عزّام المُكَوَّلَجَة — معاينة لمعرض الخريف." },
    { id:"figures", title: locale==="en"?"On the Figure":"عن الجسد", img:"media/artwork-sadik-alfraji-soaring-body.webp", count:7, blurb: locale==="en"?"Alfraji, Jaber, Salman, Pirhashemi — a survey of the figure across painting and ink.":"الفرجي، جبر، سلمان، بير هاشمي — استعراض للجسد في الرسم والحبر." }
  ];
  return (
    <section className="shell section" data-screen-label="05 Viewing rooms">
      <div className="s-head">
        <div>
          <span className="eyebrow">{locale==="en"?"By appointment":"بموعد مسبق"}</span>
          <h2>{t.nav[3]}.</h2>
        </div>
        <div className="s-action">
          <button className="btn btn-ghost" onClick={() => openEnquiryFor({kind:"viewing"})}>{t.requestViewing}</button>
        </div>
      </div>

      <p style={{maxWidth:"68ch", fontSize:17, marginBottom:40}}>
        {locale==="en"
          ? "Curated online viewing rooms group available works by theme. All works are priced on application; private viewings can be arranged at B11, Alserkal Avenue, or by appointment in your city."
          : "غرف العرض الإلكترونية تُجمع الأعمال المتاحة حسب الموضوع. جميع الأسعار عند الطلب؛ يمكن ترتيب جلسات خاصة في B11 العسكر أفينيو، أو في مدينتك بموعد مسبق."}
      </p>

      <div className="vr-grid">
        {rooms.map(r => (
          <div key={r.id} className="vr">
            <div className="vr-img"><img src={r.img} alt={r.title} /></div>
            <span className="poa-line">{r.count} {locale==="en"?"works · POA":"أعمال · السعر عند الطلب"}</span>
            <h3>{r.title}</h3>
            <p style={{color:"var(--muted)", fontSize:14, margin:"4px 0 18px"}}>{r.blurb}</p>
            <div style={{display:"flex", gap:10, flexWrap:"wrap"}}>
              <button className="btn" onClick={() => openEnquiryFor({kind:"viewing"})}>{t.requestViewing}</button>
              <button className="btn-link" onClick={() => openEnquiryFor({kind:"catalogue"})}>{locale==="en"?"Request PDF":"اطلب ملف PDF"}</button>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------- ART FAIRS ---------- */
function FairsPage({ locale, openEnquiryFor }) {
  const t = window.L[locale];
  return (
    <section className="shell section" data-screen-label="06 Art fairs">
      <div className="s-head">
        <div>
          <span className="eyebrow">{locale==="en"?"International programme":"البرنامج الدولي"}</span>
          <h2>{t.nav[4]}.</h2>
        </div>
        <div className="s-action">
          <button className="btn btn-ghost" onClick={() => openEnquiryFor({kind:"general"})}>{t.enquire}</button>
        </div>
      </div>

      <div>
        {FR.map(f => (
          <div key={f.id} className="fair">
            <div>
              <span className={"state-tag " + (f.state || "")}>{f.state === "upcoming" ? t.upcoming : t.past}</span>
              <div className="f-name" style={{marginTop:8}}>{f.name}</div>
              <div className="f-meta">{f.dates}</div>
              {f.booth && f.booth !== "—" && <div className="f-meta" style={{marginTop:4, color:"var(--accent-ink)"}}>{f.booth}</div>}
            </div>
            <div className="f-art">
              {f.artists.length > 0
                ? (locale==="en"?"With ":"مع: ") + f.artists.join(" · ")
                : (locale==="en" ? "Programme to be announced." : "البرنامج سيُعلن قريباً.")}
            </div>
            <div style={{textAlign:"end"}}>
              <button className="btn-link" onClick={() => openEnquiryFor({kind:"general"})}>{locale==="en"?"Press / works list":"الصحافة / قائمة الأعمال"}</button>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------- PRESS ---------- */
function PressPage({ locale }) {
  const t = window.L[locale];
  return (
    <section className="shell section" data-screen-label="07 Press">
      <div className="s-head">
        <div>
          <span className="eyebrow">{locale==="en"?"Selected references":"مراجع مختارة"}</span>
          <h2>{t.nav[5]}.</h2>
        </div>
      </div>

      <p style={{maxWidth:"68ch", fontSize:15, color:"var(--muted)", marginBottom:32}}>
        {locale==="en"
          ? "Institutional reach below is attributed as the gallery's own About claim, not an independent endorsement. The live Selected Press archive (articles + assets) will be supplied by the gallery."
          : "تُنسب المراجع المؤسسية أدناه إلى نصّ «حول» الخاص بالغاليري، وليست تأييداً مستقلاً. سيُزوَّد أرشيف الصحافة المختارة (المقالات والأصول) من قِبَل الغاليري."}
      </p>

      <div className="press-list">
        {PR.map(p => (
          <div key={p.id} className="press-row">
            <div className="outlet">{p.outlet}</div>
            <div className="note">{p.note}</div>
            <div className="year">{p.year}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------- ABOUT ---------- */
function AboutPage({ locale, setRoute }) {
  const t = window.L[locale];
  return (
    <section className="shell section" data-screen-label="08 About">
      <div className="s-head">
        <div>
          <span className="eyebrow">{locale==="en"?"The story":"الحكاية"}</span>
          <h2>{t.nav[6]}.</h2>
        </div>
      </div>

      <div className="about-grid">
        <div>
          <h3>
            {locale==="en"
              ? <>Damascus, 2006 →<br/><em style={{color:"var(--accent-ink)"}}>Dubai, today.</em></>
              : <>دمشق 2006 →<br/><em style={{color:"var(--accent-ink)"}}>دبي اليوم.</em></>}
          </h3>
        </div>
        <div>
          <p>{locale==="en"
            ? <>Ayyam Gallery was founded in Damascus in 2006 by <b>Khaled and Jouhayna Samawi</b> at a moment when Syrian and broader Middle Eastern contemporary art was building its first sustained international audiences.</>
            : <>تأسس غاليري أيام في دمشق عام 2006 على يد <b>خالد وجوهينا سماوي</b> في لحظة كان فيها الفن السوري والشرق أوسطي المعاصر يبني جمهوره الدولي الأول.</>}</p>
          <p>{locale==="en"
            ? <>After expansions to and from London, Jeddah, DIFC and Beirut, the gallery's permanent home is now <b>B11 at Alserkal Avenue, Dubai</b>. Those past spaces remain part of the gallery's story; they are not current public venues.</>
            : "بعد توسعات شملت لندن وجدّة ومركز دبي المالي العالمي وبيروت، أصبح المقر الدائم الآن B11 في العسكر أفينيو، دبي. تظل تلك المواقع السابقة جزءاً من حكاية الغاليري، لا مساحات عامة حالية."}</p>
          <p>{locale==="en"
            ? "Alongside its commercial programme the gallery runs Shabab Ayyam, an emerging-artist platform; a publishing arm; custodianship and estates work; education and charity-auction activity. Its About text cites placements and loans with institutions including Institut du Monde Arabe, LACMA, Centre Pompidou and The British Museum — attributed as the gallery's own claim."
            : "إلى جانب البرنامج التجاري، يدير الغاليري «شباب أيام» منصة الفنانين الناشئين، وذراع نشر، وعمل عهدة وأرشيف، ونشاطات تعليمية ومزادات خيرية."}</p>
        </div>
      </div>

      <div className="about-pillars">
        {[
          {h: locale==="en"?"Shabab Ayyam":"شباب أيام", p: locale==="en"?"An emerging-artist platform supporting first solo shows, commissions and studio support.":"منصة تدعم الفنانين الناشئين بمعارضهم الفردية الأولى والإقامات الفنية."},
          {h: locale==="en"?"Custodianship":"العهدة الفنية", p: locale==="en"?"Long-term stewardship of selected estates, archives and unpublished work.":"إشراف طويل الأمد على عهد فنية مختارة وأرشيفاتها وأعمالها غير المنشورة."},
          {h: locale==="en"?"Publishing":"النشر", p: locale==="en"?"Monographs, catalogues and essay collections produced in-house since 2007.":"كتب مخصصة وكتالوغات ومقالات تُنتج داخل الغاليري منذ 2007."},
          {h: locale==="en"?"Education / charity":"التعليم والمزادات الخيرية", p: locale==="en"?"Charity auctions and education partnerships across the region.":"مزادات خيرية وشراكات تعليمية في المنطقة."}
        ].map((c, i) => (
          <div className="pillar" key={i}>
            <h4>{c.h}</h4>
            <p>{c.p}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------- VISIT ---------- */
function VisitPage({ locale, openEnquiryFor }) {
  const t = window.L[locale];
  return (
    <section className="shell section" data-screen-label="09 Visit">
      <div className="s-head">
        <div>
          <span className="eyebrow">{locale==="en"?"Alserkal Avenue · Dubai":"العسكر أفينيو · دبي"}</span>
          <h2>{t.nav[7]}.</h2>
        </div>
        <div className="s-action">
          <button className="btn" onClick={() => openEnquiryFor({kind:"general"})}>{t.enquire}</button>
        </div>
      </div>

      <div className="visit-grid">
        <div className="visit-info">
          <dl>
            <dt>{t.address}</dt>
            <dd>B11, Alserkal Avenue<br/>Street 8, Al Quoz Industrial 1<br/>Dubai, U.A.E. — P.O. Box 283174</dd>
            <dt>{t.hours}</dt>
            <dd>{locale==="en"?<>Mon–Fri · 10:00–19:00<br/>Sat · 12:00–18:00<br/>Sun · Closed</>:<>الإثنين–الجمعة · 10:00–19:00<br/>السبت · 12:00–18:00<br/>الأحد · مغلق</>}</dd>
            <dt>{t.contact}</dt>
            <dd>
              <a href="tel:+97143236242" className="btn-link" style={{borderBottomColor:"var(--hairline)"}}>+971 4 323 6242</a><br/>
              <a href="mailto:info@ayyamgallery.com" className="btn-link" style={{borderBottomColor:"var(--hairline)"}}>info@ayyamgallery.com</a>
              <div style={{fontSize:12, color:"var(--muted)", marginTop:6}}>{locale==="en"?"Fax · +971 4 323 6243":"فاكس · +971 4 323 6243"}</div>
            </dd>
            <dt>{locale==="en"?"Getting here":"كيفية الوصول"}</dt>
            <dd style={{fontSize:14.5, color:"var(--muted)"}}>
              {locale==="en"
                ? "Alserkal Avenue is a 15-minute drive from Dubai Marina and 25 minutes from DXB. The nearest metro is Noor Bank (red line). Paid parking on Street 8."
                : "العسكر أفينيو على بُعد 15 دقيقة من دبي مارينا و25 دقيقة من مطار دبي. أقرب محطة مترو: نور بنك (الخط الأحمر). موقف سيارات مدفوع في الشارع 8."}
            </dd>
          </dl>
        </div>
        <div>
          <div className="visit-map">
            <div className="grid-lines"></div>
            <div className="pin" aria-hidden="true"></div>
            <div className="label">
              <b style={{fontWeight:500}}>Ayyam Gallery — B11</b><br/>
              <span style={{color:"var(--muted)", fontSize:11.5}}>25.1414665, 55.2262893</span><br/>
              <a className="btn-link" style={{marginTop:6, display:"inline-block"}}
                 href={`https://www.google.com/maps/place/Ayyam+Gallery/@25.1414665,55.2262893,17z`}
                 target="_blank" rel="noreferrer">{locale==="en"?"Open in Google Maps":"افتح في خرائط جوجل"} ↗</a>
            </div>
          </div>
          <div className="credit-line" style={{marginTop:10}}>
            {locale==="en"?"Schematic map. Geo verified to official Google Place link.":"خريطة تخطيطية. الإحداثيات مأخوذة من رابط Google Place الرسمي."}
          </div>
        </div>
      </div>

      <MailingList locale={locale} />
    </section>
  );
}

Object.assign(window, {
  HomePage, ExhibitionsPage, ExhibitionDetailPage, ArtistsPage,
  PublicationsPage, ViewingRoomsPage, FairsPage, PressPage, AboutPage, VisitPage
});

/* ====================== APP SHELL ====================== */
function App() {
  const T = window.AYYAM_TWEAKS;
  const tweaks = window.useTweaks(T);
  const t = tweaks[0];
  const setTweak = tweaks[1];

  const [route, setRoute] = uS("home");
  const [dossierArtist, setDossierArtist] = uS(null);
  const [enquiry, setEnquiry] = uS({ open:false, kind:"general", work:null });

  const locale = t.locale || "en";
  const accent = t.accent || "#9A6A3C";
  const density = t.density || "comfortable";

  // Apply tweaks to root
  uE(() => {
    document.documentElement.style.setProperty("--accent", accent);
    document.documentElement.style.setProperty("--accent-ink", shade(accent, -0.18));
    document.documentElement.style.setProperty("--focus", accent);
    document.documentElement.style.setProperty("--pad-y",
      density === "tight" ? "clamp(40px, 5vw, 80px)" :
      density === "airy"  ? "clamp(96px, 11vw, 160px)" :
      "clamp(64px, 8vw, 120px)");
    document.documentElement.lang = locale;
    document.documentElement.dir = locale === "ar" ? "rtl" : "ltr";
  }, [accent, density, locale]);

  // Scroll top on route change
  uE(() => { window.scrollTo({top:0, behavior:"instant"}); }, [route]);

  function openDossier(name) { setDossierArtist(name); }
  function openEnquiryFor({ kind, work }) { setEnquiry({ open:true, kind: kind||"general", work: work||null }); }
  function closeEnquiry() { setEnquiry(e => ({ ...e, open:false })); }

  // Routes
  let page = null;
  if (route === "home") page = <HomePage locale={locale} setRoute={setRoute} openEnquiryFor={openEnquiryFor} openDossier={openDossier} />;
  else if (route === "exhibitions") page = <ExhibitionsPage locale={locale} setRoute={setRoute} />;
  else if (route.startsWith("exhibition:")) page = <ExhibitionDetailPage id={route.split(":")[1]} locale={locale} setRoute={setRoute} openEnquiryFor={openEnquiryFor} />;
  else if (route === "artists") page = <ArtistsPage locale={locale} openDossier={openDossier} />;
  else if (route === "publications") page = <PublicationsPage locale={locale} openEnquiryFor={openEnquiryFor} />;
  else if (route === "viewing-rooms") page = <ViewingRoomsPage locale={locale} openEnquiryFor={openEnquiryFor} />;
  else if (route === "art-fairs") page = <FairsPage locale={locale} openEnquiryFor={openEnquiryFor} />;
  else if (route === "press") page = <PressPage locale={locale} />;
  else if (route === "about") page = <AboutPage locale={locale} setRoute={setRoute} />;
  else if (route === "visit") page = <VisitPage locale={locale} openEnquiryFor={openEnquiryFor} />;

  return (
    <>
      <Navbar route={route.split(":")[0]} setRoute={setRoute} locale={locale}
        setLocale={(v)=>setTweak("locale", v)}
        openEnquiry={() => openEnquiryFor({kind:"general"})} />

      <main>{page}</main>

      <Footer locale={locale} setRoute={setRoute} />

      <Dossier artistName={dossierArtist} onClose={() => setDossierArtist(null)} locale={locale} openEnquiryFor={openEnquiryFor} />
      <EnquiryModal open={enquiry.open} onClose={closeEnquiry} work={enquiry.work} locale={locale} kind={enquiry.kind} />

      <TweaksPanelHost tweaks={t} setTweak={setTweak} />
    </>
  );
}

/* ---------- Tweaks Panel ---------- */
function TweaksPanelHost({ tweaks, setTweak }) {
  return (
    <window.TweaksPanel title="Tweaks">
      <window.TweakSection label="Language">
        <window.TweakRadio value={tweaks.locale} onChange={(v)=>setTweak("locale", v)}
          options={[{value:"en", label:"EN"},{value:"ar", label:"عربي (RTL)"}]} />
      </window.TweakSection>

      <window.TweakSection label="Accent color">
        <window.TweakColor value={tweaks.accent} onChange={(v)=>setTweak("accent", v)}
          options={["#9A6A3C", "#16140F", "#2E4D3F", "#6E3A3A"]} />
        <div style={{fontSize:11, color:"var(--muted)", marginTop:6, letterSpacing:".02em"}}>
          Restrained bronze (default) · pure ink · forest · oxblood.
        </div>
      </window.TweakSection>

      <window.TweakSection label="Density">
        <window.TweakRadio value={tweaks.density} onChange={(v)=>setTweak("density", v)}
          options={[{value:"tight", label:"Tight"},{value:"comfortable", label:"Comfy"},{value:"airy", label:"Airy"}]} />
      </window.TweakSection>
    </window.TweaksPanel>
  );
}

/* ---------- helpers ---------- */
function shade(hex, amt) {
  // mix toward black (amt<0) or white (amt>0)
  const n = hex.replace("#","");
  const r = parseInt(n.substring(0,2),16), g = parseInt(n.substring(2,4),16), b = parseInt(n.substring(4,6),16);
  const adj = (c) => Math.round(amt < 0 ? c*(1+amt) : c + (255-c)*amt);
  return "#" + [adj(r),adj(g),adj(b)].map(v=>Math.max(0,Math.min(255,v)).toString(16).padStart(2,"0")).join("");
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
