/* Brand page — header, bio, tabs (Products / Reviews / About). */
(function () {
  const D = window.WeedReviewDesignSystem_dcaedb;
  const { Thumbnail, LeafRating, ProductCard, ReviewCard, Card, Tabs, Tag, Badge, Button, Divider, Icon, FanLeaf } = 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;
  }

  const Wrap = ({ children, style }) => (
    <div style={{ maxWidth: 'var(--container-max)', margin: '0 auto', padding: '0 var(--space-7)', ...style }}>{children}</div>
  );

  function BrandPage({ navigate, id, focusCategory }) {
    const b = WR.brands[id] || WR.brands[WR.order.topBrands[0]];
    const [tab, setTab] = React.useState('about');
    const narrow = useMaxWidth(860);
    const isGrower = /flower|cultivat|sungrown/i.test(b.category);
    const productIds = WR.order.products.filter((pid) => WR.products[pid].brand === b.id);
    const brandReviews = [];
    productIds.forEach((pid) => (WR.reviews[pid] || []).forEach((r) => brandReviews.push({ ...r, product: WR.products[pid].name })));
    WR.recentReviews.forEach((r) => { if (productIds.some((pid) => WR.products[pid].name === r.product)) brandReviews.push(r); });
    const cats = b.categoryScores ? Object.keys(b.categoryScores) : [];
    const specialty = cats.slice().sort((x, y) => b.categoryScores[y].rating - b.categoryScores[x].rating)[0];
    const [selCat, setSelCat] = React.useState(focusCategory && b.categoryScores && b.categoryScores[focusCategory] ? focusCategory : specialty);
    const tw = (typeof window !== 'undefined' && window.WR_TWEAKS) || {};
    const facility = (tw.growFacility && tw.growFacility.trim()) ? tw.growFacility : b.facility;
    const philosophy = (tw.growPhilosophy && tw.growPhilosophy.trim()) ? tw.growPhilosophy : b.philosophy;
    const growStyles = (tw.growStyle && tw.growStyle.trim()) ? [tw.growStyle].concat(b.growStyles) : b.growStyles;

    return (
      <div style={{ paddingBottom: 80 }}>
        {/* Header band */}
        <section style={{ background: 'var(--surface-page-alt)', borderBottom: '1px solid var(--border-subtle)' }}>
          <Wrap style={{ padding: '40px var(--space-7)' }}>
            <div style={{ display: 'flex', gap: 'var(--space-8)', alignItems: 'center', flexWrap: 'wrap' }}>
              <div style={{ width: 108, flex: 'none' }}><Thumbnail tone={b.tone} monogram={b.name[0]} ratio="1 / 1" radius="var(--radius-xl)" /></div>
              <div style={{ flex: 1, minWidth: 260 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                  <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-4xl)', fontWeight: 600, color: 'var(--text-heading)', letterSpacing: '-0.02em', lineHeight: 1 }}>{b.name}</h1>
                  {b.verified && <Badge variant="verified">Verified</Badge>}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: 'var(--text-muted)', fontSize: 15, marginTop: 10 }}>
                  <Icon name="map-pin" size={15} /> {b.location}
                  <span aria-hidden="true">·</span> {b.category}
                </div>
                <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
                  <Button size="sm" iconLeft="plus">Follow</Button>
                  <Button size="sm" variant="secondary" iconLeft="pen-line" onClick={() => navigate('submit')}>Write a Review</Button>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 'var(--space-7)' }}>
                <div style={{ textAlign: 'center', paddingLeft: 'var(--space-7)', borderLeft: '1px solid var(--divider)' }}>
                  {b.rating != null ? (
                    <React.Fragment>
                      <div style={{ fontFamily: 'var(--font-display)', fontSize: 60, fontWeight: 600, color: 'var(--text-heading)', lineHeight: 1 }}>{b.rating.toFixed(1)}</div>
                      <div style={{ display: 'flex', justifyContent: 'center', margin: '8px 0 6px' }}><LeafRating value={b.rating} size="sm" showScore={false} /></div>
                      <div className="u-tnum" style={{ fontSize: 13, color: 'var(--text-muted)' }}>{(b.reviews || 0).toLocaleString()} reviews</div>
                    </React.Fragment>
                  ) : (
                    <React.Fragment>
                      <div style={{ display: 'flex', justifyContent: 'center', margin: '10px 0 8px' }}><LeafRating value={null} size="sm" showScore={false} /></div>
                      <div style={{ fontSize: 13, color: 'var(--text-muted)', maxWidth: 150 }}>No reviews yet</div>
                    </React.Fragment>
                  )}
                </div>
                {b.price && (
                  <div style={{ textAlign: 'center', paddingLeft: 'var(--space-7)', borderLeft: '1px solid var(--divider)' }}>
                    <div style={{ fontFamily: 'var(--font-display)', fontSize: 60, fontWeight: 600, color: 'var(--text-heading)', lineHeight: 1 }}>{b.price.amount}</div>
                    <div className="u-label" style={{ color: 'var(--text-faint)', marginTop: 12 }}>avg · {b.price.unit}</div>
                  </div>
                )}
              </div>
            </div>
            <p style={{ maxWidth: 720, marginTop: 22, color: 'var(--text-body)', fontSize: 'var(--text-md)', lineHeight: 1.6 }}>{b.bio}</p>
          </Wrap>
        </section>

        {/* Grades by category */}
        {cats.length > 0 && (
          <Wrap style={{ paddingTop: 24 }}>
            <Card padding="md" elevation="sm">
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap', marginBottom: 14 }}>
                <div>
                  <div className="u-label" style={{ color: 'var(--sage-600)', marginBottom: 4 }}>Grades by Category</div>
                  <div style={{ fontSize: 14, color: 'var(--text-muted)' }}>Specializes in <b style={{ color: 'var(--text-body)' }}>{specialty}</b></div>
                </div>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {cats.map((c) => <Tag key={c} interactive active={selCat === c} onClick={() => setSelCat(c)}>{c === specialty ? '★ ' : ''}{c}</Tag>)}
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-9)', flexWrap: 'wrap', paddingTop: 16, borderTop: '1px solid var(--divider)' }}>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, flex: 'none' }}>
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 52, fontWeight: 600, color: 'var(--text-heading)', lineHeight: 1 }}>{b.categoryScores[selCat].rating.toFixed(1)}</span>
                  <div>
                    <LeafRating value={b.categoryScores[selCat].rating} size="md" showScore={false} />
                    <div className="u-tnum" style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4 }}>{b.categoryScores[selCat].reviews.toLocaleString()} {selCat} reviews</div>
                  </div>
                </div>
                <div style={{ flex: '1 1 260px', minWidth: 240, display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {cats.map((c) => {
                    const cs = b.categoryScores[c];
                    return (
                      <button key={c} type="button" onClick={() => setSelCat(c)} style={{ display: 'grid', gridTemplateColumns: '104px 1fr 34px', alignItems: 'center', gap: 12, background: 'none', border: 'none', cursor: 'pointer', padding: '2px 0', textAlign: 'left' }}>
                        <span style={{ fontSize: 13, fontWeight: 600, color: selCat === c ? 'var(--forest-700)' : 'var(--text-muted)' }}>{c}</span>
                        <span style={{ position: 'relative', height: 8, borderRadius: 999, background: 'var(--cream-300)', overflow: 'hidden' }}>
                          <span style={{ position: 'absolute', top: 0, left: 0, bottom: 0, width: (cs.rating / 5 * 100) + '%', background: selCat === c ? 'var(--leaf-600)' : 'var(--leaf-500)', borderRadius: 999 }} />
                        </span>
                        <span className="u-tnum" style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-body)', textAlign: 'right' }}>{cs.rating.toFixed(1)}</span>
                      </button>
                    );
                  })}
                </div>
              </div>
            </Card>
          </Wrap>
        )}

        {/* Tabs */}
        <Wrap style={{ paddingTop: 24 }}>
          <Tabs value={tab} onChange={setTab} tabs={[
            { id: 'about', label: 'About' },
            { id: 'products', label: 'Products', count: productIds.length },
            { id: 'reviews', label: 'Reviews', count: b.reviews || 0 },
          ]} />
          <div style={{ paddingTop: 'var(--space-7)' }}>
            {tab === 'products' && (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))', gap: 'var(--space-6)' }}>
                {productIds.map((pid) => {
                  const p = WR.products[pid];
                  return <ProductCard key={pid} name={p.name} category={p.category} rating={null} reviewCount={null} thc={p.thc}
                    tone={p.tone} icon={p.icon} onClick={() => navigate('product', pid)} />;
                })}
              </div>
            )}
            {tab === 'reviews' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)', maxWidth: 820 }}>
                {brandReviews.length ? brandReviews.map((r, i) => (
                  <ReviewCard key={i} username={r.username} date={r.date} product={r.product} verifiedPurchase={r.verified} overall={r.overall} helpful={r.helpful || 0} attributes={r.attributes} text={r.text} />
                )) : (
                  <div>
                    <p style={{ color: 'var(--text-muted)', margin: '0 0 14px' }}>No reviews yet — be the first to review a {b.name} product.</p>
                    <Button iconLeft="pen-line" onClick={() => navigate('submit')}>Write a Review</Button>
                  </div>
                )}
              </div>
            )}
            {tab === 'about' && (
              <div style={{ display: 'grid', gridTemplateColumns: narrow ? '1fr' : 'minmax(0, 1.6fr) minmax(0, 1fr)', gap: 'var(--space-9)', alignItems: 'start' }}>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-9)' }}>
                  {/* Philosophy */}
                  <div>
                    <FanLeaf size={34} />
                    <p style={{ margin: '14px 0 0', fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', fontStyle: 'italic', fontWeight: 500, color: 'var(--text-heading)', lineHeight: 1.32, letterSpacing: '-0.01em' }}>{philosophy}</p>
                  </div>
                  {/* The Grow / Craft */}
                  <div>
                    <div className="u-label" style={{ color: 'var(--sage-600)', marginBottom: 12 }}>{isGrower ? 'The Grow' : 'The Craft'}</div>
                    <p style={{ color: 'var(--text-body)', fontSize: 'var(--text-md)', lineHeight: 1.7, margin: 0 }}>{facility}</p>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 18 }}>
                      {growStyles.map((g) => <Tag key={g} tone="sage" iconLeft="leaf">{g}</Tag>)}
                    </div>
                  </div>
                  {/* Where to find */}
                  <div>
                    <div className="u-label" style={{ color: 'var(--sage-600)', marginBottom: 12 }}>Where to Find</div>
                    <p style={{ color: 'var(--text-muted)', fontSize: 15, margin: '0 0 10px' }}>Based in {b.location} · {b.region}. Look for {b.name} at:</p>
                    <div style={{ display: 'flex', flexDirection: 'column' }}>
                      {b.findAt.map((f, i) => (
                        <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 0', borderBottom: i < b.findAt.length - 1 ? '1px solid var(--divider)' : 'none' }}>
                          <Icon name="map-pin" size={16} color="var(--sage-600)" />
                          <span style={{ fontSize: 15, color: 'var(--text-body)' }}>{f}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
                {/* Aside */}
                <Card padding="md" elevation="sm">
                  <div className="u-label" style={{ color: 'var(--text-faint)', marginBottom: 16 }}>At a Glance</div>
                  <dl style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '13px 16px', margin: 0, fontSize: 15 }}>
                    <dt style={{ color: 'var(--text-muted)' }}>Category</dt><dd style={{ margin: 0, textAlign: 'right', color: 'var(--text-body)' }}>{b.category}</dd>
                    <dt style={{ color: 'var(--text-muted)' }}>Location</dt><dd style={{ margin: 0, textAlign: 'right', color: 'var(--text-body)' }}>{b.location}</dd>
                    <dt style={{ color: 'var(--text-muted)' }}>Founded</dt><dd style={{ margin: 0, textAlign: 'right', color: 'var(--text-body)' }}>{b.founded || '—'}</dd>
                    {b.price && (<React.Fragment><dt style={{ color: 'var(--text-muted)' }}>Avg price</dt><dd className="u-mono" style={{ margin: 0, textAlign: 'right', color: 'var(--text-body)', fontWeight: 500 }}>{b.price.amount} / {b.price.unit}</dd></React.Fragment>)}
                    <dt style={{ color: 'var(--text-muted)' }}>Products</dt><dd style={{ margin: 0, textAlign: 'right', color: 'var(--text-body)' }}>{productIds.length} listed</dd>
                    <dt style={{ color: 'var(--text-muted)' }}>Status</dt><dd style={{ margin: 0, textAlign: 'right', color: 'var(--text-body)' }}>{b.verified ? 'Verified brand' : 'Unclaimed profile'}</dd>
                  </dl>
                  <div style={{ marginTop: 20 }}><Button fullWidth iconLeft="map-pin">Find in stores</Button></div>
                </Card>
              </div>
            )}
          </div>
        </Wrap>
      </div>
    );
  }
  window.BrandPage = BrandPage;
})();
