// pages/home.jsx — landing page

function MobileShopHeader() {
  const store = useStore();
  return (
    <header className="mobile-shop-header">
      <button type="button" className="icon-btn" onClick={() => store.openDrawer('menu')} aria-label="Open menu">
        <Icon name="menu" size={22} />
      </button>
      <button type="button" className="mobile-shop-header__search" onClick={() => store.openDrawer('search')}>
        <Icon name="search" size={18} />
        Search pebbles, pots…
      </button>
    </header>
  );
}

function CategoryChips() {
  const chips = [
    ['Coloured', 'coloured-pebbles'],
    ['White', 'white-pebbles'],
    ['Black', 'black-pebbles'],
    ['Glass', 'glass-pebbles'],
    ['Buddha', 'buddha'],
    ['Planters', 'pots-planters'],
  ];
  return (
    <nav className="category-chips" aria-label="Quick categories">
      {chips.map(([label, slug]) => (
        <a key={slug} href={'#/collections/' + slug}>{label}</a>
      ))}
    </nav>
  );
}

function MobileProductGrid() {
  const products = HAP.productsInCategory('pebbles').slice(0, 8);
  const store = useStore();
  return (
    <section className="section-sm" style={{ paddingTop: 0 }}>
      <div className="container">
        <div style={{ background: 'var(--forest)', color: 'var(--paper)', borderRadius: 'var(--r-xl)', padding: '18px 20px', marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div className="eyebrow" style={{ color: 'var(--sage)' }}>New collection</div>
            <div className="serif" style={{ fontSize: '1.2rem', marginTop: 4 }}>Coloured pebbles</div>
          </div>
          <a href="#/collections/coloured-pebbles" className="btn btn--ghost btn--sm" style={{ color: 'var(--paper)', borderColor: 'rgba(255,255,255,0.25)', border: '1px solid' }}>Shop</a>
        </div>
        <div className="product-grid--mobile-2">
          {products.map((p) => (
            <MobileProductCard key={p.id} p={p} store={store} />
          ))}
        </div>
      </div>
    </section>
  );
}

function MobileProductCard({ p, store }) {
  const C = window.CustomerCommerce;
  const purchasable = C ? C.isPurchasable(p, 1) : p.stock > 0;
  const price = C ? C.unitPrice(p.price, (p.variants && p.variants[0]) || '1 kg') : p.price;
  return (
    <article className="pc pc--mobile" style={{ borderRadius: 'var(--r-xl)', overflow: 'hidden', background: 'var(--shell)', boxShadow: 'var(--shadow-1)' }}>
      <a href={'#/products/' + p.slug} style={{ display: 'block' }}>
        <div style={{ aspectRatio: '1', background: 'var(--cream)', position: 'relative' }}>
          <img src={p.image} alt={p.name} loading="lazy" decoding="async" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          {purchasable && (
            <button
              type="button"
              aria-label={'Add ' + p.name + ' to cart'}
              onClick={(e) => { e.preventDefault(); store.addToCart(p.id, p.variants[0] || '1 kg', 1); }}
              style={{
                position: 'absolute', bottom: 10, right: 10, width: 36, height: 36, borderRadius: 999,
                background: 'var(--forest)', color: 'var(--paper)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                boxShadow: 'var(--shadow-2)'
              }}
            >
              <Icon name="plus" size={18} />
            </button>
          )}
        </div>
        <div style={{ padding: '12px 14px' }}>
          <h3 className="serif" style={{ fontSize: '0.95rem', lineHeight: 1.25 }}>{p.name}</h3>
          <div style={{ fontSize: '0.88rem', color: 'var(--forest)', fontWeight: 600, marginTop: 6 }}>{HAP.formatPrice(price)}</div>
        </div>
      </a>
    </article>
  );
}

function Hero() {
  return (
    <section className="hero-section">
      <div className="container">
        <div className="hero-grid">
          <div className="hero-copy">
            <span className="eyebrow reveal reveal--1" style={{ marginBottom: 16, display: 'inline-block' }}>
              <span className="hero-dot"></span>
              Decorative pebbles · Path stones · Garden decor
            </span>
            <h1 className="serif reveal reveal--2" style={{ fontSize: 'var(--fs-hero)', lineHeight: 0.98, letterSpacing: '-0.025em', marginBottom: 20 }}>
              Colour up<br/>
              your garden,<br/>
              <em style={{ color: 'var(--terra)' }}>stone by stone.</em>
            </h1>
            <p className="reveal reveal--3" style={{ fontSize: '1.05rem', maxWidth: 460, color: 'var(--ink-2)', marginBottom: 28 }}>
              Premium pebbles, path stones, planters and garden decor from Mannuthy, Thrissur.
              Delivered across India — free shipping on orders above ₹999.
            </p>
            <div className="reveal reveal--4" style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 36 }}>
              <a className="btn btn--primary btn--lg" href="#/collections/pebbles">Shop pebbles <Icon name="arrow-right" size={16}/></a>
              <a className="btn btn--secondary btn--lg" href="#/services/bulk-supply">Order in bulk</a>
            </div>
            <div className="reveal reveal--5" style={{ display: 'flex', gap: 28, flexWrap: 'wrap' }}>
              <HeroStat n="12+" l="pebble colours" />
              <HeroStat n="All-India" l="delivery" />
              <HeroStat n="Wholesale" l="& retail" l2="trade welcome" />
            </div>
          </div>

          <div className="hero-collage reveal reveal--6">
            <div className="hero-collage__grid">
              <div className="hero-collage__cell hero-collage__cell--tall">
                <img className="cover-img" src="images/pot-white-matte.jpg" alt="White matte pot styled with decorative pebbles" decoding="async" />
                <div className="hero-collage__caption">
                  <div className="eyebrow" style={{ color: 'var(--sage)' }}>Featured</div>
                  <div className="serif" style={{ fontSize: '1.2rem', marginTop: 4 }}>Pebbles for pot styling</div>
                  <div style={{ fontSize: '.85rem', color: 'rgba(255,255,255,0.7)' }}>Top your pots with colour. Shipped pan-India.</div>
                </div>
              </div>
              <div className="hero-collage__cell">
                <img className="cover-img" src="images/pebble-white-polished.jpg" alt="White polished pebbles" decoding="async" />
              </div>
              <div className="hero-collage__cell">
                <img className="cover-img" src="images/pebble-multicolour.jpg" alt="Multicolour pebbles" decoding="async" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function HeroStat({ n, l, l2 }) {
  return (
    <div>
      <div className="serif" style={{ fontSize: '2rem', lineHeight: 1, color: 'var(--forest)' }}>{n}</div>
      <div style={{ fontSize: '.78rem', color: 'var(--muted)', marginTop: 4, lineHeight: 1.3 }}>
        {l}{l2 && <><br/>{l2}</>}
      </div>
    </div>
  );
}

function CategoryTiles() {
  const tiles = HAP.PROMO_TILES.slice(0, 6);
  const TILE_IMG = {
    'coloured-pebbles': 'images/pebble-multicolour.jpg',
    'white-pebbles': 'images/pebble-white-polished.jpg',
    'path-stones': 'images/pebble-white-polished.jpg',
    'buddha': 'images/buddha-cream-dhyana.jpg',
    'pots-planters': 'images/planter-white-large.jpg',
    'glass-pebbles': 'images/glass-pebbles.jpg'
  };
  return (
    <section className="section">
      <div className="container">
        <div className="spread" style={{ marginBottom: 28, alignItems: 'flex-end' }}>
          <div>
            <span className="eyebrow">Shop by category</span>
            <h2 className="serif" style={{ fontSize: 'var(--fs-display)', lineHeight: 1.05, marginTop: 6 }}>
              Stones for every corner.
            </h2>
          </div>
          <a href="#/collections" className="btn btn--ghost">All collections <Icon name="arrow-right" size={16}/></a>
        </div>
        <div className="cat-tiles">
          {tiles.map((t, i) => (
            <a key={t.slug} href={t.href} className={'cat-tile' + (i === 0 ? ' cat-tile--lg' : '') + (i === 3 ? ' cat-tile--wide' : '')}>
              <div className="cat-tile__bg">
                <img className="cover-img" src={TILE_IMG[t.slug]} alt={t.title} decoding="async" />
                <div className="cat-tile__shade"></div>
              </div>
              <div className="cat-tile__top">
                <span className="eyebrow" style={{ color: 'rgba(255,255,255,0.9)' }}>{t.subtitle}</span>
                <span className={'serif cat-tile__title' + (i === 0 ? ' cat-tile__title--lg' : '')}>{t.title}</span>
              </div>
              <div className="cat-tile__cta">
                Shop <Icon name="arrow-up-right" size={14} />
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

function FeaturedRow({ title, eyebrow, slug, limit = 8 }) {
  const products = HAP.productsInCategory(slug).slice(0, limit);
  return (
    <section className="section-sm">
      <div className="container">
        <div className="spread" style={{ marginBottom: 24, alignItems: 'flex-end' }}>
          <div>
            <span className="eyebrow">{eyebrow}</span>
            <h2 className="serif" style={{ fontSize: 'clamp(1.6rem, 3vw, 2.4rem)', marginTop: 6 }}>{title}</h2>
          </div>
          <a href={'#/collections/' + slug} className="btn btn--ghost">View all <Icon name="arrow-right" size={14} /></a>
        </div>
        <div className="product-grid product-grid--4">
          {products.map(p => <ProductCard key={p.id} p={p} />)}
        </div>
      </div>
    </section>
  );
}

function ServiceCta() {
  return (
    <section className="section">
      <div className="container">
        <div style={{
          background: 'var(--forest)', color: 'var(--paper)',
          borderRadius: 'var(--r-xl)',
          padding: 'clamp(36px, 6vw, 80px)',
          display: 'grid', gridTemplateColumns: '1.1fr 1fr',
          gap: 'clamp(24px, 4vw, 64px)',
          position: 'relative', overflow: 'hidden'
        }} className="service-cta">
          <div>
            <span className="eyebrow" style={{ color: 'var(--sage)' }}>For trade & projects</span>
            <h2 className="serif" style={{ fontSize: 'clamp(2.4rem, 5vw, 4rem)', lineHeight: 1, marginTop: 8 }}>
              Need pebbles<br/>in bulk?
            </h2>
            <p style={{ color: 'rgba(255,255,255,0.7)', maxWidth: 480, marginTop: 16, fontSize: '1rem' }}>
              We supply builders, resorts, landscapers and nurseries across India by the bag or the truckload — plus on-site pot styling,
              pathway design and garden decor around Thrissur.
            </p>
            <div style={{ display: 'flex', gap: 12, marginTop: 28, flexWrap: 'wrap' }}>
              <a href="#/services/bulk-supply" className="btn btn--terra btn--lg">Wholesale enquiry</a>
              <a href="#/services" className="btn btn--ghost btn--lg" style={{ color: 'var(--paper)', borderColor: 'rgba(255,255,255,0.18)', border: '1px solid' }}>All services</a>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, alignContent: 'center' }}>
            <ServiceTile icon="truck" title="Bulk & wholesale" body="By the bag or truckload" />
            <ServiceTile icon="leaf" title="Pot styling" body="Right pebbles for your pots" />
            <ServiceTile icon="map" title="Pathway design" body="Stepping-stone walkways" />
            <ServiceTile icon="spark" title="Garden decor" body="Statues, planters & more" />
          </div>
        </div>
      </div>
    </section>
  );
}
function ServiceTile({ icon, title, body }) {
  return (
    <div style={{ background: 'rgba(255,255,255,0.08)', borderRadius: 'var(--r-lg)', padding: 20 }}>
      <Icon name={icon} size={22} style={{ color: 'var(--sage)' }} />
      <div className="serif" style={{ fontSize: '1.1rem', marginTop: 8 }}>{title}</div>
      <div style={{ fontSize: '.82rem', color: 'rgba(255,255,255,0.7)', marginTop: 4 }}>{body}</div>
    </div>
  );
}

function WhyAmbady() {
  const items = [
    { i: 'truck',   t: 'Pan-India delivery', b: 'Carefully packed and shipped anywhere in India. Free above ₹999.' },
    { i: 'spark',   t: 'UV-stable colour', b: 'Coated pebbles keep their shine indoors and out.' },
    { i: 'shield',  t: 'Quality checked', b: 'Cleaned, graded and weighed before every despatch.' },
    { i: 'phone',   t: 'Talk to us', b: 'Call or WhatsApp +91 7559 907 176 for help & bulk orders.' }
  ];
  return (
    <section className="section-sm" style={{ background: 'var(--cream)' }}>
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 24 }}>
          {items.map(it => (
            <div key={it.t} style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
              <div style={{ width: 42, height: 42, borderRadius: 999, background: 'var(--paper)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--forest)', flexShrink: 0 }}>
                <Icon name={it.i} size={20} />
              </div>
              <div>
                <div className="serif" style={{ fontSize: '1.1rem' }}>{it.t}</div>
                <div style={{ fontSize: '.85rem', color: 'var(--muted)', marginTop: 4 }}>{it.b}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function SocialGrid() {
  return (
    <section className="section">
      <div className="container">
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <span className="eyebrow">Ambady in the wild</span>
          <h2 className="serif" style={{ fontSize: 'var(--fs-display)', marginTop: 8 }}>Styled with our stones</h2>
          <p style={{ color: 'var(--muted)', marginTop: 8 }}>Tag us — we love re-sharing your pots, paths and corners.</p>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12 }} className="social-grid">
          {['pebble-pink.jpg','glass-pebbles.jpg','buddha-white-bowl.jpg','pebble-blue.jpg','pebble-blackwhite-mix.jpg'].map((img, i) => (
            <a key={i} href="https://www.instagram.com/" target="_blank" rel="noreferrer"
               style={{ aspectRatio: '1', borderRadius: 'var(--r-md)', overflow: 'hidden', background: 'var(--cream)', position: 'relative' }}>
              <img src={'images/' + img} alt={`Ambady styling ${i+1}`} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'flex-end', justifyContent: 'flex-end', padding: 12, opacity: 0.85 }}>
                <div style={{ background: 'rgba(255,255,255,0.92)', borderRadius: 999, width: 32, height: 32, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink)' }}>
                  <Icon name="instagram" size={14} />
                </div>
              </div>
            </a>
          ))}
        </div>
        <div style={{ textAlign: 'center', marginTop: 24 }}>
          <a href="https://www.instagram.com/" target="_blank" rel="noreferrer" className="btn btn--secondary">Follow Ambady Pebbles Garden</a>
        </div>
      </div>
      <style>{`
        @media (max-width: 720px) {
          .social-grid { grid-template-columns: repeat(2, 1fr) !important; }
        }
      `}</style>
    </section>
  );
}

function HomePage() {
  const intelForYou = window.CustomerIntelligence && window.CustomerIntelligence.forYou
    ? window.CustomerIntelligence.forYou({ limit: 8 })
    : null;
  const forYou = intelForYou && intelForYou.products.length
    ? intelForYou
    : (window.CustomerPersonalization
      ? window.CustomerPersonalization.forYou(8)
      : { products: [], label: '', note: '' });
  const intelPopular = window.CustomerIntelligence && window.CustomerIntelligence.popular
    ? window.CustomerIntelligence.popular(8)
    : null;
  const popular = intelPopular && intelPopular.length
    ? { products: intelPopular, label: 'Popular now', source: 'intelligence_engine' }
    : (window.CustomerPersonalization
      ? window.CustomerPersonalization.popularProducts(8)
      : { products: [], label: 'Best sellers', source: 'catalog_fallback' });
  const recent = window.CustomerPersonalization
    ? window.CustomerPersonalization.recentlyViewed(8)
    : [];
  const ship = window.CustomerCommerce ? window.CustomerCommerce.shippingSettings() : { freeAbove: 999 };

  return (
    <>
      <MobileShopHeader />
      <CategoryChips />
      <MobileProductGrid />
      <div className="home-desktop-only">
      <Hero />
      <CategoryTiles />
      {forYou.products.length > 0 && (
        <section className="section-sm">
          <div className="container">
            <div className="spread" style={{ marginBottom: 24, alignItems: 'flex-end' }}>
              <div>
                <span className="eyebrow">For you</span>
                <h2 className="serif" style={{ fontSize: 'clamp(1.6rem, 3vw, 2.4rem)', marginTop: 6 }}>{forYou.label}</h2>
                {forYou.note && <p style={{ color: 'var(--muted)', fontSize: '.85rem', marginTop: 6 }}>{forYou.note}</p>}
              </div>
            </div>
            <div className="product-grid product-grid--4">
              {forYou.products.map((p) => <ProductCard key={p.id} p={p} />)}
            </div>
          </div>
        </section>
      )}
      <FeaturedRow eyebrow={popular.source === 'order_lines' ? 'From real orders' : 'In the garden'} title={popular.label === 'Best sellers' ? 'Coloured pebbles to top your pots.' : popular.label} slug="coloured-pebbles" />
      {popular.source === 'order_lines' && popular.products.length > 0 && (
        <section className="section-sm">
          <div className="container">
            <div className="spread" style={{ marginBottom: 24 }}>
              <div>
                <span className="eyebrow">Best sellers</span>
                <h2 className="serif" style={{ fontSize: 'clamp(1.6rem, 3vw, 2.4rem)', marginTop: 6 }}>Ranked from actual order lines</h2>
              </div>
            </div>
            <div className="product-grid product-grid--4">
              {popular.products.map((p) => <ProductCard key={'pop-' + p.id} p={p} />)}
            </div>
          </div>
        </section>
      )}
      <ServiceCta />
      <FeaturedRow eyebrow="Clean & premium" title="White & natural pebbles." slug="white-pebbles" />
      {recent.length > 0 && (
        <section className="section-sm">
          <div className="container">
            <div className="spread" style={{ marginBottom: 24 }}>
              <div>
                <span className="eyebrow">Continue browsing</span>
                <h2 className="serif" style={{ fontSize: 'clamp(1.6rem, 3vw, 2.4rem)', marginTop: 6 }}>Recently viewed</h2>
              </div>
            </div>
            <div className="product-grid product-grid--4">
              {recent.map((p) => <ProductCard key={'rv-' + p.id} p={p} />)}
            </div>
          </div>
        </section>
      )}
      <WhyAmbady />
      <FeaturedRow eyebrow="Quiet corners" title="Buddha statues & garden decor." slug="decor" />
      <p className="container" style={{ fontSize: '.78rem', color: 'var(--muted)', marginBottom: 24 }}>
        Free shipping above {HAP.formatPrice(ship.freeAbove)} (from store shipping settings).
      </p>
      <SocialGrid />
      </div>
    </>
  );
}

window.HomePage = HomePage;
