/* Homepage — hero, Trending, Top Rated Brands, Recent Reviews, Categories. */
(function () {
  const D = window.WeedReviewDesignSystem_dcaedb;
  const { SearchBar, ProductCard, BrandRankRow, ReviewCard, CategoryTile, Card, Divider, FanLeaf, Button } = D;
  const WR = window.WR_DATA;

  function useMaxWidth(px) {
    const [m, setM] = React.useState(false);
    React.useEffect(() => {
      const mq = window.matchMedia('(max-width: ' + px + 'px)');
      const on = () => setM(mq.matches); on();
      mq.addEventListener ? mq.addEventListener('change', on) : mq.addListener(on);
      return () => { mq.removeEventListener ? mq.removeEventListener('change', on) : mq.removeListener(on); };
    }, []);
    return m;
  }

  function RisingLeaves() {
    const leaves = React.useMemo(() => {
      const rnd = (a, b) => a + Math.random() * (b - a);
      return Array.from({ length: 36 }, (_, i) => ({
        left: rnd(1, 97),
        size: Math.round(rnd(22, 60)),
        dur: rnd(15, 30),
        delay: -rnd(0, 30),
        o: rnd(0.08, 0.24).toFixed(3),
        r: Math.round(rnd(120, 220)) * (i % 2 ? 1 : -1),
        sx: Math.round(rnd(10, 28)) * (i % 2 ? 1 : -1),
        color: i % 3 === 0 ? '#BFE29A' : '#EDE7D8',
      }));
    }, []);
    return (
      <div aria-hidden="true" style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none', zIndex: 0 }}>
        <style>{'@keyframes wrRise{0%{transform:translateY(0) translateX(0) rotate(0deg);opacity:0}7%{opacity:var(--o)}50%{transform:translateY(58vh) translateX(var(--sx)) rotate(calc(var(--r) * 0.5))}90%{opacity:var(--o)}100%{transform:translateY(116vh) translateX(calc(var(--sx) * -1)) rotate(var(--r));opacity:0}}'}</style>
        {leaves.map((l, i) => (
          <div key={i} style={{ position: 'absolute', left: l.left + '%', top: -60, '--o': l.o, '--sx': l.sx + 'px', '--r': l.r + 'deg', animation: 'wrRise ' + l.dur + 's linear ' + l.delay + 's infinite', willChange: 'transform, opacity' }}>
            <FanLeaf size={l.size} filledColor={l.color} />
          </div>
        ))}
      </div>
    );
  }

  const Wrap = ({ children, style }) => (
    <div style={{ maxWidth: 'var(--container-max)', margin: '0 auto', padding: '0 var(--space-7)', ...style }}>{children}</div>
  );
  const SectionHead = ({ eyebrow, title, action, onAction }) => (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, marginBottom: 'var(--space-6)' }}>
      <div>
        <div className="u-label" style={{ color: 'var(--sage-600)', marginBottom: 6 }}>{eyebrow}</div>
        <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', fontWeight: 600, color: 'var(--text-heading)', letterSpacing: '-0.02em' }}>{title}</h2>
      </div>
      {action && <button onClick={onAction} style={{ background: 'none', border: 'none', color: 'var(--text-link)', fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 14, cursor: 'pointer', whiteSpace: 'nowrap' }}>{action} →</button>}
    </div>
  );

  function Homepage({ navigate }) {
    const narrow = useMaxWidth(1024);
    return (
      <div>
        {/* Hero */}
        <section style={{ position: 'relative', background: 'radial-gradient(120% 140% at 85% 0%, #24503F 0%, #1B3B2F 55%, #14301F 100%)', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', right: -70, top: -70, opacity: 0.09, pointerEvents: 'none' }}><FanLeaf size={480} filledColor="#EDE7D8" /></div>
          <div style={{ position: 'absolute', left: -50, bottom: -110, opacity: 0.06, pointerEvents: 'none' }}><FanLeaf size={320} filledColor="#EDE7D8" /></div>
          <RisingLeaves />
          <Wrap style={{ position: 'relative', zIndex: 1, padding: '84px var(--space-7) 92px', textAlign: 'center' }}>
            <div className="u-label" style={{ color: 'var(--leaf-400)', fontSize: '15px', letterSpacing: '0.18em', marginBottom: 16 }}>The connoisseur’s guide to cannabis</div>
            <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(44px, 6vw, 76px)', fontWeight: 600, color: '#F3EEE2', letterSpacing: '-0.03em', lineHeight: 1.02 }}>{(window.WR_TWEAKS && window.WR_TWEAKS.heroTagline) || 'Puff, Puff, Rate.'}</h1>
            <p style={{ color: 'var(--text-on-forest-muted)', fontSize: 'var(--text-md)', maxWidth: 560, margin: '18px auto 32px', lineHeight: 1.5 }}>
              Trusted, community-driven leaf ratings for every brand and product — flower, vapes, edibles, beverages, and more.
            </p>
            <div style={{ maxWidth: 620, margin: '0 auto' }}>
              <SearchBar variant="hero" onSubmit={() => navigate('rankings')} />
            </div>
            <div style={{ display: 'flex', gap: 28, justifyContent: 'center', marginTop: 28, flexWrap: 'wrap', color: 'var(--text-on-forest-muted)', fontFamily: 'var(--font-mono)', fontSize: 13 }}>
              <span><b style={{ color: '#EDE7D8', fontWeight: 600 }}>{Object.keys(WR.brands).length}</b> brands</span>
              <span><b style={{ color: '#EDE7D8', fontWeight: 600 }}>{Object.keys(WR.products).length}</b> products</span>
              <span><b style={{ color: '#EDE7D8', fontWeight: 600 }}>{WR.categories.length}</b> categories</span>
            </div>
          </Wrap>
        </section>

        {/* Featured products */}
        <Wrap style={{ padding: '64px var(--space-7) 0' }}>
          <SectionHead eyebrow="Featured Products" title="Real products from real brands" action="Browse all" onAction={() => navigate('products')} />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))', gap: 'var(--space-6)' }}>
            {WR.order.trending.map((pid) => {
              const p = WR.products[pid];
              return <ProductCard key={pid} name={p.name} brand={WR.brandName(p.brand)} category={p.category}
                rating={null} reviewCount={null} thc={p.thc}
                tone={p.tone} icon={p.icon} onClick={() => navigate('product', pid)} />;
            })}
          </div>
        </Wrap>

        {/* Top Rated Brands + Categories side by side */}
        <Wrap style={{ padding: '64px var(--space-7) 0', display: 'grid', gridTemplateColumns: narrow ? '1fr' : 'minmax(0, 1.3fr) minmax(0, 1fr)', gap: 'var(--space-9)', alignItems: 'start' }}>
          <div>
            <SectionHead eyebrow="Featured Brands" title="Cultivators & makers we track" action="All brands" onAction={() => navigate('brands')} />
            <Card padding="sm" elevation="sm">
              {WR.order.topBrands.slice(0, 5).map((bid, i) => {
                const b = WR.brands[bid];
                return (
                  <React.Fragment key={bid}>
                    {i > 0 && <Divider />}
                    <BrandRankRow rank={i + 1} name={b.name} category={b.category} location={b.location}
                      rating={null} reviewCount={null}
                      tone={b.tone} onClick={() => navigate('brand', bid)} />
                  </React.Fragment>
                );
              })}
            </Card>
          </div>
          <div>
            <SectionHead eyebrow="Recent Reviews" title="Fresh from the community" />
            {WR.recentReviews.length ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
                {WR.recentReviews.map((r, i) => (
                  <ReviewCard key={i} username={r.username} date={r.date} product={r.product} overall={r.overall} text={r.text} helpful={0} />
                ))}
              </div>
            ) : (
              <Card padding="md" elevation="sm" style={{ textAlign: 'center' }}>
                <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 12 }}><FanLeaf size={40} fill={0} outline /></div>
                <p style={{ color: 'var(--text-body)', fontSize: 15, margin: '0 0 6px', fontWeight: 600 }}>No reviews yet</p>
                <p style={{ color: 'var(--text-muted)', fontSize: 14, lineHeight: 1.5, margin: '0 0 16px' }}>
                  WeedReview just launched. Every product and brand here is real — the ratings are waiting on you.
                </p>
                <Button iconLeft="pen-line" onClick={() => navigate('submit')}>Write the first review</Button>
              </Card>
            )}
          </div>
        </Wrap>

        {/* Categories */}
        <Wrap style={{ padding: '64px var(--space-7) 80px' }}>
          <SectionHead eyebrow="Browse by Category" title="Find your format" />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(210px, 250px))', justifyContent: 'center', gap: 'var(--space-5)' }}>
            {WR.categories.map((c) => (
              <CategoryTile key={c.label} label={c.label} icon={c.icon} count={c.count} onClick={() => navigate('rankings')} />
            ))}
          </div>
        </Wrap>
      </div>
    );
  }
  window.Homepage = Homepage;
})();
