// Maison Yeya — shared components

const { useState, useEffect, useRef, useMemo, useCallback, createContext, useContext } = React;

// ──────────────────────────────────────────────────────────
// Logo / mark
// ──────────────────────────────────────────────────────────
function YeyaMark({ size = 40, color = "currentColor", className = "" }) {
  // Stylized "Y / bridge" abstraction inspired by the official wordmark, drawn
  // from primitives (not a tracing of the brand logo).
  return (
    <svg width={size} height={size * 1.22} viewBox="0 0 36 44" fill="none" className={className} aria-hidden="true">
      <path d="M2 2 L18 30 L34 2 M18 30 L18 42 M10 16 L26 16"
            stroke={color} strokeWidth="1" strokeLinecap="square"/>
    </svg>
  );
}

function Wordmark({ size = 18, color = "currentColor" }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 16, color }}>
      <YeyaMark size={size * 1.6} color={color} />
      <span className="wordmark-W" style={{ fontSize: size, color }}>Maison Yeya</span>
    </span>
  );
}

// ──────────────────────────────────────────────────────────
// Vertical tracked rail label
// ──────────────────────────────────────────────────────────
function VRail({ children, side = "left", top = 80, style = {} }) {
  const tweaks = useContext(TweakCtx);
  if (!tweaks?.showVerticals) return null;
  const sideStyle = side === "left" ? { left: 24 } : { right: 24 };
  return (
    <div className="v-text" style={{ position: "absolute", top, ...sideStyle, ...style }}>
      {children}
    </div>
  );
}

// ──────────────────────────────────────────────────────────
// Tweak context
// ──────────────────────────────────────────────────────────
const TweakCtx = createContext({});

const ACCENTS = {
  champagne: { value: "oklch(0.78 0.035 75)", deep: "oklch(0.55 0.06 60)" },
  blush:     { value: "oklch(0.82 0.04 20)",  deep: "oklch(0.55 0.06 20)" },
  ink:       { value: "oklch(0.42 0.02 60)",  deep: "oklch(0.28 0.02 60)" },
  rouge:     { value: "oklch(0.45 0.12 25)",  deep: "oklch(0.32 0.12 25)" }
};

// ──────────────────────────────────────────────────────────
// Persistent CTA cluster (used in nav)
// ──────────────────────────────────────────────────────────
function HeaderCTA({ onAppointment, onEnquiry, enquiryCount }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 24 }}>
      <button className="label" onClick={onEnquiry}
              style={{ display: "inline-flex", alignItems: "center", gap: 10, color: "var(--ink)" }}>
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
          <path d="M2 4 H14 L13 13 H3 Z" stroke="currentColor" strokeWidth="1"/>
          <path d="M6 4 V3 a2 2 0 0 1 4 0 V4" stroke="currentColor" strokeWidth="1"/>
        </svg>
        <span>Enquiry</span>
        <span className="num" style={{ minWidth: 18, textAlign: "center", padding: "1px 6px",
              border: "1px solid var(--ink)", borderRadius: 999, fontSize: 10, letterSpacing: 0 }}>
          {enquiryCount}
        </span>
      </button>
      <button className="btn solid" onClick={onAppointment}>Request Appointment</button>
    </div>
  );
}

// ──────────────────────────────────────────────────────────
// Site Header (sticky)
// ──────────────────────────────────────────────────────────
function SiteHeader({ route, setRoute, onAppointment, onEnquiry, enquiryCount }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 16);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const nav = [
    { id: "home",         label: "Maison" },
    { id: "bridal",       label: "Bridal" },
    { id: "couture",      label: "Couture" },
    { id: "atelier",      label: "L'Atelier" },
    { id: "press",        label: "Press" },
    { id: "contact",      label: "Contact" }
  ];

  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 100,
      background: scrolled ? "rgba(244,239,231,0.92)" : "rgba(244,239,231,0)",
      backdropFilter: scrolled ? "blur(14px)" : "none",
      WebkitBackdropFilter: scrolled ? "blur(14px)" : "none",
      borderBottom: scrolled ? "1px solid var(--hair)" : "1px solid transparent",
      transition: "background 240ms ease, border-color 240ms ease"
    }}>
      <div className="container" style={{
        display: "grid", gridTemplateColumns: "1fr auto 1fr", alignItems: "center",
        padding: scrolled ? "16px 56px" : "26px 56px",
        transition: "padding 240ms ease",
        gap: 32
      }}>
        {/* Left: nav */}
        <nav style={{ display: "flex", gap: 28, alignItems: "center" }}>
          {nav.slice(0, 3).map(n => (
            <NavLink key={n.id} active={route === n.id} onClick={() => setRoute(n.id)}>{n.label}</NavLink>
          ))}
        </nav>

        {/* Center: mark */}
        <button onClick={() => setRoute("home")} style={{ display: "flex", alignItems: "center", gap: 12, cursor: "pointer" }}>
          <YeyaMark size={scrolled ? 22 : 28} />
          <span className="wordmark-W" style={{ fontSize: scrolled ? 13 : 15, transition: "font-size 240ms ease" }}>
            Maison Yeya
          </span>
        </button>

        {/* Right: meta nav + CTA */}
        <div style={{ display: "flex", gap: 28, alignItems: "center", justifyContent: "flex-end" }}>
          {nav.slice(3).map(n => (
            <NavLink key={n.id} active={route === n.id} onClick={() => setRoute(n.id)}>{n.label}</NavLink>
          ))}
          <span style={{ width: 1, height: 18, background: "var(--hair)" }}></span>
          <HeaderCTA onAppointment={onAppointment} onEnquiry={onEnquiry} enquiryCount={enquiryCount} />
        </div>
      </div>
    </header>
  );
}

function NavLink({ active, onClick, children }) {
  return (
    <button onClick={onClick} className="label"
            style={{
              position: "relative", paddingBottom: 2,
              color: active ? "var(--ink)" : "var(--ink-soft)",
              fontWeight: active ? 500 : 400
            }}>
      {children}
      <span style={{
        position: "absolute", left: 0, right: 0, bottom: -4, height: 1,
        background: "var(--ink)",
        transform: active ? "scaleX(1)" : "scaleX(0)",
        transformOrigin: "left center",
        transition: "transform 240ms ease"
      }}></span>
    </button>
  );
}

// ──────────────────────────────────────────────────────────
// Footer
// ──────────────────────────────────────────────────────────
function SiteFooter({ setRoute, onAppointment }) {
  return (
    <footer style={{ background: "#14110f", color: "var(--paper)", marginTop: 120 }}>
      <div className="container" style={{ padding: "100px 56px 40px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr 1fr", gap: 56, alignItems: "start" }}>
          {/* Brand block */}
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 28 }}>
              <YeyaMark size={28} color="#f4efe7" />
              <span className="wordmark-W" style={{ fontSize: 15, color: "#f4efe7" }}>Maison Yeya</span>
            </div>
            <p className="editorial" style={{
              fontSize: 16, lineHeight: 1.6, color: "rgba(244,239,231,0.7)", maxWidth: 320,
              margin: 0, fontStyle: "italic"
            }}>
              Bridal and couture by Yasmine Yeya — by private appointment in Dubai Design District.
            </p>
            <button className="btn on-dark" style={{ marginTop: 36 }} onClick={onAppointment}>
              Request a VIP Appointment
            </button>
          </div>

          <FooterCol title="Maison" items={[
            ["Home", () => setRoute("home")],
            ["La Maison", () => setRoute("atelier")],
            ["Press", () => setRoute("press")],
            ["Contact", () => setRoute("contact")],
          ]}/>
          <FooterCol title="Bridal" items={[
            ["Bridal Couture Privée", () => setRoute("bridal")],
            ["Gharami", () => setRoute("bridal")],
            ["Shades of White", () => setRoute("bridal")],
            ["Utopia", () => setRoute("bridal")],
          ]}/>
          <FooterCol title="Couture" items={[
            ["Couture Privée", () => setRoute("couture")],
            ["Les Marionettes", () => setRoute("couture")],
            ["Les Nuits d'Aphrodite", () => setRoute("couture")],
            ["Harmony", () => setRoute("couture")],
          ]}/>
          <FooterCol title="Atelier" items={[
            ["Showroom", () => setRoute("contact")],
            ["Press enquiries", () => setRoute("contact")],
            ["Careers", () => setRoute("contact")],
            ["Appointments", onAppointment],
          ]}/>
        </div>

        <div className="hair-dark" style={{ margin: "72px 0 28px" }}></div>

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center",
                      gap: 32, flexWrap: "wrap" }}>
          <div style={{ display: "flex", gap: 32, flexWrap: "wrap" }}>
            <a className="micro" style={{ color: "rgba(244,239,231,0.6)" }} href={CONTACT.social.instagram} target="_blank" rel="noopener">Instagram</a>
            <a className="micro" style={{ color: "rgba(244,239,231,0.6)" }} href={CONTACT.social.facebook} target="_blank" rel="noopener">Facebook</a>
            <a className="micro" style={{ color: "rgba(244,239,231,0.6)" }} href={CONTACT.social.pinterest} target="_blank" rel="noopener">Pinterest</a>
          </div>
          <div className="micro" style={{ color: "rgba(244,239,231,0.5)" }}>
            © {new Date().getFullYear()} Maison Yeya · Office 203A, Building 4A, Dubai Design District
          </div>
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ title, items }) {
  return (
    <div>
      <div className="micro" style={{ color: "rgba(244,239,231,0.5)", marginBottom: 20 }}>{title}</div>
      <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "flex", flexDirection: "column", gap: 12 }}>
        {items.map(([label, onClick], i) => (
          <li key={i}>
            <button onClick={onClick} className="editorial"
                    style={{ fontSize: 17, color: "rgba(244,239,231,0.85)", textAlign: "left", lineHeight: 1.4 }}>
              {label}
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

// ──────────────────────────────────────────────────────────
// Look card (used everywhere)
// ──────────────────────────────────────────────────────────
function LookCard({ look, onOpen, onSave, saved, large = false, lift = false, dark = false, aspect = "2/3" }) {
  const [hover, setHover] = useState(false);
  return (
    <article className="look-card"
             onMouseEnter={() => setHover(true)}
             onMouseLeave={() => setHover(false)}
             style={{ display: "flex", flexDirection: "column", gap: 0, cursor: "pointer" }}
             onClick={() => onOpen && onOpen(look)}>
      <div className="img-frame" style={{ aspectRatio: aspect, position: "relative" }}>
        <img src={look.image} alt={look.name} loading="lazy"
             style={{ transform: hover ? "scale(1.04)" : "scale(1)", transition: "transform 1200ms cubic-bezier(0.22, 1, 0.36, 1)" }}/>
        {/* Hover overlay */}
        <div style={{
          position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(20,17,15,0.55), rgba(20,17,15,0) 60%)",
          opacity: hover ? 1 : 0, transition: "opacity 260ms ease",
          display: "flex", alignItems: "flex-end", justifyContent: "space-between",
          padding: 18, color: "#fff"
        }}>
          <span className="label" style={{ color: "#fff" }}>View Look</span>
          <button onClick={(e) => { e.stopPropagation(); onSave && onSave(look); }}
                  className="label"
                  style={{
                    display: "inline-flex", alignItems: "center", gap: 8,
                    padding: "8px 14px", border: "1px solid rgba(255,255,255,0.6)", color: "#fff",
                    background: saved ? "#fff" : "transparent",
                    color: saved ? "var(--ink)" : "#fff"
                  }}>
            <Heart filled={saved} /> {saved ? "Saved" : "Save"}
          </button>
        </div>
      </div>
      <div className="figure-caption" style={{ marginTop: 18, color: dark ? "rgba(244,239,231,0.7)" : "var(--ink-soft)" }}>
        <div>
          <div className="display" style={{ fontSize: large ? 28 : 22, color: dark ? "var(--paper)" : "var(--ink)", marginBottom: 4 }}>
            {look.name}
          </div>
          <div className="micro" style={{ color: dark ? "rgba(244,239,231,0.55)" : "var(--ink-mute)" }}>{look.subtitle}</div>
        </div>
        <div className="micro" style={{ color: dark ? "rgba(244,239,231,0.55)" : "var(--ink-mute)" }}>
          {String(look.looks).padStart(2, "0")} Looks
        </div>
      </div>
    </article>
  );
}

function Heart({ filled, size = 12 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" fill={filled ? "currentColor" : "none"}>
      <path d="M8 13.5s-5-3.2-5-6.5a3 3 0 0 1 5-2.2A3 3 0 0 1 13 7c0 3.3-5 6.5-5 6.5z"
            stroke="currentColor" strokeWidth="1" strokeLinejoin="round"/>
    </svg>
  );
}

// ──────────────────────────────────────────────────────────
// Marquee
// ──────────────────────────────────────────────────────────
function Marquee({ items, dark = false }) {
  // Duplicate items so the keyframe wraps seamlessly
  const tail = items.concat(items);
  return (
    <div style={{
      overflow: "hidden", position: "relative",
      borderTop: dark ? "1px solid rgba(255,255,255,0.18)" : "1px solid var(--hair)",
      borderBottom: dark ? "1px solid rgba(255,255,255,0.18)" : "1px solid var(--hair)",
      padding: "20px 0",
      background: dark ? "#14110f" : "transparent"
    }}>
      <div className="marquee-track">
        {tail.map((t, i) => (
          <span key={i} className="micro"
                style={{ color: dark ? "rgba(244,239,231,0.7)" : "var(--ink-soft)", whiteSpace: "nowrap" }}>
            {t} <span style={{ marginLeft: 64, opacity: 0.5 }}>✦</span>
          </span>
        ))}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────
// Look detail drawer
// ──────────────────────────────────────────────────────────
function LookDrawer({ look, onClose, onSave, saved, onAppointment }) {
  useEffect(() => {
    if (!look) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKey);
    };
  }, [look, onClose]);

  if (!look) return null;

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 200 }}>
      <div onClick={onClose}
           style={{ position: "absolute", inset: 0, background: "rgba(20,17,15,0.5)",
                    animation: "fadeIn 240ms ease both" }}></div>
      <div className="scroll-pretty" style={{
        position: "absolute", right: 0, top: 0, bottom: 0, width: "min(720px, 92vw)",
        background: "var(--paper)", overflowY: "auto",
        animation: "drawerIn 360ms cubic-bezier(0.22, 1, 0.36, 1) both"
      }}>
        <style>{`@keyframes drawerIn { from { transform: translateX(40px); opacity: 0;} to { transform: none; opacity: 1; } }`}</style>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center",
                      padding: "20px 40px", borderBottom: "1px solid var(--hair)" }}>
          <div className="micro">{look.range}</div>
          <button className="label" onClick={onClose}>Close ✕</button>
        </div>
        <div style={{ padding: "40px 40px 56px" }}>
          <div className="micro" style={{ marginBottom: 14 }}>{look.subtitle}</div>
          <h2 className="display" style={{ fontSize: 56, margin: "0 0 24px" }}>{look.name}</h2>
          <div className="img-frame" style={{ aspectRatio: "3/4", marginBottom: 28 }}>
            <img src={look.image} alt={look.name}/>
          </div>
          <p className="editorial" style={{ fontSize: 20, lineHeight: 1.5, color: "var(--ink-soft)", maxWidth: 520, fontStyle: "italic" }}>
            "{look.note}"
          </p>

          <div className="hair" style={{ margin: "40px 0" }}></div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32, marginBottom: 36 }}>
            <Spec label="Collection" value={look.name}/>
            <Spec label="Category" value={look.range}/>
            <Spec label="Looks in Series" value={String(look.looks).padStart(2, "0")}/>
            <Spec label="Reference" value={`MY · ${look.id.toUpperCase()}`}/>
          </div>

          <p className="editorial" style={{ fontSize: 16, color: "var(--ink-soft)", lineHeight: 1.6, marginBottom: 28 }}>
            Pieces from this series are available by private appointment at the atelier in Dubai Design District.
            Each gown is hand-made to measure; quotation provided after consultation.
          </p>

          <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
            <button className="btn solid" onClick={onAppointment}>Request Appointment</button>
            <button className="btn" onClick={() => onSave(look)}>
              {saved ? "✓ Saved to Enquiry" : "Save to Enquiry"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function Spec({ label, value }) {
  return (
    <div>
      <div className="micro" style={{ marginBottom: 6 }}>{label}</div>
      <div className="editorial" style={{ fontSize: 18 }}>{value}</div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────
// Enquiry Drawer
// ──────────────────────────────────────────────────────────
function EnquiryDrawer({ open, items, onClose, onRemove, onAppointment }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKey);
    };
  }, [open, onClose]);

  if (!open) return null;
  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 200 }}>
      <div onClick={onClose}
           style={{ position: "absolute", inset: 0, background: "rgba(20,17,15,0.5)", animation: "fadeIn 240ms ease both" }}></div>
      <div className="scroll-pretty" style={{
        position: "absolute", right: 0, top: 0, bottom: 0, width: "min(540px, 92vw)",
        background: "var(--paper)", overflowY: "auto",
        animation: "drawerIn 360ms cubic-bezier(0.22, 1, 0.36, 1) both"
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center",
                      padding: "20px 32px", borderBottom: "1px solid var(--hair)" }}>
          <div>
            <div className="micro" style={{ marginBottom: 4 }}>Enquiry</div>
            <div className="display" style={{ fontSize: 26 }}>Saved Looks</div>
          </div>
          <button className="label" onClick={onClose}>Close ✕</button>
        </div>

        {items.length === 0 ? (
          <div style={{ padding: "80px 32px", textAlign: "center" }}>
            <div className="display" style={{ fontSize: 40, marginBottom: 18, color: "var(--ink-mute)" }}>
              ⌖
            </div>
            <p className="editorial" style={{ fontSize: 18, color: "var(--ink-soft)", lineHeight: 1.5, maxWidth: 320, margin: "0 auto", fontStyle: "italic" }}>
              No looks saved yet. Browse Bridal or Couture and tap "Save" on any look to begin an enquiry.
            </p>
          </div>
        ) : (
          <div style={{ padding: "24px 32px" }}>
            {items.map(it => (
              <div key={it.id} style={{
                display: "grid", gridTemplateColumns: "92px 1fr auto", gap: 18,
                padding: "20px 0", borderBottom: "1px solid var(--hair-soft)", alignItems: "center"
              }}>
                <div className="img-frame" style={{ aspectRatio: "3/4", width: 92 }}>
                  <img src={it.image} alt={it.name}/>
                </div>
                <div>
                  <div className="display" style={{ fontSize: 22, marginBottom: 4 }}>{it.name}</div>
                  <div className="micro">{it.subtitle}</div>
                </div>
                <button className="micro" style={{ color: "var(--ink-mute)", border: 0, background: "none", cursor: "pointer" }}
                        onClick={() => onRemove(it)}>
                  Remove
                </button>
              </div>
            ))}

            <div style={{ marginTop: 36, padding: "24px", background: "var(--paper-2)" }}>
              <p className="editorial" style={{ fontSize: 16, lineHeight: 1.55, margin: "0 0 18px", color: "var(--ink-soft)" }}>
                We will prepare a quotation and arrange a private fitting at the atelier in Dubai Design District. Lead times will be confirmed at consultation.
              </p>
              <button className="btn solid" style={{ width: "100%" }} onClick={onAppointment}>
                Send Enquiry & Request Appointment
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, {
  YeyaMark, Wordmark, VRail, TweakCtx, ACCENTS,
  SiteHeader, SiteFooter, LookCard, Marquee, LookDrawer, EnquiryDrawer, Heart
});
