// Header, mobile menu, cart drawer, modal, toast — Salon Crème
const { useState, useEffect, useMemo, useRef, useContext, createContext } = React;

// ---------- Cart context ----------
const CartCtx = createContext(null);
window.CartCtx = CartCtx;

window.CartProvider = function CartProvider({ children }) {
  const [items, setItems] = useState([]);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [toast, setToast] = useState(null);
  const toastTimer = useRef(null);

  const addItem = (product, qty = 1) => {
    setItems(prev => {
      const found = prev.find(i => i.id === product.id);
      if (found) return prev.map(i => i.id === product.id ? { ...i, qty: i.qty + qty } : i);
      return [...prev, { id: product.id, product, qty }];
    });
    if (toastTimer.current) clearTimeout(toastTimer.current);
    setToast(`${product.name} נוסף לסל`);
    toastTimer.current = setTimeout(() => setToast(null), 2200);
  };
  const removeItem = id => setItems(prev => prev.filter(i => i.id !== id));
  const setQty = (id, qty) => setItems(prev => prev.map(i => i.id === id ? { ...i, qty: Math.max(1, qty) } : i));
  const count = items.reduce((s, i) => s + i.qty, 0);
  const total = items.reduce((s, i) => s + i.qty * i.product.price, 0);

  return React.createElement(CartCtx.Provider, {
    value: { items, addItem, removeItem, setQty, count, total, drawerOpen, setDrawerOpen, toast }
  }, children);
};

// ---------- Icons ----------
const Icon = {
  Cart: (p) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" {...p}>
      <path d="M5 7h14l-1.5 11a2 2 0 0 1-2 1.7H8.5a2 2 0 0 1-2-1.7L5 7Z"/>
      <path d="M9 7V5a3 3 0 0 1 6 0v2"/>
    </svg>
  ),
  Menu: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M4 7h16M4 12h16M4 17h16"/>
    </svg>
  ),
  X: (p) => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M6 6l12 12M18 6L6 18"/>
    </svg>
  ),
  Plus: (p) => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <path d="M12 5v14M5 12h14"/>
    </svg>
  ),
  Arrow: (p) => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M5 12h14M13 6l6 6-6 6"/>
    </svg>
  ),
  Search: (p) => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" {...p}>
      <circle cx="11" cy="11" r="7"/>
      <path d="M20 20l-3.2-3.2"/>
    </svg>
  ),
  Insta: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" {...p}>
      <rect x="3" y="3" width="18" height="18" rx="4"/>
      <circle cx="12" cy="12" r="4"/>
      <circle cx="17.5" cy="6.5" r="0.7" fill="currentColor"/>
    </svg>
  ),
};
window.Icon = Icon;

// ---------- Header ----------
window.Header = function Header({ activeCat, setActiveCat }) {
  const cart = useContext(CartCtx);
  const [menuOpen, setMenuOpen] = useState(false);
  const cats = window.SHALEV_DATA.categories;

  return (
    <>
      <div className="announce">
        <span>משלוח לכל אזור המרכז</span>
        <span className="dot"></span>
        <span>הזמנות אישיות בתיאום מראש</span>
        <span className="dot"></span>
        <span>אירועים ‎+‎48 שעות מראש</span>
      </div>
      <header className="site-header">
        <div className="container">
          <div className="header-top">
            <div className="header-right">
              <button className="icon-btn mobile-only" onClick={() => setMenuOpen(true)} aria-label="תפריט">
                <Icon.Menu />
              </button>
              <button className="icon-btn desktop-only" aria-label="חיפוש"><Icon.Search /></button>
              <a className="icon-btn" href="#contact" aria-label="צור קשר" onClick={(e) => { e.preventDefault(); document.getElementById('contact')?.scrollIntoView({behavior:'smooth'}); }}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4"><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>
              </a>
            </div>
            <a href="#" className="brand-mark" aria-label="Salon Crème">
              <span className="name">Salon Cr&egrave;me</span>
              <span className="tag">Pâtisserie Artisanale · ראשון לציון</span>
            </a>
            <div className="header-left">
              <button className="cta-solid desktop-only" onClick={() => document.getElementById('contact')?.scrollIntoView({behavior:'smooth'})}>הזמינו עכשיו</button>
            </div>
          </div>
          <nav className="nav-row">
            {cats.map(c => (
              <a key={c.id}
                 href={`#cat-${c.id}`}
                 className={activeCat === c.id ? "is-active" : ""}
                 onClick={(e) => { e.preventDefault(); setActiveCat(c.id); document.getElementById('shop')?.scrollIntoView({behavior: 'smooth', block: 'start'}); }}>
                {c.he}
              </a>
            ))}
          </nav>
        </div>
      </header>

      {/* Mobile menu drawer */}
      <div className={"drawer-backdrop " + (menuOpen ? "open" : "")} onClick={() => setMenuOpen(false)}></div>
      <aside className={"menu-drawer " + (menuOpen ? "open" : "")}>
        <div className="head">
          <span className="name">Salon Cr&egrave;me</span>
          <button className="icon-btn" onClick={() => setMenuOpen(false)} aria-label="סגור"><Icon.X /></button>
        </div>
        <ul>
          {cats.map(c => (
            <li key={c.id}><a href={`#cat-${c.id}`} onClick={(e) => { e.preventDefault(); setActiveCat(c.id); setMenuOpen(false); document.getElementById('shop')?.scrollIntoView({behavior: 'smooth', block: 'start'}); }}>{c.he}</a></li>
          ))}
          <li><a href="#story" onClick={() => setMenuOpen(false)}>הסיפור</a></li>
          <li><a href="#contact" onClick={() => setMenuOpen(false)}>הזמנות ויצירת קשר</a></li>
        </ul>
        <div className="foot">
          <button className="cta-solid" onClick={() => setMenuOpen(false)}>הזמינו עכשיו</button>
          <span className="eyebrow-en">SALON CR&Egrave;ME · EST. 2019</span>
        </div>
      </aside>
    </>
  );
};

// ---------- Cart drawer ----------
window.CartDrawer = function CartDrawer() {
  const cart = useContext(CartCtx);
  const open = cart.drawerOpen;
  return (
    <>
      <div className={"drawer-backdrop " + (open ? "open" : "")} onClick={() => cart.setDrawerOpen(false)}></div>
      <aside className={"drawer " + (open ? "open" : "")}>
        <div className="drawer-head">
          <h4>הסל שלך</h4>
          <button className="icon-btn" aria-label="סגור" onClick={() => cart.setDrawerOpen(false)}><Icon.X /></button>
        </div>
        <div className="drawer-body">
          {cart.items.length === 0 ? (
            <div className="empty-cart">
              <span className="e-title">הסל שלך ריק עדיין</span>
              <span>העוגות מחכות. הצטרפו לסיבוב טעימה.</span>
            </div>
          ) : cart.items.map(line => (
            <div key={line.id} className="cart-line">
              <div className="img"><img src={line.product.img} alt={line.product.name} /></div>
              <div className="info">
                <span className="n">{line.product.name}</span>
                <span className="text-muted" style={{fontSize:12.5}}>{line.product.en}</span>
                <div className="qty">
                  <button onClick={() => cart.setQty(line.id, line.qty - 1)} aria-label="הפחת">−</button>
                  <span>{line.qty}</span>
                  <button onClick={() => cart.setQty(line.id, line.qty + 1)} aria-label="הוסף">+</button>
                </div>
                <button className="remove" onClick={() => cart.removeItem(line.id)}>הסירו פריט</button>
              </div>
              <div className="price-cell">‎₪‎{line.qty * line.product.price}</div>
            </div>
          ))}
        </div>
        <div className="drawer-foot">
          <div className="total"><span>משלוח</span><span className="v">חינם מעל ‎₪‎250</span></div>
          <div className="total" style={{fontSize:16}}><span>סה״כ</span><span className="v">‎₪‎{cart.total}</span></div>
          <button className="cta-solid" disabled={cart.items.length === 0}>למעבר לתשלום</button>
          <span className="eyebrow-en" style={{textAlign:'center', marginTop:4}}>SECURE CHECKOUT · ISRAEL</span>
        </div>
      </aside>
    </>
  );
};

// ---------- Quick view modal ----------
window.QuickView = function QuickView({ product, onClose }) {
  const cart = useContext(CartCtx);
  const [size, setSize] = useState("רגיל");
  const [qty, setQty] = useState(1);
  const open = !!product;
  if (!product) return <div className="modal-backdrop"></div>;
  return (
    <div className={"modal-backdrop open"} onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{position:'relative'}}>
        <button className="close icon-btn" onClick={onClose} aria-label="סגור"><Icon.X /></button>
        <div className="img"><img src={product.img} alt={product.name} /></div>
        <div className="body">
          <span className="eyebrow">קולקציה / {product.en}</span>
          <h3>{product.name}</h3>
          <span className="price">‎₪‎{product.price}</span>
          <p>{product.desc} מוכן ביום ההזמנה בראשון לציון, נארז בקופסת קרפט וסרט ורוד. לבירור פרטים נוספים — צרו קשר ונסגור הכל יחד.</p>
          <div className="opts">
            <label>גודל</label>
            <div className="swatches">
              {["אישית", "רגיל", "משפחתית"].map(s => (
                <button key={s} className={size === s ? "active" : ""} onClick={() => setSize(s)}>{s}</button>
              ))}
            </div>
          </div>
          <div className="opts">
            <label>כמות</label>
            <div className="swatches">
              <button onClick={() => setQty(Math.max(1, qty - 1))}>−</button>
              <button className="active" style={{minWidth:48}}>{qty}</button>
              <button onClick={() => setQty(qty + 1)}>+</button>
            </div>
          </div>
          <div className="actions">
            <button className="cta-solid" onClick={() => {
              window.dispatchEvent(new CustomEvent('maison:contact', { detail: { product, size, qty } }));
              onClose();
              setTimeout(() => document.getElementById('contact')?.scrollIntoView({behavior:'smooth'}), 220);
            }}>צרו קשר להזמנה</button>
          </div>
          <span className="eyebrow-en">MADE TO ORDER · 48H NOTICE</span>
        </div>
      </div>
    </div>
  );
};

// ---------- Toast ----------
window.Toast = function Toast() {
  const cart = useContext(CartCtx);
  return (
    <div className={"toast " + (cart.toast ? "show" : "")}>
      <span className="dot"></span>
      <span>{cart.toast || ""}</span>
    </div>
  );
};

Object.assign(window, { Header: window.Header, CartDrawer: window.CartDrawer, QuickView: window.QuickView, Toast: window.Toast, CartProvider: window.CartProvider, CartCtx, Icon });
