// Bagel&Co customer-facing app components
// Exposes: Header, Hero, LocationStrip, MenuView, ProductModal, CartDrawer,
// Checkout, OrderSuccess, LocationsSection, DeliveryCard, Footer, useCart, useI18n

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

// ---------- Hooks ----------
function useI18n(lang) {
  return useCallback((key) => (window.I18N[lang] && window.I18N[lang][key]) || key, [lang]);
}

function priceOf(item) {
  let p = (typeof item.unitPrice === "number") ? item.unitPrice : item.price;
  if (item.variant && typeof item.variant.priceDelta === "number" && typeof item.unitPrice !== "number") {
    p += item.variant.priceDelta;
  }
  if (Array.isArray(item.addons)) {
    for (const a of item.addons) p += (a.priceDelta || 0);
  }
  return p;
}

function fmt(n) { return "€" + n.toFixed(2); }

// ---------- Responsive Picture (webp + srcset + lazy) ----------
// Accepts:
//   - legacy path like "assets/photos/bagel-1.jpg" → uses -sm/-md/-lg .webp variants
//   - data URL ("data:image/webp;base64,...") → just renders it directly (admin-uploaded photos)
//   - any URL with no known suffix → just renders it
function Picture({ src, alt = "", sizes, eager, className, style, imgStyle }) {
  if (!src) return null;
  const finalImgStyle = imgStyle || { width: "100%", height: "100%", objectFit: "cover", display: "block" };
  // Data URL or external URL — render directly, no srcset
  const isData = src.startsWith("data:");
  const m = !isData && src.match(/^(.*\/)?([^\/]+?)\.(jpg|jpeg|png|webp)$/i);
  if (isData || !m) {
    return (
      <picture className={className} style={style}>
        <img
          src={src}
          alt={alt}
          loading={eager ? "eager" : "lazy"}
          decoding="async"
          fetchpriority={eager ? "high" : "auto"}
          style={finalImgStyle}
        />
      </picture>
    );
  }
  const dir = m[1] || "";
  const stem = m[2];
  const base = dir + stem;
  const fallback = `${base}-md.jpg`;
  const webpSet = `${base}-sm.webp 480w, ${base}-md.webp 800w, ${base}-lg.webp 1600w`;
  const defaultSizes = sizes || "(max-width: 480px) 50vw, (max-width: 880px) 90vw, 33vw";
  return (
    <picture className={className} style={style}>
      <source type="image/webp" srcSet={webpSet} sizes={defaultSizes} />
      <img
        src={fallback}
        alt={alt}
        loading={eager ? "eager" : "lazy"}
        decoding="async"
        fetchpriority={eager ? "high" : "auto"}
        style={finalImgStyle}
      />
    </picture>
  );
}
window.Picture = Picture;

// ---------- Header ----------
function Header({ lang, setLang, view, setView, cartCount, openCart }) {
  const t = useI18n(lang);
  const [navOpen, setNavOpen] = useState(false);
  const closeNav = () => setNavOpen(false);
  const go = (v) => { setView(v); closeNav(); };
  // Lock body when sheet open
  useBodyScrollLock(navOpen);
  // Close on Escape
  useEffect(() => {
    if (!navOpen) return;
    const onKey = (e) => { if (e.key === "Escape") setNavOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [navOpen]);

  return (
    <header className="site-header">
      <div className="container site-header__row">
        <button className="site-header__logo" onClick={() => setView("home")} aria-label="Home">
          <img className="site-header__logo-mark" src="assets/brand/logo-real.png" alt="Bagel&Co" />
        </button>
        <nav className="site-header__nav">
          <button className={view === "menu" ? "active" : ""} onClick={() => setView("menu")}>{t("nav_menu")}</button>
          <button className={view === "about" ? "active" : ""} onClick={() => setView("about")}>{t("nav_about")}</button>
          <button className={view === "delivery" ? "active" : ""} onClick={() => setView("delivery")}>{t("nav_delivery")}</button>
          <button className={view === "locations" ? "active" : ""} onClick={() => setView("locations")}>{t("nav_locations")}</button>
          <button className={view === "contact" ? "active" : ""} onClick={() => setView("contact")}>{t("nav_contact")}</button>
        </nav>
        <div className="site-header__actions">
          {/* Quick Menu CTA on mobile, prominent */}
          <button
            className={"header-menu-cta" + (view === "menu" ? " active" : "")}
            onClick={() => setView("menu")}
            aria-label={t("nav_menu")}
          >
            {t("nav_menu")}
          </button>
          <div className="lang-pill" role="tablist" aria-label="Language">
            {["lv","en","ru"].map(l => (
              <button key={l} className={lang === l ? "active" : ""} onClick={() => setLang(l)}>{l}</button>
            ))}
          </div>
          <button className="cart-btn" onClick={openCart} aria-label={t("cart")}>
            <span>{t("cart")}</span>
            <span className="cart-btn__count">{cartCount}</span>
          </button>
          <button className="hamburger" onClick={() => setNavOpen(true)} aria-label="Open menu">
            <span></span><span></span><span></span>
          </button>
        </div>
      </div>

      {/* Mobile sheet */}
      {navOpen && (
        <div className="mobile-sheet-backdrop" onClick={closeNav}>
          <div className="mobile-sheet" onClick={(e)=>e.stopPropagation()}>
            <div className="mobile-sheet__head">
              <span className="eyebrow">Bagel&Co</span>
              <button className="modal__close" style={{position:"static"}} onClick={closeNav} aria-label="Close">×</button>
            </div>
            <nav className="mobile-sheet__nav">
              <button className={view === "menu" ? "active" : ""} onClick={() => go("menu")}>{t("nav_menu")}</button>
              <button className={view === "about" ? "active" : ""} onClick={() => go("about")}>{t("nav_about")}</button>
              <button className={view === "delivery" ? "active" : ""} onClick={() => go("delivery")}>{t("nav_delivery")}</button>
              <button className={view === "locations" ? "active" : ""} onClick={() => go("locations")}>{t("nav_locations")}</button>
              <button className={view === "contact" ? "active" : ""} onClick={() => go("contact")}>{t("nav_contact")}</button>
            </nav>
            <div className="mobile-sheet__lang">
              {["lv","en","ru"].map(l => (
                <button key={l} className={lang === l ? "active" : ""} onClick={() => { setLang(l); }}>{l.toUpperCase()}</button>
              ))}
            </div>
          </div>
        </div>
      )}
    </header>
  );
}

// ---------- Hero ----------
function Hero({ lang, setView, heroVariant }) {
  const t = useI18n(lang);
  const headline = {
    lv: <>Beigeles, kas <em>tiešām</em> ir vērtas</>,
    en: <>Bagels worth <em>showing up</em> for</>,
    ru: <>Бейглы, ради которых <em>стоит зайти</em></>,
  }[lang];
  const sub = {
    lv: "Ģimenes kafejnīca Latvijā. Cepam paši, gatavojam pēc pasūtījuma. Paņemšana Piņķos un Bulduros.",
    en: "A family-run café in Latvia. We bake our own, we make to order. Pick up in Piņķi or Bulduri.",
    ru: "Семейная кафешка в Латвии. Печём сами, готовим под заказ. Самовывоз в Пиньки и Булдури.",
  }[lang];

  if (heroVariant === "split") {
    return (
      <section className="hero">
        <div className="container">
          <div className="hero__grid">
            <div className="hero__copy">
              <span className="eyebrow">Piņķi · Bulduri</span>
              <h1 className="display">{headline}</h1>
              <p>{sub}</p>
              <div className="hero__ctas">
                <button className="btn btn-primary btn-lg" onClick={() => setView("menu")}>{t("cta_order")} →</button>
                <button className="btn btn-ghost btn-lg" onClick={() => setView("about")}>{t("nav_about")}</button>
              </div>
            </div>
            <div className="hero__photo">
              <Picture src="assets/photos/main-hero.jpg"
                       alt="Hand-rolled bagels at Bagel&Co café in Jūrmala — salmon, pastrami, mozzarella"
                       eager sizes="(max-width: 880px) 100vw, 50vw" />
            </div>
          </div>
        </div>
      </section>
    );
  }
  // mosaic variant
  return (
    <section className="hero">
      <div className="container">
        <div style={{display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:14, marginBottom:28}}>
          <div style={{gridRow:"span 2", borderRadius:24, overflow:"hidden"}}>
            <Picture src="assets/photos/main-hero.jpg" alt="" eager sizes="(max-width: 720px) 100vw, 33vw" />
          </div>
          <div style={{borderRadius:24, overflow:"hidden", aspectRatio:"1/1"}}>
            <Picture src="assets/photos/bagel-3.jpg" alt="" eager sizes="(max-width: 720px) 50vw, 22vw" />
          </div>
          <div style={{borderRadius:24, overflow:"hidden", aspectRatio:"1/1"}}>
            <Picture src="assets/photos/panini-1.jpg" alt="" sizes="(max-width: 720px) 50vw, 22vw" />
          </div>
          <div style={{borderRadius:24, overflow:"hidden", aspectRatio:"1/1"}}>
            <Picture src="assets/photos/cafe-12.jpg" alt="" sizes="(max-width: 720px) 50vw, 22vw" />
          </div>
          <div style={{borderRadius:24, overflow:"hidden", aspectRatio:"1/1"}}>
            <Picture src="assets/photos/bagel-1.jpg" alt="" sizes="(max-width: 720px) 50vw, 22vw" />
          </div>
        </div>
        <div style={{textAlign:"center", maxWidth:780, margin:"0 auto"}}>
          <span className="eyebrow">Piņķi · Bulduri</span>
          <h1 className="display" style={{fontSize:"clamp(48px, 8vw, 110px)", margin:"14px 0 18px"}}>{headline}</h1>
          <p style={{fontSize:18, color:"var(--c-coffee)", margin:"0 auto 28px", maxWidth:"50ch"}}>{sub}</p>
          <div className="hero__ctas" style={{justifyContent:"center"}}>
            <button className="btn btn-primary btn-lg" onClick={() => setView("menu")}>{t("cta_order")} →</button>
            <button className="btn btn-ghost btn-lg" onClick={() => setView("locations")}>{t("nav_locations")}</button>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Location strip ----------
function LocationStrip({ lang, location, setLocation }) {
  const t = useI18n(lang);
  return (
    <div className="container">
      <div className="location-strip">
        <div className="location-strip__label">
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 22s7-7.58 7-13a7 7 0 0 0-14 0c0 5.42 7 13 7 13z"/><circle cx="12" cy="9" r="2.5"/></svg>
          <span>{t("choose_location")}</span>
        </div>
        <div className="location-strip__pills">
          {window.LOCATIONS.map(loc => (
            <button key={loc.id} className={"loc-pill" + (location === loc.id ? " active" : "")} onClick={() => setLocation(loc.id)}>
              <span>{loc.name}</span>
              <span className="loc-pill__hours">{loc.hours}</span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ---------- Category tabs scroller (with edge gradients + arrows on overflow) ----------
function CatTabsScroller({ children }) {
  const ref = useRef(null);
  const [showLeft, setShowLeft] = useState(false);
  const [showRight, setShowRight] = useState(false);
  const update = useCallback(() => {
    const el = ref.current; if (!el) return;
    const max = el.scrollWidth - el.clientWidth;
    setShowLeft(el.scrollLeft > 4);
    setShowRight(max > 4 && el.scrollLeft < max - 4);
  }, []);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    update();
    el.addEventListener("scroll", update, { passive: true });
    window.addEventListener("resize", update);
    const t1 = setTimeout(update, 150);
    return () => { el.removeEventListener("scroll", update); window.removeEventListener("resize", update); clearTimeout(t1); };
  }, [update]);
  const scrollBy = (dir) => {
    const el = ref.current; if (!el) return;
    el.scrollBy({ left: dir * Math.round(el.clientWidth * 0.7), behavior: "smooth" });
  };
  return (
    <div className={"cat-tabs-wrap" + (showLeft ? " has-left" : "") + (showRight ? " has-right" : "")}>
      <div className="cat-tabs" ref={ref}>{children}</div>
      <button className={"cat-tabs__arrow cat-tabs__arrow--left" + (showLeft ? "" : " is-hidden")}
              onClick={() => scrollBy(-1)} aria-label="Scroll left">‹</button>
      <button className={"cat-tabs__arrow cat-tabs__arrow--right" + (showRight ? "" : " is-hidden")}
              onClick={() => scrollBy(1)} aria-label="Scroll right">›</button>
    </div>
  );
}

// ---------- Scroll arrows wrapper ----------
function ScrollerWithArrows({ children, ariaLabel }) {
  const ref = useRef(null);
  const [showLeft, setShowLeft] = useState(false);
  const [showRight, setShowRight] = useState(true);
  const update = useCallback(() => {
    const el = ref.current; if (!el) return;
    const max = el.scrollWidth - el.clientWidth;
    setShowLeft(el.scrollLeft > 8);
    setShowRight(el.scrollLeft < max - 8);
  }, []);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    update();
    el.addEventListener("scroll", update, { passive: true });
    window.addEventListener("resize", update);
    // also check after layout settles
    const t1 = setTimeout(update, 150);
    return () => {
      el.removeEventListener("scroll", update);
      window.removeEventListener("resize", update);
      clearTimeout(t1);
    };
  }, [update]);
  const scrollBy = (dir) => {
    const el = ref.current; if (!el) return;
    el.scrollBy({ left: dir * Math.round(el.clientWidth * 0.85), behavior: "smooth" });
  };
  return (
    <div className="scroller">
      <div className="scroll-snap-row" ref={ref} aria-label={ariaLabel}>{children}</div>
      <button className={"scroller__arrow scroller__arrow--left" + (showLeft ? "" : " is-hidden")}
              onClick={() => scrollBy(-1)} aria-label="Scroll left">‹</button>
      <button className={"scroller__arrow scroller__arrow--right" + (showRight ? "" : " is-hidden")}
              onClick={() => scrollBy(1)} aria-label="Scroll right">›</button>
    </div>
  );
}

// ---------- Popular row (home) ----------
function PopularRow({ lang, openProduct }) {
  const t = useI18n(lang);
  const items = window.MENU_DATA.filter(p => p.popular).slice(0, 6);
  return (
    <section className="section" style={{paddingBottom: 24}}>
      <div className="container">
        <div className="section__head">
          <div>
            <span className="eyebrow">{t("popular")}</span>
            <h2>{ {lv:"Iecienītākie", en:"Crowd favourites", ru:"Любимцы публики"}[lang] }</h2>
          </div>
        </div>
        <ScrollerWithArrows ariaLabel={t("popular")}>
          {items.map(p => <ProductCard key={p.id} p={p} lang={lang} openProduct={openProduct} />)}
        </ScrollerWithArrows>
      </div>
    </section>
  );
}

// ---------- Product card ----------
function ProductCard({ p, lang, openProduct }) {
  const t = useI18n(lang);
  const isVegan = p.dietary && p.dietary.includes("vegan");
  const isVeg = p.dietary && p.dietary.includes("vegetarian");
  return (
    <button className={"product-card" + (!p.available ? " sold-out" : "")} onClick={() => p.available && openProduct(p)}>
      <div className="product-card__img">
        {p.popular && <span className="badge-popular">{t("popular")}</span>}
        <Picture src={p.image}
                 alt={`${p.name[lang]} — Bagel&Co · Jūrmala`}
                 sizes="(max-width: 480px) 50vw, (max-width: 880px) 33vw, 25vw" />
        {!p.available && <div className="badge-soldout">{t("sold_out")}</div>}
      </div>
      <div className="product-card__body">
        <div className="product-card__title">{p.name[lang]}</div>
        <div className="product-card__desc">{p.desc[lang]}</div>
        <div className="product-card__meta">
          {p.kcal != null && <span>{p.kcal} {t("kcal")}</span>}
          {p.kcal != null && (isVegan || isVeg) && <span className="product-card__meta-dot"></span>}
          {isVegan && <span className="badge-dietary">{t("vegan")}</span>}
          {!isVegan && isVeg && <span className="badge-dietary">{t("vegetarian")}</span>}
        </div>
        <div className="product-card__foot">
          <span className="product-card__price">{fmt(p.price)}</span>
          <span className="product-card__add" aria-label={t("cta_add")}>+</span>
        </div>
      </div>
    </button>
  );
}

// ---------- Menu view ----------
function MenuView({ lang, openProduct, location }) {
  const t = useI18n(lang);
  const [cat, setCat] = useState("bagels");
  const [q, setQ] = useState("");

  const items = useMemo(() => {
    const query = q.trim().toLowerCase();
    // When user is searching, look across ALL categories (not just active one).
    // Empty search → respect the active category tab.
    const pool = query
      ? window.MENU_DATA
      : window.MENU_DATA.filter(p => p.category === cat);
    return pool.filter(p =>
      !query
      || (p.name?.[lang]||"").toLowerCase().includes(query)
      || (p.desc?.[lang]||"").toLowerCase().includes(query)
      || (p.name?.lv||"").toLowerCase().includes(query)
      || (p.name?.en||"").toLowerCase().includes(query)
      || (p.name?.ru||"").toLowerCase().includes(query)
    );
  }, [cat, q, lang]);
  const isSearching = q.trim().length > 0;

  return (
    <section className="section">
      <div className="container">
        <span className="eyebrow">{t("nav_menu")}</span>
        <h2>{ {lv:"Mūsu ēdienkarte", en:"Our menu", ru:"Наше меню"}[lang] }</h2>
        <div className="menu-controls">
          <CatTabsScroller>
            {window.CATEGORIES.map(c => (
              <button key={c.id} className={"cat-tab" + (cat === c.id ? " active" : "")} onClick={() => setCat(c.id)}>
                {c.name[lang]}
              </button>
            ))}
          </CatTabsScroller>
          <div className="search-bar">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{opacity:.5}}><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
            <input value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("search")} />
          </div>
        </div>
        {isSearching && items.length > 0 && (
          <div style={{margin:"-12px 0 18px", fontFamily:"var(--font-mono)", fontSize:12, color:"var(--c-mute)"}}>
            { {lv:`Atrasts: ${items.length}`, en:`Found: ${items.length}`, ru:`Найдено: ${items.length}`}[lang] }
          </div>
        )}
        {items.length === 0 ? (
          <div style={{padding:"60px 20px", textAlign:"center", color:"var(--c-mute)"}}>
            { {lv:"Nekas nav atrasts", en:"No items found", ru:"Ничего не найдено"}[lang] }
          </div>
        ) : (
          <div className="product-grid">
            {items.map(p => <ProductCard key={p.id} p={p} lang={lang} openProduct={openProduct} />)}
          </div>
        )}
      </div>
    </section>
  );
}

// ---------- Body scroll lock helper (refcounted, so multiple modals coexist) ----------
window.__scrollLockCount = window.__scrollLockCount || 0;
function useBodyScrollLock(active) {
  useEffect(() => {
    if (!active) return;
    window.__scrollLockCount++;
    document.body.classList.add("is-modal-open");
    return () => {
      window.__scrollLockCount = Math.max(0, window.__scrollLockCount - 1);
      if (window.__scrollLockCount === 0) document.body.classList.remove("is-modal-open");
    };
  }, [active]);
}
// Safety net: release scroll lock on Escape and on hot-reload
function useEscapeAndCleanup(onClose) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);
}

// ---------- Product modal ----------
function ProductModal({ p, lang, onClose, addToCart }) {
  const t = useI18n(lang);
  const [removed, setRemoved] = useState(new Set());
  const [chosenAddons, setChosenAddons] = useState(new Set());
  const [variant, setVariant] = useState(p.variants ? p.variants[0] : null);
  const [qty, setQty] = useState(1);
  const [comment, setComment] = useState("");
  useBodyScrollLock(true);
  useEscapeAndCleanup(onClose);

  const addonsList = Array.isArray(p.addons) ? p.addons : [];
  const ingredientsList = Array.isArray(p.ingredients) ? p.ingredients : [];

  const finalPrice = useMemo(() => {
    let pr = p.price + (variant && variant.priceDelta ? variant.priceDelta : 0);
    for (const a of addonsList) if (chosenAddons.has(a.id)) pr += (a.priceDelta || 0);
    return pr * qty;
  }, [p, variant, qty, chosenAddons, addonsList]);

  const toggleRemove = (id) => {
    const next = new Set(removed);
    if (next.has(id)) next.delete(id); else next.add(id);
    setRemoved(next);
  };
  const toggleAddon = (id) => {
    const next = new Set(chosenAddons);
    if (next.has(id)) next.delete(id); else next.add(id);
    setChosenAddons(next);
  };

  const handleAdd = () => {
    const chosen = addonsList.filter(a => chosenAddons.has(a.id));
    const unit = p.price
      + (variant && variant.priceDelta ? variant.priceDelta : 0)
      + chosen.reduce((s, a) => s + (a.priceDelta || 0), 0);
    addToCart({
      id: p.id + "-" + Date.now(),
      productId: p.id,
      name: p.name,
      image: p.image,
      basePrice: p.price,
      removed: Array.from(removed),
      removedNames: ingredientsList.filter(i => removed.has(i.id)).map(i => i.name),
      addons: chosen,
      addedNames: chosen.map(a => a.name),
      variant: variant,
      qty,
      comment,
      unitPrice: unit,
    });
    onClose();
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal__photo">
          <Picture src={p.image} alt={p.name[lang]} eager sizes="(max-width: 720px) 100vw, 720px" />
          <button className="modal__close" onClick={onClose}>×</button>
        </div>
        <div className="modal__body">
          <h3 className="modal__title">{p.name[lang]}</h3>
          <div className="modal__price mono">{fmt(p.price)}</div>
          <p className="modal__desc">{p.desc[lang]}</p>

          {(p.kcal != null || (p.allergens && p.allergens.length > 0)) && (
            <div className="modal__section">
              <h4>{t("nutrition")}</h4>
              <div className="nutrition-strip">
                {p.kcal != null && (
                  <div className="nutrition-strip__item">
                    <div className="num">{p.kcal}</div>
                    <div className="lbl">{t("kcal")}</div>
                  </div>
                )}
                {p.dietary && p.dietary.includes("vegan") && (
                  <div className="nutrition-strip__item">
                    <div className="num" style={{color:"var(--c-success)"}}>✓</div>
                    <div className="lbl">{t("vegan")}</div>
                  </div>
                )}
                {p.dietary && p.dietary.includes("vegetarian") && !p.dietary.includes("vegan") && (
                  <div className="nutrition-strip__item">
                    <div className="num" style={{color:"var(--c-success)"}}>✓</div>
                    <div className="lbl">{t("vegetarian")}</div>
                  </div>
                )}
              </div>
              {p.allergens && p.allergens.length > 0 && (
                <>
                  <div style={{fontFamily:"var(--font-mono)", fontSize:11, textTransform:"uppercase", letterSpacing:"0.1em", color:"var(--c-mute)", marginBottom:8}}>
                    {t("contains")}
                  </div>
                  <div className="allergen-row">
                    {p.allergens.map(a => (
                      <span key={a} className="allergen-pill">
                        {window.ALLERGENS[a] ? window.ALLERGENS[a][lang] : a}
                      </span>
                    ))}
                  </div>
                </>
              )}
            </div>
          )}

          {p.variants && (
            <div className="modal__section">
              <h4>{ {lv:"Variants", en:"Variant", ru:"Вариант"}[lang] }</h4>
              <div className="variant-row">
                {p.variants.map(v => (
                  <button key={v.id} className={"variant-pill" + (variant && variant.id === v.id ? " active" : "")} onClick={() => setVariant(v)}>
                    {v.name[lang]}
                    {v.priceDelta ? <span className="variant-pill__delta">+{fmt(v.priceDelta)}</span> : null}
                  </button>
                ))}
              </div>
            </div>
          )}

          {ingredientsList.length > 0 && ingredientsList.some(i => i.removable) && (
            <div className="modal__section">
              <h4>{t("remove_ingredients")}</h4>
              <div className="ingredient-list">
                {ingredientsList.map(ing => {
                  const isRemoved = removed.has(ing.id);
                  const locked = !ing.removable;
                  return (
                    <div key={ing.id}
                         className={"ingredient-row" + (isRemoved ? " removed" : "") + (locked ? " locked" : "")}
                         onClick={() => !locked && toggleRemove(ing.id)}
                         style={{cursor: locked ? "default" : "pointer"}}>
                      <span className="ingredient-row__toggle">{isRemoved ? "" : "✓"}</span>
                      <span className="ingredient-row__name">{ing.name[lang]}</span>
                      {locked && <span className="ingredient-row__lock">{ {lv:"Pamats", en:"Core", ru:"Основа"}[lang] }</span>}
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {addonsList.length > 0 && (
            <div className="modal__section">
              <h4>{t("add_extras")}</h4>
              <div className="ingredient-list">
                {addonsList.map(a => {
                  const isOn = chosenAddons.has(a.id);
                  return (
                    <div key={a.id}
                         className={"ingredient-row" + (isOn ? " is-added" : "")}
                         onClick={() => toggleAddon(a.id)}
                         style={{cursor:"pointer"}}>
                      <span className="ingredient-row__toggle" style={{background: isOn ? "var(--accent)" : "var(--c-cream)", color: isOn ? "#fff" : "var(--c-coffee)"}}>
                        {isOn ? "+" : ""}
                      </span>
                      <span className="ingredient-row__name">{a.name[lang]}</span>
                      <span className="ingredient-row__lock" style={{color:"var(--accent)"}}>+{fmt(a.priceDelta || 0)}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          <div className="modal__section">
            <h4>{t("comment")}</h4>
            <textarea className="modal__textarea" rows="2"
              placeholder={ {lv:"Piezīmes vārdam, alergijai...", en:"Notes for the kitchen...", ru:"Заметки для кухни..."}[lang] }
              value={comment} onChange={(e)=>setComment(e.target.value)} />
          </div>

          <div className="modal__section qty-row">
            <h4 style={{margin:0}}>{t("quantity")}</h4>
            <div className="qty-stepper">
              <button onClick={() => setQty(Math.max(1, qty-1))}>−</button>
              <span className="qty-stepper__val">{qty}</span>
              <button onClick={() => setQty(qty+1)}>+</button>
            </div>
          </div>
        </div>
        <div className="modal__cta-row">
          <button className="btn btn-primary btn-block btn-lg" onClick={handleAdd}>
            {t("cta_add")} · {fmt(finalPrice)}
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------- Cart drawer ----------
function CartDrawer({ lang, cart, onClose, removeItem, clearCart, goCheckout, location, setView }) {
  const t = useI18n(lang);
  const subtotal = cart.reduce((s, it) => s + priceOf(it) * it.qty, 0);
  useBodyScrollLock(true);
  useEscapeAndCleanup(onClose);

  return (
    <div className="drawer-backdrop" onClick={onClose}>
      <div className="drawer" onClick={(e) => e.stopPropagation()}>
        <div className="drawer__head">
          <h3>{t("cart")}</h3>
          <button className="modal__close" style={{position:"static"}} onClick={onClose}>×</button>
        </div>
        <div className="drawer__body">
          {cart.length === 0 ? (
            <div className="cart-empty">
              <div className="cart-empty__icon">🥯</div>
              <p>{t("cart_empty")}</p>
              <button className="btn btn-primary" style={{marginTop:14}} onClick={() => { onClose(); setView("menu"); }}>
                {t("cta_view_menu")}
              </button>
            </div>
          ) : cart.map(it => (
            <div className="cart-row" key={it.id}>
              <Picture src={it.image} alt="" className="cart-row__img" sizes="64px"
                       imgStyle={{width:"100%", height:"100%", objectFit:"cover", borderRadius:12, display:"block"}} />
              <div className="cart-row__main">
                <div className="cart-row__title">{it.qty}× {it.name[lang]}</div>
                {it.variant && <div className="cart-row__meta">{it.variant.name[lang]}</div>}
                {it.removedNames && it.removedNames.length > 0 && (
                  <div className="pill-row" style={{marginTop:6}}>
                    {it.removedNames.map((n, i) => <span key={i} className="removed-pill">— {n[lang]}</span>)}
                  </div>
                )}
                {it.addedNames && it.addedNames.length > 0 && (
                  <div className="pill-row" style={{marginTop:6}}>
                    {it.addedNames.map((n, i) => <span key={i} className="removed-pill" style={{borderColor:"var(--accent)", color:"var(--accent)"}}>+ {n[lang]}</span>)}
                  </div>
                )}
                {it.comment && <div className="cart-row__meta" style={{marginTop:4}}>“{it.comment}”</div>}
                <button className="cart-row__remove" onClick={() => removeItem(it.id)}>{t("cta_remove")}</button>
              </div>
              <div className="cart-row__price">{fmt(priceOf(it) * it.qty)}</div>
            </div>
          ))}
        </div>
        {cart.length > 0 && (
          <div className="drawer__foot">
            <div className="total-row"><span>{t("cart_subtotal")}</span><span className="mono">{fmt(subtotal)}</span></div>
            <div className="total-row big"><span>{t("cart_total")}</span><span className="total-row__val">{fmt(subtotal)}</span></div>
            <button className="btn btn-primary btn-block btn-lg" onClick={goCheckout} style={{marginTop:8}}>
              {t("cta_checkout")} →
            </button>
            <button className="btn btn-soft btn-block btn-sm" style={{marginTop:8}} onClick={clearCart}>
              {t("cta_clear")}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

// ---------- Checkout ----------
function Checkout({ lang, cart, location, setLocation, onSubmit, setView }) {
  const t = useI18n(lang);
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  // Promo code state
  const [promoInput, setPromoInput] = useState("");
  const [promo, setPromo] = useState(null);  // { code, type, value, label }
  const [promoErr, setPromoErr] = useState("");
  // Pickup-time mode: 'asap' | 'today' | 'tomorrow'
  const [pickupMode, setPickupMode] = useState("asap");
  // Working-hours-aware default time
  const locHours = (locId) => {
    const loc = window.LOCATIONS.find(l => l.id === locId);
    if (!loc?.hours) return null;
    const m = loc.hours.match(/(\d{1,2}):(\d{2})\s*[–-]\s*(\d{1,2}):(\d{2})/);
    if (!m) return null;
    return { openH: +m[1], openM: +m[2], closeH: +m[3], closeM: +m[4] };
  };
  const sensibleTime = (mode, locId) => {
    const h = locHours(locId);
    const now = new Date();
    if (mode === "tomorrow" || !h) {
      // For tomorrow: opening + 30 min (or 11:00 fallback)
      if (h) return String(h.openH).padStart(2, "0") + ":" + String(Math.min(59, h.openM + 30)).padStart(2, "0");
      return "11:00";
    }
    // today: max(now+1h, open) clamped to close-15min
    const cur = now.getHours() * 60 + Math.ceil(now.getMinutes() / 5) * 5;
    const open = h.openH * 60 + h.openM;
    const close = h.closeH * 60 + h.closeM;
    const want = Math.max(cur + 30, open);
    const clamped = Math.min(want, close - 15);
    if (clamped < open) return String(h.openH).padStart(2, "0") + ":" + String(h.openM).padStart(2, "0");
    return String(Math.floor(clamped / 60)).padStart(2, "0") + ":" + String(clamped % 60).padStart(2, "0");
  };
  const [chosenTime, setChosenTime] = useState(() => sensibleTime("today", location));
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");
  // Recompute time when user switches mode or location
  useEffect(() => {
    if (pickupMode === "asap") return;
    setChosenTime(sensibleTime(pickupMode, location));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pickupMode, location]);
  const [comment, setComment] = useState("");
  const [errors, setErrors] = useState({});

  const subtotal = cart.reduce((s, it) => s + priceOf(it) * it.qty, 0);
  // Compute discount from promo
  const discount = useMemo(() => {
    if (!promo) return 0;
    if (promo.type === "percent") return +(subtotal * promo.value / 100).toFixed(2);
    if (promo.type === "fixed") return Math.min(promo.value, subtotal);
    return 0;
  }, [promo, subtotal]);
  const totalAfterDiscount = Math.max(0, subtotal - discount);

  // (Min-order rule removed — accept any cart total)

  // Working hours validation: warn if requested time is outside the location's hours
  const isTimeWithinHours = () => {
    if (pickupMode === "asap") return true;
    const loc = window.LOCATIONS.find(l => l.id === location);
    if (!loc?.hours || !chosenTime) return true;
    const m = loc.hours.match(/(\d{1,2}):(\d{2})\s*[–-]\s*(\d{1,2}):(\d{2})/);
    if (!m) return true;
    const [openH, openM, closeH, closeM] = [+m[1], +m[2], +m[3], +m[4]];
    const [tH, tM] = chosenTime.split(":").map(Number);
    const open = openH*60 + openM;
    const close = closeH*60 + closeM;
    const t = tH*60 + tM;
    return t >= open && t <= close - 15; // last order at least 15 min before close
  };

  const applyPromo = () => {
    setPromoErr("");
    const code = promoInput.trim().toUpperCase();
    if (!code) return;
    const found = window.PROMO_CODES?.[code];
    if (!found) { setPromoErr({lv:"Nederīgs kods", en:"Invalid code", ru:"Неверный код"}[lang]); setPromo(null); return; }
    setPromo({ code, ...found });
  };
  const clearPromo = () => { setPromo(null); setPromoInput(""); setPromoErr(""); };

  // Build a human-readable string for the order payload, in the user's language
  const formatPickupTime = () => {
    if (pickupMode === "asap") return { lv:"Tūlīt", en:"Right away", ru:"Сразу" }[lang];
    const labelMap = {
      today:    { lv:"Šodien",  en:"Today",    ru:"Сегодня" },
      tomorrow: { lv:"Rītdien", en:"Tomorrow", ru:"Завтра" },
    };
    return labelMap[pickupMode][lang] + " · " + chosenTime;
  };

  const PICK_TXT = {
    lv: { asap: "Tūlīt", today: "Šodien", tomorrow: "Rītdien", time_label: "Laiks" },
    en: { asap: "Right away", today: "Today", tomorrow: "Tomorrow", time_label: "Time" },
    ru: { asap: "Сразу", today: "Сегодня", tomorrow: "Завтра", time_label: "Время" },
  }[lang];

  const submit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setSubmitError("");
    const errs = {};
    if (!name.trim()) errs.name = true;
    if (!phone.trim() || phone.replace(/\D/g, "").length < 7) errs.phone = true;
    if (!location) errs.location = true;
    if (pickupMode !== "asap" && !chosenTime) errs.time = true;
    if (!email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) errs.email = true;
    setErrors(errs);
    if (Object.keys(errs).length) return;
    if (pickupMode !== "asap" && !isTimeWithinHours()) {
      const ok = confirm({
        lv: "Šajā laikā mēs varbūt būsim slēgti. Iesniegt pasūtījumu?",
        en: "We may be closed at that time. Submit the order anyway?",
        ru: "В это время мы можем быть закрыты. Всё равно оформить заказ?"
      }[lang]);
      if (!ok) return;
    }
    setSubmitting(true);
    try {
      // onSubmit is async (kicks off backend POST + clears cart on .finally)
      await onSubmit({
        name, phone, email, location, comment,
        pickupTime: formatPickupTime(),
        items: cart,
        subtotal,
        discount,
        promoCode: promo?.code || "",
        total: totalAfterDiscount,
      });
    } catch (err) {
      // If backend hints that Telegram chat isn't connected, show actionable message
      const msg = (err && err.detail) || "";
      if (err && err.status === 503 && /telegram/i.test(msg)) {
        setSubmitError({
          lv: "Pasūtījumu sistēma vēl nav pilnībā aktivizēta. Lūdzu, sazinies ar mums e-pastā support@bagelsco.lv vai mēģini vēlāk.",
          en: "The order system is still being set up. Please email support@bagelsco.lv or try again shortly.",
          ru: "Система приёма заказов ещё настраивается. Напиши на support@bagelsco.lv или попробуй чуть позже.",
        }[lang]);
      } else {
        setSubmitError({
          lv: "Neizdevās nosūtīt pasūtījumu. Mēģini vēlreiz.",
          en: "Couldn't submit your order. Please try again.",
          ru: "Не удалось отправить заказ. Попробуй ещё раз.",
        }[lang]);
      }
      setSubmitting(false);
    }
  };

  return (
    <section className="section">
      <div className="container">
        <button className="btn btn-soft btn-sm" onClick={() => setView("menu")} style={{marginBottom:18}}>← {t("cta_back_menu")}</button>
        <h2>{t("checkout_title")}</h2>
        <div className="checkout-grid" style={{marginTop:28}}>
          <form className="form-card" onSubmit={submit}>
            <h3>{ {lv:"Tavi dati", en:"Your details", ru:"Ваши данные"}[lang] }</h3>
            <div className="form-row__pair">
              <div className="form-row">
                <label>{t("customer_name")}</label>
                <input value={name} onChange={(e)=>setName(e.target.value)}
                  placeholder={ {lv:"Jānis", en:"Your name", ru:"Ваше имя"}[lang] }
                  style={errors.name?{borderColor:"#A33"}:{}} />
              </div>
              <div className="form-row">
                <label>{t("phone")}</label>
                <input type="tel" inputMode="tel" value={phone} onChange={(e)=>setPhone(e.target.value)}
                  placeholder="+371 2X XXX XXX" style={errors.phone?{borderColor:"#A33"}:{}} />
              </div>
            </div>

            <h3 style={{marginTop:24}}>{t("pickup_location")}</h3>
            <div className="pickup-options" style={errors.location?{outline:"1.5px solid #A33", outlineOffset:6, borderRadius:18}:{}}>
              {window.LOCATIONS.map(loc => (
                <button type="button" key={loc.id} className={"pickup-option" + (location === loc.id ? " active" : "")} onClick={() => setLocation(loc.id)}>
                  <span className="pickup-option__name">{loc.name}</span>
                  <span className="pickup-option__addr">{loc.address[lang]}</span>
                  <span className="pickup-option__addr">{loc.hours}</span>
                </button>
              ))}
            </div>

            <h3 style={{marginTop:24}}>{t("pickup_time")}</h3>
            <div className="pickup-time-row">
              <button type="button" className={"variant-pill" + (pickupMode === "asap" ? " active" : "")} onClick={()=>setPickupMode("asap")}>{PICK_TXT.asap}</button>
              <button type="button" className={"variant-pill" + (pickupMode === "today" ? " active" : "")} onClick={()=>setPickupMode("today")}>{PICK_TXT.today}</button>
              <button type="button" className={"variant-pill" + (pickupMode === "tomorrow" ? " active" : "")} onClick={()=>setPickupMode("tomorrow")}>{PICK_TXT.tomorrow}</button>
            </div>
            {pickupMode !== "asap" && (
              <div className="form-row" style={{marginTop:12, maxWidth:240}}>
                <label>{PICK_TXT.time_label}</label>
                <input type="time" value={chosenTime} onChange={(e)=>setChosenTime(e.target.value)}
                  style={errors.time ? {borderColor:"#A33"} : {}} />
              </div>
            )}

            <h3 style={{marginTop:24}}>{t("order_comment")}</h3>
            <textarea className="modal__textarea" rows="3" value={comment} onChange={(e)=>setComment(e.target.value)}
              placeholder={ {lv:"Piezīmes komandai...", en:"Notes for the team...", ru:"Заметки для команды..."}[lang] } />

            <h3 style={{marginTop:24}}>
              { {lv:"E-pasts *", en:"Email *", ru:"Email *"}[lang] }
            </h3>
            <div className="form-row">
              <input type="email" inputMode="email" value={email} onChange={(e)=>setEmail(e.target.value)}
                placeholder="you@example.com"
                required
                style={errors.email?{borderColor:"#A33"}:{}} />
              <div style={{fontSize:12, color:"var(--c-mute)", marginTop:6}}>
                { {lv:"Saņemsi pasūtījuma čeku un statusa atjaunojumus.",
                   en:"You'll receive the receipt and status updates.",
                   ru:"На него придёт чек и обновления статуса заказа."}[lang] }
              </div>
            </div>

            <h3 style={{marginTop:24}}>{t("payment")}</h3>
            <div className="pickup-option active" style={{cursor:"default"}}>
              <span className="pickup-option__name">{t("pay_at_pickup")}</span>
              <span className="pickup-option__addr">
                { {lv:"Caur šo vietni — tikai paņemšana.",
                   en:"Through this site — pickup only.",
                   ru:"Через сайт — только самовывоз."}[lang] }
              </span>
            </div>

            <h3 style={{marginTop:24}}>{t("promo")}</h3>
            <div className="form-row">
              {!promo ? (
                <div style={{display:"flex", gap:8, flexWrap:"wrap"}}>
                  <input value={promoInput} onChange={(e)=>setPromoInput(e.target.value.toUpperCase())}
                    placeholder="WELCOME10"
                    style={{flex:1, minWidth:140, fontFamily:"var(--font-mono)", letterSpacing:".05em", textTransform:"uppercase"}}
                    onKeyDown={(e)=>{ if (e.key === "Enter") { e.preventDefault(); applyPromo(); } }} />
                  <button type="button" className="btn btn-soft btn-sm" onClick={applyPromo} style={{whiteSpace:"nowrap"}}>{t("promo_apply")}</button>
                </div>
              ) : (
                <div style={{display:"flex", alignItems:"center", justifyContent:"space-between", padding:"12px 16px", background:"#E5F5EC", borderRadius:14, color:"#1F6F4A"}}>
                  <div style={{display:"flex", flexDirection:"column", gap:2}}>
                    <span style={{fontFamily:"var(--font-mono)", fontWeight:700}}>✓ {promo.code}</span>
                    <span style={{fontSize:13}}>{promo.label?.[lang] || ""} · −{fmt(discount)}</span>
                  </div>
                  <button type="button" className="cart-row__remove" style={{color:"#1F6F4A"}} onClick={clearPromo}>{t("cta_remove")}</button>
                </div>
              )}
              {promoErr && <div style={{marginTop:8, fontSize:13, color:"#A33"}}>{promoErr}</div>}
            </div>

            {submitError && (
              <div style={{padding:"12px 16px", background:"#F8D7DA", color:"#A33", borderRadius:14, marginTop:18, fontSize:14}}>
                ⚠ {submitError}
              </div>
            )}
            <button type="submit" className="btn btn-primary btn-block btn-lg"
              style={{marginTop:28}} disabled={submitting}>
              {submitting ? (
                <>
                  <span className="spinner" aria-hidden="true"></span>
                  <span>{ {lv:"Sūtām...", en:"Sending...", ru:"Отправляем..."}[lang] }</span>
                </>
              ) : (
                <>{t("cta_submit")} · {fmt(totalAfterDiscount)}</>
              )}
            </button>
          </form>

          <aside className="summary-card">
            <h3 style={{fontFamily:"var(--font-display)", margin:"0 0 14px"}}>{t("order_summary")}</h3>
            {cart.map(it => (
              <div key={it.id} style={{display:"flex", justifyContent:"space-between", padding:"10px 0", borderBottom:"1px dashed var(--c-line)", fontSize:14}}>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontWeight:600}}>{it.qty}× {it.name[lang]}</div>
                  {it.removedNames.length > 0 && (
                    <div className="cart-row__meta">
                      — { it.removedNames.map(n => n[lang]).join(", ") }
                    </div>
                  )}
                </div>
                <div className="mono">{fmt(priceOf(it) * it.qty)}</div>
              </div>
            ))}
            {discount > 0 && (
              <>
                <div className="total-row" style={{marginTop:14}}>
                  <span>{t("cart_subtotal")}</span>
                  <span className="mono">{fmt(subtotal)}</span>
                </div>
                <div className="total-row" style={{color:"var(--c-success)"}}>
                  <span>{t("discount")} · {promo?.code}</span>
                  <span className="mono">−{fmt(discount)}</span>
                </div>
              </>
            )}
            <div className="total-row big" style={{marginTop:18}}>
              <span>{t("cart_total")}</span>
              <span className="total-row__val">{fmt(totalAfterDiscount)}</span>
            </div>

            {/* Delivery via Bolt / Wolt — moved here per design */}
            <div style={{marginTop:24, paddingTop:18, borderTop:"1px solid var(--c-line)"}}>
              <h3 style={{fontFamily:"var(--font-display)", margin:"0 0 6px", fontSize:20}}>
                { {lv:"Vajag piegādi?", en:"Need delivery?", ru:"Нужна доставка?"}[lang] }
              </h3>
              <p style={{margin:"0 0 12px", fontSize:13, color:"var(--c-mute)"}}>
                { {lv:"Saites ievirzīsies uz izvēlēto vietu.",
                   en:"Links go to your chosen spot.",
                   ru:"Ссылки откроются на выбранную точку."}[lang] }
                {" "}
                <strong>{ window.LOCATIONS.find(l => l.id === location)?.name || "—" }</strong>
              </p>
              <div className="checkout-delivery-row">
                <a href={window.deliveryLinkFor ? window.deliveryLinkFor(location, "bolt") : window.DELIVERY_LINKS.bolt}
                   target="_blank" rel="noopener" className="checkout-delivery-btn checkout-delivery-btn--bolt">
                  <span>Bolt Food</span>
                  <span className="checkout-delivery-btn__arrow">↗</span>
                </a>
                <a href={window.deliveryLinkFor ? window.deliveryLinkFor(location, "wolt") : window.DELIVERY_LINKS.wolt}
                   target="_blank" rel="noopener" className="checkout-delivery-btn checkout-delivery-btn--wolt">
                  <span>Wolt</span>
                  <span className="checkout-delivery-btn__arrow">↗</span>
                </a>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </section>
  );
}

// ---------- Order success ----------
function OrderSuccess({ lang, order, setView, clearCart }) {
  const t = useI18n(lang);
  const loc = window.LOCATIONS.find(l => l.id === order.location);
  const placeName = "Bagel&Co " + (loc ? loc.name : "");
  const PICKUP_LBL = { lv: "Paņemt var šeit", en: "Pick up here", ru: "Забрать можно тут" }[lang];
  return (
    <section className="section">
      <div className="container">
        <div className="success">
          <div className="success__check">✓</div>
          <span className="eyebrow">{t("order_received")}</span>
          <div className="success__num">#{order.number}</div>

          <div style={{margin:"22px 0 6px", textAlign:"left"}}>
            <div className="eyebrow">{PICKUP_LBL}</div>
          </div>
          <a href={loc?.mapUrl} target="_blank" rel="noopener"
             style={{
               display:"flex", alignItems:"center", gap:14, padding:"16px 18px",
               background:"var(--c-cream)", borderRadius:16, border:"1px solid var(--c-line)",
               textAlign:"left", textDecoration:"none", color:"var(--c-espresso)",
               margin:"0 0 22px", transition:"border-color .15s ease, transform .12s ease"
             }}
             onMouseEnter={(e)=>{e.currentTarget.style.borderColor="var(--accent)";}}
             onMouseLeave={(e)=>{e.currentTarget.style.borderColor="var(--c-line)";}}
          >
            <div style={{
              width:44, height:44, borderRadius:999, background:"var(--accent)",
              color:"var(--on-accent)", display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0
            }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M12 22s7-7.58 7-13a7 7 0 0 0-14 0c0 5.42 7 13 7 13z"/>
                <circle cx="12" cy="9" r="2.5"/>
              </svg>
            </div>
            <div style={{flex:1, minWidth:0}}>
              <div style={{fontFamily:"var(--font-display)", fontSize:20, lineHeight:1.1, letterSpacing:"-0.01em"}}>{placeName}</div>
              <div style={{fontSize:13, color:"var(--c-mute)", marginTop:4, fontFamily:"var(--font-mono)"}}>
                {loc?.address?.[lang] || ""}
              </div>
              <div style={{fontSize:12, color:"var(--accent)", marginTop:6, fontWeight:600}}>
                { {lv:"Atvērt kartē", en:"Open in Maps", ru:"Открыть в Google Картах"}[lang] } ↗
              </div>
            </div>
          </a>

          <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:12, margin:"0 0 22px", textAlign:"left"}}>
            <div style={{background:"var(--c-cream)", padding:14, borderRadius:14}}>
              <div className="eyebrow">{t("estimated_time")}</div>
              <div style={{fontFamily:"var(--font-display)", fontSize:24, marginTop:4}}>~12 {t("min")}</div>
            </div>
            <div style={{background:"var(--c-cream)", padding:14, borderRadius:14}}>
              <div className="eyebrow">{t("payment")}</div>
              <div style={{fontFamily:"var(--font-display)", fontSize:18, marginTop:4}}>{t("pay_at_pickup")}</div>
            </div>
          </div>

          <button className="btn btn-primary btn-lg" onClick={() => { clearCart(); setView("menu"); }}>{t("cta_back_menu")}</button>
        </div>
      </div>
    </section>
  );
}

// ---------- Locations section ----------
function LocationsSection({ lang, setView, setLocation }) {
  const t = useI18n(lang);
  const mapRef = useRef(null);
  const [mapInstance, setMapInstance] = useState(null);
  const [activeLoc, setActiveLoc] = useState(null);

  useEffect(() => {
    if (!mapRef.current || !window.L || mapInstance) return;
    const L = window.L;
    const map = L.map(mapRef.current, { zoomControl: false, scrollWheelZoom: false, attributionControl: false })
      .setView([56.97, 23.88], 12);

    L.tileLayer('https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png', {
      maxZoom: 18, subdomains: 'abcd'
    }).addTo(map);
    L.tileLayer('https://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}{r}.png', {
      maxZoom: 18, subdomains: 'abcd', opacity: 0.85
    }).addTo(map);

    L.control.zoom({ position: 'bottomright' }).addTo(map);

    const markers = [];
    window.LOCATIONS.forEach((loc, i) => {
      const accent = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim() || '#1D4491';
      const html = `
        <div style="position:relative; display:flex; align-items:center; justify-content:center;">
          <div style="position:absolute; width:48px; height:48px; border-radius:999px; background:${accent}; opacity:.18;"></div>
          <div style="position:relative; width:34px; height:34px; border-radius:999px; background:${accent}; color:white; display:flex; align-items:center; justify-content:center; font-family:'BioRhyme',serif; font-weight:800; font-size:13px; border:3px solid white; box-shadow:0 4px 12px rgba(26,20,16,.25);">${i+1}</div>
        </div>`;
      const icon = L.divIcon({ html, className: '', iconSize: [48,48], iconAnchor: [24,24] });
      const m = L.marker(loc.coords, { icon }).addTo(map);
      m.on('click', () => setActiveLoc(loc.id));
      markers.push(m);
    });

    const group = L.featureGroup(markers);
    map.fitBounds(group.getBounds().pad(0.6));

    setMapInstance(map);
  }, [mapRef.current]);

  const focusLocation = (loc) => {
    if (mapInstance) mapInstance.flyTo(loc.coords, 16, { duration: 1.2 });
    setActiveLoc(loc.id);
  };

  return (
    <section className="section">
      <div className="container">
        <div style={{display:"flex", justifyContent:"space-between", alignItems:"flex-end", flexWrap:"wrap", gap:24, marginBottom:36}}>
          <div>
            <span className="eyebrow">{t("nav_locations")}</span>
            <h2 style={{margin:"12px 0 0"}}>{t("locations_title")}</h2>
          </div>
          <div style={{fontFamily:"var(--font-mono)", fontSize:13, color:"var(--c-mute)"}}>
            { {lv:"2 vietas Pierīgā", en:"2 spots near Riga", ru:"2 точки в окрестностях Риги"}[lang] }
          </div>
        </div>

        <div className="loc-map-grid">
          <div className="loc-map" ref={mapRef} aria-label="Map of Bagel&Co locations"></div>
          <div className="loc-list">
            {window.LOCATIONS.map((loc, i) => (
              <article key={loc.id} className={"loc-list__card" + (activeLoc === loc.id ? " is-active" : "")} onClick={() => focusLocation(loc)}>
                <div className="loc-list__num">{i+1}</div>
                <div className="loc-list__body">
                  <div style={{display:"flex", alignItems:"baseline", gap:10, flexWrap:"wrap"}}>
                    <h3 className="loc-list__name">{loc.fullName || loc.name}</h3>
                    <span style={{fontFamily:"var(--font-mono)", fontSize:11, color:"var(--c-mute)", letterSpacing:"0.08em", textTransform:"uppercase"}}>{loc.name}</span>
                  </div>
                  <div className="loc-list__row">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 22s7-7.58 7-13a7 7 0 0 0-14 0c0 5.42 7 13 7 13z"/><circle cx="12" cy="9" r="2.5"/></svg>
                    <span>{loc.address[lang]}</span>
                  </div>
                  <div className="loc-list__row">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>
                    <span>{loc.hoursLabel ? loc.hoursLabel[lang] : loc.hours}</span>
                  </div>
                  <div className="loc-list__row">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0 1 22 16.92z"/></svg>
                    <a href={"tel:" + loc.phone.replace(/\s/g, '')} onClick={(e)=>e.stopPropagation()}>{loc.phone}</a>
                  </div>
                  <div className="loc-list__cta">
                    <button className="btn btn-dark btn-sm" onClick={(e) => { e.stopPropagation(); setLocation(loc.id); setView("menu"); }}>
                      {t("order_now_at")} →
                    </button>
                    <a className="btn btn-ghost btn-sm" href={loc.mapUrl} target="_blank" rel="noopener" onClick={(e)=>e.stopPropagation()}>
                      { {lv:"Maršruts", en:"Directions", ru:"Маршрут"}[lang] } ↗
                    </a>
                  </div>
                </div>
              </article>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Delivery card ----------
function DeliveryCard({ lang, location }) {
  const t = useI18n(lang);
  const boltUrl = window.deliveryLinkFor ? window.deliveryLinkFor(location, "bolt") : window.DELIVERY_LINKS.bolt;
  const woltUrl = window.deliveryLinkFor ? window.deliveryLinkFor(location, "wolt") : window.DELIVERY_LINKS.wolt;
  const locName = (window.LOCATIONS || []).find(l => l.id === location)?.name || "";
  return (
    <section className="section">
      <div className="container">
        <div className="delivery-card">
          <div>
            <span className="eyebrow" style={{color:"var(--c-pink)"}}>{t("nav_delivery")}{locName ? " · " + locName : ""}</span>
            <h3>{t("delivery_title")}</h3>
            <p>{t("delivery_body")}</p>
            <div className="delivery-card__btns">
              <a href={boltUrl} target="_blank" rel="noopener" className="btn">Order on Bolt →</a>
              <a href={woltUrl} target="_blank" rel="noopener" className="btn">Order on Wolt →</a>
            </div>
          </div>
          <div className="delivery-card__art">
            <Picture src="assets/photos/main-hero.jpg" alt="" sizes="(max-width: 720px) 100vw, 40vw" />
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Footer ----------
function Footer({ lang, setView, location }) {
  const t = useI18n(lang);
  const boltUrl = window.deliveryLinkFor ? window.deliveryLinkFor(location, "bolt") : window.DELIVERY_LINKS.bolt;
  const woltUrl = window.deliveryLinkFor ? window.deliveryLinkFor(location, "wolt") : window.DELIVERY_LINKS.wolt;
  const C = {
    lv: { tagline: "Ģimenes kafejnīca Latvijā. Beigeles, panini, kafija un deserti.", explore: "Pārlūkot", hours: "Darba laiks", follow: "Seko", legal: "Juridiski" },
    en: { tagline: "A family-run café in Latvia. Bagels, panini, coffee and pastries.", explore: "Explore", hours: "Hours", follow: "Follow", legal: "Legal" },
    ru: { tagline: "Семейная кафешка в Латвии. Бейглы, панини, кофе и десерты.", explore: "Разделы", hours: "Часы работы", follow: "Соцсети", legal: "Юридическое" },
  }[lang];
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="site-footer__grid">
          <div>
            <div style={{fontFamily:"var(--font-display)", fontSize:32, color:"var(--c-cream)", marginBottom:10, letterSpacing:"-0.01em"}}>Bagel&Co</div>
            <p style={{maxWidth: 280}}>{C.tagline}</p>
            <div style={{display:"flex", gap:10, marginTop:18}}>
              <a href={boltUrl} target="_blank" rel="noopener"
                 style={{display:"inline-flex", alignItems:"center", gap:6, padding:"7px 14px", borderRadius:999, border:"1px solid rgba(249,238,228,.25)", fontSize:12, fontFamily:"var(--font-mono)", color:"var(--c-cream)", textDecoration:"none"}}>Bolt</a>
              <a href={woltUrl} target="_blank" rel="noopener"
                 style={{display:"inline-flex", alignItems:"center", gap:6, padding:"7px 14px", borderRadius:999, border:"1px solid rgba(249,238,228,.25)", fontSize:12, fontFamily:"var(--font-mono)", color:"var(--c-cream)", textDecoration:"none"}}>Wolt</a>
            </div>
          </div>
          <div>
            <h4>{C.explore}</h4>
            <a onClick={()=>setView && setView("menu")} style={{cursor:"pointer"}}>{t("nav_menu")}</a>
            <a onClick={()=>setView && setView("about")} style={{cursor:"pointer"}}>{t("nav_about")}</a>
            <a onClick={()=>setView && setView("delivery")} style={{cursor:"pointer"}}>{t("nav_delivery")}</a>
            <a onClick={()=>setView && setView("contact")} style={{cursor:"pointer"}}>{t("nav_contact")}</a>
          </div>
          <div>
            <h4>{C.hours}</h4>
            <p style={{fontFamily:"var(--font-mono)", fontSize:13}}>{ {lv:"Bulduri · Pn–Sv · 10:00–19:00", en:"Bulduri · Mon–Sun · 10:00–19:00", ru:"Bulduri · Пн–Вс · 10:00–19:00"}[lang] }</p>
            <p style={{fontFamily:"var(--font-mono)", fontSize:13}}>{ {lv:"Piņķi · Pn–Pk · 08:00–17:00", en:"Piņķi · Mon–Fri · 08:00–17:00", ru:"Piņķi · Пн–Пт · 08:00–17:00"}[lang] }</p>
            <p style={{marginTop:14, fontSize:13}}>support@bagelsco.lv</p>
            <p style={{fontFamily:"var(--font-mono)", fontSize:13}}>+371 20 207 878</p>
          </div>
          <div>
            <h4>{C.follow}</h4>
            <a href="https://www.instagram.com/bagel.and.co/" target="_blank" rel="noopener">Instagram</a>
            <a href="https://www.tiktok.com/@bagel.and.co" target="_blank" rel="noopener">TikTok</a>
          </div>
        </div>
        <div className="site-footer__legal">
          <span>© 2026 Bagel&Co · SIA Bagel&Co · LV40000000000</span>
          <span>Made with care in Latvia 🥯</span>
        </div>
      </div>
    </footer>
  );
}

// ---------- Floating cart (mobile) ----------
// Russian needs three plural forms (1, 2-4, 5+). Latvian needs two (1, 2+).
function pluralizeItems(lang, n) {
  if (lang === "ru") {
    const mod10 = n % 10, mod100 = n % 100;
    if (mod10 === 1 && mod100 !== 11) return "товар";
    if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return "товара";
    return "товаров";
  }
  if (lang === "lv") return n === 1 ? "prece" : "preces";
  return n === 1 ? "item" : "items";
}
function FloatingCart({ lang, count, total, openCart }) {
  const t = useI18n(lang);
  if (count === 0) return null;
  return (
    <button className="floating-cart" onClick={openCart}>
      <span style={{fontWeight:600}}>{count} {pluralizeItems(lang, count)} · {fmt(total)}</span>
      <span style={{fontFamily:"var(--font-mono)", fontSize:13}}>{t("cta_checkout")} →</span>
    </button>
  );
}

// ---------- About page ----------
function AboutPage({ lang, setView }) {
  const t = useI18n(lang);
  const C = {
    lv: {
      eyebrow: "Mūsu stāsts",
      h: "Maza ģimenes kafejnīca, kas rūpīgi domā par katru beigeli.",
      lead: "Bagel&Co sākās 2022. gadā Bulduros, kā vieta, kur mēs paši gribējām pavadīt rītus. Šodien mums ir divas vietas un viens noteikums — gatavojam tikai to, ko paši ēdam.",
      p1Head: "Cepam paši, no rīta",
      p1: "Beigeles no rauga mīklas. Mīklu gatavojam vakarā, mīcam un cepam pirms pirmā klienta. Ja kaut kas beidzies — beidzies, jaunu partiju nepiegādājam.",
      p2Head: "Tikai sastāvdaļas, kuras mēs zinām",
      p2: "Lasis no Latvijas piegādātāja, čedars no Anglijas, kafija no maza grauzdētāja Rīgā. Nekādu pievienoto cukuru, gatavu mērču vai garlaicīgu kompromisu.",
      p3Head: "Pasūti iepriekš, neaizmirsti smaidu",
      p3: "Lai jūs nestāvētu rindā, šī mājaslapa pieņem pasūtījumus iepriekš. Atnāc, satiec mūs, parunā par dienu. Tā kafejnīcā vajadzētu būt.",
      stat1: "08:00", stat1lbl: "Pirmā partija no krāsns (Piņķi)", stat2: "0", stat2lbl: "Saldētas sastāvdaļas", stat3: "2", stat3lbl: "Vietas Latvijā", stat4: "—", stat4lbl: "Cik dieniņas Bagel&Co",
      cta: "Skatīt ēdienkarti",
    },
    en: {
      eyebrow: "Our story",
      h: "A small family café that thinks carefully about every bagel.",
      lead: "Bagel&Co started in 2022 in Bulduri, as a place where we ourselves wanted to spend mornings. Today we have two locations and one rule — we only make what we eat.",
      p1Head: "We bake here, in the morning",
      p1: "Yeasted bagel dough, mixed the night before, shaped and baked before the first customer. When something runs out, it runs out — no second batch shipped in.",
      p2Head: "Only ingredients we know",
      p2: "Salmon from a Latvian supplier, English cheddar, coffee from a small Riga roaster. No added sugars, no jarred sauces, no boring compromises.",
      p3Head: "Order ahead, keep the smile",
      p3: "So you don't queue, this website takes orders in advance. Come in, say hi, talk about the day. The way a café should feel.",
      stat1: "08:00", stat1lbl: "First batch out (Piņķi)", stat2: "0", stat2lbl: "Frozen ingredients", stat3: "2", stat3lbl: "Locations in Latvia", stat4: "—", stat4lbl: "Days as Bagel&Co",
      cta: "See the menu",
    },
    ru: {
      eyebrow: "Наша история",
      h: "Маленькая семейная кафешка, которая думает над каждым бейглом.",
      lead: "Bagel&Co открылся в 2022 в Булдури — как место, где мы сами хотели проводить утро. Сегодня у нас две точки и одно правило — готовим только то, что едим сами.",
      p1Head: "Печём здесь, с утра",
      p1: "Дрожжевое тесто месим вечером, формуем и печём до первого клиента. Закончилось — значит закончилось, новой партии не привезут.",
      p2Head: "Только ингредиенты, которым доверяем",
      p2: "Лосось от латвийского поставщика, английский чеддер, кофе от маленькой обжарки в Риге. Без сахара, без банок, без скучных компромиссов.",
      p3Head: "Заказывай заранее — оставь улыбку",
      p3: "Чтобы не стоять в очереди, этот сайт принимает заказы заранее. Заходи, поздоровайся, поговори про день. Кафе должно ощущаться именно так.",
      stat1: "08:00", stat1lbl: "Первая партия из печи (Piņķi)", stat2: "0", stat2lbl: "Замороженных продуктов", stat3: "2", stat3lbl: "Точки в Латвии", stat4: "—", stat4lbl: "Дней как Bagel&Co",
      cta: "Открыть меню",
    },
  }[lang];

  return (
    <section className="section">
      <div className="container">
        <div style={{maxWidth: 720, marginBottom: 64}}>
          <span className="eyebrow">{C.eyebrow}</span>
          <h2 style={{fontSize:"clamp(40px, 5.5vw, 76px)", margin:"12px 0 24px"}}>{C.h}</h2>
          <p style={{fontSize:18, color:"var(--c-coffee)", lineHeight:1.55, margin:0}}>{C.lead}</p>
        </div>
        <div className="grid-mosaic" style={{marginBottom:48}}>
          <div style={{borderRadius:24, overflow:"hidden", aspectRatio:"4/5"}}>
            <Picture src="assets/photos/cafe-3.jpg" alt="" sizes="(max-width: 720px) 50vw, 33vw" />
          </div>
          <div style={{display:"grid", gridTemplateRows:"1fr 1fr", gap:14}}>
            <div style={{borderRadius:24, overflow:"hidden"}}>
              <Picture src="assets/photos/bagel-3.jpg" alt="" sizes="(max-width: 720px) 50vw, 33vw" />
            </div>
            <div style={{borderRadius:24, overflow:"hidden"}}>
              <Picture src="assets/photos/cafe-15.jpg" alt="" sizes="(max-width: 720px) 50vw, 33vw" />
            </div>
          </div>
        </div>

        <div className="grid-3" style={{marginBottom:64}}>
          {[[C.p1Head, C.p1], [C.p2Head, C.p2], [C.p3Head, C.p3]].map(([h,p], i) => (
            <div key={i}>
              <div style={{fontFamily:"var(--font-mono)", fontSize:12, color:"var(--c-mute)", letterSpacing:"0.1em"}}>0{i+1}</div>
              <h3 style={{fontFamily:"var(--font-display)", fontSize:24, margin:"10px 0 12px", letterSpacing:"-0.01em"}}>{h}</h3>
              <p style={{color:"var(--c-coffee)", lineHeight:1.6, fontSize:15, margin:0}}>{p}</p>
            </div>
          ))}
        </div>

        <div className="grid-4" style={{borderTop:"1px solid var(--c-line)", paddingTop:32, marginBottom:48}}>
          {[[C.stat1, C.stat1lbl],[C.stat2,C.stat2lbl],[C.stat3,C.stat3lbl],[C.stat4,C.stat4lbl]].map(([n,l],i)=>(
            <div key={i}>
              <div style={{fontFamily:"var(--font-display)", fontSize:42, lineHeight:1, letterSpacing:"-0.02em"}}>{n}</div>
              <div style={{fontFamily:"var(--font-mono)", fontSize:11, textTransform:"uppercase", letterSpacing:"0.1em", color:"var(--c-mute)", marginTop:8}}>{l}</div>
            </div>
          ))}
        </div>

        <button className="btn btn-primary btn-lg" onClick={() => setView("menu")}>{C.cta} →</button>
      </div>
    </section>
  );
}

// ---------- Delivery page ----------
function DeliveryPage({ lang, location, setLocation }) {
  const t = useI18n(lang);
  // Local location override so user can preview both spots without changing global state
  const [activeLoc, setActiveLoc] = useState(location || "bulduri");
  useEffect(() => { if (location) setActiveLoc(location); }, [location]);
  const boltUrl = window.deliveryLinkFor ? window.deliveryLinkFor(activeLoc, "bolt") : window.DELIVERY_LINKS.bolt;
  const woltUrl = window.deliveryLinkFor ? window.deliveryLinkFor(activeLoc, "wolt") : window.DELIVERY_LINKS.wolt;
  const PICK_LBL = { lv: "No kuras vietas?", en: "From which spot?", ru: "Откуда заказываем?" }[lang];
  const C = {
    lv: {
      eyebrow: "Piegāde",
      h: "Piegādi pa Jūrmalu un apkārtni nodrošina mūsu draugi.",
      lead: "Mēs koncentrējamies uz to, ko mākam labi — cept beigeles. Piegādi uzticam Bolt Food un Wolt — viņi to dara ātrāk un drošāk nekā mēs jebkad varētu.",
      bolt: "Pasūtīt caur Bolt Food",
      wolt: "Pasūtīt caur Wolt",
      time: "30–45 min", timeLbl: "Vidējais piegādes laiks",
      area: "Jūrmala · Babīte", areaLbl: "Piegādes zona",
      hours: "10:00–19:00", hoursLbl: "Piegādes stundas",
      faqHead: "Bieži uzdoti jautājumi",
      faq: [
        ["Vai mēs piedāvājam paši savu kurjeru?", "Nē. Mēs strādājam tikai caur Bolt un Wolt — viņiem ir profesionāli kurjeri un termo somas."],
        ["Cik maksā piegāde?", "Piegādes cenu nosaka Bolt vai Wolt. Tā parādās redzama, kad pievienojam pasūtījumam adresi."],
        ["Vai var pasūtīt no abām vietām?", "Jā — gan Bolt, gan Wolt strādā ar abām mūsu vietām (Bulduri un Piņķi)."],
        ["Vai gatavojat speciāli piegādei?", "Visi mūsu produkti ir piemēroti piegādei. Beigeles iesaiņojam tā, lai tās paliktu kraukšķīgas."],
      ],
    },
    en: {
      eyebrow: "Delivery",
      h: "Delivery in Jūrmala and around is handled by our friends.",
      lead: "We focus on what we do best — baking bagels. Delivery we leave to Bolt Food and Wolt — they do it faster and safer than we ever could.",
      bolt: "Order via Bolt Food",
      wolt: "Order via Wolt",
      time: "30–45 min", timeLbl: "Average delivery time",
      area: "Jūrmala · Babīte", areaLbl: "Delivery area",
      hours: "10:00–19:00", hoursLbl: "Delivery hours",
      faqHead: "Frequently asked",
      faq: [
        ["Do you have your own couriers?", "No. We only work through Bolt and Wolt — they have proper couriers and insulated bags."],
        ["How much is delivery?", "Delivery fee is set by Bolt or Wolt. It shows up clearly when you add an address to your order."],
        ["Can I order from both locations?", "Yes — Bolt and Wolt both cover our two spots (Bulduri and Piņķi)."],
        ["Do you prepare differently for delivery?", "Every product is delivery-friendly. Bagels are wrapped to stay crisp on the way."],
      ],
    },
    ru: {
      eyebrow: "Доставка",
      h: "Доставку по Юрмале и окрестностям делают наши друзья.",
      lead: "Мы фокусируемся на том, что умеем — печём бейглы. Доставку оставили Bolt Food и Wolt — у них быстрее и надёжнее.",
      bolt: "Заказать через Bolt Food",
      wolt: "Заказать через Wolt",
      time: "30–45 мин", timeLbl: "Среднее время",
      area: "Юрмала · Бабите", areaLbl: "Зона доставки",
      hours: "10:00–19:00", hoursLbl: "Часы доставки",
      faqHead: "Частые вопросы",
      faq: [
        ["Есть ли свой курьер?", "Нет. Только через Bolt и Wolt — у них профессиональные курьеры и термосумки."],
        ["Сколько стоит доставка?", "Стоимость определяет Bolt или Wolt. Цена видна сразу при добавлении адреса."],
        ["Можно заказать из обеих точек?", "Да — Bolt и Wolt работают с обеими нашими точками (Bulduri и Piņķi)."],
        ["Готовите специально для доставки?", "Все позиции подходят для доставки. Бейглы упаковываем так, чтобы они оставались хрустящими."],
      ],
    },
  }[lang];

  return (
    <section className="section">
      <div className="container">
        <div style={{maxWidth: 720, marginBottom: 56}}>
          <span className="eyebrow">{C.eyebrow}</span>
          <h2 style={{margin:"12px 0 24px"}}>{C.h}</h2>
          <p style={{fontSize:18, color:"var(--c-coffee)", lineHeight:1.55, margin:0}}>{C.lead}</p>
        </div>

        {/* Location switcher (Bulduri / Piņķi) — controls which Bolt/Wolt links open */}
        <div style={{marginBottom:24}}>
          <div className="eyebrow" style={{marginBottom:12}}>{PICK_LBL}</div>
          <div className="delivery-loc-switch">
            {window.LOCATIONS.map(loc => (
              <button key={loc.id}
                className={"delivery-loc-pill" + (activeLoc === loc.id ? " is-active" : "")}
                onClick={() => { setActiveLoc(loc.id); if (setLocation) setLocation(loc.id); }}>
                <span className="delivery-loc-pill__num">{window.LOCATIONS.indexOf(loc)+1}</span>
                <span>
                  <span className="delivery-loc-pill__name">Bagel&Co {loc.name}</span>
                  <span className="delivery-loc-pill__hours">{loc.hoursLabel ? loc.hoursLabel[lang] : loc.hours}</span>
                </span>
              </button>
            ))}
          </div>
        </div>

        <div className="grid-2" style={{marginBottom:48}}>
          <a href={boltUrl} target="_blank" rel="noopener"
             style={{background:"#34D186", color:"white", borderRadius:24, padding:32, textDecoration:"none", display:"block",
                     transition:"transform .15s ease, box-shadow .2s ease", boxShadow:"0 12px 32px -12px rgba(52,209,134,.5)"}}>
            <div style={{fontFamily:"var(--font-mono)", fontSize:11, opacity:.9, letterSpacing:"0.12em", textTransform:"uppercase", marginBottom:18}}>Bolt Food</div>
            <div style={{fontFamily:"var(--font-display)", fontSize:32, marginBottom:24, letterSpacing:"-0.01em"}}>{C.bolt}</div>
            <div style={{display:"inline-flex", alignItems:"center", gap:8, fontWeight:600, fontSize:15}}>
              <span>→</span> <span style={{borderBottom:"1px solid white"}}>food.bolt.eu</span>
            </div>
          </a>
          <a href={woltUrl} target="_blank" rel="noopener"
             style={{background:"#009DE0", color:"white", borderRadius:24, padding:32, textDecoration:"none", display:"block",
                     transition:"transform .15s ease, box-shadow .2s ease", boxShadow:"0 12px 32px -12px rgba(0,157,224,.5)"}}>
            <div style={{fontFamily:"var(--font-mono)", fontSize:11, opacity:.9, letterSpacing:"0.12em", textTransform:"uppercase", marginBottom:18}}>Wolt</div>
            <div style={{fontFamily:"var(--font-display)", fontSize:32, marginBottom:24, letterSpacing:"-0.01em"}}>{C.wolt}</div>
            <div style={{display:"inline-flex", alignItems:"center", gap:8, fontWeight:600, fontSize:15}}>
              <span>→</span> <span style={{borderBottom:"1px solid white"}}>wolt.com</span>
            </div>
          </a>
        </div>

        <div className="grid-3" style={{padding:"32px 0", borderTop:"1px solid var(--c-line)", borderBottom:"1px solid var(--c-line)", marginBottom:56}}>
          {[[C.time, C.timeLbl],[C.area, C.areaLbl],[C.hours, C.hoursLbl]].map(([n,l],i)=>(
            <div key={i}>
              <div style={{fontFamily:"var(--font-display)", fontSize:32, lineHeight:1, letterSpacing:"-0.01em"}}>{n}</div>
              <div style={{fontFamily:"var(--font-mono)", fontSize:11, textTransform:"uppercase", letterSpacing:"0.1em", color:"var(--c-mute)", marginTop:8}}>{l}</div>
            </div>
          ))}
        </div>

        <h3 style={{fontFamily:"var(--font-display)", fontSize:32, margin:"0 0 28px", letterSpacing:"-0.01em"}}>{C.faqHead}</h3>
        <div>
          {C.faq.map(([q,a],i) => (
            <details key={i} style={{borderTop: i===0 ? "1px solid var(--c-line)" : "none", borderBottom:"1px solid var(--c-line)", padding:"20px 0"}}>
              <summary style={{cursor:"pointer", listStyle:"none", display:"flex", justifyContent:"space-between", alignItems:"center", fontWeight:600, fontSize:16}}>
                <span>{q}</span>
                <span style={{fontFamily:"var(--font-mono)", fontSize:18, color:"var(--c-mute)"}}>+</span>
              </summary>
              <p style={{marginTop:12, color:"var(--c-coffee)", lineHeight:1.6, fontSize:15}}>{a}</p>
            </details>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Contact page ----------
function ContactPage({ lang }) {
  const t = useI18n(lang);
  const [form, setForm] = useState({ name:"", email:"", subject:"", message:"" });
  const [sent, setSent] = useState(false);
  const C = {
    lv: { eyebrow: "Kontakti", h: "Sazinies ar mums.", lead: "Jautājumi, kafijas iespējas, sūdzības, iedvesma — viss vienā vietā." },
    en: { eyebrow: "Contact", h: "Get in touch.", lead: "Questions, catering enquiries, complaints, ideas — all welcome here." },
    ru: { eyebrow: "Контакты", h: "Напиши нам.", lead: "Вопросы, кейтеринг, жалобы, идеи — пиши обо всём." },
  }[lang];

  return (
    <section className="section">
      <div className="container">
        <div style={{maxWidth:680, marginBottom:48}}>
          <span className="eyebrow">{C.eyebrow}</span>
          <h2 style={{margin:"12px 0 18px"}}>{C.h}</h2>
          <p style={{fontSize:18, color:"var(--c-coffee)", lineHeight:1.55, margin:0}}>{C.lead}</p>
        </div>
        <div className="grid-13-1">
          <div className="form-card">
            {sent ? (
              <div style={{padding:"40px 20px", textAlign:"center"}}>
                <div style={{width:64, height:64, margin:"0 auto 18px", borderRadius:999, background:"var(--accent)", color:"var(--on-accent)", display:"flex", alignItems:"center", justifyContent:"center", fontSize:30}}>✓</div>
                <h3 style={{fontFamily:"var(--font-display)", margin:"0 0 8px"}}>{t("contact_thanks")}</h3>
              </div>
            ) : (
              <form onSubmit={(e)=>{e.preventDefault(); setSent(true);}}>
                <div className="form-row__pair">
                  <div className="form-row">
                    <label>{t("customer_name")}</label>
                    <input value={form.name} onChange={(e)=>setForm({...form, name:e.target.value})} required />
                  </div>
                  <div className="form-row">
                    <label>{t("email")}</label>
                    <input type="email" value={form.email} onChange={(e)=>setForm({...form, email:e.target.value})} required />
                  </div>
                </div>
                <div className="form-row">
                  <label>{t("contact_subject")}</label>
                  <input value={form.subject} onChange={(e)=>setForm({...form, subject:e.target.value})} required />
                </div>
                <div className="form-row">
                  <label>{t("contact_message")}</label>
                  <textarea rows="6" value={form.message} onChange={(e)=>setForm({...form, message:e.target.value})} required />
                </div>
                <button type="submit" className="btn btn-primary btn-lg" style={{marginTop:8}}>{t("contact_send")} →</button>
              </form>
            )}
          </div>
          <aside style={{display:"flex", flexDirection:"column", gap:24}}>
            {window.LOCATIONS.map(loc => (
              <div key={loc.id} style={{background:"var(--c-card)", border:"1px solid var(--c-line)", borderRadius:22, padding:24}}>
                <div style={{fontFamily:"var(--font-display)", fontSize:24, marginBottom:8, letterSpacing:"-0.01em"}}>{loc.name}</div>
                <div style={{fontSize:14, color:"var(--c-coffee)", lineHeight:1.6, marginBottom:6}}>{loc.address[lang]}</div>
                <div style={{fontFamily:"var(--font-mono)", fontSize:13, color:"var(--c-mute)", marginBottom:6}}>{loc.hours}</div>
                <div style={{fontFamily:"var(--font-mono)", fontSize:13}}>{loc.phone}</div>
              </div>
            ))}
            <div style={{padding:"24px 0", borderTop:"1px solid var(--c-line)"}}>
              <div style={{fontFamily:"var(--font-mono)", fontSize:11, textTransform:"uppercase", letterSpacing:"0.1em", color:"var(--c-mute)", marginBottom:10}}>Email</div>
              <a href="mailto:support@bagelsco.lv" style={{fontWeight:600, fontSize:16, borderBottom:"1px solid var(--c-line)", paddingBottom:2}}>support@bagelsco.lv</a>
            </div>
            <div style={{padding:"24px 0", borderTop:"1px solid var(--c-line)"}}>
              <div style={{fontFamily:"var(--font-mono)", fontSize:11, textTransform:"uppercase", letterSpacing:"0.1em", color:"var(--c-mute)", marginBottom:10}}>{ {lv:"Sociālie tīkli",en:"Social",ru:"Соцсети"}[lang] }</div>
              <div style={{display:"flex", flexDirection:"column", gap:8}}>
                <a href="https://www.instagram.com/bagel.and.co/" target="_blank" rel="noopener" style={{fontWeight:600, fontSize:15}}>Instagram · @bagel.and.co</a>
                <a href="https://www.tiktok.com/@bagel.and.co" target="_blank" rel="noopener" style={{fontWeight:600, fontSize:15}}>TikTok · @bagel.and.co</a>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  Header, Hero, LocationStrip, PopularRow, ProductCard, MenuView,
  ProductModal, CartDrawer, Checkout, OrderSuccess,
  LocationsSection, DeliveryCard, Footer, FloatingCart,
  AboutPage, DeliveryPage, ContactPage,
  WhyUsBand, ProcessBand, TestimonialsBand, NewsletterBand,
  useI18n, priceOf, fmt
});

// ---------- Why us band ----------
function WhyUsBand({ lang }) {
  const C = {
    lv: { eyebrow:"Kāpēc Bagel&Co", h:"Ne tikai ēdiens — rūpīgs darbs.",
      items:[
        ["Cepts šorīt","Mīklu mīcam vakarā, formējam un cepam pirms pirmā klienta. Ja kaut kas beidzies — beidzies."],
        ["Bez kompromisiem","Lasis no vietējā piegādātāja, čedars no Anglijas, kafija no Rīgas grauzdētavas. Nekādu pievienoto cukuru."],
        ["Pasūti iepriekš","Nestāvi rindā: pasūti telefonā, atnāc, satiec mūs. Tā kafejnīcā vajadzētu būt."],
        ["Trīs valodās","Latviski, angliski un krieviski — tā, kā runā mūsu klienti."],
      ]},
    en: { eyebrow:"Why Bagel&Co", h:"More than food — careful work.",
      items:[
        ["Baked this morning","Dough mixed the night before, shaped and baked before the first customer. When something runs out — it's out."],
        ["No compromises","Salmon from a Latvian supplier, English cheddar, coffee from a Riga roastery. No added sugars, ever."],
        ["Order ahead","Skip the queue: order on your phone, walk in, say hi. The way a café should feel."],
        ["Three languages","Latvian, English and Russian — the way our customers speak."],
      ]},
    ru: { eyebrow:"Почему Bagel&Co", h:"Не просто еда — внимательная работа.",
      items:[
        ["Печём с утра","Тесто месим вечером, формуем и печём до первого клиента. Закончилось — значит закончилось."],
        ["Без компромиссов","Лосось от латвийского поставщика, английский чеддер, кофе от рижской обжарки. Без добавленного сахара."],
        ["Заказывай заранее","Не стой в очереди: закажи в телефоне, зайди, поздоровайся."],
        ["На трёх языках","Латышский, английский, русский — как говорят наши клиенты."],
      ]},
  }[lang];
  return (
    <section className="section" style={{paddingTop:24}}>
      <div className="container">
        <div style={{maxWidth:680, marginBottom:48}}>
          <span className="eyebrow">{C.eyebrow}</span>
          <h2 style={{margin:"12px 0 0"}}>{C.h}</h2>
        </div>
        <div style={{display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:24, borderTop:"1px solid var(--c-line)"}}>
          {C.items.map(([h,p],i)=>(
            <div key={i} style={{padding:"32px 0 8px", borderRight: i<3 ? "1px solid var(--c-line)" : "none", paddingRight: i<3 ? 24 : 0}}>
              <div style={{fontFamily:"var(--font-mono)", fontSize:11, color:"var(--c-mute)", letterSpacing:"0.12em", marginBottom:18}}>0{i+1}</div>
              <h3 style={{fontFamily:"var(--font-display)", fontSize:22, margin:"0 0 10px", letterSpacing:"-0.01em"}}>{h}</h3>
              <p style={{color:"var(--c-coffee)", fontSize:14.5, lineHeight:1.55, margin:0}}>{p}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Process band ----------
function ProcessBand({ lang }) {
  const C = {
    lv: { eyebrow:"Mūsu rīts", h:"Tā tas notiek katru dienu.",
      steps: [
        ["05:30","Mīkla nāk no ledusskapja","Vakarā mīcīta, nakti pavadījusi vēsumā — tā beigele iegūst raksturu."],
        ["06:00","Formēšana","Katru beigeli rokām tinam un ievietojam vāra ūdenī. Tas dod kraukšķi."],
        ["07:00","Cepšana","Krāsnī uz akmens, līdz zelta garoza — tā iznāk pirmā partija."],
        ["08:00","Atveramies","Tu atnāc, mēs iesim pakaļ pārējam — kafijai, sieram, mērcēm. Sākam dienu."],
      ]},
    en: { eyebrow:"Our morning", h:"This is how every day starts.",
      steps: [
        ["05:30","Dough out of the fridge","Mixed last night, slow-fermented through the dark — that's where the character comes from."],
        ["06:00","Shaping","Every bagel hand-rolled and dropped into boiling water. That's where the chew is born."],
        ["07:00","Baking","Onto the stone, into the oven, until the crust turns gold."],
        ["08:00","We open","You walk in, we get to work — coffee, cheese, sauces. The day starts."],
      ]},
    ru: { eyebrow:"Наше утро", h:"Так начинается каждый день.",
      steps: [
        ["05:30","Тесто из холодильника","Замешано вечером, всю ночь медленно бродит — отсюда характер."],
        ["06:00","Формовка","Каждый бейгл вручную, потом в кипяток. Так получается жевательная корочка."],
        ["07:00","Выпечка","На камень в печь до золотой корочки — вот первая партия."],
        ["08:00","Открываемся","Ты заходишь, мы идём за остальным — кофе, сыр, соусы. Поехали."],
      ]},
  }[lang];
  return (
    <section className="section" style={{background:"var(--c-espresso)", color:"var(--c-cream)"}}>
      <div className="container">
        <div style={{maxWidth:680, marginBottom:56}}>
          <span className="eyebrow" style={{color:"var(--accent-soft)"}}>{C.eyebrow}</span>
          <h2 style={{margin:"12px 0 0", color:"var(--c-cream)"}}>{C.h}</h2>
        </div>
        <div style={{display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:0, position:"relative"}}>
          <div style={{position:"absolute", top:14, left:"6%", right:"6%", height:1, background:"rgba(249,238,228,.2)"}}></div>
          {C.steps.map(([t,h,p],i)=>(
            <div key={i} style={{padding:"0 16px"}}>
              <div style={{width:28, height:28, borderRadius:999, background:"var(--accent-soft)", color:"var(--c-espresso)", display:"flex", alignItems:"center", justifyContent:"center", fontFamily:"var(--font-mono)", fontSize:11, fontWeight:700, position:"relative", zIndex:1, marginBottom:24}}>{i+1}</div>
              <div style={{fontFamily:"var(--font-mono)", fontSize:13, opacity:.7, marginBottom:6}}>{t}</div>
              <h3 style={{fontFamily:"var(--font-display)", fontSize:22, color:"var(--c-cream)", margin:"0 0 10px", letterSpacing:"-0.01em"}}>{h}</h3>
              <p style={{color:"rgba(249,238,228,.75)", fontSize:14, lineHeight:1.55, margin:0}}>{p}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Testimonials ----------
function TestimonialsBand({ lang }) {
  const C = {
    lv: { eyebrow:"Klienti saka",
      items:[
        ["„Bagel & Co. — joprojām viena no mūsu mīļākajām vietām. Vienmēr svaigi, vienmēr garšīgi.\"","A. N., Google atsauksmes", "★★★★★"],
        ["„Sestdienas rīta rituāls. Lasis ar īsta lasa garšu, nevis sāli.\"","E. J., Google atsauksmes", "★★★★★"],
        ["„Mīļa, mājīga vieta. Personāls draudzīgs, kafija laba.\"","A. L., Google atsauksmes", "★★★★★"],
        ["„Mazs ģimenes kafejnīca ar dvēseli. Atgriežamies regulāri.\"","Bulduri viesis", "★★★★★"],
      ]},
    en: { eyebrow:"What people say",
      items:[
        ["„Bagel & Co. — still one of our favorite places. Always fresh, always tasty.\"","A. N., Google review", "★★★★★"],
        ["„Saturday-morning ritual. Salmon that actually tastes like salmon, not salt.\"","E. J., Google review", "★★★★★"],
        ["„Cosy little spot. Friendly staff, good coffee.\"","A. L., Google review", "★★★★★"],
        ["„A small family café with soul. We come back regularly.\"","Bulduri visitor", "★★★★★"],
      ]},
    ru: { eyebrow:"Отзывы",
      items:[
        ["„Bagel & Co. — по-прежнему одно из наших любимых мест. Всегда свежо, всегда вкусно.\"","А. Н., отзыв в Google", "★★★★★"],
        ["„Суббота утром — наш ритуал. Лосось со вкусом лосося, а не соли.\"","Э. Е., отзыв в Google", "★★★★★"],
        ["„Уютное маленькое место. Приветливый персонал, хороший кофе.\"","А. Л., отзыв в Google", "★★★★★"],
        ["„Маленькое семейное кафе с душой. Возвращаемся регулярно.\"","Гость из Булдури", "★★★★★"],
      ]},
  }[lang];
  const reviewsTxt = {lv:"67 atsauksmes Google",en:"67 Google reviews",ru:"67 отзывов в Google"}[lang];
  return (
    <section className="section">
      <div className="container">
        <div style={{maxWidth:680, marginBottom:40}}>
          <span className="eyebrow">{C.eyebrow}</span>
          <div style={{display:"flex", alignItems:"baseline", gap:18, marginTop:12, flexWrap:"wrap"}}>
            <h2 style={{margin:0}}>4.7 / 5</h2>
            <div style={{fontFamily:"var(--font-mono)", color:"var(--c-mute)", fontSize:14}}>· {reviewsTxt}</div>
          </div>
        </div>
        <div className="testimonials-grid">
          {C.items.map(([q,n,s],i)=>(
            <div key={i} style={{background:"var(--c-card)", border:"1px solid var(--c-line)", borderRadius:22, padding:28}}>
              <div style={{color:"var(--accent)", fontSize:14, letterSpacing:"0.1em", marginBottom:16}}>{s}</div>
              <p style={{fontFamily:"var(--font-display)", fontSize:20, lineHeight:1.4, margin:"0 0 22px", letterSpacing:"-0.01em"}}>{q}</p>
              <div style={{fontFamily:"var(--font-mono)", fontSize:12, color:"var(--c-mute)", letterSpacing:"0.06em"}}>{n}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Newsletter band ----------
function NewsletterBand({ lang }) {
  const [email, setEmail] = useState("");
  const [sent, setSent] = useState(false);
  const C = {
    lv: { eyebrow:"Esi pirmais", h:"Jaunumi par sezonas beigelēm, akcijām un atvērtajām dienām.", placeholder:"tavs@epasts.lv", cta:"Pierakstīties", thanks:"Paldies — tu sarakstā!" },
    en: { eyebrow:"Be first to know", h:"Updates on seasonal bagels, deals, and open days.", placeholder:"your@email.com", cta:"Subscribe", thanks:"Thanks — you're on the list!" },
    ru: { eyebrow:"Будь в курсе", h:"Сезонные бейглы, акции и открытые дни.", placeholder:"ваш@email.com", cta:"Подписаться", thanks:"Спасибо — ты в списке!" },
  }[lang];
  return (
    <section className="section newsletter-band" style={{paddingTop:24}}>
      <div className="container">
        <div className="newsletter-band__card">
          <div>
            <span className="eyebrow">{C.eyebrow}</span>
            <h3 className="newsletter-band__h">{C.h}</h3>
          </div>
          {sent ? (
            <div style={{fontFamily:"var(--font-display)", fontSize:24}}>{C.thanks} ✓</div>
          ) : (
            <form onSubmit={(e)=>{e.preventDefault(); setSent(true);}} className="newsletter-band__form">
              <input value={email} onChange={(e)=>setEmail(e.target.value)} type="email" required placeholder={C.placeholder}
                className="newsletter-band__input" />
              <button type="submit" className="btn btn-primary btn-lg newsletter-band__btn">{C.cta}</button>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}
