// Chrome — nav, footer, drawers, modals
const { useState, useEffect, useRef } = React;

function fmtPrice(p, cur) {
  if (cur === 'USD') return '$' + p.toLocaleString();
  if (cur === 'EUR') return '€' + p.toLocaleString();
  if (cur === 'AED') return 'AED ' + p.toLocaleString();
  return p.toLocaleString();
}

function convertPrice(p, fromCur, toCur) {
  // illustrative rates only
  const toUSD = { USD: 1, EUR: 1.09, AED: 0.272 };
  const fromUSD = { USD: 1, EUR: 0.92, AED: 3.67 };
  return Math.round(p * toUSD[fromCur] * fromUSD[toCur]);
}

function Logo({ size = 'md', inverse = false }) {
  const fz = size === 'lg' ? 36 : size === 'sm' ? 14 : 22;
  return (
    <div style={{
      fontFamily: 'var(--font-display)',
      fontWeight: 800,
      letterSpacing: '0.04em',
      fontSize: fz,
      lineHeight: 1,
      color: inverse ? 'var(--paper)' : 'var(--ink)',
      whiteSpace: 'nowrap',
    }}>
      MRS<span style={{fontSize: fz*0.6, verticalAlign: '0.18em'}}>.</span>KEEPA
    </div>
  );
}

function Mark({ inverse = false, sz = 12 }) {
  // a small "·MK·" mark for utility spots
  return (
    <span style={{
      fontFamily: 'var(--font-display)',
      fontWeight: 700,
      fontSize: sz,
      letterSpacing: '0.18em',
      color: inverse ? 'var(--paper)' : 'var(--ink)',
    }}>MK</span>
  );
}

function UtilityBar({ currency, setCurrency }) {
  return (
    <div className="util-bar">
      <div className="util-inner">
        <div className="util-left">
          <span>Complimentary worldwide express over $400</span>
          <span className="dot">·</span>
          <span>Atelier appointments in Dubai Design District</span>
        </div>
        <div className="util-right">
          <div className="cur-switch">
            {['USD','EUR','AED'].map(c => (
              <button key={c} onClick={() => setCurrency(c)}
                className={currency === c ? 'on' : ''}>{c}</button>
            ))}
          </div>
          <span className="dot">·</span>
          <a href="#" onClick={(e)=>e.preventDefault()}>EN</a>
        </div>
      </div>
    </div>
  );
}

function Nav({ route, setRoute, openBag, bagCount, openAppt, openSearch }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', on);
    return () => window.removeEventListener('scroll', on);
  }, []);
  const go = (r) => (e) => { e.preventDefault(); setRoute(r); window.scrollTo({top:0,behavior:'instant'}); };
  return (
    <header className={'nav ' + (scrolled ? 'scrolled' : '')}>
      <div className="nav-row">
        <div className="nav-left">
          <a href="#" onClick={go({page:'shop'})} className={'navlink ' + (route.page==='shop'?'on':'')}>Ready to Wear</a>
          <a href="#" onClick={go({page:'studio'})} className={'navlink ' + (route.page==='studio'?'on':'')}>Studio / Couture</a>
          <a href="#" onClick={go({page:'collections'})} className={'navlink ' + (route.page==='collections'?'on':'')}>Collections</a>
          <a href="#" onClick={go({page:'designer'})} className={'navlink ' + (route.page==='designer'?'on':'')}>Atelier</a>
        </div>
        <a href="#" onClick={go({page:'home'})} className="nav-logo" aria-label="Mrs. Keepa — home">
          <Logo size="md" />
        </a>
        <div className="nav-right">
          <button className="navlink" onClick={openSearch}>Search</button>
          <button className="navlink" onClick={openAppt}>Appointment</button>
          <button className="navlink" onClick={openBag}>
            Bag<sup style={{marginLeft:4}}>{bagCount}</sup>
          </button>
        </div>
      </div>
    </header>
  );
}

function Footer({ setRoute, openAppt }) {
  const go = (r) => (e) => { e.preventDefault(); setRoute(r); window.scrollTo({top:0}); };
  return (
    <footer className="footer">
      <div className="footer-grid">
        <div className="footer-col footer-mark">
          <Logo size="md" inverse />
          <p className="footer-tag">Where Ready to Wear Meets Couture.<br/>Dubai · since May 2016.</p>
          <div className="footer-socials">
            <a href="https://instagram.com/mrskeepaofficial" target="_blank" rel="noopener">Instagram</a>
            <a href="https://wa.me/971526933359" target="_blank" rel="noopener">WhatsApp</a>
            <a href="mailto:queries@mrskeepa.com">queries@mrskeepa.com</a>
          </div>
        </div>
        <div className="footer-col">
          <h6>Shop</h6>
          <a href="#" onClick={go({page:'shop'})}>Ready to Wear</a>
          <a href="#" onClick={go({page:'studio'})}>Studio / Couture</a>
          <a href="#" onClick={go({page:'collections'})}>Collections</a>
          <a href="#" onClick={go({page:'shop', filter:{category:'evening-dresses'}})}>Evening Dresses</a>
          <a href="#" onClick={go({page:'shop', filter:{category:'kimonos'}})}>Kimonos</a>
        </div>
        <div className="footer-col">
          <h6>House</h6>
          <a href="#" onClick={go({page:'designer'})}>The Atelier</a>
          <a href="#" onClick={go({page:'sustainability'})}>Materials & Practice</a>
          <a href="#" onClick={go({page:'press'})}>Press</a>
          <a href="#" onClick={openAppt}>Book an Appointment</a>
          <a href="#" onClick={go({page:'contact'})}>Contact</a>
        </div>
        <div className="footer-col">
          <h6>Atelier</h6>
          <p className="footer-addr">
            B307, Building 7<br/>
            Dubai Design District (d3)<br/>
            Dubai, United Arab Emirates
          </p>
          <p className="footer-addr small">
            +971 52 693 3359<br/>
            Appointments by request — Sat–Thu.
          </p>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© Mrs. Keepa {new Date().getFullYear()}. Designed in Dubai.</span>
        <span className="footer-bottom-right">
          <a href="#" onClick={(e)=>e.preventDefault()}>Terms</a>
          <a href="#" onClick={(e)=>e.preventDefault()}>Privacy</a>
          <a href="#" onClick={(e)=>e.preventDefault()}>Shipping & Returns</a>
        </span>
      </div>
    </footer>
  );
}

function BagDrawer({ open, onClose, items, currency, removeItem }) {
  const total = items.reduce((s, it) => s + convertPrice(it.price, it.currency, currency) * it.qty, 0);
  return (
    <>
      <div className={'overlay ' + (open ? 'on' : '')} onClick={onClose} />
      <aside className={'drawer ' + (open ? 'on' : '')} aria-hidden={!open}>
        <div className="drawer-head">
          <h3>Your Bag</h3>
          <button className="x" onClick={onClose} aria-label="Close">✕</button>
        </div>
        {items.length === 0 ? (
          <div className="bag-empty">
            <p className="display">Your bag is empty.</p>
            <p className="muted">When you find a piece worth keeping, it lives here.</p>
          </div>
        ) : (
          <>
            <div className="bag-items">
              {items.map((it, i) => (
                <div className="bag-item" key={it.id + i}>
                  <div className="bag-img" style={{backgroundImage: `url(${it.img})`}} />
                  <div className="bag-info">
                    <p className="bag-name">{it.name}</p>
                    <p className="bag-meta">Size {it.size} · {it.colorway}</p>
                    <p className="bag-meta">Qty {it.qty}</p>
                    <button className="bag-remove" onClick={() => removeItem(i)}>Remove</button>
                  </div>
                  <div className="bag-price">
                    {fmtPrice(convertPrice(it.price, it.currency, currency) * it.qty, currency)}
                  </div>
                </div>
              ))}
            </div>
            <div className="bag-foot">
              <div className="bag-total">
                <span>Subtotal</span>
                <span>{fmtPrice(total, currency)}</span>
              </div>
              <p className="muted small">Duties and shipping calculated at checkout.</p>
              <button className="btn primary block">Checkout</button>
              <button className="btn ghost block">Continue Shopping</button>
            </div>
          </>
        )}
      </aside>
    </>
  );
}

function AppointmentModal({ open, onClose }) {
  const [stage, setStage] = useState('form');
  const [form, setForm] = useState({ name: '', email: '', kind: 'Studio / Couture', date: '', time: '14:00', note: '' });
  useEffect(() => { if (open) { setStage('form'); setForm({ name: '', email: '', kind: 'Studio / Couture', date: '', time: '14:00', note: '' }); } }, [open]);
  const submit = (e) => { e.preventDefault(); setStage('done'); };
  return (
    <>
      <div className={'overlay ' + (open ? 'on' : '')} onClick={onClose} />
      <div className={'modal ' + (open ? 'on' : '')} aria-hidden={!open}>
        <button className="x modal-x" onClick={onClose}>✕</button>
        {stage === 'form' ? (
          <div className="modal-body">
            <div className="modal-left">
              <p className="eyebrow">Atelier · Dubai Design District</p>
              <h2 className="display lg">Book an appointment.</h2>
              <p className="lede">A private consultation at the Mrs. Keepa atelier — Ready to Wear fittings, Studio commissions, or a closer look at the Inhale couture collection.</p>
              <div className="modal-meta">
                <div>
                  <p className="eyebrow xs">Location</p>
                  <p>B307, Building 7<br/>Dubai Design District</p>
                </div>
                <div>
                  <p className="eyebrow xs">Hours</p>
                  <p>By appointment<br/>Sat–Thu</p>
                </div>
                <div>
                  <p className="eyebrow xs">Direct</p>
                  <p>+971 52 693 3359<br/>WhatsApp accepted</p>
                </div>
              </div>
            </div>
            <form className="modal-right" onSubmit={submit}>
              <label className="field">
                <span>Name</span>
                <input required value={form.name} onChange={e=>setForm({...form, name: e.target.value})} />
              </label>
              <label className="field">
                <span>Email or WhatsApp</span>
                <input required value={form.email} onChange={e=>setForm({...form, email: e.target.value})} />
              </label>
              <label className="field">
                <span>What you're looking for</span>
                <select value={form.kind} onChange={e=>setForm({...form, kind: e.target.value})}>
                  <option>Studio / Couture</option>
                  <option>Inhale — couture commission</option>
                  <option>Ready to Wear styling</option>
                  <option>Bridal & event dressing</option>
                  <option>Press / stylist appointment</option>
                </select>
              </label>
              <div className="field-row">
                <label className="field">
                  <span>Preferred date</span>
                  <input required type="date" value={form.date} onChange={e=>setForm({...form, date: e.target.value})} />
                </label>
                <label className="field">
                  <span>Time</span>
                  <select value={form.time} onChange={e=>setForm({...form, time: e.target.value})}>
                    {['10:00','11:00','12:00','13:00','14:00','15:00','16:00','17:00'].map(t =>
                      <option key={t}>{t}</option>
                    )}
                  </select>
                </label>
              </div>
              <label className="field">
                <span>A note (optional)</span>
                <textarea rows={3} value={form.note} onChange={e=>setForm({...form, note: e.target.value})}
                  placeholder="Event, silhouette, references — anything you'd like us to know in advance." />
              </label>
              <button type="submit" className="btn primary block">Request appointment</button>
              <p className="muted small">We confirm by email within one business day.</p>
            </form>
          </div>
        ) : (
          <div className="modal-done">
            <p className="eyebrow">Request received</p>
            <h2 className="display lg">Thank you, {form.name.split(' ')[0] || 'we have it'}.</h2>
            <p className="lede">A member of the atelier team will reach out within one business day to confirm your appointment on {form.date || 'your requested date'} at {form.time}.</p>
            <p className="muted">In the meantime, you're welcome to message us directly on WhatsApp.</p>
            <div className="row gap">
              <a href="https://wa.me/971526933359" target="_blank" rel="noopener" className="btn primary">Open WhatsApp</a>
              <button onClick={onClose} className="btn ghost">Close</button>
            </div>
          </div>
        )}
      </div>
    </>
  );
}

function SearchOverlay({ open, onClose, allProducts, openProduct }) {
  const [q, setQ] = useState('');
  const inputRef = useRef(null);
  useEffect(() => { if (open) setTimeout(() => inputRef.current && inputRef.current.focus(), 100); }, [open]);
  useEffect(() => { if (!open) setQ(''); }, [open]);
  const results = q.length > 0
    ? allProducts.filter(p =>
        p.name.toLowerCase().includes(q.toLowerCase()) ||
        p.collection.toLowerCase().includes(q.toLowerCase()) ||
        p.category.toLowerCase().includes(q.toLowerCase())
      ).slice(0, 8)
    : [];
  return (
    <div className={'search-overlay ' + (open ? 'on' : '')} aria-hidden={!open}>
      <div className="search-inner">
        <div className="search-row">
          <input ref={inputRef} value={q} onChange={e=>setQ(e.target.value)}
            placeholder="Search a piece, a collection, a colour…" />
          <button className="x" onClick={onClose}>Close</button>
        </div>
        {q.length === 0 ? (
          <div className="search-suggest">
            <p className="eyebrow">Try</p>
            <div className="chips">
              {['Dresses','Kimonos','Mushroom Print','The Getaway','Inhale','Evening'].map(s =>
                <button key={s} className="chip" onClick={() => setQ(s)}>{s}</button>
              )}
            </div>
          </div>
        ) : (
          <div className="search-results">
            {results.length === 0 && <p className="muted">No piece matches that — try a collection name, or write us on WhatsApp.</p>}
            {results.map(p => (
              <button key={p.id} className="search-hit" onClick={() => { openProduct(p); onClose(); }}>
                <div className="search-hit-img" style={{backgroundImage: `url(${p.img})`}}/>
                <div className="search-hit-info">
                  <p className="search-hit-name">{p.name}</p>
                  <p className="search-hit-meta">{p.collection} · {p.category}</p>
                </div>
                <div className="search-hit-price">{fmtPrice(p.price, p.currency)}</div>
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function WhatsAppFab() {
  return (
    <a href="https://wa.me/971526933359" target="_blank" rel="noopener" className="wa-fab" aria-label="Message us on WhatsApp">
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
        <path d="M3 21l1.65-3.8A8.5 8.5 0 1 1 7.4 19.5L3 21z"/>
        <path d="M8.5 9.5c.5 1.7 2.3 3.5 4 4 0 0 .9-.3 1.2-.6.3-.3.7-.3 1 0l1.3 1c.3.2.3.6.1.9-.7 1-1.7 1.5-2.8 1.2-2.4-.6-5-3.2-5.6-5.6-.3-1 .2-2.1 1.2-2.8.3-.2.7-.2.9.1l1 1.3c.3.3.3.7 0 1l-.6 1.2z"/>
      </svg>
    </a>
  );
}

Object.assign(window, {
  Logo, Mark, UtilityBar, Nav, Footer, BagDrawer, AppointmentModal, SearchOverlay, WhatsAppFab,
  fmtPrice, convertPrice,
});
