// ==========================================================
// itooth — main App (dynamic + ProductDetail + search + polish)
// ==========================================================

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

// ============ Announcement ============
function Announcement({ lang, messages }) {
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    if (!messages.length) return;
    const t = setInterval(() => setIdx((i) => (i + 1) % messages.length), 4000);
    return () => clearInterval(t);
  }, [messages.length]);
  if (!messages.length) return null;
  const msg = messages[idx];
  return (
    <div className="announce">
      <span key={idx} className="announce__msg">{tr(msg, 'message', lang)}</span>
    </div>
  );
}

// ============ Brand mark (logo) ============
function BrandMark({ size = 36, logoUrl, onDark }) {
  if (logoUrl) {
    return (
      <span className="brand-mark brand-mark--img" style={{ width: size, height: size }}>
        <img src={asset(logoUrl)} alt="itooth" />
      </span>
    );
  }
  return (
    <span className="brand-mark" style={{ width: size, height: size }}>
      <svg width={size * 0.6} height={size * 0.6} viewBox="0 0 64 64" fill="none" aria-hidden="true">
        <defs>
          <linearGradient id={`lg${size}`} x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="var(--brand-deep)" />
            <stop offset="100%" stopColor="var(--brand)" />
          </linearGradient>
        </defs>
        <path
          d="M32 6c-8 0-13 2-18 2-4 0-6 4-6 10 0 6 2 10 4 16 2 5 3 10 4 16 1 6 4 8 6 8 3 0 4-4 5-9 1-4 2-7 5-7s4 3 5 7c1 5 2 9 5 9 2 0 5-2 6-8 1-6 2-11 4-16 2-6 4-10 4-16 0-6-2-10-6-10-5 0-10-2-18-2z"
          fill={`url(#lg${size})`}
        />
      </svg>
    </span>
  );
}

function Stars({ value = 5, size = 14 }) {
  const v = Math.max(0, Math.min(5, value));
  const full = Math.floor(v);
  const half = v - full >= 0.5;
  const stars = [];
  for (let i = 0; i < 5; i++) {
    if (i < full) stars.push(<span key={i}>★</span>);
    else if (i === full && half) stars.push(<span key={i}>★</span>);
    else stars.push(<span key={i} style={{ opacity: 0.25 }}>★</span>);
  }
  return <span style={{ color: '#F5B301', fontSize: size, letterSpacing: 1 }}>{stars}</span>;
}

// ============ Nav ============
function Nav({ lang, setLang, cartCount, onOpenCart, onOpenSearch, scrolled, logoUrl, route, navigate, customer, soundOn, onToggleSound }) {
  const S = window.ITOOTH_STRINGS[lang];
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    if (menuOpen) document.body.style.overflow = 'hidden';
    else document.body.style.overflow = '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);

  useEffect(() => {
    const onResize = () => { if (window.innerWidth > 900) setMenuOpen(false); };
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  const go = (path) => {
    setMenuOpen(false);
    navigate(path);
  };

  const accountHref = customer ? '/account' : '/account/login';
  const isActive = (p) => route === p || (p !== '/' && route.startsWith(p));

  return (
    <>
      <header className={`nav ${scrolled ? "nav--scrolled" : ""}`}>
        <div className="nav__inner">
          <button className="nav__burger" onClick={() => setMenuOpen(true)} aria-label="menu">
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <path d="M4 6h16M4 12h16M4 18h16" />
            </svg>
          </button>

          <a href="/" className="nav__brand" onClick={(e) => { e.preventDefault(); go('/'); }}>
            <BrandMark size={36} logoUrl={logoUrl} />
            <span className="nav__brand-text">itooth<sup>®</sup></span>
          </a>

          <nav className="nav__links">
            <a href="/shop" className={isActive('/shop') ? 'is-active' : ''} onClick={(e) => { e.preventDefault(); go('/shop'); }}>{S.nav.shop}</a>
            <a href="/about" className={isActive('/about') ? 'is-active' : ''} onClick={(e) => { e.preventDefault(); go('/about'); }}>{S.nav.about}</a>
            <a href="/blog" className={isActive('/blog') ? 'is-active' : ''} onClick={(e) => { e.preventDefault(); go('/blog'); }}>{S.nav.blog}</a>
            <a href="/contact" className={isActive('/contact') ? 'is-active' : ''} onClick={(e) => { e.preventDefault(); go('/contact'); }}>{S.nav.contact}</a>
          </nav>

          <div className="nav__actions">
            <button className="nav__lang" onClick={() => setLang(lang === "ar" ? "en" : "ar")} aria-label="switch language">
              {lang === "ar" ? "EN" : "ع"}
            </button>
            <button className="nav__icon nav__icon--optional" aria-label="sound" onClick={onToggleSound} title={soundOn ? 'Sound on' : 'Sound off'}>
              {soundOn ? <Icon.SoundOn /> : <Icon.SoundOff />}
            </button>
            <button className="nav__icon nav__icon--optional" aria-label={S.nav.search} onClick={onOpenSearch}><Icon.Search /></button>
            <button className="nav__icon nav__icon--optional" aria-label={S.nav.account} onClick={() => go(accountHref)} title={customer ? customer.name : S.account.login}>
              <Icon.User />
            </button>
            <button className="nav__cart" onClick={onOpenCart} aria-label={S.nav.cart}>
              <Icon.Bag />
              {cartCount > 0 && <span className="nav__cart-badge">{cartCount}</span>}
            </button>
          </div>
        </div>
      </header>

      {/* Mobile menu drawer */}
      <div className={`mmenu-overlay ${menuOpen ? 'is-open' : ''}`} onClick={() => setMenuOpen(false)} />
      <aside className={`mmenu ${menuOpen ? 'is-open' : ''}`} aria-hidden={!menuOpen}>
        <div className="mmenu__head">
          <a href="/" className="nav__brand" onClick={(e) => { e.preventDefault(); go('/'); }}>
            <BrandMark size={36} logoUrl={logoUrl} />
            <span className="nav__brand-text">itooth<sup>®</sup></span>
          </a>
          <button className="btn btn--ghost btn--icon" onClick={() => setMenuOpen(false)} aria-label="close">
            <Icon.Close />
          </button>
        </div>
        <nav className="mmenu__links">
          <a href="/shop" onClick={(e) => { e.preventDefault(); go('/shop'); }}>{S.nav.shop}<Icon.Arrow flip={lang === 'ar'} /></a>
          <a href="/about" onClick={(e) => { e.preventDefault(); go('/about'); }}>{S.nav.about}<Icon.Arrow flip={lang === 'ar'} /></a>
          <a href="/blog" onClick={(e) => { e.preventDefault(); go('/blog'); }}>{S.nav.blog}<Icon.Arrow flip={lang === 'ar'} /></a>
          <a href="/contact" onClick={(e) => { e.preventDefault(); go('/contact'); }}>{S.nav.contact}<Icon.Arrow flip={lang === 'ar'} /></a>
          <a href={accountHref} onClick={(e) => { e.preventDefault(); go(accountHref); }}>
            {customer ? `${S.account.title} — ${customer.name}` : S.account.login}
            <Icon.Arrow flip={lang === 'ar'} />
          </a>
        </nav>
        <div className="mmenu__actions">
          <button className="btn btn--ghost btn--md btn--block" onClick={() => { setMenuOpen(false); onOpenSearch(); }}>
            <Icon.Search />
            {lang === 'ar' ? 'بحث' : 'Search'}
          </button>
          <button className="btn btn--ghost btn--md btn--block" onClick={() => { setMenuOpen(false); onToggleSound(); }}>
            {soundOn ? <Icon.SoundOn /> : <Icon.SoundOff />}
            {lang === 'ar' ? (soundOn ? 'إيقاف الصوت' : 'تشغيل الصوت') : (soundOn ? 'Mute sound' : 'Unmute')}
          </button>
          <button className="btn btn--ghost btn--md btn--block" onClick={() => { setMenuOpen(false); setLang(lang === 'ar' ? 'en' : 'ar'); }}>
            {lang === 'ar' ? 'English' : 'العربية'}
          </button>
        </div>
      </aside>
    </>
  );
}

// ============ Hero ============
function Hero({ lang, settings, onShop }) {
  const eyebrow = tr(settings, 'hero_eyebrow', lang);
  const title1 = tr(settings, 'hero_title1', lang);
  const title2 = tr(settings, 'hero_title2', lang);
  const stat1 = tr(settings, 'hero_stat1', lang);
  const stat2 = tr(settings, 'hero_stat2', lang);
  const stat3 = tr(settings, 'hero_stat3', lang);
  const S = window.ITOOTH_STRINGS[lang].hero;
  return (
    <section className="hero hero--medical" id="home">
      <div className="hero__inner">
        <div className="hero__copy">
          <div className="hero__eyebrow">
            <span className="hero__eyebrow-dot" />
            {eyebrow}
          </div>
          <h1 className="hero__title">
            <span className="hero__title-line">{title1}</span>
            <span className="hero__title-line hero__title-line--accent">{title2}</span>
          </h1>
          <div className="hero__stats">
            <div className="hero__stat"><Icon.Shield /><span>{stat1}</span></div>
            <div className="hero__stat"><Icon.Sparkle /><span>{stat2}</span></div>
            <div className="hero__stat"><Icon.Leaf /><span>{stat3}</span></div>
          </div>
          <div className="hero__ctas">
            <button className="btn btn--primary btn--lg" onClick={onShop}>
              {S.cta1}
              <Icon.Arrow flip={lang === "ar"} />
            </button>
            <a className="btn btn--ghost btn--lg" href="#shop">{S.cta2}</a>
          </div>
        </div>
        <div className="hero__visual"><HeroVisual lang={lang} /></div>
      </div>
      <div className="hero__marquee">
        <div className="hero__marquee-track">
          {Array.from({ length: 3 }).map((_, i) => (
            <div className="hero__marquee-group" key={i}>
              <span>• {lang === "ar" ? "صنع في العراق" : "Made in Iraq"}</span>
              <span>• {lang === "ar" ? "خالي من البارابين" : "Paraben-free"}</span>
              <span>• {lang === "ar" ? "مختبر إكلينيكياً" : "Clinically tested"}</span>
              <span>• {lang === "ar" ? "فلورايد طبي" : "Medical-grade fluoride"}</span>
              <span>• {lang === "ar" ? "تركيبة طبيعية" : "Natural formula"}</span>
              <span>• {lang === "ar" ? "نباتي 100%" : "100% vegan"}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function HeroVisual({ lang }) {
  return (
    <div className="hero-visual">
      <div className="hero-visual__bg">
        <svg viewBox="0 0 400 500" className="hero-visual__tooth" aria-hidden="true">
          <defs>
            <linearGradient id="toothGrad" x1="0" y1="0" x2="1" y2="1">
              <stop offset="0%" stopColor="var(--brand-soft)" />
              <stop offset="100%" stopColor="var(--brand)" />
            </linearGradient>
          </defs>
          <path
            d="M200 40c-50 0-80 10-115 10-25 0-40 25-40 70 0 40 15 70 25 110 12 40 18 70 25 110 8 40 25 55 40 55 20 0 25-25 30-60 6-30 10-50 35-50s30 20 35 50c5 35 10 60 30 60 15 0 32-15 40-55 7-40 13-70 25-110 10-40 25-70 25-110 0-45-15-70-40-70-35 0-65-10-115-10z"
            fill="url(#toothGrad)"
          />
        </svg>
        <div className="hero-visual__dots">
          {Array.from({ length: 24 }).map((_, i) => (<span key={i} style={{ ["--i"]: i }} />))}
        </div>
      </div>
      <div className="hero-visual__card hero-visual__card--1">
        <img src={(window.ITOOTH_BASE || '') + "/assets/mouthwash.jpg"} alt="mouthwash" />
      </div>
      <div className="hero-visual__card hero-visual__card--2">
        <div className="hero-visual__card-icon"><Icon.Check /></div>
        <div>
          <div className="hero-visual__card-k">98%</div>
          <div className="hero-visual__card-v">{lang === "ar" ? "رضا المرضى" : "Patient satisfaction"}</div>
        </div>
      </div>
      <div className="hero-visual__card hero-visual__card--3">
        <div className="hero-visual__card-stars">★★★★★</div>
        <div className="hero-visual__card-v">{lang === "ar" ? "2,400+ تقييم" : "2,400+ reviews"}</div>
      </div>
    </div>
  );
}

// ============ Product card ============
function ProductCard({ product, lang, onAdd, onOpen }) {
  const S = window.ITOOTH_STRINGS[lang].product;
  const variants = product.variants || [];
  const [variant, setVariant] = useState(variants[0] || null);
  const [added, setAdded] = useState(false);
  const cardRef = useRef(null);

  useEffect(() => { setVariant(variants[0] || null); }, [product.id]);

  const handleAdd = (e) => {
    e?.stopPropagation();
    const vname = variant ? tr(variant, 'name', lang) : '';
    onAdd({
      id: product.id,
      slug: product.slug,
      name: tr(product, 'name', lang),
      image: product.image || product.images?.[0]?.url,
      illus_key: product.illus_key,
      name_ar: product.name_ar,
      name_en: product.name_en,
      price: product.price,
      variant: vname,
    }, cardRef.current);
    setAdded(true);
    setTimeout(() => setAdded(false), 1400);
  };

  const name = tr(product, 'name', lang);
  const desc = tr(product, 'desc', lang);
  const badge = tr(product, 'badge', lang);
  const primaryImage = product.image || product.images?.[0]?.url;

  return (
    <article className="pcard" ref={cardRef} onClick={() => onOpen(product)}>
      <div className="pcard__media">
        {primaryImage
          ? <img src={asset(primaryImage)} alt={name} className="pcard__photo" />
          : <ProductIllustration product={product} />}
        {badge && (
          <span className={`pcard__badge pcard__badge--${product.slug === 'whitening-kit' ? 'dark' : 'brand'}`}>{badge}</span>
        )}
        <button className="pcard__quickview" onClick={(e) => { e.stopPropagation(); onOpen(product); }} aria-label="quick view">
          <Icon.Search />
        </button>
        <button className="pcard__quickadd" onClick={handleAdd} aria-label="add">
          {added ? <Icon.Check /> : <Icon.Plus />}
        </button>
      </div>

      <div className="pcard__body">
        <div className="pcard__rating">
          <Stars value={product.rating || 4.8} />
          <span>({product.review_count || 0})</span>
        </div>
        <h3 className="pcard__name">{name}</h3>
        <p className="pcard__desc">{desc}</p>

        {variants.length > 1 && (
          <div className="pcard__variants" onClick={(e) => e.stopPropagation()}>
            {variants.slice(0, 4).map((v) => (
              <button
                key={v.id || tr(v, 'name', lang)}
                className={`vchip ${variant && variant.id === v.id ? "is-active" : ""}`}
                onClick={(e) => { e.stopPropagation(); setVariant(v); }}
              >{tr(v, 'name', lang)}</button>
            ))}
          </div>
        )}

        <div className="pcard__foot">
          <div className="pcard__price">
            <span className="pcard__price-now">{fmt(product.price, lang)} {S.iqd}</span>
            {product.old_price && <span className="pcard__price-old">{fmt(product.old_price, lang)}</span>}
          </div>
          <button className={`btn btn--primary btn--sm ${added ? "btn--ok" : ""}`} onClick={handleAdd}>
            {added ? S.added : S.addToCart}
          </button>
        </div>
      </div>
    </article>
  );
}

// ============ Shop ============
function Shop({ lang, products, categories, onAdd, onOpen, initialCat, hideHead }) {
  const S = window.ITOOTH_STRINGS[lang];
  const [activeCat, setActiveCat] = useState(initialCat || "all");
  const [sort, setSort] = useState("default");
  const gridRef = useRef(null);
  const allCats = [{ id: 'all', slug: 'all', name_ar: 'كل المنتجات', name_en: 'All products' }, ...categories];
  useEffect(() => { if (initialCat) setActiveCat(initialCat); }, [initialCat]);

  const filtered = useMemo(() => {
    let list = activeCat === "all" ? products : products.filter((p) => p.category_slug === activeCat);
    if (sort === 'price-asc') list = [...list].sort((a, b) => a.price - b.price);
    else if (sort === 'price-desc') list = [...list].sort((a, b) => b.price - a.price);
    else if (sort === 'rating') list = [...list].sort((a, b) => (b.rating || 0) - (a.rating || 0));
    else if (sort === 'newest') list = [...list].sort((a, b) => (b.id - a.id));
    return list;
  }, [products, activeCat, sort]);

  useEffect(() => {
    const g = gridRef.current;
    if (!g) return;
    g.classList.remove('is-ready');
    const id = requestAnimationFrame(() => {
      requestAnimationFrame(() => g.classList.add('is-ready'));
    });
    return () => cancelAnimationFrame(id);
  }, [filtered]);

  return (
    <section className="shop" id="shop">
      {!hideHead && (
      <div className="section-head">
        <div>
          <div className="eyebrow">{S.sections.shop}</div>
          <h2 className="section-title">{S.sections.shopTitle}</h2>
          <p className="section-sub">{S.sections.shopSub}</p>
        </div>
      </div>
      )}
      <div className="shop__filters">
        <div className="shop__cats" role="tablist">
          {allCats.map((c) => (
            <button
              key={c.slug}
              className={`cat-pill ${activeCat === c.slug ? "is-active" : ""}`}
              onClick={() => setActiveCat(c.slug)}
            >{tr(c, 'name', lang)}</button>
          ))}
        </div>
        <div className="sort">
          <label>{lang === 'ar' ? 'ترتيب:' : 'Sort:'}</label>
          <select value={sort} onChange={(e) => setSort(e.target.value)}>
            <option value="default">{lang === 'ar' ? 'افتراضي' : 'Default'}</option>
            <option value="price-asc">{lang === 'ar' ? 'السعر: الأقل' : 'Price: Low to High'}</option>
            <option value="price-desc">{lang === 'ar' ? 'السعر: الأعلى' : 'Price: High to Low'}</option>
            <option value="rating">{lang === 'ar' ? 'الأعلى تقييماً' : 'Top Rated'}</option>
            <option value="newest">{lang === 'ar' ? 'الأحدث' : 'Newest'}</option>
          </select>
        </div>
      </div>

      <div className="product-grid" ref={gridRef}>
        {filtered.map((p) => (
          <ProductCard key={p.id} product={p} lang={lang} onAdd={onAdd} onOpen={onOpen} />
        ))}
      </div>
    </section>
  );
}

// ============ Product slider ============
function ProductSlider({ slider, lang, onAdd, onOpen, dark }) {
  const trackRef = useRef(null);
  const title = tr(slider, 'title', lang);
  const subtitle = tr(slider, 'subtitle', lang);

  const scrollBy = (dir) => {
    const t = trackRef.current;
    if (!t) return;
    const card = t.querySelector('.pcard');
    const step = card ? card.offsetWidth + 24 : 280;
    t.scrollBy({ left: dir * step * (lang === 'ar' ? -1 : 1), behavior: 'smooth' });
  };

  return (
    <section className={`pslider ${dark ? "pslider--dark" : ""}`}>
      <div className={dark ? "container" : ""}>
        <div className="section-head">
          <div>
            <div className="eyebrow">{lang === 'ar' ? '⚡ مختار' : '⚡ Featured'}</div>
            <h2 className="section-title">{title}</h2>
            {subtitle && <p className="section-sub">{subtitle}</p>}
          </div>
          <div className="pslider__arrows">
            <button className="pslider__arrow" onClick={() => scrollBy(-1)} aria-label="prev"><Icon.ArrowLeft /></button>
            <button className="pslider__arrow" onClick={() => scrollBy(1)} aria-label="next"><Icon.ArrowRight /></button>
          </div>
        </div>
        <div className="pslider__track-wrap">
          <div className="pslider__track" ref={trackRef}>
            {slider.products.map((p) => (
              <ProductCard key={p.id} product={p} lang={lang} onAdd={onAdd} onOpen={onOpen} />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ============ Product Detail Modal ============
function ProductDetail({ lang, product, open, onClose, onAdd }) {
  const [active, setActive] = useState(0);
  const [variant, setVariant] = useState(null);
  const [qty, setQty] = useState(1);
  const [tab, setTab] = useState('features');
  const [full, setFull] = useState(null);
  const sourceRef = useRef(null);

  useEffect(() => {
    setActive(0); setQty(1); setTab('features');
    if (open && product) {
      setFull(product); // instant show
      window.ITOOTH_API.get('/api/products/id/' + product.id)
        .then(setFull).catch(() => {});
    }
  }, [product?.id, open]);

  useEffect(() => {
    if (full?.variants?.length) setVariant(full.variants[0]);
  }, [full?.variants?.length]);

  useEffect(() => {
    if (open) {
      // Prevent body scroll while keeping the modal scrollable on mobile.
      // overflow:hidden on body alone fails on iOS Safari — we also lock position with the current scroll preserved.
      const y = window.scrollY;
      document.body.dataset.lockY = String(y);
      document.body.style.overflow = 'hidden';
    } else {
      const y = parseInt(document.body.dataset.lockY || '0', 10);
      document.body.style.overflow = '';
      delete document.body.dataset.lockY;
      if (y) window.scrollTo(0, y);
    }
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  if (!product) return null;
  const p = full || product;
  const P = window.ITOOTH_STRINGS[lang].product;
  const CH = window.ITOOTH_STRINGS[lang];

  const images = [
    ...(p.image ? [p.image] : []),
    ...((p.images || []).map((i) => i.url)),
  ].filter((v, i, arr) => arr.indexOf(v) === i);
  const activeImg = images[active] || null;

  const name = tr(p, 'name', lang);
  const desc = tr(p, 'desc', lang);
  const longDesc = tr(p, 'long_desc', lang) || desc;
  const features = (tr(p, 'features', lang) || '').split('|').map((s) => s.trim()).filter(Boolean);
  const usage = tr(p, 'usage', lang);
  const ingredients = tr(p, 'ingredients', lang);
  const badge = tr(p, 'badge', lang);
  const catName = lang === 'ar' ? (p.category_name_ar || '') : (p.category_name_en || '');

  const handleAdd = (close = false) => {
    const vname = variant ? tr(variant, 'name', lang) : '';
    const src = document.querySelector('.pd__main') || sourceRef.current;
    for (let i = 0; i < qty; i++) {
      setTimeout(() => {
        onAdd({
          id: p.id,
          slug: p.slug,
          name,
          image: p.image || p.images?.[0]?.url,
          illus_key: p.illus_key,
          name_ar: p.name_ar, name_en: p.name_en,
          price: p.price,
          variant: vname,
        }, i === 0 ? src : null);
      }, i * 150);
    }
    if (close) setTimeout(() => onClose(), 900);
  };

  const submitReview = async (payload) => {
    try {
      await window.ITOOTH_API.post(`/api/products/${p.id}/reviews`, payload);
      window.ITOOTH_FX.toast(lang === 'ar' ? 'شكراً! تم نشر تقييمك' : 'Thanks! Review posted');
      const fresh = await window.ITOOTH_API.get('/api/products/id/' + p.id);
      setFull(fresh);
    } catch (e) { window.ITOOTH_FX.toast(e.message || 'Error', '✗', true); }
  };

  return (
    <div className={`pd-overlay ${open ? 'is-open' : ''}`} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="pd" ref={sourceRef}>
        <button className="pd__close" onClick={onClose} aria-label="close"><Icon.Close /></button>

        <div className="pd__gallery">
          {badge && <span className="pd__badge-top">{badge}</span>}
          <div className="pd__main">
            {activeImg
              ? <img src={asset(activeImg)} alt={name} />
              : <ProductIllustration product={p} />}
          </div>
          {images.length > 1 && (
            <div className="pd__thumbs">
              {images.map((img, i) => (
                <button key={i} className={`pd__thumb ${i === active ? 'is-active' : ''}`} onClick={() => setActive(i)}>
                  <img src={asset(img)} alt="" />
                </button>
              ))}
            </div>
          )}
        </div>

        <div className="pd__info">
          {catName && <span className="pd__cat">{catName}</span>}
          <h2 className="pd__name">{name}</h2>
          <div className="pd__rating">
            <Stars value={p.rating || 4.8} size={15} />
            <span>({p.review_count || 0} {lang === 'ar' ? 'تقييم' : 'reviews'})</span>
            {p.sku && <span className="pd__rating-sku">SKU: {p.sku}</span>}
          </div>

          <div className="pd__prices">
            <span className="pd__price-now">{fmt(p.price, lang)} {P.iqd}</span>
            {p.old_price && (
              <>
                <span className="pd__price-old">{fmt(p.old_price, lang)}</span>
                <span className="pd__save">−{Math.round((1 - p.price / p.old_price) * 100)}%</span>
              </>
            )}
          </div>

          <p className="pd__desc">{longDesc}</p>

          {p.variants?.length > 0 && (
            <div className="pd__block">
              <h4>{P.variant}</h4>
              <div className="pd__variants">
                {p.variants.map((v) => (
                  <button key={v.id}
                    className={`pd__variant ${variant?.id === v.id ? 'is-active' : ''}`}
                    onClick={() => setVariant(v)}>
                    {tr(v, 'name', lang)}
                  </button>
                ))}
              </div>
            </div>
          )}

          <div className="pd__block">
            <h4>{lang === 'ar' ? 'الكمية' : 'Quantity'}</h4>
            <div className="pd__qty">
              <div className="qtyctrl">
                <button onClick={() => setQty((q) => Math.max(1, q - 1))}><Icon.Minus /></button>
                <span>{qty}</span>
                <button onClick={() => setQty((q) => q + 1)}><Icon.Plus /></button>
              </div>
              <span className="pd__stock"><span className="pd__stock-dot" />{lang === 'ar' ? 'متوفر في المخزون' : 'In stock'}</span>
            </div>
          </div>

          <div className="pd__actions">
            <button className="btn btn--primary btn--lg" onClick={() => handleAdd(false)}>
              <Icon.Bag />{P.addToCart}
            </button>
            <button className="btn btn--ghost btn--lg" onClick={() => handleAdd(true)}>
              {P.buyNow}
              <Icon.Arrow flip={lang === 'ar'} />
            </button>
          </div>

          <div className="pd__tabs">
            {features.length > 0 && <button className={`pd__tab ${tab === 'features' ? 'is-active' : ''}`} onClick={() => setTab('features')}>{lang === 'ar' ? 'المميزات' : 'Features'}</button>}
            {usage && <button className={`pd__tab ${tab === 'usage' ? 'is-active' : ''}`} onClick={() => setTab('usage')}>{lang === 'ar' ? 'طريقة الاستخدام' : 'How to use'}</button>}
            {ingredients && <button className={`pd__tab ${tab === 'ingredients' ? 'is-active' : ''}`} onClick={() => setTab('ingredients')}>{lang === 'ar' ? 'المكونات' : 'Ingredients'}</button>}
            <button className={`pd__tab ${tab === 'reviews' ? 'is-active' : ''}`} onClick={() => setTab('reviews')}>{lang === 'ar' ? 'التقييمات' : 'Reviews'} ({p.review_count || 0})</button>
          </div>

          {tab === 'features' && (
            features.length ? (
              <ul className="pd__features">{features.map((f, i) => <li key={i}>{f}</li>)}</ul>
            ) : <div className="pd__tab-content">{longDesc}</div>
          )}
          {tab === 'usage' && <div className="pd__tab-content">{usage}</div>}
          {tab === 'ingredients' && <div className="pd__tab-content">{ingredients}</div>}
          {tab === 'reviews' && (
            <div>
              {(p.reviews || []).length === 0 && <div className="pd__tab-content muted">{lang === 'ar' ? 'لا توجد تقييمات بعد. كن أول من يقيّم!' : 'No reviews yet. Be the first!'}</div>}
              <ul className="pd__reviews">
                {(p.reviews || []).map((r) => (
                  <li className="pd__review" key={r.id}>
                    <div className="pd__review-head">
                      <b>{r.reviewer_name}</b>
                      <span className="pd__review-stars">{'★'.repeat(r.rating)}{'☆'.repeat(5 - r.rating)}</span>
                    </div>
                    <div className="pd__review-body">{tr(r, 'comment', lang) || r.comment_ar || r.comment_en}</div>
                  </li>
                ))}
              </ul>
              <ReviewForm lang={lang} onSubmit={submitReview} />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function ReviewForm({ lang, onSubmit }) {
  const [name, setName] = useState('');
  const [rating, setRating] = useState(5);
  const [comment, setComment] = useState('');
  const submit = async (e) => {
    e.preventDefault();
    if (!name.trim() || !comment.trim()) return;
    await onSubmit({ reviewer_name: name, rating, [lang === 'ar' ? 'comment_ar' : 'comment_en']: comment });
    setName(''); setRating(5); setComment('');
  };
  return (
    <form className="pd__review-form" onSubmit={submit}>
      <h4 style={{ margin: '0 0 12px', fontSize: 14, fontWeight: 600 }}>{lang === 'ar' ? 'أضف تقييمك' : 'Add your review'}</h4>
      <input placeholder={lang === 'ar' ? 'اسمك' : 'Your name'} value={name} onChange={(e) => setName(e.target.value)} />
      <div className="pd__star-pick">
        {[1, 2, 3, 4, 5].map((n) => (
          <span key={n} className={rating >= n ? 'is-on' : ''} onClick={() => setRating(n)}>★</span>
        ))}
      </div>
      <textarea rows="3" placeholder={lang === 'ar' ? 'اكتب رأيك...' : 'Write your review...'} value={comment} onChange={(e) => setComment(e.target.value)} />
      <button className="btn btn--primary btn--sm" type="submit">{lang === 'ar' ? 'نشر التقييم' : 'Post review'}</button>
    </form>
  );
}

// ============ About ============
function About({ lang, settings, founders }) {
  const S = window.ITOOTH_STRINGS[lang].sections;
  const title = tr(settings, 'about_title', lang) || (lang === 'ar' ? 'قصتنا' : 'Our story');
  const body = tr(settings, 'about_body', lang) || (lang === 'ar'
    ? 'itooth علامة عناية بالفم عراقية، طُوّرت بإشراف أطباء أسنان لتقدّم منتجات بجودة طبية وأسعار يصلها الجميع.'
    : 'itooth is an Iraqi oral-care brand, developed by dentists to deliver clinical-grade products at accessible prices.');
  const hasFounders = (founders || []).length > 0;
  return (
    <section className={`about ${hasFounders ? '' : 'about--solo'}`} id="about">
      <div className="about__grid">
        {hasFounders && (
          <div className="about__media">
            <div className="about__photo-stack">
              {founders.slice(0, 3).map((f, i) => (
                <div className={`about__photo about__photo--${i} ${f.image ? 'about__photo--has-image' : ''}`} key={f.id}>
                  {f.image ? (
                    <>
                      <img src={asset(f.image)} alt={tr(f, 'name', lang)} className="about__photo-img" />
                      <div className="about__photo-name">{tr(f, 'name', lang)}</div>
                    </>
                  ) : (
                    <>
                      <div className="about__photo-initials">{f.initials}</div>
                      <div className="about__photo-badge">DDS</div>
                    </>
                  )}
                </div>
              ))}
              <div className="about__photo-bg" />
            </div>
          </div>
        )}
        <div className="about__copy">
          <div className="eyebrow">{S.aboutEyebrow}</div>
          <h2 className="section-title">{title}</h2>
          <p className="about__body">{body}</p>
          {hasFounders && (
            <ul className="about__founders">
              {founders.map((f) => (
                <li key={f.id}>
                  <strong>{tr(f, 'name', lang)}</strong>
                  <span>{tr(f, 'role', lang)}</span>
                </li>
              ))}
            </ul>
          )}
          <div className="about__metrics">
            <div><b>6+</b><span>{lang === "ar" ? "سنوات ممارسة" : "Years practice"}</span></div>
            <div><b>12k+</b><span>{lang === "ar" ? "مريض عالجوه" : "Patients treated"}</span></div>
            <div><b>9</b><span>{lang === "ar" ? "منتجات" : "Products"}</span></div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Routine({ lang, steps }) {
  const S = window.ITOOTH_STRINGS[lang];
  return (
    <section className="routine">
      <div className="eyebrow eyebrow--center">{S.sections.dailyRoutine}</div>
      <h2 className="section-title section-title--center">{S.sections.routineTitle}</h2>
      <div className="routine__timeline">
        {steps.map((s, i) => (
          <div className="routine__step" key={s.id}>
            <div className="routine__num">{s.step_num}</div>
            <div className="routine__body">
              <h4>{tr(s, 'title', lang)}</h4>
              <p>{tr(s, 'desc', lang)}</p>
            </div>
            {i < steps.length - 1 && <div className="routine__line" aria-hidden="true" />}
          </div>
        ))}
      </div>
    </section>
  );
}

function Bundle({ lang, products, onAdd }) {
  const S = window.ITOOTH_STRINGS[lang].sections;
  const bundleSlugs = ["brush-soft", "paste-mint", "tongue-scraper", "mouthwash"];
  const items = bundleSlugs.map((slug) => products.find((p) => p.slug === slug)).filter(Boolean);
  if (items.length < 2) return null;
  const total = items.reduce((s, p) => s + (p.price || 0), 0);
  const bundlePrice = Math.round(total * 0.82);
  const cardRef = useRef(null);

  const handleAdd = () => {
    onAdd({
      id: -1, slug: 'starter-bundle',
      name: lang === 'ar' ? 'باقة البداية' : 'Starter Bundle',
      name_ar: 'باقة البداية', name_en: 'Starter Bundle',
      image: null, illus_key: 'bundle',
      price: bundlePrice,
      variant: lang === 'ar' ? 'الطقم الكامل' : 'Full set',
    }, cardRef.current);
  };

  return (
    <section className="bundle">
      <div className="bundle__inner">
        <div className="bundle__copy" ref={cardRef}>
          <div className="eyebrow eyebrow--light">{S.offer}</div>
          <h2 className="bundle__title">{S.bundleTitle}</h2>
          <p className="bundle__sub">{S.bundleDesc}</p>
          <div className="bundle__price">
            <span className="bundle__price-now">{fmt(bundlePrice, lang)} {lang === "ar" ? "د.ع" : "IQD"}</span>
            <span className="bundle__price-old">{fmt(total, lang)}</span>
            <span className="bundle__save">−18%</span>
          </div>
          <button className="btn btn--white btn--lg" onClick={handleAdd}>
            {S.bundleCta}<Icon.Arrow flip={lang === "ar"} />
          </button>
        </div>
        <div className="bundle__items">
          {items.slice(0, 4).map((p, i) => (
            <div className={`bundle__item bundle__item--${i}`} key={p.id}>
              {p.image ? <img src={asset(p.image)} alt="" /> : <ProductIllustration product={p} />}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function PostCover({ idx }) {
  const palettes = [
    { bg: "#E9F6EE", a: "var(--brand)" },
    { bg: "#111", a: "var(--brand)" },
    { bg: "#F2F6F2", a: "var(--brand-deep)" },
  ];
  const p = palettes[idx % palettes.length];
  return (
    <div className="post__cover-svg" style={{ background: p.bg }}>
      <svg viewBox="0 0 200 160" className="post__cover-art">
        {idx % 3 === 0 && (<><circle cx="100" cy="80" r="50" fill={p.a} opacity="0.2" /><path d="M60 80 q40 -30 80 0" stroke={p.a} strokeWidth="3" fill="none" strokeLinecap="round" /><circle cx="100" cy="80" r="12" fill={p.a} /></>)}
        {idx % 3 === 1 && (<><path d="M70 50 q30 -20 60 0 l-5 70 q-25 15 -50 0 Z" fill={p.a} /><rect x="95" y="90" width="10" height="40" rx="2" fill="#fff" /></>)}
        {idx % 3 === 2 && (<><rect x="50" y="60" width="100" height="50" rx="6" fill="#fff" stroke={p.a} strokeWidth="1.5" /><rect x="58" y="68" width="84" height="8" rx="2" fill={p.a} opacity="0.3" /><rect x="58" y="82" width="84" height="8" rx="2" fill={p.a} opacity="0.6" /><rect x="58" y="96" width="84" height="8" rx="2" fill={p.a} /></>)}
      </svg>
    </div>
  );
}

function Footer({ lang, settings, logoUrl, navigate }) {
  const S = window.ITOOTH_STRINGS[lang].footer;
  const tagline = tr(settings, 'footer_tagline', lang);
  const pay = tr(settings, 'payment', lang);
  const city = tr(settings, 'contact_city', lang);
  const phone = settings.contact_phone || '';
  const waLink = phone ? `https://wa.me/${phone.replace(/[^\d]/g, '')}` : '#';
  const links = lang === 'ar'
    ? {
        col1: [ ['فرش الأسنان','/shop/brush'], ['المعاجين','/shop/paste'], ['التبييض','/shop/whitening'], ['الغسول','/shop/rinse'], ['الأدوات','/shop/tools'] ],
        col2: [ ['من نحن','/about'], ['المدونة','/blog'], ['تواصل معنا','/contact'], ['حسابي','/account'] ],
        col3: [ ['واتساب', waLink, true], ['البريد الإلكتروني', 'mailto:' + (settings.contact_email || ''), true], ['الهاتف', 'tel:' + phone, true] ],
      }
    : {
        col1: [ ['Toothbrushes','/shop/brush'], ['Pastes','/shop/paste'], ['Whitening','/shop/whitening'], ['Rinse','/shop/rinse'], ['Tools','/shop/tools'] ],
        col2: [ ['About','/about'], ['Journal','/blog'], ['Contact','/contact'], ['My account','/account'] ],
        col3: [ ['WhatsApp', waLink, true], ['Email', 'mailto:' + (settings.contact_email || ''), true], ['Phone', 'tel:' + phone, true] ],
      };

  const NavLink = ({ to, children, external }) => external
    ? <a href={to} target="_blank" rel="noreferrer">{children}</a>
    : <a href={to} onClick={(e) => { e.preventDefault(); navigate(to); }}>{children}</a>;

  return (
    <footer className="footer">
      <div className="footer__inner">
        <div className="footer__brand">
          <div className="footer__logo">
            <BrandMark size={42} logoUrl={logoUrl} />
            <span>itooth<sup>®</sup></span>
          </div>
          <p>{tagline}</p>
          <div className="footer__pay">{pay}</div>
        </div>
        <div className="footer__col"><h4>{S.col1}</h4><ul>{links.col1.map(([label, to]) => <li key={label}><NavLink to={to}>{label}</NavLink></li>)}</ul></div>
        <div className="footer__col"><h4>{S.col2}</h4><ul>{links.col2.map(([label, to]) => <li key={label}><NavLink to={to}>{label}</NavLink></li>)}</ul></div>
        <div className="footer__col"><h4>{S.col3}</h4><ul>{links.col3.map(([label, to, ext]) => <li key={label}><NavLink to={to} external={ext}>{label}</NavLink></li>)}</ul></div>
      </div>
      <div className="footer__bottom">
        <span>{S.rights}</span>
        <span>{city}</span>
      </div>
      <div className="footer__powered">
        <a href="https://awtartech.co" target="_blank" rel="noreferrer">
          {S.poweredBy} <strong>AWTAR TECH</strong>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M7 17L17 7M17 7H9M17 7v8" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </a>
      </div>
    </footer>
  );
}

// ============ Cart ============
function Cart({ lang, open, onClose, items, setItems, onCheckout }) {
  const S = window.ITOOTH_STRINGS[lang].cart;
  const P = window.ITOOTH_STRINGS[lang].product;
  const subtotal = items.reduce((s, it) => s + it.price * it.qty, 0);

  const updateQty = (idx, delta) => {
    setItems((prev) => {
      const next = [...prev];
      next[idx] = { ...next[idx], qty: Math.max(1, next[idx].qty + delta) };
      return next;
    });
  };
  const remove = (idx) => {
    window.ITOOTH_FX.play('remove');
    setItems((prev) => prev.filter((_, i) => i !== idx));
  };

  return (
    <>
      <div className={`cart-overlay ${open ? "is-open" : ""}`} onClick={onClose} />
      <aside className={`cart ${open ? "is-open" : ""}`} aria-hidden={!open}>
        <div className="cart__head">
          <h3>{S.title} <span className="cart__count">({items.length})</span></h3>
          <button className="cart__close" onClick={onClose}><Icon.Close /></button>
        </div>
        <div className="cart__body">
          {items.length === 0 ? (
            <div className="cart__empty">
              <BrandMark size={64} />
              <p>{S.empty}</p>
              <button className="btn btn--ghost btn--sm" onClick={onClose}>{S.continue}</button>
            </div>
          ) : items.map((it, i) => (
            <div className={`cart-item ${it._isNew ? 'is-new' : ''}`} key={`${it.id}-${it.variant}-${i}`}>
              <div className="cart-item__media">
                {it.image ? <img src={asset(it.image)} alt="" /> : <ProductIllustration product={it} />}
              </div>
              <div className="cart-item__body">
                <h4>{tr(it, 'name', lang) || it.name}</h4>
                {it.variant && <div className="cart-item__variant">{it.variant}</div>}
                <div className="cart-item__foot">
                  <div className="qtyctrl">
                    <button onClick={() => updateQty(i, -1)}><Icon.Minus /></button>
                    <span>{it.qty}</span>
                    <button onClick={() => updateQty(i, 1)}><Icon.Plus /></button>
                  </div>
                  <span className="cart-item__price">{fmt(it.price * it.qty, lang)} {P.iqd}</span>
                </div>
              </div>
              <button className="cart-item__remove" onClick={() => remove(i)} aria-label={S.remove}><Icon.Close /></button>
            </div>
          ))}
        </div>
        {items.length > 0 && (
          <div className="cart__foot">
            <div className="cart__subtotal">
              <span>{S.subtotal}</span>
              <strong>{fmt(subtotal, lang)} {P.iqd}</strong>
            </div>
            <button className="btn btn--primary btn--lg btn--block" onClick={onCheckout}>
              {S.checkout}<Icon.Arrow flip={lang === "ar"} />
            </button>
            <button className="cart__continue" onClick={onClose}>{S.continue}</button>
          </div>
        )}
      </aside>
    </>
  );
}

// ============ Checkout ============
function Checkout({ lang, open, onClose, items, onOrdered, customer, onAccountCreated, navigate }) {
  const S = window.ITOOTH_STRINGS[lang].checkout;
  const P = window.ITOOTH_STRINGS[lang].product;
  const [form, setForm] = useState({ name: '', phone: '', address: '', notes: '', password: '' });
  const [busy, setBusy] = useState(false);
  const [success, setSuccess] = useState(null);

  useEffect(() => {
    if (open) {
      setSuccess(null);
      setForm({
        name: customer?.name || '',
        phone: customer?.phone || '',
        address: [customer?.address, customer?.city].filter(Boolean).join(' — ') || '',
        notes: '',
        password: '',
      });
    }
  }, [open, customer]);

  const total = items.reduce((s, it) => s + it.price * it.qty, 0);
  const isGuest = !customer;

  const submit = async (e) => {
    e.preventDefault();
    if (isGuest && (!form.password || form.password.length < 6)) {
      window.ITOOTH_FX.toast(lang === 'ar' ? 'كلمة المرور قصيرة (6 أحرف على الأقل)' : 'Password too short', '✗', true);
      return;
    }
    setBusy(true);
    try {
      const res = await window.ITOOTH_API.createOrder({
        customer_name: form.name,
        customer_phone: form.phone,
        customer_address: form.address,
        customer_notes: form.notes,
        password: isGuest ? form.password : undefined,
        items: items.map((it) => ({
          product_id: it.id && it.id > 0 ? it.id : null,
          name: tr(it, 'name', lang) || it.name,
          variant: it.variant || '',
          price: it.price,
          qty: it.qty,
        })),
      });
      window.ITOOTH_FX.play('success');
      setSuccess(res);
      onOrdered && onOrdered(res);
      if (res.customer && onAccountCreated) onAccountCreated(res.customer);
    } catch (err) { window.ITOOTH_FX.toast(err.message || 'Error', '✗', true); }
    finally { setBusy(false); }
  };

  return (
    <div className={`checkout-overlay ${open ? "is-open" : ""}`} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="checkout">
        {success ? (
          <div className="checkout__success">
            <div className="checkout__success-icon" style={{ width: 72, height: 72 }}>
              <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M5 12.5l4.5 4.5L20 6" strokeLinecap="round" strokeLinejoin="round" /></svg>
            </div>
            <h4>{S.success}</h4>
            <p>{S.successDesc}</p>
            <p style={{ fontSize: 14, color: 'var(--ink-3)' }}>{lang === 'ar' ? 'رقم الطلب' : 'Order #'}: <strong>{success.id}</strong></p>
            {success.customer && success.account_created && (
              <div className="checkout__account-note">
                <strong>{lang === 'ar' ? '✓ تم إنشاء حسابك' : '✓ Account created'}</strong>
                <p>{lang === 'ar' ? 'يمكنك الآن متابعة طلباتك من ' : 'You can now track your orders from '}<a href="/account" onClick={(e) => { e.preventDefault(); onClose(); navigate && navigate('/account'); }}>{lang === 'ar' ? 'صفحة حسابي' : 'My Account'}</a></p>
              </div>
            )}
            <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
              {success.customer && (
                <button className="btn btn--ghost btn--md btn--block" onClick={() => { onClose(); navigate && navigate('/account'); }}>{lang === 'ar' ? 'حسابي' : 'My Account'}</button>
              )}
              <button className="btn btn--primary btn--md btn--block" onClick={onClose}>{lang === 'ar' ? 'متابعة التسوق' : 'Continue shopping'}</button>
            </div>
          </div>
        ) : (
          <form onSubmit={submit}>
            <h3>{S.title}</h3>
            <div className="checkout__field"><label>{S.name}</label><input required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
            <div className="checkout__field"><label>{S.phone}</label><input required type="tel" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="07XX XXX XXXX" /></div>
            <div className="checkout__field"><label>{S.address}</label><input required value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} /></div>
            <div className="checkout__field"><label>{S.notes}</label><textarea rows="2" value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} /></div>
            {isGuest && (
              <div className="checkout__field checkout__field--account">
                <label>{lang === 'ar' ? 'كلمة المرور (لإنشاء حسابك ومتابعة طلبك)' : 'Password (to create your account and track your order)'}</label>
                <input required type="password" minLength="6" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} placeholder={lang === 'ar' ? '6 أحرف على الأقل' : 'min 6 characters'} />
                <small className="checkout__hint">{lang === 'ar' ? 'سننشئ لك حساباً برقم هاتفك ' + (form.phone || '...') + ' لتتمكن من متابعة طلباتك.' : 'We\'ll create an account using your phone number so you can track future orders.'}</small>
              </div>
            )}
            <p style={{ fontSize: 13, color: 'var(--ink-3)', margin: '12px 0' }}>{S.shipInfo}</p>
            <div className="checkout__total"><span>{S.total}</span><strong>{fmt(total, lang)} {P.iqd}</strong></div>
            <div className="checkout__actions">
              <button type="button" className="btn btn--ghost btn--md" onClick={onClose}>{S.cancel}</button>
              <button type="submit" className="btn btn--primary btn--md btn--block" disabled={busy}>{busy ? '...' : S.submit}</button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

// ============ Search overlay ============
function SearchModal({ lang, open, onClose, products, onOpenProduct }) {
  const [q, setQ] = useState('');
  const inputRef = useRef(null);
  useEffect(() => { if (open) { setQ(''); setTimeout(() => inputRef.current?.focus(), 50); } }, [open]);

  const results = useMemo(() => {
    if (!q) return products.slice(0, 6);
    const qq = q.toLowerCase();
    return products.filter((p) => (p.name_ar + ' ' + p.name_en + ' ' + (p.desc_ar || '') + ' ' + (p.desc_en || '')).toLowerCase().includes(qq)).slice(0, 10);
  }, [q, products]);

  const P = window.ITOOTH_STRINGS[lang].product;

  return (
    <>
      <div className={`search-overlay ${open ? 'is-open' : ''}`} onClick={onClose} />
      <div className={`search-box ${open ? 'is-open' : ''}`}>
        <input ref={inputRef} className="search-input" placeholder={lang === 'ar' ? 'ابحث عن منتج...' : 'Search products...'} value={q} onChange={(e) => setQ(e.target.value)} />
        <div className="search-results">
          {results.length === 0 ? (
            <div className="search-empty">{lang === 'ar' ? 'لا نتائج مطابقة' : 'No matches'}</div>
          ) : results.map((p) => (
            <div key={p.id} className="search-result" onClick={() => { onOpenProduct(p); onClose(); }}>
              {p.image ? <img src={asset(p.image)} className="search-result__img" /> : <div className="search-result__img"><ProductIllustration product={p} /></div>}
              <div className="search-result__name">
                {tr(p, 'name', lang)}
                <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{tr(p, 'desc', lang)?.slice(0, 60)}</div>
              </div>
              <div className="search-result__price">{fmt(p.price, lang)} {P.iqd}</div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

// ============ Product Page (full-page replacement for the modal) ============
function ProductPage({ lang, slug, products, onAdd, navigate }) {
  const S = window.ITOOTH_STRINGS[lang];
  const P = S.product;
  const [product, setProduct] = useState(() => products.find((p) => p.slug === slug) || null);
  const [active, setActive] = useState(0);
  const [variant, setVariant] = useState(null);
  const [qty, setQty] = useState(1);
  const [tab, setTab] = useState('features');
  const [related, setRelated] = useState([]);

  useEffect(() => {
    setActive(0); setQty(1); setTab('features');
    window.ITOOTH_API.get('/api/products/' + slug)
      .then(setProduct)
      .catch(() => setProduct(null));
  }, [slug]);

  useEffect(() => {
    if (product?.variants?.length) setVariant(product.variants[0]);
  }, [product?.id]);

  useEffect(() => {
    if (!product || !products?.length) return setRelated([]);
    // prefer same-category matches; fall back to any other products so the
    // "you may also like" section always has something to show
    let r = products.filter((p) => p.id !== product.id && p.category_slug && p.category_slug === product.category_slug);
    if (r.length < 4) {
      const extras = products.filter((p) => p.id !== product.id && !r.find((x) => x.id === p.id));
      r = [...r, ...extras];
    }
    setRelated(r.slice(0, 4));
  }, [product?.id, products]);

  if (!product) {
    return (
      <div className="page-wrap">
        <div className="container" style={{ padding: '120px 20px', textAlign: 'center' }}>
          <h2 style={{ fontFamily: 'var(--font-display-ar)', fontWeight: 700 }}>
            {lang === 'ar' ? 'المنتج غير موجود' : 'Product not found'}
          </h2>
          <button className="btn btn--primary btn--lg" style={{ marginTop: 18 }} onClick={() => navigate('/shop')}>
            {S.sections.shopTitle}
          </button>
        </div>
      </div>
    );
  }

  const p = product;
  const images = [
    ...(p.image ? [p.image] : []),
    ...((p.images || []).map((i) => i.url)),
  ].filter((v, i, arr) => arr.indexOf(v) === i);
  const activeImg = images[active] || null;

  const name = tr(p, 'name', lang);
  const desc = tr(p, 'desc', lang);
  const longDesc = tr(p, 'long_desc', lang) || desc;
  const features = (tr(p, 'features', lang) || '').split('|').map((s) => s.trim()).filter(Boolean);
  const usage = tr(p, 'usage', lang);
  const ingredients = tr(p, 'ingredients', lang);
  const badge = tr(p, 'badge', lang);
  const catName = lang === 'ar' ? (p.category_name_ar || '') : (p.category_name_en || '');

  const handleAdd = (close = false) => {
    const vname = variant ? tr(variant, 'name', lang) : '';
    const src = document.querySelector('.pp__main');
    for (let i = 0; i < qty; i++) {
      setTimeout(() => {
        onAdd({
          id: p.id, slug: p.slug, name,
          image: p.image || p.images?.[0]?.url, illus_key: p.illus_key,
          name_ar: p.name_ar, name_en: p.name_en, price: p.price,
          variant: vname,
        }, i === 0 ? src : null);
      }, i * 150);
    }
  };

  const submitReview = async (payload) => {
    try {
      await window.ITOOTH_API.post(`/api/products/${p.id}/reviews`, payload);
      window.ITOOTH_FX.toast(lang === 'ar' ? 'شكراً! تم نشر تقييمك' : 'Thanks!');
      const fresh = await window.ITOOTH_API.get('/api/products/' + slug);
      setProduct(fresh);
    } catch (e) { window.ITOOTH_FX.toast(e.message || 'Error', '✗', true); }
  };

  return (
    <div className="page-wrap pp">
      <div className="container">
        <nav className="pp__crumbs" aria-label="breadcrumb">
          <a href="/" onClick={(e) => { e.preventDefault(); navigate('/'); }}>{lang === 'ar' ? 'الرئيسية' : 'Home'}</a>
          <span className="pp__crumbs-sep">/</span>
          <a href="/shop" onClick={(e) => { e.preventDefault(); navigate('/shop'); }}>{S.sections.shop}</a>
          <span className="pp__crumbs-sep">/</span>
          <span className="pp__crumbs-current">{name}</span>
        </nav>

        <div className="pp__grid">
          <div className="pp__gallery">
            <div className="pp__main">
              {badge && <span className="pp__badge">{badge}</span>}
              {activeImg
                ? <img src={asset(activeImg)} alt={name} />
                : <ProductIllustration product={p} />}
            </div>
            {images.length > 1 && (
              <div className="pp__thumbs">
                {images.map((img, i) => (
                  <button key={i} className={`pp__thumb ${i === active ? 'is-active' : ''}`} onClick={() => setActive(i)}>
                    <img src={asset(img)} alt="" />
                  </button>
                ))}
              </div>
            )}
          </div>

          <div className="pp__info">
            {catName && <span className="pp__cat">{catName}</span>}
            <h1 className="pp__name">{name}</h1>
            <div className="pp__rating">
              <Stars value={p.rating || 4.8} size={16} />
              <span>{p.rating?.toFixed(1) || '4.8'}</span>
              <span className="pp__rating-sep">·</span>
              <a href="#tab-reviews" onClick={(e) => { e.preventDefault(); setTab('reviews'); document.getElementById('pp-tabs')?.scrollIntoView({ behavior: 'smooth' }); }}>
                {p.review_count || 0} {lang === 'ar' ? 'تقييم' : 'reviews'}
              </a>
              {p.sku && <span className="pp__sku">SKU: {p.sku}</span>}
            </div>

            <div className="pp__price-row">
              <div className="pp__price">{fmt(p.price, lang)} <span>{P.iqd}</span></div>
              {p.old_price && (
                <>
                  <div className="pp__price-old">{fmt(p.old_price, lang)} {P.iqd}</div>
                  <div className="pp__save">−{Math.round((1 - p.price / p.old_price) * 100)}%</div>
                </>
              )}
            </div>

            <p className="pp__desc">{longDesc}</p>

            {p.variants?.length > 0 && (
              <div className="pp__field">
                <div className="pp__field-label">{P.variant} {variant ? <span className="pp__field-value">— {tr(variant, 'name', lang)}</span> : null}</div>
                <div className="pp__variants">
                  {p.variants.map((v) => (
                    <button key={v.id}
                      className={`pp__variant ${variant?.id === v.id ? 'is-active' : ''}`}
                      onClick={() => setVariant(v)}>
                      {tr(v, 'name', lang)}
                    </button>
                  ))}
                </div>
              </div>
            )}

            <div className="pp__field">
              <div className="pp__field-label">{lang === 'ar' ? 'الكمية' : 'Quantity'}</div>
              <div className="pp__qty-row">
                <div className="pp__qty">
                  <button onClick={() => setQty((q) => Math.max(1, q - 1))} aria-label="dec"><Icon.Minus /></button>
                  <span>{qty}</span>
                  <button onClick={() => setQty((q) => q + 1)} aria-label="inc"><Icon.Plus /></button>
                </div>
                <span className="pp__stock">
                  <span className="pp__stock-dot" />
                  {lang === 'ar' ? 'متوفر في المخزون' : 'In stock'}
                </span>
              </div>
            </div>

            <div className="pp__actions">
              <button className="btn btn--primary pp__btn" onClick={() => handleAdd(false)}>
                <Icon.Bag />
                {P.addToCart}
              </button>
              <button className="btn btn--outline pp__btn pp__btn--ghost" onClick={() => { handleAdd(false); setTimeout(() => navigate('/account'), 400); }}>
                {P.buyNow}
                <Icon.Arrow flip={lang === 'ar'} />
              </button>
            </div>

            <ul className="pp__perks">
              <li><span className="pp__perk-icon">🚚</span><span>{lang === 'ar' ? 'توصيل خلال 1–3 أيام' : 'Delivery in 1–3 days'}</span></li>
              <li><span className="pp__perk-icon">💰</span><span>{lang === 'ar' ? 'الدفع عند الاستلام' : 'Cash on delivery'}</span></li>
              <li><span className="pp__perk-icon">🦷</span><span>{lang === 'ar' ? 'مطوّر بإشراف أطباء أسنان' : 'Dentist-developed'}</span></li>
            </ul>
          </div>
        </div>

        <div className="pp__tabs-wrap" id="pp-tabs">
          <div className="pp__tabs">
            {features.length > 0 && <button className={`pp__tab ${tab === 'features' ? 'is-active' : ''}`} onClick={() => setTab('features')}>{lang === 'ar' ? 'المميزات' : 'Features'}</button>}
            {usage && <button className={`pp__tab ${tab === 'usage' ? 'is-active' : ''}`} onClick={() => setTab('usage')}>{lang === 'ar' ? 'طريقة الاستخدام' : 'How to use'}</button>}
            {ingredients && <button className={`pp__tab ${tab === 'ingredients' ? 'is-active' : ''}`} onClick={() => setTab('ingredients')}>{lang === 'ar' ? 'المكونات' : 'Ingredients'}</button>}
            <button className={`pp__tab ${tab === 'reviews' ? 'is-active' : ''}`} onClick={() => setTab('reviews')}>{lang === 'ar' ? 'التقييمات' : 'Reviews'} ({p.review_count || 0})</button>
          </div>
          <div className="pp__tab-panel">
            {tab === 'features' && (
              features.length ? (
                <ul className="pp__features">{features.map((f, i) => <li key={i}>{f}</li>)}</ul>
              ) : <p>{longDesc}</p>
            )}
            {tab === 'usage' && <p style={{ whiteSpace: 'pre-wrap' }}>{usage}</p>}
            {tab === 'ingredients' && <p style={{ whiteSpace: 'pre-wrap' }}>{ingredients}</p>}
            {tab === 'reviews' && (
              <div>
                {(p.reviews || []).length === 0 && (
                  <div className="pp__empty">{lang === 'ar' ? 'لا توجد تقييمات بعد. كن أول من يقيّم!' : 'No reviews yet — be the first!'}</div>
                )}
                <ul className="pp__reviews">
                  {(p.reviews || []).map((r) => (
                    <li className="pp__review" key={r.id}>
                      <div className="pp__review-head">
                        <strong>{r.reviewer_name}</strong>
                        <span className="pp__review-stars">{'★'.repeat(r.rating)}{'☆'.repeat(5 - r.rating)}</span>
                      </div>
                      <p>{tr(r, 'comment', lang) || r.comment_ar || r.comment_en}</p>
                    </li>
                  ))}
                </ul>
                <ReviewForm lang={lang} onSubmit={submitReview} />
              </div>
            )}
          </div>
        </div>

        {related.length > 0 && (
          <section className="pp__related">
            <h2 className="section-title" style={{ fontSize: 'clamp(24px, 3vw, 36px)', textAlign: 'center', marginBottom: 28 }}>
              {lang === 'ar' ? 'منتجات قد تعجبك' : 'You may also like'}
            </h2>
            <div className="product-grid">
              {related.map((rp) => (
                <ProductCard key={rp.id} product={rp} lang={lang} onAdd={onAdd} onOpen={(np) => navigate('/product/' + np.slug)} />
              ))}
            </div>
          </section>
        )}
      </div>
    </div>
  );
}

// ============ App root ============
// ============ Router ============
const stripBase = (p) => {
  const b = window.ITOOTH_BASE || '';
  if (b && p.startsWith(b)) return p.slice(b.length) || '/';
  return p;
};
const withBase = (p) => (window.ITOOTH_BASE || '') + (p.startsWith('/') ? p : '/' + p);

function useRouter() {
  const [route, setRoute] = useState(() => stripBase(window.location.pathname) || '/');
  const scrollTop = () => {
    // instant scroll — smooth scroll loses the race against React rerender,
    // leaving the new page appearing to start at the previous page's offset (often the footer)
    window.scrollTo(0, 0);
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
  };
  const navigate = useCallback((to, replace = false) => {
    const target = withBase(to);
    if (replace) window.history.replaceState({}, '', target);
    else window.history.pushState({}, '', target);
    setRoute(to);
    scrollTop();
  }, []);
  useEffect(() => {
    const onPop = () => { setRoute(stripBase(window.location.pathname) || '/'); scrollTop(); };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);
  // Re-assert scroll on every route change (covers async content loads pushing layout)
  useEffect(() => { scrollTop(); }, [route]);
  return { route, navigate };
}

// ============ Page: Home ============
function HomePage({ lang, settings, sliders, products, categories, founders, routineSteps, blogPosts, onAdd, onOpenProduct, onOpenShop, navigate }) {
  return (
    <>
      <Hero lang={lang} settings={settings} onShop={onOpenShop} />
      {sliders.length > 0 && sliders.slice(0, 2).map((slider, i) => (
        <ProductSlider key={slider.id} slider={slider} lang={lang} onAdd={onAdd} onOpen={onOpenProduct} dark={i % 2 === 1} />
      ))}
      {products.length > 0 && (
        <Shop lang={lang} products={products} categories={categories} onAdd={onAdd} onOpen={onOpenProduct} initialCat="all" />
      )}
      {products.length > 3 && <Bundle lang={lang} products={products} onAdd={onAdd} />}
      <AboutPreview lang={lang} settings={settings} founders={founders} navigate={navigate} />
      {routineSteps.length > 0 && <Routine lang={lang} steps={routineSteps} />}
      {blogPosts.length > 0 && <BlogPreview lang={lang} posts={blogPosts.slice(0, 3)} navigate={navigate} />}
    </>
  );
}

function AboutPreview({ lang, settings, founders, navigate }) {
  const S = window.ITOOTH_STRINGS[lang];
  return (
    <>
      <About lang={lang} settings={settings} founders={founders} />
      <div style={{ textAlign: 'center', padding: '0 20px 60px' }}>
        <button className="btn btn--ghost btn--lg" onClick={() => navigate('/about')}>
          {lang === 'ar' ? 'اقرأ المزيد عن قصتنا' : 'Read more about us'}
          <Icon.Arrow flip={lang === 'ar'} />
        </button>
      </div>
    </>
  );
}

function BlogPreview({ lang, posts, navigate }) {
  const S = window.ITOOTH_STRINGS[lang];
  return (
    <section className="blog">
      <div className="section-head">
        <div>
          <div className="eyebrow">{S.sections.journal}</div>
          <h2 className="section-title">{S.sections.blogTitle}</h2>
          <p className="section-sub">{S.sections.blogSub}</p>
        </div>
        <a className="btn btn--ghost btn--sm" href="/blog" onClick={(e) => { e.preventDefault(); navigate('/blog'); }}>
          {S.sections.allArticles}<Icon.Arrow flip={lang === "ar"} />
        </a>
      </div>
      <div className="blog__grid">
        {posts.map((post, i) => (
          <article className={`post post--${i}`} key={post.id} onClick={() => navigate('/blog/' + post.slug)}>
            <div className="post__cover">
              {post.image ? <img src={asset(post.image)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <PostCover idx={i} />}
              <span className="post__tag">{tr(post, 'tag', lang)}</span>
            </div>
            <div className="post__body">
              <h3>{tr(post, 'title', lang)}</h3>
              <p>{tr(post, 'excerpt', lang)}</p>
              <div className="post__meta">
                <Icon.Clock />
                <span>{post.read_time} {S.minRead}</span>
              </div>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

// ============ Page: Shop ============
function ShopPage({ lang, products, categories, onAdd, onOpenProduct, catSlug }) {
  const S = window.ITOOTH_STRINGS[lang];
  return (
    <div className="page-wrap">
      <div className="page-head-wrap">
        <div className="container">
          <div className="eyebrow">{S.sections.shop}</div>
          <h1 className="page-title">{S.sections.shopTitle}</h1>
          <p className="page-sub">{S.sections.shopSub}</p>
        </div>
      </div>
      <Shop lang={lang} products={products} categories={categories} onAdd={onAdd} onOpen={onOpenProduct} initialCat={catSlug || 'all'} hideHead />
    </div>
  );
}

// ============ Page: About ============
function AboutPage({ lang, settings, founders }) {
  const S = window.ITOOTH_STRINGS[lang];
  return (
    <div className="page-wrap">
      <div className="page-head-wrap">
        <div className="container">
          <div className="eyebrow">{S.sections.aboutEyebrow}</div>
          <h1 className="page-title">{tr(settings, 'about_title', lang) || (lang === 'ar' ? 'قصتنا' : 'Our story')}</h1>
        </div>
      </div>
      <About lang={lang} settings={settings} founders={founders} />
    </div>
  );
}

// ============ Page: Blog list ============
function BlogListPage({ lang, posts, navigate }) {
  const S = window.ITOOTH_STRINGS[lang];
  return (
    <div className="page-wrap">
      <div className="page-head-wrap">
        <div className="container">
          <div className="eyebrow">{S.sections.journal}</div>
          <h1 className="page-title">{S.sections.blogTitle}</h1>
          <p className="page-sub">{S.sections.blogSub}</p>
        </div>
      </div>
      <section className="blog blog--list">
        <div className="blog__grid">
          {posts.map((post, i) => (
            <article className={`post post--${i}`} key={post.id} onClick={() => navigate('/blog/' + post.slug)}>
              <div className="post__cover">
                {post.image ? <img src={asset(post.image)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <PostCover idx={i} />}
                <span className="post__tag">{tr(post, 'tag', lang)}</span>
              </div>
              <div className="post__body">
                <h3>{tr(post, 'title', lang)}</h3>
                <p>{tr(post, 'excerpt', lang)}</p>
                <div className="post__meta">
                  <Icon.Clock />
                  <span>{post.read_time} {S.minRead}</span>
                </div>
              </div>
            </article>
          ))}
        </div>
      </section>
    </div>
  );
}

// ============ Page: Blog single ============
function BlogPostPage({ lang, slug, posts, navigate }) {
  const S = window.ITOOTH_STRINGS[lang];
  const post = posts.find((p) => p.slug === slug);
  if (!post) return (
    <div className="page-wrap">
      <div className="container" style={{ padding: '80px 20px', textAlign: 'center' }}>
        <h2>{lang === 'ar' ? 'المقال غير موجود' : 'Article not found'}</h2>
        <button className="btn btn--primary" onClick={() => navigate('/blog')}>{S.sections.allArticles}</button>
      </div>
    </div>
  );
  const title = tr(post, 'title', lang);
  const excerpt = tr(post, 'excerpt', lang);
  const content = tr(post, 'content', lang);
  const tag = tr(post, 'tag', lang);
  const idx = posts.indexOf(post);
  return (
    <article className="blog-post">
      <div className="blog-post__cover">
        {post.image ? <img src={asset(post.image)} alt={title} /> : <PostCover idx={idx} />}
      </div>
      <div className="blog-post__body">
        <div className="blog-post__meta">
          {tag && <span className="blog-post__tag">{tag}</span>}
          <span><Icon.Clock />{post.read_time} {S.minRead}</span>
        </div>
        <h1 className="blog-post__title">{title}</h1>
        {excerpt && <blockquote className="blog-post__excerpt">{excerpt}</blockquote>}
        {content ? (
          <div className="blog-post__content">{content}</div>
        ) : (
          <div className="blog-post__empty">{lang === 'ar' ? 'لم يُضف محتوى للمقال بعد.' : 'No article content yet.'}</div>
        )}
        <div style={{ marginTop: 32 }}>
          <button className="btn btn--ghost" onClick={() => navigate('/blog')}>
            <Icon.Arrow flip={lang !== 'ar'} />
            {S.sections.allArticles}
          </button>
        </div>
      </div>
    </article>
  );
}

// ============ Page: Contact ============
function ContactPage({ lang, settings }) {
  const S = window.ITOOTH_STRINGS[lang].contact;
  const [form, setForm] = useState({ name: '', email: '', phone: '', subject: '', message: '' });
  const [busy, setBusy] = useState(false);
  const [sent, setSent] = useState(false);
  const phone = settings.contact_phone || '';
  const email = settings.contact_email || '';
  const city = tr(settings, 'contact_city', lang);
  const waLink = phone ? `https://wa.me/${phone.replace(/[^\d]/g, '')}` : '#';

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true);
    try {
      await window.ITOOTH_API.post('/api/contact', form);
      setSent(true);
      window.ITOOTH_FX.play('success');
      setForm({ name: '', email: '', phone: '', subject: '', message: '' });
    } catch (err) { window.ITOOTH_FX.toast(err.message || 'Error', '✗', true); }
    finally { setBusy(false); }
  };

  return (
    <div className="page-wrap">
      <div className="page-head-wrap">
        <div className="container">
          <div className="eyebrow">{lang === 'ar' ? 'تواصل' : 'Contact'}</div>
          <h1 className="page-title">{S.title}</h1>
          <p className="page-sub">{S.sub}</p>
        </div>
      </div>
      <div className="contact">
        <div className="contact__grid">
          <div className="contact__info">
            <h3>{lang === 'ar' ? 'معلومات التواصل' : 'Get in touch'}</h3>
            {phone && (
              <a className="contact__item" href={'tel:' + phone}>
                <Icon.User />
                <div><span className="contact__label">{S.phoneLabel}</span>{phone}</div>
              </a>
            )}
            {email && (
              <a className="contact__item" href={'mailto:' + email}>
                <Icon.Check />
                <div><span className="contact__label">{S.emailLabel}</span>{email}</div>
              </a>
            )}
            {city && (
              <div className="contact__item">
                <Icon.Leaf />
                <div><span className="contact__label">{S.address}</span>{city}</div>
              </div>
            )}
            <a className="contact__item contact__item--wa" href={waLink} target="_blank" rel="noreferrer">
              <Icon.Whatsapp />
              <div><span className="contact__label">WhatsApp</span>{lang === 'ar' ? 'تواصل مباشر' : 'Direct chat'}</div>
            </a>
          </div>
          <form className="contact__form" onSubmit={submit}>
            {sent ? (
              <div className="contact__success">
                <div className="contact__success-icon"><Icon.Check /></div>
                <h3>{S.sent}</h3>
                <button type="button" className="btn btn--ghost" onClick={() => setSent(false)}>{lang === 'ar' ? 'إرسال رسالة أخرى' : 'Send another'}</button>
              </div>
            ) : (
              <>
                <div className="field"><label>{S.name}</label><input required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
                <div className="field"><label>{S.email}</label><input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} /></div>
                <div className="field"><label>{S.phone}</label><input type="tel" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} /></div>
                <div className="field"><label>{S.subject}</label><input value={form.subject} onChange={(e) => setForm({ ...form, subject: e.target.value })} /></div>
                <div className="field"><label>{S.message}</label><textarea rows="5" required value={form.message} onChange={(e) => setForm({ ...form, message: e.target.value })} /></div>
                <button className="btn btn--primary btn--lg btn--block" type="submit" disabled={busy}>
                  {busy ? '...' : S.send}
                  <Icon.Arrow flip={lang === 'ar'} />
                </button>
              </>
            )}
          </form>
        </div>
      </div>
    </div>
  );
}

// ============ Page: Customer login ============
function LoginPage({ lang, navigate, onLoggedIn }) {
  const S = window.ITOOTH_STRINGS[lang].account;
  const [form, setForm] = useState({ phone: '', password: '' });
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);
  const submit = async (e) => {
    e.preventDefault();
    setErr(''); setBusy(true);
    try {
      const res = await window.ITOOTH_API.post('/api/customer/login', form);
      onLoggedIn(res.customer || { id: res.id, phone: res.phone, name: res.name });
      navigate('/account');
      window.ITOOTH_FX.play('success');
    } catch (e2) { setErr(e2.message || 'Error'); }
    finally { setBusy(false); }
  };
  return (
    <div className="page-wrap auth-wrap">
      <div className="auth-card">
        <h1 className="auth-title">{S.welcomeBack}</h1>
        <p className="auth-sub">{lang === 'ar' ? 'سجّل دخولك لمتابعة طلباتك' : 'Sign in to track your orders'}</p>
        {err && <div className="auth-err">{err}</div>}
        <form onSubmit={submit}>
          <div className="field"><label>{S.phone}</label><input type="tel" required value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="07XX XXX XXXX" /></div>
          <div className="field"><label>{S.password}</label><input type="password" required value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} /></div>
          <button className="btn btn--primary btn--lg btn--block" disabled={busy} type="submit">{busy ? '...' : S.login}</button>
        </form>
        <p className="auth-foot">
          {S.dontHaveAccount} <a href="/account/signup" onClick={(e) => { e.preventDefault(); navigate('/account/signup'); }}>{S.signup}</a>
        </p>
      </div>
    </div>
  );
}

// ============ Page: Customer signup ============
function SignupPage({ lang, navigate, onLoggedIn }) {
  const S = window.ITOOTH_STRINGS[lang].account;
  const [form, setForm] = useState({ name: '', phone: '', password: '', password2: '' });
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);
  const submit = async (e) => {
    e.preventDefault();
    setErr('');
    if (form.password !== form.password2) return setErr(S.passwordMismatch);
    if (form.password.length < 6) return setErr(S.passwordShort);
    setBusy(true);
    try {
      const res = await window.ITOOTH_API.post('/api/customer/register', {
        phone: form.phone, password: form.password, name: form.name,
      });
      onLoggedIn(res.customer || { id: res.id, phone: res.phone, name: res.name });
      navigate('/account');
      window.ITOOTH_FX.play('success');
    } catch (e2) { setErr(e2.message || 'Error'); }
    finally { setBusy(false); }
  };
  return (
    <div className="page-wrap auth-wrap">
      <div className="auth-card">
        <h1 className="auth-title">{S.createTitle}</h1>
        <p className="auth-sub">{S.createSub}</p>
        {err && <div className="auth-err">{err}</div>}
        <form onSubmit={submit}>
          <div className="field"><label>{S.name}</label><input required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
          <div className="field"><label>{S.phone}</label><input type="tel" required value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="07XX XXX XXXX" /></div>
          <div className="field"><label>{S.password}</label><input type="password" required value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} /></div>
          <div className="field"><label>{S.passwordConfirm}</label><input type="password" required value={form.password2} onChange={(e) => setForm({ ...form, password2: e.target.value })} /></div>
          <button className="btn btn--primary btn--lg btn--block" disabled={busy} type="submit">{busy ? '...' : S.signup}</button>
        </form>
        <p className="auth-foot">
          {S.haveAccount} <a href="/account/login" onClick={(e) => { e.preventDefault(); navigate('/account/login'); }}>{S.login}</a>
        </p>
      </div>
    </div>
  );
}

// ============ Page: Customer account ============
function AccountPage({ lang, customer, onLogout, navigate }) {
  const S = window.ITOOTH_STRINGS[lang].account;
  const P = window.ITOOTH_STRINGS[lang].product;
  const [tab, setTab] = useState('profile');
  const [profile, setProfile] = useState(customer);
  const [orders, setOrders] = useState([]);
  const [busy, setBusy] = useState(false);
  const [pwForm, setPwForm] = useState({ current: '', next: '', next2: '' });

  useEffect(() => { setProfile(customer); }, [customer?.id]);
  useEffect(() => {
    window.ITOOTH_API.get('/api/customer/orders').then(setOrders).catch(() => {});
  }, []);

  const saveProfile = async (e) => {
    e.preventDefault();
    setBusy(true);
    try {
      await window.ITOOTH_API.put('/api/customer/me', profile);
      window.ITOOTH_FX.toast(lang === 'ar' ? 'تم الحفظ' : 'Saved');
    } catch (err) { window.ITOOTH_FX.toast(err.message, '✗', true); }
    finally { setBusy(false); }
  };

  const changePw = async (e) => {
    e.preventDefault();
    if (pwForm.next !== pwForm.next2) return window.ITOOTH_FX.toast(S.passwordMismatch, '✗', true);
    if (pwForm.next.length < 6) return window.ITOOTH_FX.toast(S.passwordShort, '✗', true);
    try {
      await window.ITOOTH_API.post('/api/customer/change-password', { current: pwForm.current, next: pwForm.next });
      window.ITOOTH_FX.toast(lang === 'ar' ? 'تم تغيير كلمة المرور' : 'Password changed');
      setPwForm({ current: '', next: '', next2: '' });
    } catch (err) { window.ITOOTH_FX.toast(err.message || 'Error', '✗', true); }
  };

  const logout = async () => {
    await window.ITOOTH_API.post('/api/customer/logout');
    onLogout();
    navigate('/');
    window.ITOOTH_FX.toast(S.loggedOut);
  };

  return (
    <div className="page-wrap">
      <div className="page-head-wrap">
        <div className="container" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 12 }}>
          <div>
            <div className="eyebrow">{S.title}</div>
            <h1 className="page-title" style={{ marginBottom: 0 }}>{lang === 'ar' ? 'أهلاً' : 'Hi'}, {customer.name}</h1>
          </div>
          <button className="btn btn--ghost" onClick={logout}>{S.logout}</button>
        </div>
      </div>
      <div className="account">
        <div className="account__tabs">
          <button className={`account__tab ${tab === 'profile' ? 'is-active' : ''}`} onClick={() => setTab('profile')}>{S.profile}</button>
          <button className={`account__tab ${tab === 'orders' ? 'is-active' : ''}`} onClick={() => setTab('orders')}>{S.orders} ({orders.length})</button>
          <button className={`account__tab ${tab === 'password' ? 'is-active' : ''}`} onClick={() => setTab('password')}>{S.changePassword}</button>
        </div>
        {tab === 'profile' && (
          <form className="account__form" onSubmit={saveProfile}>
            <div className="field"><label>{S.name}</label><input required value={profile.name || ''} onChange={(e) => setProfile({ ...profile, name: e.target.value })} /></div>
            <div className="field"><label>{S.phone}</label><input type="tel" disabled value={profile.phone || ''} /></div>
            <div className="field"><label>{S.city}</label><input value={profile.city || ''} onChange={(e) => setProfile({ ...profile, city: e.target.value })} /></div>
            <div className="field field--full"><label>{S.address}</label><input value={profile.address || ''} onChange={(e) => setProfile({ ...profile, address: e.target.value })} /></div>
            <button className="btn btn--primary" disabled={busy} type="submit">{S.save}</button>
          </form>
        )}
        {tab === 'orders' && (
          orders.length === 0 ? (
            <div className="account__empty">{S.noOrders}</div>
          ) : (
            <div className="account__orders">
              {orders.map((o) => (
                <div className="account__order" key={o.id}>
                  <div className="account__order-head">
                    <strong>#{o.id}</strong>
                    <span className="account__order-date">{new Date(o.created_at).toLocaleDateString(lang === 'ar' ? 'ar-IQ' : 'en-US')}</span>
                    <span className={`badge badge--${o.status === 'done' ? 'ok' : o.status === 'cancelled' ? 'off' : 'warn'}`}>{o.status}</span>
                  </div>
                  <ul className="account__order-items">
                    {(o.items || []).map((it) => (
                      <li key={it.id}><span>{it.product_name}{it.variant ? ' — ' + it.variant : ''}</span><span>{it.qty} × {fmt(it.price, lang)}</span></li>
                    ))}
                  </ul>
                  <div className="account__order-total"><span>{S.orderTotal}</span><strong>{fmt(o.total, lang)} {P.iqd}</strong></div>
                </div>
              ))}
            </div>
          )
        )}
        {tab === 'password' && (
          <form className="account__form" onSubmit={changePw}>
            <div className="field field--full"><label>{S.currentPassword}</label><input type="password" required value={pwForm.current} onChange={(e) => setPwForm({ ...pwForm, current: e.target.value })} /></div>
            <div className="field"><label>{S.newPassword}</label><input type="password" required value={pwForm.next} onChange={(e) => setPwForm({ ...pwForm, next: e.target.value })} /></div>
            <div className="field"><label>{S.passwordConfirm}</label><input type="password" required value={pwForm.next2} onChange={(e) => setPwForm({ ...pwForm, next2: e.target.value })} /></div>
            <button className="btn btn--primary" type="submit">{S.changePassword}</button>
          </form>
        )}
      </div>
    </div>
  );
}

function App() {
  const [lang, setLang] = useState(localStorage.getItem('itooth_lang') || 'ar');
  const [settings, setSettings] = useState({});
  const [categories, setCategories] = useState([]);
  const [products, setProducts] = useState([]);
  const [sliders, setSliders] = useState([]);
  const [blogPosts, setBlogPosts] = useState([]);
  const [founders, setFounders] = useState([]);
  const [announcements, setAnnouncements] = useState([]);
  const [routineSteps, setRoutineSteps] = useState([]);
  const [cart, setCart] = useState([]);
  const [cartOpen, setCartOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [showTop, setShowTop] = useState(false);
  const [soundOn, setSoundOn] = useState(window.ITOOTH_FX?.soundOn ?? true);
  const [searchOpen, setSearchOpen] = useState(false);
  const [pdProduct, setPdProduct] = useState(null);
  const [customer, setCustomer] = useState(null);
  const { route, navigate } = useRouter();

  useEffect(() => {
    (async () => {
      try {
        const [s, c, p, sl, b, f, a, r] = await Promise.all([
          window.ITOOTH_API.getSettings(),
          window.ITOOTH_API.getCategories(),
          window.ITOOTH_API.getProducts(),
          window.ITOOTH_API.getSliders(),
          window.ITOOTH_API.getBlog(),
          window.ITOOTH_API.getFounders(),
          window.ITOOTH_API.getAnnouncements(),
          window.ITOOTH_API.getRoutine(),
        ]);
        setSettings(s); setCategories(c); setProducts(p); setSliders(sl);
        setBlogPosts(b); setFounders(f); setAnnouncements(a); setRoutineSteps(r);
        applyShade(s.green_shade || '#2D8F5F');
      } catch (err) { console.error(err); }
    })();
  }, []);

  useEffect(() => {
    document.documentElement.lang = lang;
    document.documentElement.dir = lang === 'ar' ? 'rtl' : 'ltr';
    document.body.setAttribute('dir', lang === 'ar' ? 'rtl' : 'ltr');
    localStorage.setItem('itooth_lang', lang);
  }, [lang]);

  useEffect(() => {
    const onScroll = () => { setScrolled(window.scrollY > 20); setShowTop(window.scrollY > 500); };
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    const h = (e) => setSoundOn(e.detail);
    document.addEventListener('itooth:sound', h);
    return () => document.removeEventListener('itooth:sound', h);
  }, []);

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') { setPdProduct(null); setSearchOpen(false); }
      if ((e.ctrlKey || e.metaKey) && e.key === 'k') { e.preventDefault(); setSearchOpen(true); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  // Fetch logged-in customer on mount
  useEffect(() => {
    window.ITOOTH_API.get('/api/customer/me').then(setCustomer).catch(() => setCustomer(null));
  }, []);

  const applyShade = (hex) => {
    const shades = {
      "#0F5132": { deep: "#0F5132", base: "#0F5132", soft: "#BAD9C4", pale: "#E8F2EC", ink: "#0A2F1D" },
      "#1B6A44": { deep: "#1B6A44", base: "#1B6A44", soft: "#C7E6D3", pale: "#F1F8F4", ink: "#0E3A26" },
      "#2D8F5F": { deep: "#1B6A44", base: "#2D8F5F", soft: "#C7E6D3", pale: "#F1F8F4", ink: "#0E3A26" },
      "#3AA66D": { deep: "#1F7A4C", base: "#3AA66D", soft: "#CDEBD9", pale: "#F2FAF5", ink: "#113F27" },
      "#4CAF50": { deep: "#2E8B43", base: "#4CAF50", soft: "#D4EBD5", pale: "#F3FAF4", ink: "#153A1A" },
      "#00A86B": { deep: "#006B45", base: "#00A86B", soft: "#B8E6D0", pale: "#EAF7F0", ink: "#003823" },
    };
    const s = shades[hex] || shades["#2D8F5F"];
    const r = document.documentElement.style;
    r.setProperty('--brand', s.base);
    r.setProperty('--brand-deep', s.deep);
    r.setProperty('--brand-soft', s.soft);
    r.setProperty('--brand-pale', s.pale);
    r.setProperty('--brand-ink', s.ink);
  };

  const addToCart = (item, sourceEl) => {
    setCart((prev) => {
      const existing = prev.findIndex(p => p.id === item.id && p.variant === item.variant);
      if (existing >= 0) {
        const next = [...prev];
        next[existing] = { ...next[existing], qty: next[existing].qty + 1, _isNew: true };
        return next;
      }
      return [...prev, { ...item, qty: 1, _isNew: true }];
    });
    setTimeout(() => setCart((prev) => prev.map((p) => ({ ...p, _isNew: false }))), 900);
    if (sourceEl) window.ITOOTH_FX.flyToCart(sourceEl, item.image);
    else window.ITOOTH_FX.play('add');
    window.ITOOTH_FX.toast(window.ITOOTH_STRINGS[lang].addedToast);
    // pulse the floating cart fab so the user notices the count grew
    document.getElementById('cart-fab')?.classList.add('is-pulse');
    setTimeout(() => document.getElementById('cart-fab')?.classList.remove('is-pulse'), 800);
  };

  const cartCount = cart.reduce((s, it) => s + it.qty, 0);
  const handleCheckout = () => { setCartOpen(false); setTimeout(() => setCheckoutOpen(true), 280); };
  const onOrdered = () => { setCart([]); };

  // Route dispatch
  let page;
  const r = route || '/';
  const openProduct = (p) => navigate('/product/' + p.slug);
  if (r === '/' || r === '') {
    page = <HomePage lang={lang} settings={settings} sliders={sliders} products={products}
      categories={categories} founders={founders} routineSteps={routineSteps} blogPosts={blogPosts}
      onAdd={addToCart} onOpenProduct={openProduct} onOpenShop={() => navigate('/shop')} navigate={navigate} />;
  } else if (r.startsWith('/product/')) {
    page = <ProductPage lang={lang} slug={r.slice('/product/'.length)} products={products}
      onAdd={addToCart} navigate={navigate} />;
  } else if (r.startsWith('/shop')) {
    const catSlug = r === '/shop' ? 'all' : r.split('/')[2] || 'all';
    page = <ShopPage lang={lang} products={products} categories={categories}
      onAdd={addToCart} onOpenProduct={openProduct} catSlug={catSlug} />;
  } else if (r === '/about') {
    page = <AboutPage lang={lang} settings={settings} founders={founders} />;
  } else if (r === '/blog') {
    page = <BlogListPage lang={lang} posts={blogPosts} navigate={navigate} />;
  } else if (r.startsWith('/blog/')) {
    page = <BlogPostPage lang={lang} slug={r.slice('/blog/'.length)} posts={blogPosts} navigate={navigate} />;
  } else if (r === '/contact') {
    page = <ContactPage lang={lang} settings={settings} />;
  } else if (r === '/account/login') {
    page = <LoginPage lang={lang} navigate={navigate} onLoggedIn={setCustomer} />;
  } else if (r === '/account/signup') {
    page = <SignupPage lang={lang} navigate={navigate} onLoggedIn={setCustomer} />;
  } else if (r.startsWith('/account')) {
    page = customer
      ? <AccountPage lang={lang} customer={customer} navigate={navigate} onLogout={() => setCustomer(null)} />
      : <LoginPage lang={lang} navigate={navigate} onLoggedIn={setCustomer} />;
  } else {
    page = <HomePage lang={lang} settings={settings} sliders={sliders} products={products}
      categories={categories} founders={founders} routineSteps={routineSteps} blogPosts={blogPosts}
      onAdd={addToCart} onOpenProduct={openProduct} onOpenShop={() => navigate('/shop')} navigate={navigate} />;
  }

  return (
    <>
      <Announcement lang={lang} messages={announcements} />
      <Nav lang={lang} setLang={setLang} cartCount={cartCount}
        onOpenCart={() => setCartOpen(true)} onOpenSearch={() => setSearchOpen(true)}
        scrolled={scrolled} logoUrl={settings.brand_logo}
        route={route} navigate={navigate} customer={customer}
        soundOn={soundOn} onToggleSound={() => window.ITOOTH_FX.toggleSound()} />

      {page}

      <Footer lang={lang} settings={settings} logoUrl={settings.brand_logo} navigate={navigate} />

      <Cart lang={lang} open={cartOpen} onClose={() => setCartOpen(false)}
        items={cart} setItems={setCart} onCheckout={handleCheckout} />
      <Checkout lang={lang} open={checkoutOpen} onClose={() => setCheckoutOpen(false)}
        items={cart} onOrdered={onOrdered} customer={customer}
        onAccountCreated={setCustomer} navigate={navigate} />

      <SearchModal lang={lang} open={searchOpen} onClose={() => setSearchOpen(false)}
        products={products} onOpenProduct={(p) => { setSearchOpen(false); navigate('/product/' + p.slug); }} />

      <button id="cart-fab" className={`cart-fab ${cartCount > 0 ? 'is-show' : ''}`}
        onClick={() => setCartOpen(true)}
        aria-label={lang === 'ar' ? `سلة التسوق — ${cartCount} عنصر` : `Cart — ${cartCount} items`}>
        <Icon.Bag />
        <span className="cart-fab__count">{cartCount}</span>
      </button>

      <button className={`top-fab ${showTop ? 'is-show' : ''}`}
        onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
        aria-label="top">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 15l6-6 6 6" strokeLinecap="round" /></svg>
      </button>
    </>
  );
}

setTimeout(() => {
  ReactDOM.createRoot(document.getElementById('root')).render(<App />);
}, 50);
