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

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentHex": "#B08D57",
  "backgroundHex": "#FBFAF7",
  "displaySerif": "Cormorant Garamond",
  "heroVariantIndex": 0,
  "tightTopbar": false,
  "showStickyPill": true
}/*EDITMODE-END*/;

function App() {
  const [page, setPage] = useState("home");
  const [locale, setLocale] = useState("en");
  const [openId, setOpenId] = useState(null);
  const [submitted, setSubmitted] = useState(null);
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Listen for cross-product navigation from the modal
  useEffect(() => {
    const handler = (e) => setOpenId(e.detail);
    window.addEventListener("sk-open", handler);
    return () => window.removeEventListener("sk-open", handler);
  }, []);

  // Apply tweaks to CSS vars
  useEffect(() => {
    document.documentElement.style.setProperty("--accent", t.accentHex);
    document.documentElement.style.setProperty("--focus", t.accentHex);
    document.documentElement.style.setProperty("--bg", t.backgroundHex);
    document.documentElement.style.setProperty("--serif", `"${t.displaySerif}", "EB Garamond", Georgia, serif`);
  }, [t.accentHex, t.backgroundHex, t.displaySerif]);

  // Apply RTL
  useEffect(() => {
    document.documentElement.lang = locale;
    document.documentElement.dir = locale === "ar" ? "rtl" : "ltr";
  }, [locale]);

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

  // Hero variant kept here so the home page survives navigation
  const [heroVariant, setHeroVariant] = useState(t.heroVariantIndex || 0);
  useEffect(() => { setHeroVariant(t.heroVariantIndex || 0); }, [t.heroVariantIndex]);

  const go = (k) => { setPage(k); setOpenId(null); };
  const openProduct = (id) => setOpenId(id);
  const closeModal = () => setOpenId(null);

  // Auto-clear submitted after 7s
  useEffect(() => {
    if (!submitted) return;
    const id = setTimeout(() => setSubmitted(null), 8000);
    return () => clearTimeout(id);
  }, [submitted]);

  let body;
  switch (page) {
    case "couture":     body = <SK.CoutureGallery openProduct={openProduct} locale={locale}/>; break;
    case "rtw":         body = <SK.RTWGallery openProduct={openProduct} locale={locale}/>; break;
    case "bridal":      body = <SK.BridalPage openProduct={openProduct} go={go} locale={locale}/>; break;
    case "custom":      body = <SK.CustomMadePage go={go}/>; break;
    case "house":       body = <SK.HousePage go={go}/>; break;
    case "stores":      body = <SK.StoresPage go={go}/>; break;
    case "appointments":body = <SK.AppointmentsPage submitted={submitted} setSubmitted={setSubmitted} locale={locale}/>; break;
    default:            body = <HomePage go={go} openProduct={openProduct} locale={locale} heroVariant={heroVariant} setHeroVariant={setHeroVariant}/>;
  }

  return (
    <>
      {!t.tightTopbar && <SK.TopBar locale={locale}/>}
      <SK.Nav page={page} go={go} locale={locale} setLocale={setLocale}/>
      <main key={page} className="page">{body}</main>
      <SK.Footer go={go}/>

      {t.showStickyPill && page !== "appointments" && (
        <button className="appt-pill" onClick={() => go("appointments")}>
          <span className="dot live"/> {window.SK.STRINGS[locale].appointmentPill}
        </button>
      )}

      {openId && <SK.ProductModal id={openId} close={closeModal} go={go} locale={locale}/>}

      {submitted && (
        <div className="toast">
          <button className="t-close" onClick={() => setSubmitted(null)}>✕</button>
          <div className="t-title">Request received.</div>
          <div>Thank you, {submitted.name}. We'll confirm your <strong>{submitted.line}</strong> appointment in {submitted.showroom} within one business day. A pre-filled WhatsApp is ready —{" "}
            <a href={submitted.waHref} target="_blank" rel="noreferrer" style={{color:"var(--accent-soft)", borderBottom:"1px solid currentColor"}}>continue now →</a>.
          </div>
        </div>
      )}

      <TweaksPanel title="Tweaks · House" defaultOpen={false}>
        <TweakSection title="Identity">
          <TweakColor label="Accent (whisper gold)" value={t.accentHex} onChange={v => setTweak("accentHex", v)}
            options={["#B08D57","#8C6B4F","#1A1A1A","#6E6A63","#C9A876"]}/>
          <TweakColor label="Background tone" value={t.backgroundHex} onChange={v => setTweak("backgroundHex", v)}
            options={["#FBFAF7","#FFFFFF","#F2EDE3","#EDE8DC","#181613"]}/>
          <TweakSelect label="Display serif" value={t.displaySerif} onChange={v => setTweak("displaySerif", v)}
            options={["Cormorant Garamond", "Playfair Display", "EB Garamond", "Tenor Sans", "Italiana"]}/>
        </TweakSection>
        <TweakSection title="Home">
          <TweakSelect label="Hero feature look" value={String(t.heroVariantIndex)} onChange={v => setTweak("heroVariantIndex", Number(v))}
            options={[
              { value: "0", label: "Feather sculpted (SS26)" },
              { value: "1", label: "Double satin train (SS26)" },
              { value: "2", label: "Feather organza (SS26)" },
              { value: "3", label: "Bridal · Tayla (FW26)" },
            ]}/>
        </TweakSection>
        <TweakSection title="Chrome">
          <TweakToggle label="Showroom topbar" value={!t.tightTopbar} onChange={v => setTweak("tightTopbar", !v)}/>
          <TweakToggle label="Sticky appointment pill" value={t.showStickyPill} onChange={v => setTweak("showStickyPill", v)}/>
        </TweakSection>
        <TweakSection title="Demo">
          <TweakButton label="Jump to appointments" onClick={() => go("appointments")}/>
          <TweakButton label="Open a couture look" onClick={() => { go("couture"); setTimeout(()=>openProduct("royal-bloom"), 350); }}/>
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

/* ---------- Home composition ---------- */
function HomePage({ go, openProduct, locale, heroVariant, setHeroVariant }) {
  return (
    <>
      <SK.Hero go={go} locale={locale} heroVariant={heroVariant} setHeroVariant={setHeroVariant}/>
      <SK.TrustSpine/>
      <SK.LineTiles go={go}/>
      <section style={{paddingTop: 0, borderTop: 0}}>
        <SK.LookbookStrip
          title="Couture · Evening SS26"
          sub="A four-look excerpt from the spring/summer couture presentation. By appointment."
          ids={["feather-sculpted", "double-satin-train", "feather-organza", "royal-bloom"]}
          openProduct={openProduct}
        />
      </section>
      <section>
        <SK.LookbookStrip
          title="Ready-to-Wear · in stock"
          sub="Priced looks shipping from Beirut. Click for fabric notes and to add to your bag."
          ids={["ruffled-jumpsuit", "brocade-bow-dress", "halter-neck-embroidered", "crystal-one-shoulder"]}
          openProduct={openProduct}
        />
      </section>
      <BridalTeaser go={go}/>
      <PressRow/>
    </>
  );
}

function BridalTeaser({ go }) {
  return (
    <section style={{background: "var(--text)", color: "var(--bg)", borderTop: 0}}>
      <div className="split lopsided" style={{alignItems: "center", gap: 80}}>
        <img src="media/product-04-royal-bloom-gown.webp" alt="" style={{aspectRatio:"3/4", objectFit:"cover", maxHeight: 640, width: "100%"}}/>
        <div style={{display:"grid", gap: 24}}>
          <span className="eyebrow" style={{color: "var(--accent-soft)"}}>Bridal · 2027</span>
          <h2 style={{fontFamily:"var(--serif)", fontSize: "clamp(40px, 5vw, 72px)", lineHeight: 1.02, color:"#fff"}}>
            For one body,<br/>
            <em style={{color:"var(--accent-soft)", fontStyle:"italic"}}>and one aisle.</em>
          </h2>
          <p style={{color: "rgba(239,234,224,0.75)", maxWidth:"48ch", fontSize: 16}}>
            Bridal Couture is a four-month conversation between you and our Beirut atelier — three to five fittings, embroidery samples for sign-off, and a single delivery in your colour, your silhouette, your light.
          </p>
          <div style={{display:"flex", gap: 10, flexWrap:"wrap", marginTop: 10}}>
            <button className="btn gold" onClick={() => go("bridal")}>Enter Bridal →</button>
            <button className="btn ghost" onClick={() => go("appointments")} style={{color: "#fff", borderColor: "rgba(255,255,255,0.4)"}}>Begin a commission</button>
          </div>
        </div>
      </div>
    </section>
  );
}

function PressRow() {
  return (
    <section style={{background: "var(--surface)"}}>
      <div className="section-head">
        <div className="lhs">
          <Eyebrow>Where we have been seen</Eyebrow>
          <h2 style={{fontSize: 44}}>Press &amp; runway.</h2>
        </div>
      </div>
      <div className="press">
        {SK_DATA.pressLines.map(p => (
          <div key={p.house + p.year} className="press-item">
            <div className="pub">{p.house}</div>
            <div className="credit">{p.credit}</div>
            <div className="y">{p.year}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

const Eyebrow = window.SK.Eyebrow;

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