// Shared components: Navbar, Footer, WhatsApp FAB, AppointmentForm, PriceBlock, etc.

const Wordmark = ({ size = 18, className = "", showMark = false }) => (
  <a href="#home" className={"mo-wordmark " + className} style={{display:"inline-flex", alignItems:"center", gap: showMark ? 14 : 0, textDecoration:"none"}}>
    {showMark && (
      <img
        src="media/logo.webp"
        alt=""
        aria-hidden="true"
        style={{width: size * 1.9, height: size * 1.9, borderRadius: "50%", display: "block", objectFit: "cover"}}
      />
    )}
    <span style={{
      fontFamily:"'Cormorant Garamond', serif", color:"var(--ink)",
      fontSize: size,
      letterSpacing:"0.32em", textTransform:"uppercase", fontWeight:500,
      lineHeight: 1, whiteSpace: "nowrap",
      paddingLeft: "0.16em", // optical balance for letter-spacing
    }}>Maryam&nbsp;Omaira</span>
  </a>
);

const Navbar = ({ page, setPage }) => {
  const [open, setOpen] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const on = () => setScrolled(window.scrollY > 20);
    on();
    window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, []);

  const go = (k) => { setPage(k); setOpen(false); window.scrollTo({ top:0, behavior:"instant" }); };

  return (
    <header className={"mo-nav " + (scrolled ? "mo-nav--scrolled" : "")}>
      <div className="mo-nav__inner">
        <button className="mo-nav__menubtn" aria-label="Menu" onClick={() => setOpen(true)}>
          <span /><span /><span />
        </button>
        <div className="mo-nav__brand" onClick={() => go("home")} role="button">
          <Wordmark size={17} />
        </div>
        <nav className="mo-nav__links">
          {NAV.slice(1, 7).map(n => (
            <a key={n.key} onClick={() => go(n.key)} className={page === n.key ? "is-active" : ""}>{n.label}</a>
          ))}
        </nav>
        <div className="mo-nav__cta">
          <a className="mo-nav__contact" onClick={() => go("contact")}>Contact</a>
          <button className="mo-btn mo-btn--ink mo-btn--sm" onClick={() => go("appointments")}>Book appointment</button>
        </div>
      </div>

      {/* Drawer */}
      <div className={"mo-drawer " + (open ? "is-open" : "")}>
        <div className="mo-drawer__scrim" onClick={() => setOpen(false)} />
        <aside className="mo-drawer__panel">
          <div className="mo-drawer__top">
            <Wordmark size={18} />
            <button aria-label="Close" className="mo-drawer__close" onClick={() => setOpen(false)}>✕</button>
          </div>
          <nav className="mo-drawer__links">
            {NAV.map(n => (
              <a key={n.key} onClick={() => go(n.key)} className={page === n.key ? "is-active" : ""}>
                <span className="mo-drawer__num">{String(NAV.indexOf(n)+1).padStart(2,"0")}</span>
                {n.label}
              </a>
            ))}
          </nav>
          <div className="mo-drawer__foot">
            <div className="mo-eyebrow">Atelier</div>
            <div>{CONTACT.address1}</div>
            <div>{CONTACT.address2}</div>
            <div style={{marginTop:14}} className="mo-eyebrow">Contact</div>
            <div><a href={`tel:${CONTACT.landline}`}>{CONTACT.landline}</a></div>
            <div><a href={`mailto:${CONTACT.email}`}>{CONTACT.email}</a></div>
          </div>
        </aside>
      </div>
    </header>
  );
};

const Footer = ({ setPage }) => (
  <footer className="mo-foot">
    <div className="mo-foot__top">
      <div className="mo-foot__col mo-foot__col--brand">
        <Wordmark size={22} />
        <p className="mo-foot__tag">An Emirati couture house in Dubai Design District. Heritage motifs, reimagined as contemporary luxury — in the finest fabrics from Europe and beyond.</p>
        <div className="mo-foot__social">
          <a href="https://instagram.com/maryamomaira" target="_blank" rel="noopener noreferrer">Instagram</a>
          <span>·</span>
          <a href="https://linkedin.com" target="_blank" rel="noopener noreferrer">LinkedIn</a>
        </div>
      </div>
      <div className="mo-foot__col">
        <div className="mo-eyebrow">The House</div>
        <a onClick={() => setPage("designer")}>The Designer</a>
        <a onClick={() => setPage("bridal")}>Bridal Couture</a>
        <a onClick={() => setPage("couture")}>Couture SS26</a>
        <a onClick={() => setPage("jewellery")}>Jewellery</a>
      </div>
      <div className="mo-foot__col">
        <div className="mo-eyebrow">Shop</div>
        <a onClick={() => setPage("shop")}>Ready-to-Wear</a>
        <a onClick={() => setPage("shop")}>Dresses</a>
        <a onClick={() => setPage("shop")}>Kaftans &amp; Tunics</a>
        <a onClick={() => setPage("shop")}>Kids</a>
      </div>
      <div className="mo-foot__col">
        <div className="mo-eyebrow">Atelier</div>
        <div>{CONTACT.address1}</div>
        <div>{CONTACT.address2}</div>
        <div>{CONTACT.address3}</div>
        <div style={{marginTop:10}}>{CONTACT.hours}</div>
        <div style={{opacity:0.55}}>{CONTACT.sundayClosed}</div>
      </div>
      <div className="mo-foot__col">
        <div className="mo-eyebrow">Reach us</div>
        <a href={waUrl()} target="_blank" rel="noopener noreferrer">WhatsApp {CONTACT.whatsappPretty}</a>
        <a href={`tel:${CONTACT.landline}`}>{CONTACT.landline}</a>
        <a href={`mailto:${CONTACT.email}`}>{CONTACT.email}</a>
        <a onClick={() => setPage("appointments")} className="mo-foot__cta">Book appointment →</a>
      </div>
    </div>
    <div className="mo-foot__bottom">
      <span>© 2026 Maryam Omaira Fashion Designing  ·  Est. 2010, Dubai</span>
      <span>Maryam Omaira New Couture  ·  Maryam Omaira Jewellery</span>
    </div>
  </footer>
);

const WhatsAppFab = () => (
  <a className="mo-fab" href={waUrl()} target="_blank" rel="noopener noreferrer" aria-label="WhatsApp">
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/>
    </svg>
    <span>Chat on WhatsApp</span>
  </a>
);

const PriceBlock = ({ p }) => (
  <span className="mo-price">
    {p.line && (p.line === "Bridal" || p.line === "Couture") && p.category !== "couture"
      ? "On request"
      : aed(p.price)}
  </span>
);

const ProductCard = ({ p, onOpen }) => (
  <article className="mo-card" onClick={() => onOpen && onOpen(p)}>
    <div className="mo-card__img">
      <img src={p.image} alt={p.name} loading="lazy" />
    </div>
    <div className="mo-card__meta">
      <div className="mo-card__code">{p.code}</div>
      <h3 className="mo-card__name">{p.name}</h3>
      <div className="mo-card__row">
        <span className="mo-card__price">{aed(p.price)}</span>
        <span className="mo-card__cta">Details →</span>
      </div>
    </div>
  </article>
);

const Eyebrow = ({ children, num }) => (
  <div className="mo-eyebrow mo-eyebrow--lg">
    {num && <span className="mo-eyebrow__num">{num}</span>}
    <span>{children}</span>
  </div>
);

const SectionHead = ({ eyebrow, title, sub, align = "left" }) => (
  <header className={"mo-sec__head mo-sec__head--" + align}>
    {eyebrow && <Eyebrow>{eyebrow}</Eyebrow>}
    <h2 className="mo-display">{title}</h2>
    {sub && <p className="mo-sec__sub">{sub}</p>}
  </header>
);

// Quick-view modal — opens from any ProductCard
const ProductModal = ({ p, onClose, setPage }) => {
  React.useEffect(() => {
    if (!p) return;
    const k = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", k);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", k); document.body.style.overflow = prev; };
  }, [p]);
  if (!p) return null;
  const isCouture = p.category === "couture" || p.category === "bridal";
  return (
    <div className="mo-modal" onClick={onClose}>
      <div className="mo-modal__panel" onClick={e => e.stopPropagation()}>
        <button className="mo-modal__close" onClick={onClose} aria-label="Close">✕</button>
        <div className="mo-modal__grid">
          <div className="mo-modal__img"><img src={p.image} alt={p.name} /></div>
          <div className="mo-modal__body">
            <div className="mo-eyebrow">{p.line}  ·  {p.code}</div>
            <h2 className="mo-display" style={{fontSize:"clamp(34px,4vw,52px)", margin:"14px 0 22px"}}>{p.name}</h2>
            <p className="mo-modal__fabric">{p.fabric}</p>
            <div className="mo-modal__price">{aed(p.price)}</div>
            <ul className="mo-modal__list">
              <li><span>Origin</span><span>Dubai atelier</span></li>
              <li><span>Made to order</span><span>4–8 weeks</span></li>
              <li><span>Fitting</span><span>By appointment</span></li>
              <li><span>Care</span><span>Atelier dry-clean only</span></li>
            </ul>
            <div className="mo-modal__actions">
              {!isCouture && <button className="mo-btn mo-btn--ink">Add to bag</button>}
              <a className="mo-btn mo-btn--outline" href={waUrl(`Hi Maryam Omaira, I'd like to enquire about ${p.code} — ${p.name}.`)} target="_blank" rel="noopener noreferrer">Enquire on WhatsApp</a>
              {isCouture && (
                <button className="mo-btn mo-btn--ink" onClick={() => { onClose(); setPage("appointments"); }}>Book a fitting</button>
              )}
            </div>
            <p className="mo-modal__note">Couture pieces are made to measure at our Dubai Design District atelier. Begin with a personal consultation.</p>
          </div>
        </div>
      </div>
    </div>
  );
};

// Appointment / contact form (validates, submits to a fake handler, persists to localStorage)
const AppointmentForm = ({ context = "Appointment", compact = false }) => {
  const [data, setData] = React.useState({
    name: "", email: "", phone: "", date: "", occasion: "Bridal", message: ""
  });
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);

  const validate = () => {
    const e = {};
    if (!data.name.trim()) e.name = "Please tell us your name.";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) e.email = "Enter a valid email.";
    if (!data.phone.trim() || data.phone.replace(/\D/g, "").length < 7) e.phone = "Enter a contact number.";
    if (!data.date) e.date = "Choose a preferred date.";
    setErrors(e);
    return Object.keys(e).length === 0;
  };
  const submit = (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    // Stash a record locally to feel real
    const all = JSON.parse(localStorage.getItem("mo_appts") || "[]");
    all.push({ ...data, context, at: new Date().toISOString() });
    localStorage.setItem("mo_appts", JSON.stringify(all));
    setSent(true);
  };

  if (sent) return (
    <div className="mo-form mo-form--sent">
      <div className="mo-eyebrow">Thank you</div>
      <h3 className="mo-display" style={{fontSize:"clamp(32px,3.4vw,46px)"}}>Your request is with the atelier.</h3>
      <p>Our team will reach out within one business day to confirm your appointment.<br/>For anything urgent, reach us on WhatsApp {CONTACT.whatsappPretty}.</p>
      <div style={{display:"flex", gap:14, marginTop:24, flexWrap:"wrap"}}>
        <a className="mo-btn mo-btn--ink" href={waUrl("Hi Maryam Omaira — I've just sent an appointment request from your site.")} target="_blank" rel="noopener noreferrer">Open WhatsApp</a>
        <button className="mo-btn mo-btn--outline" onClick={() => { setSent(false); setData({ name:"", email:"", phone:"", date:"", occasion:"Bridal", message:"" }); }}>Make another request</button>
      </div>
    </div>
  );

  const fld = (key, label, type="text", extra={}) => (
    <label className={"mo-field " + (errors[key] ? "mo-field--err" : "")}>
      <span>{label}</span>
      <input type={type} value={data[key]} onChange={e => setData({ ...data, [key]: e.target.value })} {...extra} />
      {errors[key] && <em>{errors[key]}</em>}
    </label>
  );

  return (
    <form className={"mo-form " + (compact ? "mo-form--compact" : "")} onSubmit={submit} noValidate>
      <div className="mo-form__row">
        {fld("name", "Full name")}
        {fld("email", "Email", "email")}
      </div>
      <div className="mo-form__row">
        {fld("phone", "Phone or WhatsApp", "tel")}
        {fld("date", "Preferred date", "date", { min: new Date().toISOString().slice(0,10) })}
      </div>
      <label className="mo-field">
        <span>Occasion</span>
        <div className="mo-pillrow">
          {["Bridal", "Couture", "RTW styling", "Jewellery"].map(opt => (
            <button type="button" key={opt} onClick={() => setData({ ...data, occasion: opt })}
              className={"mo-pill " + (data.occasion === opt ? "is-on" : "")}>{opt}</button>
          ))}
        </div>
      </label>
      <label className="mo-field">
        <span>Notes for the atelier (optional)</span>
        <textarea rows={4} value={data.message} placeholder="Tell us about your event, references, or fabrics you have in mind…" onChange={e => setData({ ...data, message: e.target.value })} />
      </label>
      <div className="mo-form__actions">
        <button type="submit" className="mo-btn mo-btn--ink mo-btn--lg">Request appointment</button>
        <a className="mo-btn mo-btn--outline mo-btn--lg" href={waUrl(`Hi Maryam Omaira, I'd like to book a ${data.occasion.toLowerCase()} appointment.`)} target="_blank" rel="noopener noreferrer">Or message on WhatsApp</a>
      </div>
      <p className="mo-form__legal">By submitting, you agree we may contact you about your request. We never share your details.</p>
    </form>
  );
};

Object.assign(window, { Wordmark, Navbar, Footer, WhatsAppFab, PriceBlock, ProductCard, Eyebrow, SectionHead, ProductModal, AppointmentForm });
