/* =========================================================
   VERSION A WEB — All screens in one file.
   Routes: home | product/:id | cart | checkout | confirm
   ========================================================= */
const { useState, useEffect } = React;

/* -------------------- Sign Header (reusable) -------------------- */
// Live open/closed status from the real clock. Hours: Sun–Thu 09:30–20:30, Fri 09:00–17:00, Sat closed.
function storeStatus() {
  const now = new Date();
  const day = now.getDay();                       // 0=Sun … 6=Sat
  const mins = now.getHours() * 60 + now.getMinutes();
  const sched = { 0: [570, 1230], 1: [570, 1230], 2: [570, 1230], 3: [570, 1230], 4: [570, 1230], 5: [540, 1020], 6: null };
  const fmt = m => String(Math.floor(m / 60)).padStart(2, '0') + ':' + String(m % 60).padStart(2, '0');
  const dayNames = ['ראשון', 'שני', 'שלישי', 'רביעי', 'חמישי', 'שישי', 'שבת'];
  const today = sched[day];
  if (today && mins >= today[0] && mins < today[1]) return { open: true, text: 'פתוח עכשיו · סגירה ב־' + fmt(today[1]) };
  if (today && mins < today[0]) return { open: false, text: 'סגור · פתיחה היום ב־' + fmt(today[0]) };
  for (let i = 1; i <= 7; i++) {
    const d = (day + i) % 7;
    if (sched[d]) return { open: false, text: 'סגור · פתיחה ' + (i === 1 ? 'מחר' : 'ביום ' + dayNames[d]) + ' ב־' + fmt(sched[d][0]) };
  }
  return { open: false, text: 'סגור' };
}

function SignHeader() {
  const [, tick] = React.useState(0);
  React.useEffect(() => { const t = setInterval(() => tick(n => n + 1), 60000); return () => clearInterval(t); }, []);
  const st = storeStatus();
  return (
    <>
      <div className="top-strip">
        <div className="inner">
          <span><span className={'dot' + (st.open ? '' : ' closed')}></span>{st.text}</span>
          <span className="sep">·</span>
          <span>משלוח עד הבית</span>
          <span className="sep">·</span>
          <span>איסוף עצמי</span>
        </div>
      </div>
      <div className="sign-bar">
        <div className="inner">
          <span className="phone-pill">03-6053532</span>
          <h1 className="sign-title">כל-בו יחזקאל</h1>
          <div className="addr-block">
            <div className="l1">אבן גבירול 163</div>
            <div className="l2">תל אביב</div>
          </div>
        </div>
      </div>
    </>
  );
}

/* -------------------- Nav strip (sticky categories + cart) -------------------- */
function NavStrip({ go, cart, activeCat, setActiveCat }) {
  const cartCount = Object.values(cart).reduce((s, v) => s + v, 0);
  const [bump, setBump] = React.useState(false);
  const prevCount = React.useRef(cartCount);
  React.useEffect(() => {
    if (cartCount > prevCount.current) {
      setBump(true);
      const t = setTimeout(() => setBump(false), 500);
      prevCount.current = cartCount;
      return () => clearTimeout(t);
    }
    prevCount.current = cartCount;
  }, [cartCount]);
  const cls = 'nav-cart' + (bump ? ' bump' : '');
  return (
    <div className="nav-strip">
      <div className="inner">
        {window.CATEGORIES.map(c => (
          <button
            key={c.id}
            className={'nav-chip' + (activeCat === c.id ? ' active' : '')}
            onClick={() => { const fromCart = location.hash.replace(/^#\/?/, '') === 'cart'; setActiveCat(c.id); go('home'); setTimeout(() => requestAnimationFrame(() => { const nav = document.querySelector('.nav-strip'); const head = document.querySelector('.section-head'); if (head) window.scrollTo({ top: window.scrollY + head.getBoundingClientRect().top - (nav ? nav.offsetHeight : 0) - 16, behavior: 'smooth' }); }), fromCart ? 500 : 30); }}
          >{c.name}</button>
        ))}
        <div className="nav-spacer"></div>
        <button className={cls} onClick={() => go('cart')}>
          <span className="cart-ic">🛒</span> סל הקניות
          {cartCount > 0 && <span className="cart-badge">{cartCount}</span>}
        </button>
      </div>
    </div>
  );
}

/* -------------------- Footer -------------------- */
function Footer() {
  return (
    <footer className="footer">
      <div className="inner">
        <div>
          <div className="sign-mini">כל-בו יחזקאל</div>
          <p>חנות שכונתית פעילה ברחוב אבן גבירול מאז 1987.</p>
          <p className="footer-types">חומרי ניקוי ואביזרי ניקיון · רחצה והיגיינה · כביסה · מוצרי נייר · שקיות אשפה</p>
        </div>
        <div>
          <h4>קטגוריות</h4>
          <ul>
            {window.CATEGORIES.filter(c => c.id !== 'all' && c.id !== 'sale').map(c => (
              <li key={c.id}>{c.name}</li>
            ))}
          </ul>
        </div>
        <div>
          <h4>החנות</h4>
          <ul>
            <li>אבן גבירול 163, ת״א</li>
            <li>03-6053532</li>
            <li>א׳–ה׳ 09:30–20:30</li>
            <li>ו׳ 09:00–17:00</li>
          </ul>
        </div>
        <div>
          <h4>משלוחים</h4>
          <ul>
            <li>משלוח עד הבית</li>
            <li>איסוף עצמי</li>
            <li>ההזמנה פתוחה תמיד — גם כשסגור</li>
          </ul>
        </div>
      </div>
      <div className="copy">© 2026 כל-בו יחזקאל · כל הזכויות שמורות</div>
    </footer>
  );
}

/* -------------------- HOME -------------------- */
function HomeAWeb({ go, cart, addToCart, activeCat, setActiveCat }) {
  const filtered = window.PRODUCTS.filter(p => {
    if (activeCat === 'all') return true;
    if (activeCat === 'sale') return p.sale;
    return p.cat === activeCat;
  });
  const featured = window.PRODUCTS.filter(p => p.sale);

  return (
    <>
      <SignHeader />
      <NavStrip go={go} cart={cart} activeCat={activeCat} setActiveCat={setActiveCat} />

      <div
        className="hero-strip"
        style={{ backgroundImage: 'url(assets/storefront-2.jpeg)' }}
      >
        <div className="inner">
          <div>
            <h1>מחירים שפשוט יותר משתלמים.</h1>
            <div className="blurb">כל מה שצריך לבית — במחירים שמשתלמים יותר מכל הרשתות מסביב. ניקוי · טואלטיקה · מטבח · הדברה · חד״פ.</div>
          </div>
          <div className="est-badge">מאז 1987</div>
        </div>
      </div>

      <div className="quick-stats">
        <div className="inner">
          <div className="stat">
            <div className="icon">🚚</div>
            <div><div className="lbl">משלוח עד הבית</div><div className="val">תוך 24 שעות</div></div>
          </div>
          <div className="stat">
            <div className="icon">🛍️</div>
            <div><div className="lbl">איסוף עצמי</div><div className="val">אבן גבירול 163</div></div>
          </div>
          <div className="stat">
            <div className="icon">💰</div>
            <div><div className="lbl">מאות פריטים</div><div className="val">המחירים הכי טובים בת״א</div></div>
          </div>
          <div className="stat">
            <div className="icon">📞</div>
            <div><div className="lbl">צריכים עזרה?</div><div className="val">03-6053532</div></div>
          </div>
        </div>
      </div>

      <div className="section-shell">
        <div className="cat-row">
          {window.CATEGORIES.map(c => (
            <button
              key={c.id}
              className={'cat-chip' + (activeCat === c.id ? ' active' : '')}
              onClick={() => setActiveCat(c.id)}
            >{c.name}</button>
          ))}
        </div>

        <div className="section-head">
          <h2>{activeCat === 'all'
            ? <>הכי נמכרים <span className="accent">השבוע</span></>
            : window.CATEGORIES.find(c => c.id === activeCat)?.name}
          </h2>
          <span className="count">{filtered.length} מוצרים</span>
        </div>

        <div className="prod-grid">
          {filtered.map(p => (
            <div key={p.id} className="product-card" onClick={() => go('product/' + p.id)}>
              <div className="ph" style={{ backgroundImage: `url(${p.image})` }}>
                {p.sale && <div className="sale-burst">מבצע!</div>}
                {window.topPromos && window.topPromos(p).length > 0 && (
                  <div className="promo-badge">
                    {window.topPromos(p).map((t, i) => <span key={i} className="promo-chip">{t.qty} ב-{window.fmtPrice(t.price)}₪</span>)}
                  </div>
                )}
              </div>
              <div className="info">
                <h3 className="name">{p.name}</h3>
                <div className="sub">{p.sub}</div>
                <div className="price-row">
                  <div>
                    <span className="price-tag">{window.fmtPrice(p.price)}<span className="nis">₪</span></span>
                    <div className="vat-note">כולל מע״מ</div>
                  </div>
                  <button className="add-btn" onClick={(e) => { e.stopPropagation(); addToCart(p.id, 1); }}>
                    + להוסיף
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="about-band">
        <div className="inner">
          <div className="img-stack">
            <div className="a-img big" style={{ backgroundImage: 'url(assets/storefront-1.jpeg)' }}></div>
            <div className="a-img small" style={{ backgroundImage: 'url(assets/storefront-4.jpeg)' }}></div>
          </div>
          <div>
            <h3>על החנות</h3>
            <h2>שכונה. ותק. מחיר הוגן.</h2>
            <p>כל-בו יחזקאל פתח את הדלתות באבן גבירול לפני כמעט 40 שנה. מאז הפכנו לכתובת של כל המשפחות בשכונה — מכל מה שצריך לניקוי הבית ועד לחומרי הדברה שלא משאירים מקקים. בלי הפתעות במחיר, עם שירות שאי אפשר לקבל ברשת.</p>
            <div className="badges">
              <span className="badge">37 שנות ותק</span>
              <span className="badge">משלוחים</span>
              <span className="badge">מאות מוצרים</span>
              <span className="badge">שירות אישי</span>
            </div>
          </div>
        </div>
      </div>

      <Footer />
    </>
  );
}

/* -------------------- PRODUCT (modal-style overlay) -------------------- */
function ProductAWeb({ id, go, addToCart }) {
  const p = window.PRODUCT_BY_ID[id];
  const [qty, setQty] = useState(1);
  const [closing, setClosing] = useState(false);
  function addAndClose() {
    setClosing(true);                             // fade the popup out
    setTimeout(() => go('home'), 320);            // back to the store after the fade
    setTimeout(() => addToCart(p.id, qty), 400);  // delay the cart (סל) button bump
  }
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') go('home'); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);
  if (!p) return null;

  return (
    <div className={'pd-overlay' + (closing ? ' closing' : '')} onClick={() => go('home')}>
      <div className="pd-modal" onClick={e => e.stopPropagation()}>
        <button className="close-x" onClick={() => go('home')}>✕</button>
        <div className="pd-image" style={{ backgroundImage: `url(${p.image})` }}>
          {p.sale && <div className="sale-burst">מבצע!</div>}
          {p.inStock === false && <div className="oos-badge">לא במלאי</div>}
          {window.topPromos && window.topPromos(p).length > 0 && (
            <div className="promo-badge">
              {window.topPromos(p).map((t, i) => <span key={i} className="promo-chip">{t.qty} ב-{window.fmtPrice(t.price)}₪</span>)}
            </div>
          )}
        </div>
        <div className="pd-body">
          <h1>{p.name}</h1>
          <div className="pd-sub">{p.sub}</div>
          {(p.eco || p.natural) && (
            <div className="tag-badges" style={{ marginTop: 10 }}>
              {p.eco && <span className="tag-badge eco">אקולוגי</span>}
              {p.natural && <span className="tag-badge natural">טבעי</span>}
            </div>
          )}

          <div className="pd-price-block">
            <span className="price-tag">{window.fmtPrice(p.price)}<span className="nis">₪</span></span>
            <span className="vat-note">כולל מע״מ</span>
          </div>

          {window.normPromos && window.normPromos(p.promos).length > 0 && (
            <div className="promo-deals">
              <div className="ttl">💎 מבצעים מיוחדים</div>
              {window.normPromos(p.promos).map((t, i) => (
                <div key={i} className="deal"><b>{t.qty}</b> יחידות ב-<b>{window.fmtPrice(t.price)}₪</b></div>
              ))}
            </div>
          )}

          <p className="pd-desc">{p.desc}</p>

          {p.inStock === false
            ? <div className="oos-note">המוצר אזל מהמלאי כרגע</div>
            : (
            <div className="pd-actions">
              <div className="qty-stepper">
                <button onClick={() => setQty(Math.max(1, qty - 1))}>−</button>
                <div className="qty-val">{qty}</div>
                <button onClick={() => setQty(qty + 1)}>+</button>
              </div>
              <button
                className="btn-primary"
                onClick={addAndClose}
              >
                הוסף לסל · ₪{window.fmtPrice(window.promoForItem ? window.promoForItem(p.id, qty).lineNet : p.price * qty)}
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* -------------------- CART -------------------- */
function CartAWeb({ go, cart, updateQty, activeCat, setActiveCat }) {
  const items = Object.entries(cart).map(([id, qty]) => ({ ...window.PRODUCT_BY_ID[id], qty }));
  const pricing = window.cartPricing ? window.cartPricing(cart) : { subtotal: items.reduce((s, i) => s + i.price * i.qty, 0), discount: 0 };
  const subtotal = pricing.subtotal;
  const discount = pricing.discount || 0;
  const total = subtotal - discount;   // delivery is free

  return (
    <>
      <SignHeader />
      <NavStrip go={go} cart={cart} activeCat={activeCat} setActiveCat={setActiveCat} />

      {items.length === 0 ? (
        <div className="empty-state">
          <div className="e-emoji">🛒</div>
          <h3>הסל ריק</h3>
          <p>הוסף מוצרים מהחנות כדי להתחיל הזמנה</p>
          <button className="btn-primary" onClick={() => go('home')}>חזרה לחנות</button>
        </div>
      ) : (
        <div className="split-shell">
          <div className="panel">
            <h2>סל הקניות ({items.length} פריטים)</h2>
            {items.map(i => (
              <div key={i.id} className="cart-row">
                <div className="thumb" style={{ backgroundImage: `url(${i.image})` }}>
                  {window.promoForItem && window.promoForItem(i.id, i.qty).saved > 0 && <span className="cart-burst">מבצע</span>}
                </div>
                <div className="meta">
                  <b>{i.name}</b>
                  <span>{i.sub}</span>
                </div>
                <div className="mini-qty">
                  <button onClick={() => updateQty(i.id, i.qty - 1)}>−</button>
                  <span>{i.qty}</span>
                  <button onClick={() => updateQty(i.id, i.qty + 1)}>+</button>
                </div>
                <div className="ci-price">₪{window.fmtPrice(i.price * i.qty)}</div>
                <button className="remove" onClick={() => updateQty(i.id, 0)} title="הסר">✕</button>
              </div>
            ))}
          </div>

          <div className="sidebar">
            <h3>סיכום הזמנה</h3>
            <div className="row"><span>סכום ביניים</span><span>₪{window.fmtPrice(subtotal)}</span></div>
            {discount > 0 && <div className="row promo-save"><span>מבצעים מיוחדים</span><span>−₪{window.fmtPrice(discount)}</span></div>}
            <div className="row total"><span>סה״כ <span className="vat-note">כולל מע״מ</span></span><span>₪{window.fmtPrice(total)}</span></div>
            <button className="checkout-btn" onClick={() => go('checkout')}>המשך להזמנה ←</button>
            <button
              onClick={() => { setActiveCat('all'); go('home'); setTimeout(() => requestAnimationFrame(() => { const nav = document.querySelector('.nav-strip'); const head = document.querySelector('.section-head'); if (head) window.scrollTo({ top: window.scrollY + head.getBoundingClientRect().top - (nav ? nav.offsetHeight : 0) - 16, behavior: 'smooth' }); }), 500); }}
              style={{ marginTop: 12, width: '100%', background: 'transparent', color: '#ffde00', border: '2px solid #ffde00', borderRadius: 4, padding: '10px', fontWeight: 800, fontFamily: 'inherit', fontSize: 14, cursor: 'pointer' }}
            >הוסף מוצרים</button>
            <div style={{ fontSize: 12, opacity: 0.7, marginTop: 14, textAlign: 'center' }}>
              איסוף עצמי? תוכל לבחור בעמוד הבא
            </div>
          </div>
        </div>
      )}

      <Footer />
    </>
  );
}

/* -------------------- CHECKOUT -------------------- */
function CheckoutAWeb({ go, cart, submit, activeCat, setActiveCat }) {
  const items = Object.entries(cart).map(([id, qty]) => ({ ...window.PRODUCT_BY_ID[id], qty }));
  const pricing = window.cartPricing ? window.cartPricing(cart) : { subtotal: items.reduce((s, i) => s + i.price * i.qty, 0), discount: 0 };
  const subtotal = pricing.subtotal;
  const discount = pricing.discount || 0;
  const [method, setMethod] = useState('delivery');
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [address, setAddress] = useState('');
  const [note, setNote] = useState('');
  const total = subtotal - discount;   // delivery is free
  const canSubmit = name.trim() && phone.trim();

  return (
    <>
      <SignHeader />
      <NavStrip go={go} cart={cart} activeCat={activeCat} setActiveCat={setActiveCat} />

      <div className="split-shell">
        <div className="panel">
          <h2>פרטי הזמנה</h2>

          <div style={{ marginBottom: 14, fontSize: 13, fontWeight: 800, color: '#c8181e' }}>איך לקבל את ההזמנה?</div>
          <div className="method-row">
            <div className={'method-card' + (method === 'delivery' ? ' active' : '')} onClick={() => setMethod('delivery')}>
              <div className="m-icon">🚚</div>
              <div className="m-label">משלוח</div>
              <div className="m-note">עד הבית תוך 24 שעות</div>
            </div>
            <div className={'method-card' + (method === 'pickup' ? ' active' : '')} onClick={() => setMethod('pickup')}>
              <div className="m-icon">🛍️</div>
              <div className="m-label">איסוף עצמי</div>
              <div className="m-note">אבן גבירול 163</div>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <div className="field">
              <label>שם מלא <span className="req">*</span></label>
              <input type="text" value={name} onChange={e => setName(e.target.value)} placeholder="ישראל ישראלי" />
            </div>
            <div className="field">
              <label>טלפון <span className="req">*</span></label>
              <input type="tel" value={phone} onChange={e => setPhone(e.target.value)} placeholder="050-1234567" />
            </div>
          </div>
          {method === 'delivery' && (
            <div className="field">
              <label>כתובת למשלוח</label>
              <input type="text" value={address} onChange={e => setAddress(e.target.value)} placeholder="רחוב ועיר" />
            </div>
          )}
          <div className="field">
            <label>הערות <span className="opt">(לא חובה)</span></label>
            <textarea rows="3" value={note} onChange={e => setNote(e.target.value)} placeholder="קומה, קוד דלת, וכו׳"></textarea>
          </div>
        </div>

        <div className="sidebar">
          <h3>סיכום ההזמנה</h3>
          {items.map(i => (
            <div key={i.id} className="row" style={{ fontSize: 13 }}>
              <span style={{ opacity: 0.85 }}>{i.name} × {i.qty}</span>
              <span>₪{window.fmtPrice(i.price * i.qty)}</span>
            </div>
          ))}
          <div className="row" style={{ marginTop: 10 }}><span>{method === 'delivery' ? 'משלוח עד הבית' : 'איסוף עצמי'}</span></div>
          {discount > 0 && <div className="row promo-save"><span>מבצעים מיוחדים</span><span>−₪{window.fmtPrice(discount)}</span></div>}
          <div className="row total"><span>סה״כ <span className="vat-note">כולל מע״מ</span></span><span>₪{window.fmtPrice(total)}</span></div>
          <button
            className="checkout-btn"
            disabled={!canSubmit}
            style={!canSubmit ? { opacity: 0.4, cursor: 'not-allowed' } : {}}
            onClick={async () => { await submit({ name, phone, address, method, note, total, discount }); go('confirm'); }}
          >שליחת הזמנה</button>
          <div style={{ fontSize: 12, opacity: 0.7, marginTop: 12, textAlign: 'center' }}>
            ניצור איתך קשר תוך כמה דקות לאישור.
          </div>
        </div>
      </div>

      <Footer />
    </>
  );
}

/* -------------------- CONFIRMATION -------------------- */
function ConfirmAWeb({ go, lastOrder, clearCart, activeCat, setActiveCat, cart }) {
  useEffect(() => { clearCart(); }, []);
  const id = lastOrder?.id || '4128';

  return (
    <>
      <SignHeader />
      <NavStrip go={go} cart={cart} activeCat={activeCat} setActiveCat={setActiveCat} />

      <div className="confirm-shell">
        <div className="confirm-badge">✓</div>
        <h1>ההזמנה נשלחה!</h1>
        <div className="id-pill">הזמנה #{id}</div>
        <p className="blurb">
          קיבלנו את ההזמנה שלך וניצור איתך קשר תוך כמה דקות לאישור.<br/>
          {lastOrder?.method === 'pickup'
            ? 'נשלח לך הודעה כשההזמנה מוכנה לאיסוף.'
            : 'נתאם איתך זמן משלוח.'}
        </p>
        <div className="b-row">
          <button className="btn-primary" onClick={() => window.location.href = 'status.html?order=' + id}>מעקב אחר ההזמנה ←</button>
          <button className="btn-secondary" onClick={() => go('home')}>חזרה לחנות</button>
        </div>
      </div>

      <Footer />
    </>
  );
}

/* -------------------- Manual List (רשימה ידנית) — web -------------------- */
function ListBuilderAWeb({ go, activeCat, setActiveCat, cart }) {
  const [step, setStep]   = useState('build');
  const [lines, setLines] = useState([]);
  const [pop, setPop]     = useState(null);
  const [confirmDel, setConfirmDel] = useState(null);
  const [name, setName]       = useState('');
  const [phone, setPhone]     = useState('');
  const [comment, setComment] = useState('');
  const [placing, setPlacing] = useState(false);
  const [orderId, setOrderId] = useState(null);

  const ink = '#1a1410', red = '#c8181e', yellow = '#ffde00';
  const lbwAdd  = (bg, fg) => ({ flex: 1, background: bg, color: fg, border: '2.5px solid ' + ink, borderRadius: 6, padding: '15px 10px', fontWeight: 900, fontSize: 17, fontFamily: 'inherit', cursor: 'pointer', boxShadow: '4px 4px 0 ' + ink });
  const lbwRow  = { display: 'flex', alignItems: 'center', gap: 10, background: '#fffaf0', border: '2px solid ' + ink, borderRadius: 6, padding: '13px 16px', marginBottom: 10, boxShadow: '3px 3px 0 ' + ink };
  const lbwIcon = { background: 'transparent', border: 'none', fontSize: 19, cursor: 'pointer', padding: 3 };
  const lbwInput = { width: '100%', padding: 12, border: '2px solid ' + ink, borderRadius: 5, fontSize: 16, fontFamily: 'inherit', boxSizing: 'border-box' };
  const lbwStep  = { background: red, color: yellow, border: '2px solid ' + ink, width: 46, height: 46, borderRadius: 6, fontWeight: 900, fontSize: 24, cursor: 'pointer', lineHeight: 1 };

  const openItem = (i) => setPop(i == null ? { mode: 'item', index: null, name: '', qty: 1, text: '' } : { mode: 'item', index: i, name: lines[i].name, qty: lines[i].qty, text: '' });
  const openText = (i) => setPop(i == null ? { mode: 'text', index: null, name: '', qty: 1, text: '' } : { mode: 'text', index: i, name: '', qty: 1, text: lines[i].text });
  function savePop() {
    let line;
    if (pop.mode === 'item') { if (!pop.name.trim()) return; line = { type: 'item', name: pop.name.trim(), qty: Math.max(1, pop.qty) }; }
    else { if (!pop.text.trim()) return; line = { type: 'text', text: pop.text.trim() }; }
    setLines(prev => { if (pop.index == null) return [...prev, line]; const n = prev.slice(); n[pop.index] = line; return n; });
    setPop(null);
  }
  const delLine = (i) => setLines(prev => prev.filter((_, x) => x !== i));
  async function submit() {
    if (placing) return; setPlacing(true);
    try { const o = await Store.placeListOrder({ lines, customer: name, phone, comment }); setOrderId((o && o.id) || '—'); setStep('done'); }
    catch (e) { setPlacing(false); }
  }

  const chrome = (inner) => (<><SignHeader /><NavStrip go={go} cart={cart} activeCat={activeCat} setActiveCat={setActiveCat} />{inner}<Footer /></>);
  const popup = pop && (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)', display: 'grid', placeItems: 'center', zIndex: 300, padding: 24 }} onClick={e => { if (e.target === e.currentTarget) setPop(null); }}>
      <div style={{ background: '#fffaf0', border: '3px solid ' + ink, borderRadius: 8, padding: 22, width: '100%', maxWidth: 380, boxShadow: '6px 6px 0 ' + ink }}>
        <h3 style={{ margin: '0 0 16px', fontWeight: 900, fontSize: 19 }}>{pop.mode === 'item' ? (pop.index == null ? 'הוסף מוצר' : 'עריכת מוצר') : (pop.index == null ? 'טקסט חופשי' : 'עריכת טקסט')}</h3>
        {pop.mode === 'item' ? (
          <>
            <input autoFocus type="text" value={pop.name} placeholder="שם המוצר" onChange={e => setPop({ ...pop, name: e.target.value })} onKeyDown={e => { if (e.key === 'Enter') savePop(); }} style={lbwInput} />
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 20, margin: '18px 0' }}>
              <button style={lbwStep} onClick={() => setPop({ ...pop, qty: Math.max(1, pop.qty - 1) })}>−</button>
              <span style={{ fontWeight: 900, fontSize: 26, minWidth: 38, textAlign: 'center' }}>{pop.qty}</span>
              <button style={lbwStep} onClick={() => setPop({ ...pop, qty: pop.qty + 1 })}>＋</button>
            </div>
          </>
        ) : (
          <textarea autoFocus rows="4" value={pop.text} placeholder="כתבו כל מה שתרצו…" onChange={e => setPop({ ...pop, text: e.target.value })} style={{ ...lbwInput, resize: 'none' }} />
        )}
        <div style={{ display: 'flex', gap: 12, marginTop: 14 }}>
          <button className="btn-primary" style={{ flex: 1 }} onClick={savePop}>שמור</button>
          <button className="btn-secondary" style={{ flex: 1 }} onClick={() => setPop(null)}>ביטול</button>
        </div>
      </div>
    </div>
  );

  const confirmPopup = confirmDel && (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)', display: 'grid', placeItems: 'center', zIndex: 300, padding: 24 }} onClick={e => { if (e.target === e.currentTarget) setConfirmDel(null); }}>
      <div style={{ background: '#fffaf0', border: '3px solid ' + ink, borderRadius: 8, padding: 22, width: '100%', maxWidth: 360, boxShadow: '6px 6px 0 ' + ink, textAlign: 'center' }}>
        <h3 style={{ margin: '0 0 8px', fontWeight: 900, fontSize: 19 }}>{confirmDel.mode === 'all' ? 'למחוק את כל הרשימה?' : 'למחוק את הפריט?'}</h3>
        <p style={{ margin: '0 0 18px', color: '#6b5e4f', fontWeight: 600, fontSize: 14, wordBreak: 'break-word' }}>{confirmDel.mode === 'all' ? 'כל הפריטים יימחקו — אי אפשר לבטל.' : ('«' + (lines[confirmDel.index] ? (lines[confirmDel.index].type === 'item' ? lines[confirmDel.index].name : lines[confirmDel.index].text) : '') + '»')}</p>
        <div style={{ display: 'flex', gap: 12 }}>
          <button className="btn-primary" style={{ flex: 1 }} onClick={() => { if (confirmDel.mode === 'all') setLines([]); else delLine(confirmDel.index); setConfirmDel(null); }}>מחק</button>
          <button className="btn-secondary" style={{ flex: 1 }} onClick={() => setConfirmDel(null)}>ביטול</button>
        </div>
      </div>
    </div>
  );

  if (step === 'done') {
    return chrome(
      <div className="confirm-shell" style={{ marginTop: 48 }}>
        <div className="confirm-badge">✓</div>
        <h1>נשלח!</h1>
        <div className="id-pill">הזמנה #{orderId}</div>
        <p className="blurb">קיבלנו את הרשימה שלך — ניצור איתך קשר תוך כמה דקות לאישור.</p>
        <div className="b-row"><button className="btn-secondary" onClick={() => go('home')}>חזרה לחנות</button></div>
      </div>
    );
  }
  if (step === 'contact') {
    const canSubmit = name.trim() && phone.trim();
    return chrome(
      <div className="split-shell" style={{ gridTemplateColumns: '1fr', maxWidth: 680, margin: '0 auto', paddingTop: 48 }}>
        <div className="panel">
          <h2>פרטים ליצירת קשר</h2>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <div className="field"><label>שם מלא <span className="req">*</span></label><input type="text" value={name} onChange={e => setName(e.target.value)} placeholder="ישראל ישראלי" /></div>
            <div className="field"><label>טלפון <span className="req">*</span></label><input type="tel" value={phone} onChange={e => setPhone(e.target.value)} placeholder="050-1234567" /></div>
          </div>
          <div className="field"><label>הערה <span className="opt">(לא חובה)</span></label><textarea rows="3" value={comment} onChange={e => setComment(e.target.value)} placeholder="כל דבר שתרצו להוסיף"></textarea></div>
          <button className="btn-primary" disabled={!canSubmit || placing} style={{ width: '100%', padding: '11px', fontSize: 16, background: '#16a34a', color: '#fff', ...((!canSubmit || placing) ? { opacity: 0.4, cursor: 'not-allowed' } : {}) }} onClick={submit}>{placing ? 'שולח…' : 'שליחה'}</button>
          <button className="btn-ghost" style={{ width: '100%', marginTop: 10 }} onClick={() => setStep('build')}>→ חזרה לרשימה</button>
        </div>
      </div>
    );
  }
  return chrome(
    <div className="split-shell" style={{ gridTemplateColumns: '1fr', maxWidth: 960, margin: '0 auto' }}>
      <div className="panel">
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, borderBottom: '2px dashed ' + ink, margin: '0 0 14px', paddingBottom: 10 }}>
          <h2 style={{ margin: 0, border: 'none', padding: 0 }}>📝 רשימה ידנית</h2>
          {lines.length > 0 && <button onClick={() => setConfirmDel({ mode: 'all' })} style={{ background: '#fff', border: '2px solid ' + ink, color: red, borderRadius: 5, fontWeight: 800, fontSize: 13, fontFamily: 'inherit', cursor: 'pointer', padding: '5px 11px', whiteSpace: 'nowrap', boxShadow: '2px 2px 0 ' + ink }}>🗑 מחק הכל</button>}
        </div>
        <p style={{ color: '#2a2218', fontWeight: 600, fontSize: 15, margin: '2px 0 18px' }}>הוסיפו מוצרים (שם + כמות) או טקסט חופשי — נחזור אליכם לאישור.</p>
        <div style={{ display: 'flex', gap: 12, marginBottom: 20 }}>
          <button style={lbwAdd(red, yellow)} onClick={() => openItem(null)}>＋ הוסף מוצר</button>
          <button style={lbwAdd(ink, yellow)} onClick={() => openText(null)}>＋ טקסט חופשי</button>
        </div>
        {lines.length === 0
          ? <div style={{ textAlign: 'center', color: '#9a8f82', padding: '34px 10px', fontWeight: 700, fontSize: 16 }}>הרשימה ריקה — הוסיפו פריט ראשון ↑</div>
          : lines.map((l, i) => (
            <div key={i} style={lbwRow}>
              <div style={{ flex: 1, minWidth: 0, fontSize: 16, overflowWrap: 'anywhere' }}>
                {l.type === 'item' ? <span style={{ fontWeight: 800 }}>{l.name} <span style={{ color: red }}>× {l.qty}</span></span> : <span style={{ fontWeight: 600, whiteSpace: 'pre-wrap' }}>📝 {l.text}</span>}
              </div>
              <button style={lbwIcon} title="עריכה" onClick={() => l.type === 'item' ? openItem(i) : openText(i)}>✎</button>
              <button style={lbwIcon} title="מחיקה" onClick={() => setConfirmDel({ mode: 'item', index: i })}>🗑️</button>
            </div>
          ))}
        <button className="btn-primary" disabled={lines.length === 0} style={{ width: '100%', marginTop: 18, padding: '11px', fontSize: 16, ...(lines.length === 0 ? { opacity: 0.4, cursor: 'not-allowed' } : {}) }} onClick={() => setStep('contact')}>המשך →</button>
      </div>
      {popup}
      {confirmPopup}
    </div>
  );
}

Object.assign(window, {
  HomeAWeb, ProductAWeb, CartAWeb, CheckoutAWeb, ConfirmAWeb, ListBuilderAWeb, SignHeader, NavStrip, Footer,
});
