/* A&M Kits — App */
const { useState, useEffect, useMemo } = React;

function App() {
  const [toastMsg, setToastMsg] = useState('');

  const [activeDomains, setActiveDomains] = useState(new Set());
  const [ageBucket, setAgeBucket] = useState(null);
  const [openKit, setOpenKit] = useState(null);

  function toggleDomain(id) {
    setActiveDomains(prev => {
      if (id === '__clear__') return new Set();
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  }

  // filter kits
  const filteredKits = useMemo(() => {
    return window.KITS.filter(k => {
      if (activeDomains.size > 0) {
        const inKit = k.products.map(window.productById).filter(Boolean);
        const domains = new Set([k.domain, ...inKit.map(p => p.domain)]);
        const ok = [...activeDomains].some(d => domains.has(d));
        if (!ok) return false;
      }
      if (ageBucket) {
        const [aLo, aHi] = window.parseAgeRange(k.ages);
        const bucket = window.AGE_BUCKETS.find(b => b.id === ageBucket);
        if (!bucket) return true;
        const [bLo, bHi] = bucket.range;
        if (aHi < bLo || aLo > bHi) return false;
      }
      return true;
    });
  }, [activeDomains, ageBucket]);

  // filter products
  const filteredProducts = useMemo(() => {
    return window.PRODUCTS.filter(p => {
      if (activeDomains.size > 0 && !activeDomains.has(p.domain)) return false;
      if (ageBucket) {
        const [aLo, aHi] = window.parseAgeRange(p.ages);
        const bucket = window.AGE_BUCKETS.find(b => b.id === ageBucket);
        if (!bucket) return true;
        const [bLo, bHi] = bucket.range;
        if (aHi < bLo || aLo > bHi) return false;
      }
      return true;
    });
  }, [activeDomains, ageBucket]);

  const { Nav, KitsToast, Hero, HowItWorks, FilterBar, KitDrawer } = window.AMComponents;
  const { ProductGrid, CustomKitBuilder, WhyKits, ByAge, FiveQuestionTest, CTAFooter } = window.AMSections;

  const scrollWithOffset = (id) => {
    const el = document.getElementById(id);
    if (!el) return;
    const top = el.getBoundingClientRect().top + window.scrollY - 68;
    window.scrollTo({ top, behavior:'smooth' });
  };

  // Handle deep-link hashes (#products / #method / #how-it-works / #by-age / #kits / #custom-kit)
  useEffect(() => {
    function handleHash() {
      const h = (window.location.hash || '').replace('#','');
      if (!h) return;
      setTimeout(() => scrollWithOffset(h), 100);
    }
    handleHash();
    window.addEventListener('hashchange', handleHash);
    return () => window.removeEventListener('hashchange', handleHash);
  }, []);

  return (
    <div data-screen-label="Home — A&M World">
      <Nav />
      <KitsToast msg={toastMsg} onDone={()=>setToastMsg('')} />
      <Hero />
      <HowItWorks />

      <section id="kits" data-screen-label="kit-showcase" style={{ background:'#FDFCF8' }}>
        <FilterBar
          activeDomains={activeDomains} toggleDomain={toggleDomain}
          ageBucket={ageBucket} setAgeBucket={setAgeBucket}
          kitCount={filteredKits.length} productCount={filteredProducts.length}
        />

        <div style={{ maxWidth:1240, margin:'0 auto', padding:'56px clamp(20px,4vw,52px) 80px' }}>
          <div style={{ marginBottom:36, display:'flex', justifyContent:'space-between', alignItems:'flex-end', gap:20, flexWrap:'wrap' }}>
            <div>
              <div style={{ fontFamily:'Plus Jakarta Sans', fontSize:12, color:'#7A6F68', textTransform:'uppercase', letterSpacing:'0.12em', fontWeight:600, marginBottom:14 }}>Kit Showcase · 10 curated bundles</div>
              <h2 style={{ fontFamily:'Instrument Serif', fontWeight:400, fontSize:'clamp(40px,5vw,68px)', letterSpacing:'-0.025em', lineHeight:0.98, color:'#1A1614' }}>
                Pick the <em style={{ fontStyle:'italic', color:'#D85A30' }}>skill</em>. Get the&nbsp;kit.
              </h2>
            </div>
            <div style={{ fontFamily:'Plus Jakarta Sans', fontSize:14, color:'#7A6F68', maxWidth:340 }}>
              Each kit is 3–5 toys that build the same skill from different angles. Tap any card to see what's inside.
            </div>
          </div>
          <div className="kit-grid" style={{ display:'grid', gap:22, gridTemplateColumns:'repeat(auto-fill, minmax(360px, 1fr))' }}>
            {filteredKits.map(k => <window.AMComponents.KitCard key={k.id} kit={k} onOpen={setOpenKit} />)}
          </div>
          {filteredKits.length === 0 && (
            <div style={{ padding:'80px 0', textAlign:'center', fontFamily:'Plus Jakarta Sans', color:'#7A6F68' }}>
              <div style={{ fontFamily:'Instrument Serif', fontSize:42, color:'#1A1614', fontStyle:'italic', marginBottom:10 }}>No kits match this filter.</div>
              <div>Try a different age or skill, or clear the filters.</div>
            </div>
          )}
        </div>
      </section>

      <CustomKitBuilder />

      <section id="products" data-screen-label="individual-products" style={{ background:'#F5F1E8', borderTop:'1px solid rgba(26,22,20,0.08)' }}>
        <div style={{ maxWidth:1240, margin:'0 auto', padding:'96px clamp(20px,4vw,52px) 100px' }}>
          <div style={{ marginBottom:36, display:'flex', justifyContent:'space-between', alignItems:'flex-end', gap:20, flexWrap:'wrap' }}>
            <div>
              <div style={{ fontFamily:'Plus Jakarta Sans', fontSize:12, color:'#7A6F68', textTransform:'uppercase', letterSpacing:'0.12em', fontWeight:600, marginBottom:14 }}>Individual Products · {filteredProducts.length} toys</div>
              <h2 style={{ fontFamily:'Instrument Serif', fontWeight:400, fontSize:'clamp(40px,5vw,68px)', letterSpacing:'-0.025em', lineHeight:0.98, color:'#1A1614' }}>
                Every toy, <em style={{ fontStyle:'italic', color:'#D85A30' }}>scored</em> and tagged.
              </h2>
            </div>
            <div style={{ fontFamily:'Plus Jakarta Sans', fontSize:14, color:'#7A6F68', maxWidth:340 }}>
              Filters above apply here too. Every product shows its primary skill, score, and why it works.
            </div>
          </div>
          <ProductGrid products={filteredProducts} />
        </div>
      </section>

      <ByAge />
      <WhyKits />
      <FiveQuestionTest />
      <CTAFooter />
      <window.AMShared.AMFooter page="home" />

      <KitDrawer kit={openKit} onClose={()=>setOpenKit(null)} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
