// === Ratings & reviews — aggregated from external sites/forums (per tool) ===

// Generate stable per-tool aggregated data (same tool always shows same numbers)
function hashStr(s) {
  let h = 2166136261;
  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = (h * 16777619) >>> 0; }
  return h;
}
function rngFor(seed) {
  let s = seed >>> 0;
  return () => { s = (s * 1664525 + 1013904223) >>> 0; return (s >>> 0) / 0xffffffff; };
}

const SOURCES = [
  { id: 'reddit',  label: 'Reddit',         glyph: '◉', color: '#ff5722', n: 'r/ChatGPTCoding' },
  { id: 'hn',      label: 'Hacker News',    glyph: 'Y', color: '#ff7733', n: 'news.ycombinator.com' },
  { id: 'g2',      label: 'G2',             glyph: '★', color: '#ff492c', n: 'g2.com' },
  { id: 'ph',      label: 'Product Hunt',   glyph: '▲', color: '#da552f', n: 'producthunt.com' },
  { id: 'x',       label: 'X / Twitter',    glyph: '𝕏', color: '#e0e0e0', n: 'x.com' },
  { id: 'yt',      label: 'YouTube',        glyph: '▶', color: '#ff0033', n: 'youtube.com' },
];

const REVIEW_TEMPLATES = {
  positive: [
    { author: 'devops_chris', source: 'reddit', text: 'Replaced 3 tools in my stack. Honestly didn\'t think it would stick but I\'m 6 weeks in and not going back.', stars: 5 },
    { author: 'kira.builds',  source: 'ph',     text: 'The defaults are unusually thoughtful. Most AI tools throw a thousand knobs at you. This one just works.', stars: 5 },
    { author: '@tomwrites',   source: 'x',      text: 'Underrated. Finally something that doesn\'t feel like an MVP wrapped in marketing.', stars: 5 },
    { author: 'CTO_Maya',     source: 'g2',     text: 'Rolled out to a 40-person team in a week. Adoption was instant. Pricing is fair for what you get.', stars: 5 },
    { author: 'pragmaticpete', source: 'hn',    text: 'It\'s the first tool in this space where the output is actually useful without 3 rounds of revisions.', stars: 4 },
    { author: 'Lina C.',      source: 'yt',     text: 'Did a 20-min review. Genuinely impressed by the latency on long-context tasks. Real workhorse.', stars: 4 },
  ],
  mixed: [
    { author: 'skeptical_dev', source: 'hn',    text: 'Good in the happy path. Falls over on anything weird. Support was responsive at least.', stars: 3 },
    { author: 'jenna_pm',     source: 'g2',     text: 'Solid core. Integrations feel half-finished. Would recommend with caveats.', stars: 3 },
    { author: 'casey.os',     source: 'reddit', text: 'It\'s fine. Not the breakthrough some people are claiming. But cheaper than the obvious alternative.', stars: 3 },
  ],
  negative: [
    { author: 'rita_ml',      source: 'reddit', text: 'Hit my rate limit on day two on the paid plan. Their pricing page does not match reality.', stars: 2 },
    { author: 'churned_user', source: 'g2',     text: 'Cancelled after a month. The roadmap looks great but I don\'t buy promises.', stars: 2 },
    { author: '@danwasright', source: 'x',      text: 'Not for serious production use yet. Loved the demos. Hated the bills.', stars: 2 },
  ],
};

function generateRatings(tool) {
  const seed = hashStr(tool.id + '/v3');
  const rand = rngFor(seed);

  // Overall: 3.6 – 4.8 weighted by elo
  const eloNorm = Math.max(0, Math.min(1, (tool.elo - 2050) / 200));
  const overall = +(3.6 + eloNorm * 1.1 + rand() * 0.15).toFixed(1);
  const totalReviews = Math.round(420 + rand() * 14000 + eloNorm * 8000);

  // Per-source ratings
  const sources = SOURCES.map((s, i) => {
    const variance = (rand() - 0.5) * 0.6;
    const rating = Math.max(2.8, Math.min(4.95, overall + variance));
    const count = Math.round(40 + rand() * (totalReviews / 6));
    return { ...s, rating: +rating.toFixed(1), count };
  });

  // Star distribution (sums to ~100)
  const dist = (() => {
    const r = overall;
    if (r >= 4.5) return { 5: 72, 4: 18, 3: 6, 2: 2, 1: 2 };
    if (r >= 4.0) return { 5: 54, 4: 28, 3: 10, 2: 5, 1: 3 };
    if (r >= 3.5) return { 5: 38, 4: 32, 3: 18, 2: 8, 1: 4 };
    return { 5: 22, 4: 28, 3: 26, 2: 14, 1: 10 };
  })();

  // Review picks: 3 positive, 1 mixed, 1 negative — but skew if low rating
  const positive = REVIEW_TEMPLATES.positive.slice().sort(() => rand() - 0.5);
  const mixed    = REVIEW_TEMPLATES.mixed.slice().sort(() => rand() - 0.5);
  const negative = REVIEW_TEMPLATES.negative.slice().sort(() => rand() - 0.5);

  const reviewCount = overall >= 4.3 ? [3, 1, 1] : overall >= 3.8 ? [2, 2, 1] : [1, 2, 2];
  const reviews = [
    ...positive.slice(0, reviewCount[0]),
    ...mixed.slice(0, reviewCount[1]),
    ...negative.slice(0, reviewCount[2]),
  ].map((r, idx) => {
    // Stamp tool name into text where natural, add timestamp + helpfulness
    const textVariants = [
      r.text,
      r.text.replace('this tool', tool.name).replace('It\'s', `${tool.name} is`),
      r.text,
    ];
    return {
      ...r,
      text: textVariants[idx % textVariants.length],
      ago: ['2d ago', '1w ago', '3w ago', '1m ago', '2m ago', '4m ago'][idx % 6],
      helpful: Math.round(8 + rand() * 480),
    };
  }).sort((a, b) => rand() - 0.5);

  // Sentiment summary (pulled from across forums — themes)
  const themes = [
    { label: 'Speed / latency', score: Math.round(60 + rand() * 38), polarity: 'pos' },
    { label: 'Pricing',         score: Math.round(40 + rand() * 50), polarity: rand() > 0.5 ? 'pos' : 'mixed' },
    { label: 'Setup',           score: Math.round(70 + rand() * 25), polarity: 'pos' },
    { label: 'Edge cases',      score: Math.round(30 + rand() * 35), polarity: 'mixed' },
    { label: 'Support',         score: Math.round(55 + rand() * 35), polarity: rand() > 0.6 ? 'pos' : 'mixed' },
  ].sort((a, b) => b.score - a.score);

  return { overall, totalReviews, sources, dist, reviews, themes };
}

function StarRow({ rating, size = 14, color = '#ffd14a' }) {
  const full = Math.floor(rating);
  const half = rating - full >= 0.5;
  const empty = 5 - full - (half ? 1 : 0);
  return (
    <span className="stars" style={{ '--star-size': size + 'px', '--star-color': color }}>
      {Array.from({length: full}).map((_, i) => <span key={`f${i}`} className="star star--full">★</span>)}
      {half && <span className="star star--half">★</span>}
      {Array.from({length: empty}).map((_, i) => <span key={`e${i}`} className="star star--empty">☆</span>)}
    </span>
  );
}

function Reviews({ tool }) {
  const data = React.useMemo(() => generateRatings(tool), [tool.id]);

  return (
    <div className="reviews">
      {/* Aggregated header */}
      <div className="reviews__head" style={{ '--tool-color': tool.color }}>
        <div className="reviews__head-main">
          <div className="reviews__overall">
            <div className="reviews__overall-num">{data.overall.toFixed(1)}</div>
            <div className="reviews__overall-meta">
              <StarRow rating={data.overall} size={20} />
              <div className="reviews__overall-count">
                {data.totalReviews.toLocaleString()} reviews aggregated from {data.sources.length} sources
              </div>
              <div className="reviews__overall-updated">
                <span className="dot dot--live"></span> SYNCED 18 MIN AGO
              </div>
            </div>
          </div>
          <div className="reviews__dist">
            {[5, 4, 3, 2, 1].map(n => (
              <div className="reviews__dist-row" key={n}>
                <span className="reviews__dist-n">{n}★</span>
                <div className="reviews__dist-bar">
                  <div className="reviews__dist-fill" style={{ width: `${data.dist[n]}%`, background: tool.color }}></div>
                </div>
                <span className="reviews__dist-pct">{data.dist[n]}%</span>
              </div>
            ))}
          </div>
        </div>

        {/* Per-source breakdown */}
        <div className="reviews__sources">
          {data.sources.map(s => (
            <a key={s.id} className="reviews__source" href="#" onClick={(e) => e.preventDefault()}
               style={{ '--src-color': s.color }}>
              <div className="reviews__source-head">
                <span className="reviews__source-glyph">{s.glyph}</span>
                <span className="reviews__source-name">{s.label}</span>
                <span className="reviews__source-arrow">↗</span>
              </div>
              <div className="reviews__source-body">
                <div className="reviews__source-rating">{s.rating.toFixed(1)}</div>
                <StarRow rating={s.rating} size={11} />
                <div className="reviews__source-count">{s.count.toLocaleString()}</div>
              </div>
              <div className="reviews__source-domain">{s.n}</div>
            </a>
          ))}
        </div>
      </div>

      {/* What people talk about */}
      <div className="reviews__themes">
        <div className="reviews__themes-head">WHAT PEOPLE TALK ABOUT</div>
        <div className="reviews__themes-grid">
          {data.themes.map(t => (
            <div className={`reviews__theme reviews__theme--${t.polarity}`} key={t.label}>
              <span className="reviews__theme-pol">{t.polarity === 'pos' ? '+' : t.polarity === 'neg' ? '−' : '~'}</span>
              <span className="reviews__theme-label">{t.label}</span>
              <span className="reviews__theme-score">{t.score}%</span>
            </div>
          ))}
        </div>
      </div>

      {/* Selected reviews */}
      <div className="reviews__list">
        <div className="reviews__list-head">
          <span className="reviews__list-title">SELECTED REVIEWS</span>
          <div className="reviews__list-filters">
            <button className="is-active">ALL</button>
            <button>POSITIVE</button>
            <button>CRITICAL</button>
          </div>
        </div>
        {data.reviews.map((r, i) => {
          const src = SOURCES.find(s => s.id === r.source);
          return (
            <div className="review" key={i}>
              <div className="review__head">
                <span className="review__author">{r.author}</span>
                <span className="review__src" style={{ color: src.color }}>{src.glyph} {src.label}</span>
                <span className="review__ago">· {r.ago}</span>
                <span className="review__stars"><StarRow rating={r.stars} size={12} /></span>
              </div>
              <div className="review__text">"{r.text}"</div>
              <div className="review__foot">
                <span className="review__helpful">▲ {r.helpful} found this helpful</span>
                <a href="#" onClick={(e) => e.preventDefault()} className="review__permalink">VIEW ON {src.label.toUpperCase()} ↗</a>
              </div>
            </div>
          );
        })}
        <button className="reviews__loadmore">LOAD MORE REVIEWS  ⟶</button>
      </div>
    </div>
  );
}

window.Reviews = Reviews;
window.StarRow = StarRow;
window.generateRatings = generateRatings;
