/* Rankings / Top Rated — leaderboard with category filters + Brands/Products toggle. */
(function () {
  const D = window.WeedReviewDesignSystem_dcaedb;
  const { BrandRankRow, Card, Tabs, Tag, Divider, FanLeaf, Select, LeafFall } = D;
  const WR = window.WR_DATA;

  const Wrap = ({ children, style }) => (
    <div style={{ maxWidth: 'var(--container-narrow)', margin: '0 auto', padding: '0 var(--space-7)', ...style }}>{children}</div>
  );
  const CHIPS = ['All', 'Flower', 'Pre-Rolls', 'Vapes', 'Edibles', 'Beverages', 'Concentrates', 'Topicals'];
  const matchesProduct = (p, chip) => chip === 'All'
    || (chip === 'Flower' && p.category === 'Flower')
    || (chip === 'Pre-Rolls' && p.category === 'Pre-Roll')
    || (chip === 'Vapes' && p.category === 'Vape')
    || (chip === 'Edibles' && p.category === 'Edible')
    || (chip === 'Beverages' && p.category === 'Beverage')
    || (chip === 'Concentrates' && p.category === 'Concentrate')
    || (chip === 'Topicals' && (p.category === 'Topical' || p.category === 'Tincture'));

  function RankingsPage({ navigate }) {
    const [mode, setMode] = React.useState('Products');
    const [chip, setChip] = React.useState('All');
    const az = (a, b) => a.name.localeCompare(b.name);

    let rows;
    if (mode === 'Products') {
      rows = WR.order.products.map((pid) => WR.products[pid])
        .filter((p) => matchesProduct(p, chip))
        .sort(az)
        .map((p) => ({ key: p.id, kind: 'product', name: p.name, category: `${p.category} · ${WR.brandName(p.brand)}`, tone: p.tone, mono: p.name[0] }));
    } else {
      rows = WR.order.topBrands.map((bid) => WR.brands[bid])
        .filter((b) => chip === 'All' || b.category.toLowerCase().includes(chip.slice(0, 4).toLowerCase()))
        .sort(az)
        .map((b) => ({ key: b.id, kind: 'brand', name: b.name, category: b.category, location: b.location, tone: b.tone, mono: b.name[0] }));
    }

    return (
      <div style={{ paddingBottom: 80 }}>
        {/* Header band */}
        <section style={{ position: 'relative', background: 'var(--forest-700)', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', right: -40, top: -50, opacity: 0.08 }}><FanLeaf size={300} filledColor="#EDE7D8" /></div>
          <LeafFall travel={340} count={13} />
          <Wrap style={{ position: 'relative', zIndex: 1, padding: '48px var(--space-7)', textAlign: 'center' }}>
            <div className="u-label" style={{ color: 'var(--leaf-400)', marginBottom: 10 }}>Rankings</div>
            <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-4xl)', fontWeight: 600, color: '#F3EEE2', letterSpacing: '-0.02em' }}>The Leaderboard</h1>
            <p style={{ color: 'var(--text-on-forest-muted)', fontSize: 15, marginTop: 10 }}>Every {mode === 'Products' ? 'product' : 'brand'} we track. Leaf scores and rankings appear as the community reviews them.</p>
          </Wrap>
        </section>

        {/* Controls */}
        <Wrap style={{ paddingTop: 24 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', marginBottom: 18 }}>
            <Tabs variant="pill" value={mode} onChange={(m) => { setMode(m); setChip('All'); }} tabs={['Products', 'Brands']} />
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {CHIPS.map((c) => <Tag key={c} interactive active={chip === c} onClick={() => setChip(c)}>{c}</Tag>)}
            </div>
          </div>

          {/* Table */}
          <Card padding="sm" elevation="sm">
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 12px 10px' }}>
              <span className="u-label" style={{ color: 'var(--text-faint)' }}>{mode} · A–Z</span>
              <span className="u-label" style={{ color: 'var(--text-faint)' }}>Leaf Score</span>
            </div>
            <Divider />
            <div style={{ paddingTop: 4 }}>
              {rows.map((r, i) => (
                <React.Fragment key={r.key}>
                  {i > 0 && <Divider />}
                  <BrandRankRow rank={i + 1} name={r.name} category={r.category} location={r.location}
                    rating={null} reviewCount={null} tone={r.tone} monogram={r.mono}
                    onClick={() => navigate(r.kind === 'brand' ? 'brand' : 'product', r.key, r.kind === 'brand' && chip !== 'All' ? chip : null)} />
                </React.Fragment>
              ))}
              {!rows.length && <p style={{ color: 'var(--text-muted)', padding: '20px 12px' }}>Nothing in this category yet.</p>}
            </div>
          </Card>
        </Wrap>
      </div>
    );
  }
  window.RankingsPage = RankingsPage;
})();
