// === Tool Profile screen — comparison-first ===
function ToolProfile({ tool, onBack, onCompare, backLabel }) {
  const d = window.TOOL_DETAILS[tool.id] || {};
  const alts = window.TOOLS.filter(t => t.cat === tool.cat && t.id !== tool.id).slice(0, 3);
  const updates = window.UPDATES.filter(u => u.tool === tool.name).concat(
    window.UPDATES.filter(u => u.tool !== tool.name).slice(0, 3)
  ).slice(0, 4);
  const [subscribed, setSubscribed] = React.useState(false);

  return (
    <div className="profile page-enter">
      <NeonGrid hue={tool.color} />
      <div className="profile__head">
        <button className="btn btn--ghost" onClick={onBack}>⟵ {backLabel || 'BACK'}</button>
        <div className="profile__breadcrumb">
          <span>catalog</span>
          <span>/</span>
          <span>{tool.cat}</span>
          <span>/</span>
          <span style={{ color: tool.color }}>{tool.name}</span>
        </div>
      </div>

      <div className="profile__hero" style={{ '--tool-color': tool.color }}>
        <div className="profile__hero-left">
          <FighterCard tool={tool} size="lg" />
        </div>
        <div className="profile__hero-right">
          <div className="profile__eyebrow">
            <Chip color={tool.color}>★ EDITOR'S PICK · {tool.cat.toUpperCase()}</Chip>
            <Chip color="#c6ff3d" size="sm">FIT SCORE {Math.round((tool.elo - 1900) / 6)}</Chip>
            <Chip color="#ff2bd6" size="sm">RANK 03 GLOBAL</Chip>
          </div>
          <h1 className="profile__name">
            <GlitchText>{tool.name}</GlitchText>
          </h1>
          <p className="profile__pitch">
            A {tool.tag} from {tool.owner}. {d.bestFor ? d.bestFor + '.' : ''} Built for people who already
            know what they want and stopped tab-hopping.
          </p>
          <div className="profile__quick-rating" onClick={() => {
            const el = document.querySelector('.reviews');
            const scroller = document.querySelector('.app-shell') || document.scrollingElement || document.documentElement;
            if (el && scroller) {
              const rect = el.getBoundingClientRect();
              const sRect = scroller.getBoundingClientRect ? scroller.getBoundingClientRect() : { top: 0 };
              scroller.scrollTo({ top: scroller.scrollTop + rect.top - (sRect.top || 0) - 20, behavior: 'smooth' });
            }
          }}>
            {(() => {
              const r = window.generateRatings(tool);
              return (
                <>
                  <span className="profile__quick-num">{r.overall.toFixed(1)}</span>
                  <window.StarRow rating={r.overall} size={16} />
                  <span className="profile__quick-count">{r.totalReviews.toLocaleString()} reviews · {r.sources.length} sources</span>
                  <span className="profile__quick-jump">JUMP TO REVIEWS ↓</span>
                </>
              );
            })()}
          </div>
          <div className="profile__stats">
            <Stat label="FIT" value={<NumberTick value={Math.round((tool.elo - 1900) / 6)} />} color={tool.color} size="lg" />
            <Stat label="HEAT" value={`${tool.hot}°`} color="#ff2bd6" size="lg" />
            <Stat label="PRICE" value={tool.price} color="#c6ff3d" size="lg" />
            <Stat label="OWNER" value={tool.owner} color="#ffffff" size="md" />
          </div>
          <div className="profile__cta">
            <button className={`btn ${subscribed ? 'btn--ghost' : 'btn--primary'}`} onClick={() => setSubscribed(!subscribed)}>
              {subscribed ? '✓ SUBSCRIBED TO UPDATES' : '◉ SUBSCRIBE TO UPDATES'}
            </button>
            <button className="btn btn--magenta" onClick={() => onCompare(tool)}>COMPARE WITH… ⟶</button>
            <button className="btn btn--ghost">VISIT OFFICIAL ↗</button>
          </div>
        </div>
      </div>

      <div className="profile__grid">
        <Panel title="WHAT IT DOES" accent={tool.color}>
          <p>A focused {tool.tag} that handles 80% of your {tool.cat} workflow without forcing you to learn a new mental model.</p>
          <ul className="profile__list">
            <li>Live integration with your existing stack</li>
            <li>Opinionated defaults, escapable advanced controls</li>
            <li>Exports clean — no lock-in if you bail</li>
          </ul>
        </Panel>
        <Panel title="BEST FOR" accent="#c6ff3d">
          <p style={{margin: 0}}>{d.bestFor}</p>
        </Panel>
        <Panel title="NOT FOR" accent="#ff3b6a">
          <p style={{margin: 0}}>{d.notFor}</p>
        </Panel>
        <Panel title="PROS" accent="#c6ff3d">
          <ul className="profile__list profile__list--plus">
            {(d.pros || []).map((p, i) => <li key={i}>{p}</li>)}
          </ul>
        </Panel>
        <Panel title="CONS" accent="#ff3b6a">
          <ul className="profile__list profile__list--minus">
            {(d.cons || []).map((c, i) => <li key={i}>{c}</li>)}
          </ul>
        </Panel>
        <Panel title="PRICING" accent="#00f0ff">
          <div className="profile__pricing">
            <div className="profile__pricing-row">
              <span className="lbl">FREE TIER</span>
              <span className="val">{tool.free ? 'Yes' : 'No'}</span>
            </div>
            <div className="profile__pricing-row">
              <span className="lbl">PAID</span>
              <span className="val">{tool.price}</span>
            </div>
            <div className="profile__pricing-row">
              <span className="lbl">OPEN SOURCE</span>
              <span className="val">{tool.oss ? 'Yes (Apache-2.0)' : 'No'}</span>
            </div>
            <div className="profile__pricing-row">
              <span className="lbl">RUNS LOCAL</span>
              <span className="val">{tool.local ? 'Yes' : 'Cloud only'}</span>
            </div>
          </div>
        </Panel>

        <Panel title="ALTERNATIVES IN THIS CATEGORY" accent="#a78bff" wide>
          <div className="profile__alts">
            {alts.map(a => (
              <div key={a.id} className="profile__alt" onClick={() => {}}>
                <span className="profile__alt-glyph" style={{ color: a.color }}>{a.emoji}</span>
                <div className="profile__alt-body">
                  <div className="profile__alt-name">{a.name}</div>
                  <div className="profile__alt-tag">{a.tag} · {a.price}</div>
                </div>
                <span className="profile__alt-cta">VS →</span>
              </div>
            ))}
          </div>
        </Panel>
        <Panel title="RECENT UPDATES" accent="#ffb547" wide>
          <div className="profile__feed">
            {updates.map((u, i) => (
              <div key={i} className={`feed__row feed__row--${u.heat}`}>
                <span className="feed__when">{u.when}</span>
                <span className="feed__what"><b>{u.tool}</b> {u.what}</span>
                <span className="feed__heat">{u.heat === 'hot' ? '🔥' : u.heat === 'mid' ? '↑' : '·'}</span>
              </div>
            ))}
          </div>
        </Panel>
      </div>

      <window.Reviews tool={tool} />
    </div>
  );
}

function Panel({ title, accent, children, wide }) {
  return (
    <div className={`panel ${wide ? 'panel--wide' : ''}`} style={{ '--panel-accent': accent }}>
      <div className="panel__head">
        <span className="panel__title">{title}</span>
        <span className="panel__corner">▢</span>
      </div>
      <div className="panel__body">{children}</div>
    </div>
  );
}

// === Head-to-head compare screen ===
function HeadToHead({ left, right, onBack, onSetSide, onOpenTool }) {
  const dL = window.TOOL_DETAILS[left.id] || {};
  const dR = window.TOOL_DETAILS[right.id] || {};
  const cats = ['cat', 'tag', 'owner', 'price', 'elo', 'hot', 'free', 'oss', 'local'];
  const labels = { cat: 'CATEGORY', tag: 'TYPE', owner: 'MAKER', price: 'PRICE', elo: 'FIT', hot: 'HEAT', free: 'FREE TIER', oss: 'OPEN SOURCE', local: 'RUNS LOCAL' };
  const fmt = (k, v) => {
    if (k === 'elo') return Math.round((v - 1900) / 6);
    return typeof v === 'boolean' ? (v ? 'YES' : 'NO') : String(v);
  };
  const winnerOn = (k) => {
    if (k === 'elo' || k === 'hot') return left[k] > right[k] ? 'L' : right[k] > left[k] ? 'R' : null;
    if (k === 'free' || k === 'oss' || k === 'local') return left[k] && !right[k] ? 'L' : right[k] && !left[k] ? 'R' : null;
    return null;
  };
  return (
    <div className="compare page-enter">
      <NeonGrid hue="#ff2bd6" />
      <div className="compare__head">
        <button className="btn btn--ghost" onClick={onBack}>⟵ BACK</button>
        <h1 className="compare__title"><GlitchText>HEAD&nbsp;TO&nbsp;HEAD</GlitchText></h1>
        <Chip color="#c6ff3d">SHAREABLE · /vs/{left.id}-{right.id}</Chip>
      </div>
      <div className="compare__board">
        <div className="compare__side">
          <FighterCard tool={left} size="lg" onClick={() => onOpenTool(left)} />
        </div>
        <div className="compare__center">
          <div className="compare__vs">VS</div>
          <div className="compare__rows">
            {cats.map(k => {
              const w = winnerOn(k);
              return (
                <div className="compare__row" key={k}>
                  <span className={`compare__cell ${w === 'L' ? 'is-win' : ''}`} style={{ color: w === 'L' ? left.color : 'var(--ink)' }}>{fmt(k, left[k])}</span>
                  <span className="compare__lbl">{labels[k]}</span>
                  <span className={`compare__cell ${w === 'R' ? 'is-win' : ''}`} style={{ color: w === 'R' ? right.color : 'var(--ink)' }}>{fmt(k, right[k])}</span>
                </div>
              );
            })}
          </div>

          <div className="compare__poscon">
            <div className="compare__poscon-col">
              <div className="compare__poscon-head" style={{color: left.color}}>{left.name}</div>
              <div className="compare__poscon-block">
                <div className="compare__poscon-label"><span className="dot--pro">+</span> PROS</div>
                <ul>{(dL.pros || []).slice(0, 3).map((p, i) => <li key={i}>{p}</li>)}</ul>
              </div>
              <div className="compare__poscon-block">
                <div className="compare__poscon-label"><span className="dot--con">−</span> CONS</div>
                <ul>{(dL.cons || []).slice(0, 3).map((p, i) => <li key={i}>{p}</li>)}</ul>
              </div>
            </div>
            <div className="compare__poscon-col">
              <div className="compare__poscon-head" style={{color: right.color}}>{right.name}</div>
              <div className="compare__poscon-block">
                <div className="compare__poscon-label"><span className="dot--pro">+</span> PROS</div>
                <ul>{(dR.pros || []).slice(0, 3).map((p, i) => <li key={i}>{p}</li>)}</ul>
              </div>
              <div className="compare__poscon-block">
                <div className="compare__poscon-label"><span className="dot--con">−</span> CONS</div>
                <ul>{(dR.cons || []).slice(0, 3).map((p, i) => <li key={i}>{p}</li>)}</ul>
              </div>
            </div>
          </div>

          <div className="compare__verdict">
            <div className="compare__verdict-eyebrow">OUR CALL</div>
            <div className="compare__verdict-text">
              {left.elo > right.elo ? left.name : right.name} edges it on overall fit.
              {left.price === '$0' && right.price !== '$0' ? ` ${left.name} wins on price.` :
               right.price === '$0' && left.price !== '$0' ? ` ${right.name} wins on price.` : ''}
              {" Pick the one whose pros line up with your workflow — both are solid choices."}
            </div>
          </div>
        </div>
        <div className="compare__side">
          <FighterCard tool={right} size="lg" onClick={() => onOpenTool(right)} />
        </div>
      </div>
    </div>
  );
}

window.ToolProfile = ToolProfile;
window.HeadToHead = HeadToHead;
