/* ── Single-Page Homepage — All Sections ── */

function HomePage({ onProductClick }) {
  return React.createElement('main', { id: 'main', className: 'cc-home' },
    React.createElement(HeroSection),
    React.createElement(ShopSection,  { onProductClick }),
    React.createElement(CustomOrderSection),
    React.createElement(PartnershipSection),
    React.createElement(ContactSection),
    React.createElement(FooterSection),
  );
}

/* ══════════════════════════
   HERO
══════════════════════════ */
/* ── Hero Candle Slideshow ── */
function HeroSlideshow() {
  const FEATURED = PRODUCTS.filter(p => p.featured);
  const COUNT    = FEATURED.length;
  const ITEMS    = [...FEATURED, ...FEATURED]; /* duplicate for seamless loop */

  const CARD_W = 210;
  const GAP    = 20;
  const STEP   = CARD_W + GAP;

  const [idx,      setIdx]      = React.useState(0);
  const [animated, setAnimated] = React.useState(true);

  /* Auto-advance every 2.8 s */
  React.useEffect(() => {
    const id = setInterval(() => setIdx(prev => prev + 1), 2800);
    return () => clearInterval(id);
  }, []);

  /* When we reach the duplicate set, snap back invisibly */
  React.useEffect(() => {
    if (idx === COUNT) {
      const t = setTimeout(() => {
        setAnimated(false);
        setIdx(0);
      }, 750); /* match transition duration */
      return () => clearTimeout(t);
    }
  }, [idx, COUNT]);

  /* Re-enable animation one tick after the snap */
  React.useEffect(() => {
    if (!animated) {
      const t = setTimeout(() => setAnimated(true), 50);
      return () => clearTimeout(t);
    }
  }, [animated]);

  const scrollToProduct = (product) => {
    const el = document.getElementById('product-' + product.id);
    if (el) {
      window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 100, behavior: 'smooth' });
    } else {
      const shop = document.getElementById('shop');
      if (shop) window.scrollTo({ top: shop.getBoundingClientRect().top + window.scrollY - 76, behavior: 'smooth' });
    }
  };

  const dotIdx = ((idx % COUNT) + COUNT) % COUNT;

  return React.createElement('div', { className: 'cc-hero-slideshow' },
    React.createElement('div', {
      className: 'cc-slideshow-track',
      style: {
        transform: 'translateX(-' + (idx * STEP) + 'px)',
        transition: animated ? 'transform 0.75s cubic-bezier(0.16, 1, 0.3, 1)' : 'none',
      },
    },
      ITEMS.map((p, i) =>
        React.createElement('button', {
          key: i,
          className: 'cc-slide-card',
          onClick: () => scrollToProduct(p),
          style: { width: CARD_W + 'px' },
        },
          React.createElement('div', { className: 'cc-slide-img' },
            React.createElement(CandlePlaceholder, { product: p }),
            React.createElement('div', { className: 'cc-slide-overlay' },
              React.createElement('span', null, 'View Details'),
            ),
            p.bestseller && React.createElement('span', { className: 'cc-slide-badge' }, 'Bestseller'),
          ),
          React.createElement('div', { className: 'cc-slide-info' },
            React.createElement('p', { className: 'cc-slide-subtitle' }, p.subtitle),
            React.createElement('h3', { className: 'cc-slide-name' }, p.name),
          ),
        )
      ),
    ),
    /* Progress dots */
    React.createElement('div', { className: 'cc-slideshow-dots' },
      FEATURED.map((_, i) =>
        React.createElement('button', {
          key: i,
          className: 'cc-slideshow-dot' + (i === dotIdx ? ' active' : ''),
          onClick: () => { setAnimated(true); setIdx(i); },
          'aria-label': 'Slide ' + (i + 1),
        })
      ),
    ),
  );
}

function HeroSection() {
  const [visible, setVisible] = React.useState(false);
  const bgRef = React.useRef(null);

  React.useEffect(() => { const t = setTimeout(() => setVisible(true), 80); return () => clearTimeout(t); }, []);

  /* Subtle parallax on hero background */
  React.useEffect(() => {
    const h = () => {
      const y = window.scrollY;
      if (bgRef.current) bgRef.current.style.transform = `translateY(${y * 0.25}px)`;
    };
    window.addEventListener('scroll', h, { passive: true });
    return () => window.removeEventListener('scroll', h);
  }, []);

  const scrollToShop = () => {
    const el = document.getElementById('shop');
    if (!el) return;
    window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 76, behavior: 'smooth' });
  };
  const scrollToCustom = () => {
    const el = document.getElementById('custom');
    if (!el) return;
    window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 76, behavior: 'smooth' });
  };

  return React.createElement('section', { id: 'hero', className: 'cc-hero' },
    React.createElement('div', { ref: bgRef, className: 'cc-hero-bg' }),
    /* Faint watermark stays behind everything */
    React.createElement('div', { className: 'cc-hero-watermark' },
      React.createElement('img', { src: 'assets/logo-mark-dark.png', alt: '', 'aria-hidden': 'true', className: 'cc-hero-watermark-img' }),
    ),
    /* Two-column layout: text left, slideshow right */
    React.createElement('div', { className: 'cc-hero-layout' },
      React.createElement('div', { className: 'cc-hero-content' + (visible ? ' visible' : '') },
        React.createElement('p', { className: 'cc-hero-eyebrow' }, 'Handcrafted · Soy Wax · Made in Canada'),
        React.createElement('h1', { className: 'cc-hero-title' },
          React.createElement('span', null, 'Crafted Warmth'),
          React.createElement('br'),
          React.createElement('em', { className: 'cc-hero-title-accent' }, 'for Modern Spaces'),
        ),
        React.createElement('p', { className: 'cc-hero-sub' },
          'Sculptural candles, artisan soaps & bespoke home pieces — each one poured, shaped and finished by hand.'
        ),
        React.createElement('div', { className: 'cc-hero-actions' },
          React.createElement('button', { className: 'cc-btn cc-btn-primary', onClick: scrollToShop }, 'Explore the Collection'),
          React.createElement('button', { className: 'cc-btn cc-btn-ghost', onClick: scrollToCustom }, 'Custom Orders'),
        ),
      ),
      /* Right column: auto-sliding candle carousel */
      React.createElement('div', { className: 'cc-hero-slideshow-col' + (visible ? ' visible' : '') },
        React.createElement(HeroSlideshow),
      ),
    ),
    React.createElement('button', { className: 'cc-hero-scroll', onClick: scrollToShop, 'aria-label': 'Scroll down' },
      React.createElement('div', { className: 'cc-scroll-line' }),
    ),
  );
}

/* ══════════════════════════
   SHOP SECTION
══════════════════════════ */
function ShopSection({ onProductClick }) {
  const [cat, setCat] = React.useState('all');
  const [sort, setSort] = React.useState('featured');
  const ref = React.useRef(null);
  const tabsRef = React.useRef(null);
  const [pill, setPill] = React.useState({ left: 0, width: 0, ready: false });
  const visible = useInView(ref, 0.05);

  /* Measure active tab for sliding pill */
  React.useEffect(() => {
    if (!tabsRef.current) return;
    const active = tabsRef.current.querySelector('.cc-cat-tab.active');
    if (!active) return;
    const container = tabsRef.current.getBoundingClientRect();
    const btn = active.getBoundingClientRect();
    setPill({ left: btn.left - container.left, width: btn.width, ready: true });
  }, [cat]);

  /* Also measure on mount after layout */
  React.useEffect(() => {
    const t = setTimeout(() => {
      if (!tabsRef.current) return;
      const active = tabsRef.current.querySelector('.cc-cat-tab.active');
      if (!active) return;
      const container = tabsRef.current.getBoundingClientRect();
      const btn = active.getBoundingClientRect();
      setPill({ left: btn.left - container.left, width: btn.width, ready: true });
    }, 120);
    return () => clearTimeout(t);
  }, []);

  let items = cat === 'all' ? PRODUCTS : PRODUCTS.filter(p => p.category === cat);
  if (sort === 'low')  items = [...items].sort((a, b) => (a.salePrice || a.price || Infinity) - (b.salePrice || b.price || Infinity));
  if (sort === 'high') items = [...items].sort((a, b) => (b.salePrice || b.price || 0) - (a.salePrice || a.price || 0));
  if (sort === 'name') items = [...items].sort((a, b) => a.name.localeCompare(b.name));

  return React.createElement('section', { id: 'shop', ref, className: 'cc-shop-section' + (visible ? ' in-view' : '') },
    /* Section header */
    React.createElement('div', { className: 'cc-section-header cc-shop-header' },
      React.createElement('p', { className: 'cc-eyebrow' }, 'The Collection'),
      React.createElement('h2', { className: 'cc-section-title' }, 'Shop'),
      React.createElement('p', { className: 'cc-section-desc' },
        'Each piece is hand-poured in small batches using premium soy wax. Browse our curated collection.'
      ),
    ),

    /* Filter tabs */
    React.createElement('div', { className: 'cc-shop-controls' },
      React.createElement('div', { className: 'cc-category-tabs', ref: tabsRef },
        /* Sliding pill indicator */
        pill.ready && React.createElement('div', {
          className: 'cc-tab-pill',
          style: { left: pill.left, width: pill.width },
        }),
        CATEGORIES.map(c =>
          React.createElement('button', {
            key: c.id,
            className: 'cc-cat-tab' + (cat === c.id ? ' active' : ''),
            onClick: () => setCat(c.id),
          }, c.label)
        ),
      ),
      React.createElement('select', {
        className: 'cc-sort-select', value: sort, onChange: e => setSort(e.target.value),
      },
        React.createElement('option', { value: 'featured' }, 'Featured'),
        React.createElement('option', { value: 'low'  }, 'Price: Low → High'),
        React.createElement('option', { value: 'high' }, 'Price: High → Low'),
        React.createElement('option', { value: 'name' }, 'Name A–Z'),
      ),
    ),

    /* Product grid */
    React.createElement('div', { className: 'cc-shop-grid' },
      items.map(p =>
        React.createElement(ShopCard, { key: p.id, product: p, onClick: () => !p.comingSoon && onProductClick(p) })
      ),
      items.length === 0 && React.createElement('p', { className: 'cc-no-results' }, 'No products in this category yet.'),
    ),
  );
}

function ShopCard({ product, onClick }) {
  const ref = React.useRef(null);
  const visible = useInView(ref, 0.08);
  const isSoon = product.comingSoon;
  return React.createElement('article', {
    ref,
    id: 'product-' + product.id,
    className: 'cc-shop-card' + (visible ? ' in-view' : '') + (isSoon ? ' cc-coming-soon-card' : ''),
    onClick: isSoon ? undefined : onClick,
    tabIndex: isSoon ? -1 : 0,
    role: isSoon ? undefined : 'button',
    onKeyDown: isSoon ? undefined : (e => e.key === 'Enter' && onClick()),
  },
    React.createElement('div', { className: 'cc-shop-card-img' },
      React.createElement(CandlePlaceholder, { product }),
      !isSoon && React.createElement('div', { className: 'cc-shop-card-overlay' },
        React.createElement('span', null, 'View Details'),
      ),
      product.bestseller && React.createElement('span', { className: 'cc-badge' }, 'Bestseller'),
      isSoon && React.createElement('span', { className: 'cc-badge cc-badge-soon' }, 'Coming Soon'),
    ),
    React.createElement('div', { className: 'cc-shop-card-info' },
      React.createElement('p', { className: 'cc-product-subtitle' }, product.subtitle),
      React.createElement('h3', { className: 'cc-product-name' }, product.name),
      isSoon
        ? React.createElement('p', { className: 'cc-product-coming-soon' }, 'Coming Soon')
        : React.createElement('div', { className: 'cc-product-pricing' },
            product.salePrice && React.createElement('span', { className: 'cc-price-sale' }, '$' + product.salePrice.toFixed(2)),
            React.createElement('span', { className: product.salePrice ? 'cc-price-original' : 'cc-price' }, '$' + product.price.toFixed(2)),
          ),
      !isSoon && product.colors && product.colors.length > 0 && React.createElement('div', { className: 'cc-color-dots' },
        product.colors.slice(0, 5).map(c =>
          React.createElement('span', { key: c, className: 'cc-color-dot', style: { background: COLOR_SWATCHES[c] || '#ccc' }, title: c })
        ),
      ),
    ),
  );
}

/* ══════════════════════════
   OUR STORY
══════════════════════════ */
function StorySection() {
  const ref = React.useRef(null);
  const visible = useInView(ref, 0.15);
  return React.createElement('section', {
    id: 'story', ref, className: 'cc-section cc-story' + (visible ? ' in-view' : ''),
  },
    React.createElement('div', { className: 'cc-story-inner' },
      React.createElement('div', { className: 'cc-story-img' },
        React.createElement(StudioPlaceholder),
      ),
      React.createElement('div', { className: 'cc-story-text' },
        React.createElement('p', { className: 'cc-eyebrow' }, 'Our Philosophy'),
        React.createElement('h2', { className: 'cc-section-title' }, 'Made Slowly,\nWith Intention'),
        React.createElement('p', { className: 'cc-body-text' },
          'Every piece begins as raw soy wax and becomes something worth keeping. We shape, pour, and finish each creation by hand — no shortcuts, no mass production. Just honest craft for people who notice the difference.'
        ),
        React.createElement('div', { className: 'cc-story-pillars' },
          [
            { label: 'Natural Materials', desc: 'Pure soy wax, essential oils, no synthetics' },
            { label: 'Small Batch',       desc: 'Never more than a few dozen pieces at a time' },
            { label: 'Made in Canada',    desc: 'Every piece poured in our studio' },
          ].map((p, i) =>
            React.createElement('div', { key: i, className: 'cc-story-pillar' },
              React.createElement('span', { className: 'cc-pillar-line' }),
              React.createElement('h5', null, p.label),
              React.createElement('p', null, p.desc),
            )
          ),
        ),
      ),
    ),
  );
}

/* ══════════════════════════
   CONTACT
══════════════════════════ */
function ContactSection() {
  const ref = React.useRef(null);
  const visible = useInView(ref, 0.15);
  const [news, setNews] = React.useState('');
  const [newsDone, setNewsDone] = React.useState(false);
  const [newsFocus, setNewsFocus] = React.useState(false);
  const [newsSending, setNewsSending] = React.useState(false);
  const [newsError, setNewsError] = React.useState('');

  const handleSubscribe = async (e) => {
    e.preventDefault();
    if (!news || newsSending) return;
    setNewsSending(true);
    setNewsError('');
    try {
      const fd = new FormData();
      fd.append('_subject', 'Newsletter Signup — Inner Circle');
      fd.append('_form_type', 'newsletter');
      fd.append('email', news);
      const res = await fetch('https://formspree.io/f/xjgdvwyd', { method: 'POST', body: fd, headers: { 'Accept': 'application/json' } });
      if (!res.ok) throw new Error('Server returned ' + res.status);
      setNewsDone(true);
    } catch (err) {
      setNewsError('Something went wrong — please try again.');
    } finally {
      setNewsSending(false);
    }
  };

  return React.createElement('section', {
    id: 'contact', ref, className: 'cc-section cc-contact' + (visible ? ' in-view' : ''),
  },
    React.createElement('div', { className: 'cc-contact-centered' },
      React.createElement('p', { className: 'cc-eyebrow' }, 'Stay Connected'),
      React.createElement('h2', { className: 'cc-section-title' }, 'Join the Inner Circle'),
      React.createElement('p', { className: 'cc-body-text', style: { maxWidth: '420px' } },
        'New releases and studio updates, delivered quietly to your inbox.'
      ),
      !newsDone
        ? React.createElement(React.Fragment, null,
            React.createElement('form', {
              className: 'cc-newsletter-form cc-contact-news-form' + (newsFocus ? ' focused' : ''),
              onSubmit: handleSubscribe,
            },
              React.createElement('input', {
                type: 'email', placeholder: 'your@email.com', value: news,
                onChange: e => setNews(e.target.value),
                onFocus: () => setNewsFocus(true), onBlur: () => setNewsFocus(false),
                required: true, className: 'cc-newsletter-input', 'aria-label': 'Email address',
              }),
              React.createElement('button', {
                type: 'submit', className: 'cc-btn cc-btn-primary cc-newsletter-btn',
                disabled: newsSending,
              }, newsSending ? 'Sending\u2026' : 'Subscribe'),
            ),
            newsError && React.createElement('p', { style: { color: '#e25', fontSize: '0.82rem', marginTop: '0.4rem' } }, newsError),
          )
        : React.createElement('div', { className: 'cc-newsletter-thanks' },
            React.createElement('svg', { width: 24, height: 24, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', style: { color: 'var(--cc-accent)' } },
              React.createElement('polyline', { points: '20,6 9,17 4,12' }),
            ),
            React.createElement('p', null, 'Welcome to the circle.'),
          ),
    ),
  );
}

/* ══════════════════════════
   FOOTER
══════════════════════════ */
function FooterSection() {
  const scrollTo = (id) => {
    const el = document.getElementById(id);
    if (!el) return;
    window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 76, behavior: 'smooth' });
  };

  const NAV = [
    {
      heading: 'Shop',
      links: [
        { label: 'All Products',  action: () => scrollTo('shop') },
        { label: 'Candles',       action: () => scrollTo('shop') },
        { label: 'Soaps',         action: () => scrollTo('shop') },
        { label: 'Jesmonite',     action: () => scrollTo('shop') },
        { label: 'Molds',         action: () => scrollTo('shop') },
      ],
    },
    {
      heading: 'Studio',
      links: [
        { label: 'Custom Orders',  action: () => scrollTo('custom') },
        { label: 'Partnerships',  action: () => scrollTo('partner') },
        { label: 'Process',       action: null },
        { label: 'Sustainability', action: null },
      ],
    },
    {
      heading: 'Help',
      links: [
        { label: 'Contact',  action: () => scrollTo('contact') },
        { label: 'Shipping', action: null },
        { label: 'Returns',  action: null },
        { label: 'FAQ',      action: null },
      ],
    },
  ];

  return React.createElement('footer', { className: 'cc-footer' },
    /* Accent cap line */
    React.createElement('div', { className: 'cc-footer-cap' }),

    /* Main columns */
    React.createElement('div', { className: 'cc-footer-inner' },

      /* Brand column */
      React.createElement('div', { className: 'cc-footer-brand' },
        React.createElement('img', {
          src: 'assets/logo-horizontal-footer.png',
          alt: 'Candescent Cinders Studio', loading: 'lazy',
          className: 'cc-footer-logo-img',
        }),
        React.createElement('p', { className: 'cc-footer-tagline' },
          'Crafted warmth for modern spaces.'
        ),
        /* Social row */
        React.createElement('div', { className: 'cc-footer-social-col' },
          React.createElement('a', {
            href: 'https://candescentcinders.etsy.com', target: '_blank', rel: 'noreferrer',
            className: 'cc-footer-social-link',
          }, 'Etsy'),
          React.createElement('span', { className: 'cc-footer-social-sep', 'aria-hidden': 'true' }, '·'),
          React.createElement('a', { href: '#', className: 'cc-footer-social-link' }, 'Instagram'),
          React.createElement('span', { className: 'cc-footer-social-sep', 'aria-hidden': 'true' }, '·'),
          React.createElement('a', { href: '#', className: 'cc-footer-social-link' }, 'Pinterest'),
        ),
      ),

      /* Nav columns */
      NAV.map(col =>
        React.createElement('div', { key: col.heading, className: 'cc-footer-col' },
          React.createElement('p', { className: 'cc-footer-heading' }, col.heading),
          React.createElement('nav', { className: 'cc-footer-nav' },
            col.links.map(link =>
              React.createElement('button', {
                key: link.label,
                className: 'cc-footer-link',
                onClick: link.action || undefined,
                disabled: !link.action,
              }, link.label)
            ),
          ),
        )
      ),
    ),

    /* Bottom bar */
    React.createElement('div', { className: 'cc-footer-bottom' },
      React.createElement('p', { className: 'cc-footer-copy' },
        '© 2026 Candescent Cinders Studio. All rights reserved.'
      ),
      React.createElement('p', { className: 'cc-footer-made' },
        'Handcrafted in Canada.'
      ),
    ),
  );
}

/* ── Intersection Observer Hook ── */
function useInView(ref, threshold) {
  const [vis, setVis] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(
      ([e]) => { if (e.isIntersecting) { setVis(true); obs.disconnect(); } },
      { threshold: threshold || 0.1 }
    );
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return vis;
}

window.HomePage = HomePage;
window.FooterSection = FooterSection;
window.useInView = useInView;
