/* Product page — hero detail: facts, aggregate score, distribution, reviews. */
(function () {
  const D = window.WeedReviewDesignSystem_dcaedb;
  const { Thumbnail, LeafRating, AttributeRating, RatingDistribution, ReviewCard, Card, Divider, Tag, Badge, Button, Select, 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 TheBudsTake({ take }) {
    return (
      <div style={{ position: 'relative', overflow: 'hidden', background: 'linear-gradient(140deg, #1F4433, #14301F)', borderRadius: 'var(--radius-lg)', padding: 'var(--space-7)', marginBottom: 'var(--space-6)' }}>
        <div style={{ position: 'absolute', right: -28, bottom: -44, opacity: 0.12, pointerEvents: 'none' }}><FanLeaf size={200} filledColor="#EDE7D8" /></div>
        <div style={{ position: 'relative', display: 'flex', gap: 'var(--space-6)', alignItems: 'flex-start', flexWrap: 'wrap' }}>
          <div style={{ flex: 'none', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 60, height: 60, borderRadius: '50%', background: 'var(--amber-500)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'inset 0 0 0 2px rgba(255,255,255,0.35)' }}>
              <FanLeaf size={34} filledColor="#3B2A08" />
            </span>
            <span className="u-label" style={{ color: 'var(--amber-400)', fontSize: 10 }}>The Buds</span>
          </div>
          <div style={{ flex: 1, minWidth: 240 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginBottom: 10 }}>
              <span className="u-label" style={{ color: 'var(--amber-400)' }}>The Buds · Editor’s Take</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11, fontWeight: 700, color: '#14290A', background: 'var(--amber-500)', borderRadius: 'var(--radius-pill)', padding: '2px 9px', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Official</span>
            </div>
            <LeafRating value={take.score} size="lg" filledColor="var(--leaf-400)" emptyColor="rgba(237,231,216,0.22)" scoreStyle={{ color: '#F3EEE2' }} />
            <blockquote style={{ margin: '14px 0 0', fontFamily: 'var(--font-display)', fontSize: 'var(--text-xl)', fontStyle: 'italic', fontWeight: 500, lineHeight: 1.42, color: '#F3EEE2' }}>“{take.text}”</blockquote>
          </div>
        </div>
      </div>
    );
  }

  function ProductPage({ navigate, id }) {
    const p = WR.products[id] || WR.products[WR.order.products[0]];
    const b = WR.brands[p.brand];
    const baseReviews = WR.reviews[p.id] || [];
    const hasReviews = baseReviews.length > 0 && p.rating != null;
    const [sort, setSort] = React.useState('Most Helpful');
    const [level, setLevel] = React.useState(null);
    const narrow = useMaxWidth(1024);
    const narrowSm = useMaxWidth(560);

    let list = baseReviews.slice();
    if (level != null) list = list.filter((r) => Math.round(r.overall) === level);
    if (sort === 'Most Helpful') list.sort((a, c) => c.helpful - a.helpful);
    if (sort === 'Highest') list.sort((a, c) => c.overall - a.overall);
    if (sort === 'Lowest') list.sort((a, c) => a.overall - c.overall);

    return (
      <div style={{ paddingBottom: 80 }}>
        {/* Breadcrumb */}
        <Wrap style={{ paddingTop: 24, paddingBottom: 8 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--text-muted)' }}>
            <button onClick={() => navigate('home')} style={{ background: 'none', border: 'none', color: 'var(--text-link)', cursor: 'pointer', font: 'inherit', padding: 0 }}>Home</button>
            <Icon name="chevron-right" size={14} color="var(--text-faint)" />
            <span>{p.category}</span>
            <Icon name="chevron-right" size={14} color="var(--text-faint)" />
            <span style={{ color: 'var(--text-body)' }}>{p.name}</span>
          </div>
        </Wrap>

        {/* Hero detail */}
        <Wrap style={{ paddingTop: 12, display: 'grid', gridTemplateColumns: narrow ? '1fr' : 'minmax(300px, 380px) minmax(0, 1fr)', gap: 'var(--space-9)', alignItems: 'start' }}>
          {/* Left: image + facts */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
            <div style={{ width: '100%', maxWidth: 460, margin: '0 auto' }}>
              <Thumbnail tone={p.tone} icon={p.icon} ratio="1 / 1" radius="var(--radius-xl)" />
            </div>
            <Card padding="md" elevation="sm">
              <div className="u-label" style={{ color: 'var(--text-faint)', marginBottom: 12 }}>Details</div>
              <dl style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '10px 16px', margin: 0, fontSize: 14 }}>
                <dt style={{ color: 'var(--text-muted)' }}>Brand</dt>
                <dd style={{ margin: 0, textAlign: 'right' }}><button onClick={() => navigate('brand', p.brand)} style={{ background: 'none', border: 'none', color: 'var(--text-link)', fontWeight: 600, cursor: 'pointer', font: 'inherit' }}>{b.name}</button></dd>
                <dt style={{ color: 'var(--text-muted)' }}>Category</dt>
                <dd style={{ margin: 0, textAlign: 'right', color: 'var(--text-body)' }}>{p.category}</dd>
                {p.type && (<React.Fragment><dt style={{ color: 'var(--text-muted)' }}>Type</dt><dd style={{ margin: 0, textAlign: 'right', color: 'var(--text-body)' }}>{p.type}</dd></React.Fragment>)}
                {p.lineage && (<React.Fragment><dt style={{ color: 'var(--text-muted)' }}>Lineage</dt><dd style={{ margin: 0, textAlign: 'right', color: 'var(--text-body)' }}>{p.lineage}</dd></React.Fragment>)}
                {p.spec && (<React.Fragment><dt style={{ color: 'var(--text-muted)' }}>Spec</dt><dd className="u-mono" style={{ margin: 0, textAlign: 'right', color: 'var(--text-body)', fontWeight: 500 }}>{p.spec}</dd></React.Fragment>)}
                {!p.spec && (<React.Fragment><dt style={{ color: 'var(--text-muted)' }}>Potency</dt><dd style={{ margin: 0, textAlign: 'right', color: 'var(--text-muted)' }}>Varies by batch</dd></React.Fragment>)}
              </dl>
              {p.description && (
                <p style={{ margin: '14px 0 0', fontSize: 14, color: 'var(--text-body)', lineHeight: 1.6, borderTop: '1px solid var(--divider)', paddingTop: 14 }}>{p.description}</p>
              )}
              {p.terpenes && p.terpenes.length > 0 && (
                <div style={{ marginTop: 16 }}>
                  <div className="u-label" style={{ color: 'var(--text-faint)', marginBottom: 10 }}>Dominant Terpenes</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                    {p.terpenes.map((t) => <Tag key={t} tone="sage" size="sm">{t}</Tag>)}
                  </div>
                </div>
              )}
            </Card>
          </div>

          {/* Right: summary */}
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
              <span className="u-label" style={{ color: 'var(--sage-600)' }}>{p.category}</span>
            </div>
            <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-4xl)', fontWeight: 600, color: 'var(--text-heading)', letterSpacing: '-0.02em', lineHeight: 1.04 }}>{p.name}</h1>
            <div style={{ marginTop: 6, color: 'var(--text-muted)', fontSize: 15 }}>
              by <button onClick={() => navigate('brand', p.brand)} style={{ background: 'none', border: 'none', color: 'var(--text-link)', fontWeight: 600, cursor: 'pointer', font: 'inherit' }}>{b.name}</button> · {b.location}
            </div>

            <Card padding="md" elevation="sm" style={{ marginTop: 'var(--space-6)' }}>
              {hasReviews ? (
                <div style={{ display: 'grid', gridTemplateColumns: narrow ? '1fr' : '190px 1fr', gap: 'var(--space-8)', alignItems: narrow ? 'stretch' : 'center' }}>
                  {/* Aggregate */}
                  <div style={{ textAlign: 'center', borderRight: narrow ? 'none' : '1px solid var(--divider)', paddingRight: narrow ? 0 : 'var(--space-6)', borderBottom: narrow ? '1px solid var(--divider)' : 'none', paddingBottom: narrow ? 'var(--space-6)' : 0 }}>
                    <div style={{ fontFamily: 'var(--font-display)', fontSize: 68, fontWeight: 600, color: 'var(--text-heading)', lineHeight: 1, letterSpacing: '-0.02em' }}>{p.rating.toFixed(1)}</div>
                    <div style={{ display: 'flex', justifyContent: 'center', margin: '8px 0 6px' }}><LeafRating value={p.rating} size="md" showScore={false} /></div>
                    <div className="u-tnum" style={{ fontSize: 13, color: 'var(--text-muted)' }}>{p.reviews.toLocaleString()} reviews</div>
                    <div style={{ marginTop: 16 }}><Button fullWidth iconLeft="pen-line" onClick={() => navigate('submit', p.id)}>Write a Review</Button></div>
                  </div>
                  {/* Sub-attributes + distribution */}
                  <div style={{ display: 'grid', gridTemplateColumns: narrowSm ? '1fr' : '1fr 1fr', gap: 'var(--space-7)' }}>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                      <div className="u-label" style={{ color: 'var(--text-faint)' }}>Averages</div>
                      {(p.attributes || []).map((a) => <AttributeRating key={a.label} label={a.label} value={a.value} size="sm" />)}
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                      <div className="u-label" style={{ color: 'var(--text-faint)' }}>Distribution</div>
                      <RatingDistribution distribution={p.distribution} onSelect={setLevel} activeLevel={level} />
                    </div>
                  </div>
                </div>
              ) : (
                <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-7)', flexWrap: 'wrap', justifyContent: 'space-between' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-5)', minWidth: 240 }}>
                    <LeafRating value={null} size="md" showScore={false} />
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 15, color: 'var(--text-heading)' }}>No reviews yet</div>
                      <div style={{ fontSize: 14, color: 'var(--text-muted)' }}>Tried it? Your review sets this product's first leaf score.</div>
                    </div>
                  </div>
                  <Button iconLeft="pen-line" onClick={() => navigate('submit', p.id)}>Write the first review</Button>
                </div>
              )}
            </Card>
          </div>
        </Wrap>

        {/* Reviews */}
        <Wrap style={{ paddingTop: 56 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', marginBottom: 'var(--space-6)' }}>
            <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', fontWeight: 600, color: 'var(--text-heading)' }}>
              Reviews <span className="u-tnum" style={{ color: 'var(--text-faint)', fontWeight: 400 }}>({(p.reviews || 0).toLocaleString()})</span>
            </h2>
            {hasReviews && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                {level != null && <Tag interactive active onClick={() => setLevel(null)}>{level} leaves ✕</Tag>}
                <div style={{ width: 190 }}><Select icon="arrow-up-down" options={['Most Helpful', 'Newest', 'Highest', 'Lowest']} value={sort} onChange={(e) => setSort(e.target.value)} /></div>
              </div>
            )}
          </div>
          {p.theBuds && <TheBudsTake take={p.theBuds} />}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
            {list.length ? list.map((r, i) => (
              <ReviewCard key={i} username={r.username} date={r.date} verifiedPurchase={r.verified} overall={r.overall} helpful={r.helpful} attributes={r.attributes} text={r.text} />
            )) : (
              <p style={{ color: 'var(--text-muted)', padding: '24px 0' }}>
                {hasReviews ? 'No reviews match this filter.' : 'No reviews yet — be the first to review ' + p.name + '.'}
              </p>
            )}
          </div>
        </Wrap>
      </div>
    );
  }
  window.ProductPage = ProductPage;
})();
