/* global React, ReactDOM, SK_DATA */
const { useState, useEffect, useMemo, useRef } = React;

/* ---------- shared utilities ---------- */
const formatAED = (n) =>
  "AED " + Number(n).toLocaleString("en-AE", { minimumFractionDigits: 0, maximumFractionDigits: 0 });

const PriceTag = ({ price, big }) => {
  if (!price || price === 0) {
    return <span className={"price req" + (big ? "" : "")}>On request</span>;
  }
  return <span className={"price" + (big ? " v" : "")}>{formatAED(price)}</span>;
};

const Wordmark = ({ small }) => (
  <span className={"wordmark" + (small ? " wordmark-small" : "")}>
    Saiid<span className="amp">&nbsp;&nbsp;</span>Kobeisy
  </span>
);

const Eyebrow = ({ children, gold }) => (
  <div className={"eyebrow" + (gold ? " gold" : "")}>{children}</div>
);

const Arrow = () => <span className="arrow">→</span>;

/* ---------- translations (light EN/AR for nav + hero) ---------- */
const STRINGS = {
  en: {
    bookAppointment: "Book an appointment",
    shopRTW: "Shop Ready-to-Wear",
    enquire: "Enquire on this look",
    addToBag: "Add to bag",
    onRequest: "On request",
    appointmentPill: "Book Appointment",
    nav: {
      couture: "Couture",
      rtw: "Ready-to-Wear",
      bridal: "Bridal",
      custom: "Custom-Made",
      house: "The House",
      stores: "Stores",
    },
    heroDisplay: ["A Lebanese couture", "house, by ", "appointment."],
    heroBody:
      "Couture, ready-to-wear and bridal — designed in Beirut, presented in Dubai and Paris. Each look is realised in our atelier and offered on appointment.",
  },
  ar: {
    bookAppointment: "احجز موعدًا",
    shopRTW: "تسوّق الجاهز للارتداء",
    enquire: "استفسر عن هذه الإطلالة",
    addToBag: "أضف إلى الحقيبة",
    onRequest: "حسب الطلب",
    appointmentPill: "احجز موعدًا",
    nav: {
      couture: "كوتور",
      rtw: "جاهز للارتداء",
      bridal: "العرائس",
      custom: "تفصيل خاص",
      house: "الدار",
      stores: "الفروع",
    },
    heroDisplay: ["دار أزياء راقية", "لبنانية، بموعد", "مسبق."],
    heroBody:
      "كوتور، جاهز للارتداء وأزياء العرائس — تُصمَّم في بيروت وتُقدَّم في دبي وباريس. كل قطعة تُنفَّذ في الأتيليه بموعد مسبق.",
  },
};

/* ---------- TopBar ---------- */
function TopBar({ locale }) {
  return (
    <div className="topbar">
      {locale === "ar"
        ? "صالة دبي · يونيت M04، مبنى ٦، دبي ديزاين ديستريكت — بموعد مسبق"
        : "Dubai Showroom · Unit M04, Building 06, Dubai Design District — by appointment"}
      &nbsp;&nbsp;·&nbsp;&nbsp;
      <a href="https://wa.me/9613813893" target="_blank" rel="noreferrer">WhatsApp +961 3 813 893</a>
    </div>
  );
}

/* ---------- Nav ---------- */
function Nav({ page, go, locale, setLocale }) {
  const t = STRINGS[locale];
  const links = [
    ["couture", t.nav.couture],
    ["rtw", t.nav.rtw],
    ["bridal", t.nav.bridal],
    ["custom", t.nav.custom],
    ["house", t.nav.house],
    ["stores", t.nav.stores],
  ];
  return (
    <nav className="nav">
      <div className="nav-inner">
        <div className="nav-links">
          {links.map(([k, label]) => (
            <button key={k} className={page === k ? "active" : ""} onClick={() => go(k)}>
              {label}
            </button>
          ))}
        </div>
        <button className="nav-logo" onClick={() => go("home")} style={{background:"none",border:0,cursor:"pointer"}} aria-label="Home">
          <Wordmark />
        </button>
        <div className="nav-right">
          <div className="locale-toggle" role="group" aria-label="Language">
            <button className={locale === "en" ? "active" : ""} onClick={() => setLocale("en")}>EN</button>
            <button className={locale === "ar" ? "active" : ""} onClick={() => setLocale("ar")}>AR</button>
          </div>
          <button className="btn sm" onClick={() => go("appointments")}>
            {t.bookAppointment}
          </button>
        </div>
      </div>
    </nav>
  );
}

/* ---------- Hero ---------- */
function Hero({ go, locale, heroVariant, setHeroVariant }) {
  const t = STRINGS[locale];
  const featureSlots = [
    { id: "feather-sculpted",  img: "media/product-21-couture-feather-sculpted-dress.webp",  label: "SS26 Couture · Look 31" },
    { id: "double-satin-train", img: "media/product-22-couture-double-satin-train-gown.webp", label: "SS26 Couture · Look 27" },
    { id: "feather-organza",   img: "media/product-23-couture-feather-organza-dress.webp",   label: "SS26 Couture · Look 26" },
    { id: "tayla",             img: "media/product-18-bridal-tayla-gown.webp",               label: "Bridal RTW FW26 · Tayla" },
  ];
  const cur = featureSlots[heroVariant];
  return (
    <section className="hero" style={{padding: 0, borderTop: "1px solid var(--border)"}}>
      <div className="hero-copy">
        <div className="signature">
          <Eyebrow gold>Maison Saiid Kobeisy · Est. 2000</Eyebrow>
        </div>
        <div className="hero-display">
          {t.heroDisplay[0]}<br/>
          <em>{t.heroDisplay[1]}</em>{t.heroDisplay[2]}
        </div>
        <p style={{maxWidth: "44ch", color: "var(--muted)", fontSize: 16, lineHeight: 1.6}}>
          {t.heroBody}
        </p>
        <div className="hero-cta">
          <button className="btn lg" onClick={() => go("appointments")}>
            {t.bookAppointment} <Arrow/>
          </button>
          <button className="btn ghost lg" onClick={() => go("rtw")}>
            {t.shopRTW}
          </button>
        </div>
        <div className="hero-meta">
          <div><div className="num">35+</div><div className="lbl">Countries</div></div>
          <div><div className="num">130</div><div className="lbl">Points of sale</div></div>
          <div><div className="num">3</div><div className="lbl">Cities · Beirut · Dubai · Paris</div></div>
          <div><div className="num">2000</div><div className="lbl">House founded</div></div>
        </div>
      </div>
      <div className="hero-image">
        <img src={cur.img} alt="Saiid Kobeisy couture feature look"/>
        <div className="frame-tag">
          Feature look <strong>{cur.label}</strong>
        </div>
        <div className="swap-row">
          {featureSlots.map((s, i) => (
            <button key={s.id}
              className={heroVariant === i ? "active" : ""}
              onClick={() => setHeroVariant(i)}
              aria-label={"Show " + s.label}>
              <img src={s.img} alt=""/>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Trust Spine ---------- */
function TrustSpine() {
  return (
    <div className="trust">
      <div className="trust-inner">
        <div className="trust-cell">
          <div className="num">2000</div>
          <div className="lbl">A house, since</div>
          <p>Begun as a private commission practice in Beirut; an atelier opened two years later.</p>
        </div>
        <div className="trust-cell">
          <div className="num">35<span style={{fontSize:"0.5em"}}>+</span></div>
          <div className="lbl">Countries</div>
          <p>Distributed through 130 points of sale across Europe, the Gulf, North America and Asia.</p>
        </div>
        <div className="trust-cell">
          <div className="num">3</div>
          <div className="lbl">Showrooms</div>
          <p>Beirut house & atelier, Dubai Design District showroom, Paris showroom.</p>
        </div>
        <div className="trust-cell">
          <div className="num">4</div>
          <div className="lbl">Lines</div>
          <p>Couture, Ready-to-Wear, Bridal Couture, Bridal Ready-to-Wear. Little K children's line on request.</p>
        </div>
      </div>
    </div>
  );
}

/* ---------- Line Tiles ---------- */
function LineTiles({ go }) {
  const tiles = [
    {
      k: "couture",
      label: "Couture",
      sub: "By appointment",
      copy: "Hand-finished pieces realised in the Beirut atelier — feathers, hand-set crystal, silk faille and structured corsetry.",
      img: "media/product-21-couture-feather-sculpted-dress.webp",
    },
    {
      k: "rtw",
      label: "Ready-to-Wear",
      sub: "Shop online",
      copy: "Eveningwear and tailoring shipped from Beirut. Live AED pricing, in-stock pieces, made for delivery.",
      img: "media/product-02-brocade-bow-dress.webp",
    },
    {
      k: "bridal",
      label: "Bridal",
      sub: "Couture & Ready-to-Wear",
      copy: "Two paths to the aisle — a made-to-measure couture commission, or our priced Bridal RTW range.",
      img: "media/product-04-royal-bloom-gown.webp",
    },
  ];
  return (
    <section style={{padding: "var(--section-y) 0"}}>
      <div className="section-head" style={{padding: "0 var(--page-x)"}}>
        <div className="lhs">
          <Eyebrow>The Lines</Eyebrow>
          <h2>Four houses,<br/><em style={{color:"var(--secondary)", fontStyle:"italic"}}>one atelier.</em></h2>
        </div>
        <div className="rhs">
          <button className="btn ghost sm" onClick={() => go("house")}>Read the house →</button>
        </div>
      </div>
      <div className="line-tiles">
        {tiles.map(t => (
          <button key={t.k} className="line-tile" onClick={() => go(t.k)}>
            <div className="ph"><img src={t.img} alt={t.label}/></div>
            <div className="body">
              <Eyebrow gold>{t.sub}</Eyebrow>
              <h3>{t.label}</h3>
              <p>{t.copy}</p>
              <span className="more">Enter the line <Arrow/></span>
            </div>
          </button>
        ))}
      </div>
    </section>
  );
}

/* ---------- Featured Looks strip ---------- */
function LookbookStrip({ ids, openProduct, title, sub }) {
  const products = SK_DATA.products.filter(p => ids.includes(p.id));
  return (
    <section>
      <div className="section-head">
        <div className="lhs">
          <Eyebrow>Featured looks</Eyebrow>
          <h2>{title}</h2>
          <p>{sub}</p>
        </div>
      </div>
      <div className="strip">
        {products.map(p => (
          <button key={p.id} className="strip-item"
            style={{cursor:"pointer", border: 0, padding: 0, background: "none"}}
            onClick={() => openProduct(p.id)} aria-label={"View " + p.title}>
            <img src={p.image} alt={p.title}/>
          </button>
        ))}
      </div>
    </section>
  );
}

/* ---------- Product Card ---------- */
function ProductCard({ p, openProduct, locale }) {
  const t = STRINGS[locale];
  return (
    <button className="product-card" onClick={() => openProduct(p.id)}>
      <div className="image-wrap">
        <img src={p.image} alt={p.title} loading="lazy"/>
        <span className="badge">{p.season}</span>
        <span className="quickview">{p.price > 0 ? "Quick view · " + t.addToBag : "Quick view · " + t.enquire}</span>
      </div>
      <div className="product-meta">
        <div>
          <div className="name">{p.title}</div>
          <div className="line">{p.line}</div>
        </div>
        <PriceTag price={p.price}/>
      </div>
    </button>
  );
}

/* ---------- Couture page ---------- */
function CoutureGallery({ openProduct, locale }) {
  const products = SK_DATA.products.filter(p => p.line === "Couture" || p.line === "Bridal Couture");
  return (
    <div className="page">
      <section>
        <div className="section-head">
          <div className="lhs">
            <Eyebrow gold>Couture</Eyebrow>
            <h2>By appointment,<br/><em style={{color:"var(--secondary)", fontStyle:"italic"}}>made in Beirut.</em></h2>
            <p>Each couture piece is made-to-measure in our Beirut atelier. Below is a selection from the most recent Evening Couture SS26 and Couture Bridal 2027 presentations — every look is on request and realised on commission.</p>
          </div>
          <div className="rhs">
            <span className="eyebrow">{products.length} looks</span>
          </div>
        </div>
        <div className="product-grid">
          {products.map(p => (
            <ProductCard key={p.id} p={p} openProduct={openProduct} locale={locale}/>
          ))}
        </div>
      </section>
    </div>
  );
}

/* ---------- RTW page ---------- */
function RTWGallery({ openProduct, locale }) {
  const all = SK_DATA.products.filter(p => p.line === "Ready-to-Wear");
  const [filter, setFilter] = useState("all");
  const seasons = useMemo(() => {
    const counts = {};
    all.forEach(p => { counts[p.season] = (counts[p.season]||0) + 1; });
    return Object.entries(counts);
  }, [all]);
  const products = filter === "all" ? all : all.filter(p => p.season === filter);
  return (
    <div className="page">
      <section>
        <div className="section-head">
          <div className="lhs">
            <Eyebrow gold>Ready-to-Wear</Eyebrow>
            <h2>Shop the runway,<br/><em style={{color:"var(--secondary)", fontStyle:"italic"}}>in-stock.</em></h2>
            <p>Eveningwear, tailoring and cocktail pieces shipped from Beirut. Prices in AED for the UAE storefront — re-confirmed against the live catalogue.</p>
          </div>
          <div className="rhs">
            <span className="eyebrow">{products.length} pieces</span>
          </div>
        </div>

        <div className="chips" style={{marginBottom: 36}}>
          <button className={"chip" + (filter === "all" ? " active" : "")} onClick={() => setFilter("all")}>
            All<span className="n">{all.length}</span>
          </button>
          {seasons.map(([s, n]) => (
            <button key={s} className={"chip" + (filter === s ? " active" : "")} onClick={() => setFilter(s)}>
              {s}<span className="n">{n}</span>
            </button>
          ))}
        </div>

        <div className="product-grid">
          {products.map(p => (
            <ProductCard key={p.id} p={p} openProduct={openProduct} locale={locale}/>
          ))}
        </div>

        <div style={{marginTop: 48, padding: "24px 28px", border: "1px solid var(--border)", background: "var(--surface)", fontSize: 12, color: "var(--muted)", letterSpacing: "0.04em"}}>
          <strong style={{color: "var(--text)"}}>Pricing & availability:</strong> live AED prices are pulled from the official Shopify catalogue at build time. Sizing varies; appointment-led fittings are available at the Dubai Design District showroom.
        </div>
      </section>
    </div>
  );
}

window.SK = Object.assign(window.SK || {}, {
  formatAED, PriceTag, Wordmark, Eyebrow, Arrow, STRINGS,
  TopBar, Nav, Hero, TrustSpine, LineTiles, LookbookStrip,
  ProductCard, CoutureGallery, RTWGallery,
});
