/* Ayyam Gallery — shared components (nav, footer, cards, modal, dossier). */
const { useState, useEffect, useMemo, useRef } = React;
const _CMP_DATA = window.AYYAM_DATA;
const _GALLERY_ARTISTS = _CMP_DATA.GALLERY_ARTISTS;
const _EXHIBITED_ARTISTS = _CMP_DATA.EXHIBITED_ARTISTS;
const _WORKS = _CMP_DATA.WORKS;
const _ARTIST_BIOS = _CMP_DATA.ARTIST_BIOS;

/* ---------- Localized labels ---------- */
const L = {
  en: {
    brand: "Ayyam Gallery",
    sub: "Alserkal Avenue · Dubai",
    nav: ["Exhibitions","Artists","Publications","Viewing Rooms","Art Fairs","Press","About","Visit"],
    routes: ["exhibitions","artists","publications","viewing-rooms","art-fairs","press","about","visit"],
    enquire: "Enquire — POA",
    requestViewing: "Request a viewing",
    requestCatalogue: "Request catalogue",
    visit: "Plan your visit",
    mailing: "Join the mailing list",
    mailingNote: "Monthly notes on new exhibitions, publications and viewing rooms. No prices, no marketing — gallery correspondence only.",
    mailingPlaceholder: "Your email",
    subscribe: "Subscribe",
    close: "Close",
    enquireTitle: "Enquire — Price on application",
    enquireSub: "We respond by email within two working days. Enquiries are handled discreetly by the gallery's collections desk.",
    msgPlaceholder: "Anything you'd like us to know — installation, framing, collection context.",
    submit: "Send enquiry",
    sent: "Thank you — the collections desk will be in touch.",
    name: "Name",
    email: "Email",
    message: "Message",
    rightsPending: "Rights pending",
    galleryArtists: "Gallery artists",
    exhibitedArtists: "Artists exhibited",
    current: "Current",
    upcoming: "Upcoming",
    past: "Past",
    workOnView: "On view",
    by: "by",
    address: "Address",
    hours: "Hours",
    contact: "Contact",
    socials: "Find us",
    backToArtists: "All artists",
    sinceLine: "Founded Damascus, 2006",
  },
  ar: {
    brand: "غاليري أيام",
    sub: "العسكر أفينيو · دبي",
    nav: ["المعارض","الفنانون","المنشورات","غرف العرض","المعارض الفنية","الصحافة","حول","الزيارة"],
    routes: ["exhibitions","artists","publications","viewing-rooms","art-fairs","press","about","visit"],
    enquire: "استفسر — السعر عند الطلب",
    requestViewing: "طلب مشاهدة خاصة",
    requestCatalogue: "طلب الكتالوج",
    visit: "خطّط لزيارتك",
    mailing: "اشترك في القائمة البريدية",
    mailingNote: "ملاحظات شهرية عن المعارض الجديدة والمنشورات وغرف العرض. مراسلات الغاليري فقط — لا أسعار ولا تسويق.",
    mailingPlaceholder: "بريدك الإلكتروني",
    subscribe: "اشتراك",
    close: "إغلاق",
    enquireTitle: "استفسار — السعر عند الطلب",
    enquireSub: "نرد بالبريد الإلكتروني خلال يومي عمل. تُعالَج الاستفسارات بسرية تامة من قبل مكتب المقتنيات.",
    msgPlaceholder: "أي تفاصيل ترغب بإطلاعنا عليها — التركيب، التأطير، سياق المجموعة.",
    submit: "إرسال الاستفسار",
    sent: "شكراً — سيتواصل معك مكتب المقتنيات قريباً.",
    name: "الاسم",
    email: "البريد الإلكتروني",
    message: "الرسالة",
    rightsPending: "حقوق قيد التأكيد",
    galleryArtists: "فنانو الغاليري",
    exhibitedArtists: "فنانون عرضوا أعمالهم",
    current: "حالي",
    upcoming: "قادم",
    past: "سابق",
    workOnView: "معروض",
    by: "للفنان",
    address: "العنوان",
    hours: "أوقات الزيارة",
    contact: "للتواصل",
    socials: "تابعونا",
    backToArtists: "كل الفنانين",
    sinceLine: "تأسست في دمشق، 2006",
  }
};

/* ---------- Credit line ---------- */
function CreditLine({ work, compact }) {
  return (
    <div className="credit-line">
      <b style={{color:"var(--text)", fontWeight:500}}>{work.artist}</b>,{" "}
      <em style={{fontStyle:"italic"}}>{work.title}</em>, {work.year}.<br/>
      {work.medium}, {work.dims}.{" "}
      {!compact && <>© the artist. Courtesy Ayyam Gallery.</>}
      <span className="copyright-flag">{compact ? "© rights pending" : "[Rights pending]"}</span>
    </div>
  );
}

/* ---------- Nav ---------- */
function Navbar({ route, setRoute, locale, setLocale, openEnquiry }) {
  const t = L[locale];
  return (
    <header className="topbar">
      <div className="shell-wide topbar-inner">
        <button onClick={() => setRoute("home")} className="brand" style={{textAlign: locale==="ar"?"right":"left"}}>
          <span className="aperture"></span>
          {t.brand}
          <small>{t.sub}</small>
        </button>
        <nav className="nav" aria-label="Primary">
          {t.nav.map((label, i) => (
            <button key={i}
              className={route === t.routes[i] ? "active" : ""}
              onClick={() => setRoute(t.routes[i])}>
              {label}
            </button>
          ))}
        </nav>
        <div className="nav-right">
          <div className="locale-toggle" role="tablist" aria-label="Language">
            <button className={locale==="en"?"active":""} onClick={() => setLocale("en")}>EN</button>
            <button className={locale==="ar"?"active":""} onClick={() => setLocale("ar")}>عربي</button>
          </div>
          <button className="btn btn-ghost" style={{padding:"8px 16px", fontSize:12}} onClick={openEnquiry}>
            {t.enquire}
          </button>
        </div>
      </div>
    </header>
  );
}

/* ---------- Footer ---------- */
function Footer({ locale, setRoute }) {
  const t = L[locale];
  return (
    <footer className="site">
      <div className="shell-wide foot-grid">
        <div>
          <div className="brand" style={{fontFamily:"var(--serif)", fontSize:24}}>
            <span className="aperture"></span> {t.brand}
          </div>
          <p style={{maxWidth:"42ch", color:"var(--muted)", marginTop:12, fontSize:13.5, lineHeight:1.55}}>
            {locale==="en"
              ? "A contemporary art gallery championing modern and contemporary Middle Eastern art. Founded Damascus, 2006. Permanent home — Alserkal Avenue, Dubai."
              : "غاليري للفن المعاصر يحتفي بالفن العربي والشرق أوسطي الحديث والمعاصر. تأسس في دمشق عام 2006. المقر الدائم — العسكر أفينيو، دبي."}
          </p>
        </div>
        <div>
          <h5>{locale==="en"?"Programme":"البرنامج"}</h5>
          <ul>
            <li><button onClick={() => setRoute("exhibitions")}>{t.nav[0]}</button></li>
            <li><button onClick={() => setRoute("artists")}>{t.nav[1]}</button></li>
            <li><button onClick={() => setRoute("publications")}>{t.nav[2]}</button></li>
            <li><button onClick={() => setRoute("viewing-rooms")}>{t.nav[3]}</button></li>
            <li><button onClick={() => setRoute("art-fairs")}>{t.nav[4]}</button></li>
          </ul>
        </div>
        <div>
          <h5>{locale==="en"?"Visit":"الزيارة"}</h5>
          <ul>
            <li>B11, Alserkal Avenue</li>
            <li>Street 8, Al Quoz Industrial 1</li>
            <li>Dubai, U.A.E.</li>
            <li style={{marginTop:8}}>Mon–Fri 10:00–19:00</li>
            <li>Sat 12:00–18:00</li>
          </ul>
        </div>
        <div>
          <h5>{t.socials}</h5>
          <ul>
            <li><a href="https://www.instagram.com/ayyamgallery/" target="_blank" rel="noreferrer">Instagram</a></li>
            <li><a href="https://www.facebook.com/AyyamGallery" target="_blank" rel="noreferrer">Facebook</a></li>
            <li><a href="https://www.artsy.net/partner/ayyam-gallery" target="_blank" rel="noreferrer">Artsy</a></li>
            <li><a href="https://ocula.com/art-galleries/ayyam-gallery/" target="_blank" rel="noreferrer">Ocula</a></li>
            <li><a href="https://vimeo.com/user15084622" target="_blank" rel="noreferrer">Vimeo</a></li>
            <li style={{marginTop:8}}><a href="mailto:info@ayyamgallery.com">info@ayyamgallery.com</a></li>
            <li><a href="tel:+97143236242">+971 4 323 6242</a></li>
          </ul>
        </div>
      </div>
      <div className="shell-wide foot-bottom">
        <span>© Ayyam Gallery. {locale==="en"?"All artworks reproduced courtesy of the artists; rights pending where flagged.":"جميع الأعمال الفنية مستنسخة بترخيص من الفنانين؛ الحقوق قيد التأكيد عند الإشارة إلى ذلك."}</span>
        <span>{t.sinceLine}</span>
      </div>
    </footer>
  );
}

/* ---------- Mailing list block ---------- */
function MailingList({ locale }) {
  const t = L[locale];
  const [submitted, setSubmitted] = useState(false);
  return (
    <section className="shell" style={{paddingBlock:"clamp(60px,7vw,100px)"}}>
      <div className="mailing">
        <div>
          <h3>{locale==="en"
            ? <>Notes from the gallery, <em style={{fontStyle:"italic", color:"var(--accent)"}}>once a month.</em></>
            : t.mailing}</h3>
          <p>{t.mailingNote}</p>
        </div>
        <form onSubmit={(e)=>{e.preventDefault(); setSubmitted(true);}}>
          {submitted
            ? <div style={{fontSize:15, color:"var(--bg)"}}>{t.sent}</div>
            : <>
                <input type="email" required placeholder={t.mailingPlaceholder} aria-label={t.email} />
                <button type="submit">{t.subscribe}</button>
              </>}
        </form>
      </div>
    </section>
  );
}

/* ---------- Work card ---------- */
function WorkCard({ work, onClick, locale }) {
  const t = L[locale];
  return (
    <button className="work-card" onClick={onClick} aria-label={`${work.title}, ${work.artist}`}>
      <div className="img"><img src={work.src} alt={`${work.title} by ${work.artist}`} loading="lazy" /></div>
      <div className="caption">
        <b>{work.artist}</b><br/>
        <em style={{fontStyle:"italic"}}>{work.title}</em>, {work.year}<br/>
        {work.medium} · {work.dims}<br/>
        <span className="poa">{t.enquire}</span>
      </div>
    </button>
  );
}

/* ---------- Exhibition card ---------- */
function ExhibitionCard({ ex, onClick, locale }) {
  const t = L[locale];
  const stateLabel = ex.state === "current" ? t.current : ex.state === "upcoming" ? t.upcoming : t.past;
  return (
    <button className="exh-card" onClick={onClick}>
      <div className="img">
        <span className={`state ${ex.state}`}>{stateLabel}</span>
        <img src={ex.cover} alt={ex.title} loading="lazy" />
      </div>
      <h3>{ex.title}</h3>
      <div className="meta">
        <span>{ex.artist}</span>
        <span>{ex.dates}</span>
      </div>
    </button>
  );
}

/* ---------- Artist tile ---------- */
const PORTRAITS = {
  "Tammam Azzam":"media/artist-tammam-azzam-portrait.webp",
  "Khaled Takreti":"media/artist-khaled-takreti-portrait.webp",
  "Nihad al-Turk":"media/artist-nihad-al-turk-portrait.webp"
};
function pickWorkFor(name) {
  return _WORKS.find(w => w.artist === name);
}
function ArtistTile({ name, onClick }) {
  const portrait = PORTRAITS[name];
  const work = pickWorkFor(name);
  const initial = name.split(" ").map(s=>s[0]).slice(0,2).join("");
  return (
    <button className="artist-tile" onClick={onClick}>
      <div className={"a-img " + (!portrait && !work ? "placeholder" : "")}>
        {portrait ? <img src={portrait} alt={name} loading="lazy" />
          : work ? <img src={work.src} alt={`Work by ${name}`} loading="lazy" />
          : <span>{initial}</span>}
      </div>
      <h4>{name}</h4>
      <div className="a-meta">{_ARTIST_BIOS[name] ? _ARTIST_BIOS[name].split(". ")[0] : "Biography on request"}</div>
    </button>
  );
}

/* ---------- Enquiry modal ---------- */
function EnquiryModal({ open, onClose, work, locale, kind }) {
  const t = L[locale];
  const [sent, setSent] = useState(false);
  useEffect(() => { if (open) setSent(false); }, [open, work]);
  if (!open) return null;
  const titleByKind = {
    work: t.enquireTitle,
    viewing: locale==="en" ? "Request a private viewing" : "طلب مشاهدة خاصة",
    catalogue: locale==="en" ? "Request a catalogue / publication" : "طلب كتالوج أو منشور",
    general: locale==="en" ? "Enquire — Ayyam Gallery" : "استفسر — غاليري أيام"
  };
  return (
    <div className="modal" role="dialog" aria-modal="true">
      <div className="modal-bg" onClick={onClose}></div>
      <div className="modal-card">
        <h3>{titleByKind[kind] || t.enquireTitle}</h3>
        <div className="modal-sub">{t.enquireSub}</div>
        {work && (
          <div className="credit-block">
            <CreditLine work={work} />
          </div>
        )}
        {sent ? (
          <div style={{padding:"20px 0", fontSize:15}}>{t.sent}</div>
        ) : (
          <form onSubmit={(e)=>{e.preventDefault(); setSent(true);}}>
            <div className="field">
              <label>{t.name}</label>
              <input required type="text" />
            </div>
            <div className="field">
              <label>{t.email}</label>
              <input required type="email" />
            </div>
            <div className="field">
              <label>{t.message}</label>
              <textarea rows="4" placeholder={t.msgPlaceholder}></textarea>
            </div>
            <div className="actions">
              <button type="button" className="btn btn-quiet" onClick={onClose}>{t.close}</button>
              <button type="submit" className="btn">{t.submit}</button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

/* ---------- Artist dossier overlay ---------- */
function Dossier({ artistName, onClose, locale, openEnquiryFor }) {
  const t = L[locale];
  if (!artistName) return null;
  const works = _WORKS.filter(w => w.artist === artistName);
  const portrait = PORTRAITS[artistName];
  const bio = _ARTIST_BIOS[artistName] || (locale==="en"
    ? "Full biography and CV available on request via info@ayyamgallery.com."
    : "السيرة الذاتية الكاملة متاحة عند الطلب عبر info@ayyamgallery.com.");
  const isGallery = _GALLERY_ARTISTS.includes(artistName);
  return (
    <div className="overlay" onClick={(e)=>{ if(e.target.classList.contains("overlay")) onClose(); }}>
      <aside className="overlay-panel" role="dialog" aria-modal="true" aria-label={`${artistName} dossier`}>
        <div className="overlay-head">
          <button className="overlay-close" onClick={onClose}>← {t.backToArtists}</button>
          <span className="smallcaps">{isGallery ? t.galleryArtists : t.exhibitedArtists}</span>
        </div>
        <div className="overlay-body">
          <div className="dossier-hero">
            <div>
              <span className="flag">{isGallery ? t.galleryArtists : t.exhibitedArtists}</span>
              <h2>{artistName}</h2>
              <p className="bio" style={{marginTop:18}}>{bio}</p>
              <div style={{marginTop:24, display:"flex", gap:10, flexWrap:"wrap"}}>
                <button className="btn" onClick={() => openEnquiryFor({kind:"general"})}>{t.enquire}</button>
                <button className="btn btn-ghost" onClick={() => openEnquiryFor({kind:"viewing"})}>{t.requestViewing}</button>
              </div>
            </div>
            <div>
              {portrait
                ? <img src={portrait} alt={artistName} style={{aspectRatio:"4/5", objectFit:"cover", width:"100%"}} />
                : works[0]
                  ? <img src={works[0].src} alt={`Work by ${artistName}`} style={{aspectRatio:"4/5", objectFit:"cover", width:"100%"}} />
                  : <div style={{aspectRatio:"4/5", background:"var(--surface-warm)"}}></div>}
            </div>
          </div>

          {works.length > 0 && (
            <section style={{marginTop:48}}>
              <div className="s-head" style={{marginBottom:24}}>
                <div>
                  <span className="eyebrow">{locale==="en"?"Selected works":"أعمال مختارة"}</span>
                  <h2 style={{fontSize:32}}>{works.length} {works.length===1 ? (locale==="en"?"work":"عمل") : (locale==="en"?"works":"أعمال")}</h2>
                </div>
              </div>
              <div className="works-strip">
                {works.map(w => (
                  <WorkCard key={w.id} work={w} locale={locale}
                    onClick={() => openEnquiryFor({kind:"work", work:w})} />
                ))}
              </div>
            </section>
          )}

          <section style={{marginTop:64, paddingTop:32, borderTop:"1px solid var(--hairline)"}}>
            <span className="eyebrow">{locale==="en"?"Available on request":"متاح عند الطلب"}</span>
            <ul style={{listStyle:"none", padding:0, marginTop:14, fontSize:14.5, color:"var(--muted)", display:"grid", gap:8}}>
              <li>· {locale==="en"?"Full biography and CV":"السيرة الذاتية الكاملة"}</li>
              <li>· {locale==="en"?"Exhibition history":"سجل المعارض"}</li>
              <li>· {locale==="en"?"Selected press":"مختارات الصحافة"}</li>
              <li>· {locale==="en"?"Publications":"المنشورات"}</li>
              <li>· {locale==="en"?"Available works (POA)":"الأعمال المتاحة (السعر عند الطلب)"}</li>
            </ul>
          </section>
        </div>
      </aside>
    </div>
  );
}

Object.assign(window, {
  Navbar, Footer, MailingList, WorkCard, ExhibitionCard, ArtistTile, EnquiryModal, Dossier, CreditLine,
  L, PORTRAITS
});
