// === Matchmaking transition (analysing) ===
function Matchmaking({ query, useCase, onDone }) {
  const [step, setStep] = React.useState(0);
  const steps = [
    'PARSING REQUEST',
    'LOADING ' + useCase.cat.toUpperCase() + ' CATALOG',
    'SCORING ON FIT',
    'RANKING BY USE-CASE',
    'WRITING THE TAKE',
  ];
  React.useEffect(() => {
    if (step >= steps.length) {
      const t = setTimeout(onDone, 350);
      return () => clearTimeout(t);
    }
    const t = setTimeout(() => setStep(step + 1), 380);
    return () => clearTimeout(t);
  }, [step]);
  return (
    <div className="matchmaking">
      <NeonGrid hue="#ff2bd6" />
      <div className="matchmaking__panel">
        <div className="matchmaking__title">
          <GlitchText>ANALYSING</GlitchText>
        </div>
        <div className="matchmaking__query">"{query}"</div>
        <div className="matchmaking__lines">
          {steps.map((s, i) => (
            <div key={s} className={`matchmaking__line ${i < step ? 'is-done' : ''} ${i === step ? 'is-active' : ''}`}>
              <span className="matchmaking__bullet">{i < step ? '✓' : i === step ? '▶' : '·'}</span>
              <span>{s}</span>
              {i < step && <span className="matchmaking__time">{(60 + Math.random()*40).toFixed(0)}ms</span>}
            </div>
          ))}
        </div>
        <div className="matchmaking__bar">
          <div className="matchmaking__bar-fill" style={{ width: `${Math.min(100, (step / steps.length) * 100)}%` }}></div>
        </div>
      </div>
    </div>
  );
}

// === Comparison results screen (replaces Bracket) ===
function Compare({ useCase, contenders, onOpenTool, onCompareTwo, onBack }) {
  const ranked = [...contenders].sort((a, b) => b.elo - a.elo);
  const [selected, setSelected] = React.useState({});
  const selectedIds = Object.keys(selected).filter(k => selected[k]);
  const toggleSelect = (id) => setSelected(s => ({ ...s, [id]: !s[id] }));

  const compareTwo = () => {
    if (selectedIds.length < 2) return;
    const a = window.TOOLS.find(t => t.id === selectedIds[0]);
    const b = window.TOOLS.find(t => t.id === selectedIds[1]);
    onCompareTwo(a, b);
  };

  const top = ranked[0];

  return (
    <div className="results page-enter">
      <NeonGrid hue="#00f0ff" />

      <div className="results__head">
        <button className="btn btn--ghost" onClick={onBack}>⟵ NEW SEARCH</button>
        <div className="results__head-center">
          <Chip color="#ff2bd6">COMPARISON · #{useCase.cat.toUpperCase()}</Chip>
          <h1 className="results__title">{useCase.title}</h1>
          <p className="results__sub">{useCase.subtitle}</p>
        </div>
        <div className="results__share">
          <Chip color="#c6ff3d" size="sm">SHAREABLE</Chip>
          <span className="results__share-url">/c/{useCase.cat}</span>
        </div>
      </div>

      {/* Editor's pick callout */}
      <div className="results__pick">
        <div className="results__pick-rays" aria-hidden><div></div><div></div><div></div><div></div></div>
        <div className="results__pick-left">
          <div className="results__pick-eyebrow">
            <Chip color="#c6ff3d">★ EDITOR'S PICK</Chip>
            <Chip color="#00f0ff" size="sm">FOR {useCase.cat.toUpperCase()}</Chip>
          </div>
          <h2 className="results__pick-name" style={{color: top.color}}>{top.name}</h2>
          <div className="results__pick-tag">{top.tag} · by {top.owner}</div>
          <p className="results__pick-take">
            {window.TOOL_DETAILS[top.id]?.bestFor}. The pick if you want to stop tab-hopping
            and commit to one tool you'll actually open tomorrow.
          </p>
          <div className="results__pick-actions">
            <button className="btn btn--primary" onClick={() => onOpenTool(top)}>VIEW FULL PROFILE ⟶</button>
            <button className="btn btn--ghost" onClick={() => toggleSelect(top.id)}>+ ADD TO COMPARE</button>
          </div>
        </div>
        <div className="results__pick-right">
          <FighterCard tool={top} size="md" />
        </div>
      </div>

      {/* Compare bar */}
      <div className={`compare-bar ${selectedIds.length > 0 ? 'is-on' : ''}`}>
        <span className="compare-bar__label">
          {selectedIds.length === 0 && '◇ TAP CARDS TO ADD TO COMPARE (MAX 2)'}
          {selectedIds.length === 1 && '◆ 1 SELECTED · PICK ONE MORE'}
          {selectedIds.length === 2 && '◆ 2 SELECTED · READY'}
        </span>
        {selectedIds.length === 2 && (
          <button className="btn btn--magenta compare-bar__go" onClick={compareTwo}>COMPARE HEAD-TO-HEAD ⟶</button>
        )}
        {selectedIds.length > 0 && (
          <button className="compare-bar__clear" onClick={() => setSelected({})}>clear</button>
        )}
      </div>

      {/* Ranked rows */}
      <div className="results__ranked">
        <div className="results__ranked-head">
          <span>RANK</span>
          <span>TOOL</span>
          <span>BEST FOR</span>
          <span>PRICE</span>
          <span>FIT</span>
          <span></span>
        </div>
        {ranked.map((tool, i) => {
          const d = window.TOOL_DETAILS[tool.id] || {};
          const fit = Math.round((tool.elo - 1900) / 6);
          const isSel = !!selected[tool.id];
          return (
            <div key={tool.id} className={`row ${isSel ? 'is-selected' : ''}`} style={{ '--row-color': tool.color, animationDelay: `${i * 0.06}s` }}>
              <div className="row__rank">
                <div className="row__rank-num">#{i + 1}</div>
                {i === 0 && <div className="row__rank-tag">PICK</div>}
              </div>
              <div className="row__tool" onClick={() => onOpenTool(tool)}>
                <div className="row__glyph" style={{color: tool.color}}>{tool.emoji}</div>
                <div>
                  <div className="row__name">{tool.name}</div>
                  <div className="row__tag">{tool.tag} · {tool.owner}</div>
                  <div className="row__flags">
                    {tool.free && <Chip color="#c6ff3d" size="xs">FREE</Chip>}
                    {tool.oss && <Chip color="#a78bff" size="xs">OPEN SRC</Chip>}
                    {tool.local && <Chip color="#00f0ff" size="xs">LOCAL</Chip>}
                  </div>
                </div>
              </div>
              <div className="row__bestfor">{d.bestFor || ''}</div>
              <div className="row__price">
                <div className="row__price-val">{tool.price}</div>
                <div className="row__price-note">{tool.free ? 'free tier' : 'paid only'}</div>
              </div>
              <div className="row__fit">
                <div className="row__fit-bar">
                  <div className="row__fit-fill" style={{ width: `${fit}%` }}></div>
                </div>
                <div className="row__fit-num">{fit}</div>
              </div>
              <div className="row__actions">
                <button
                  className={`row__select ${isSel ? 'is-on' : ''}`}
                  onClick={() => toggleSelect(tool.id)}
                  title="Add to compare"
                >
                  {isSel ? '✓' : '+'}
                </button>
                <button className="row__open" onClick={() => onOpenTool(tool)}>OPEN ⟶</button>
              </div>

              {/* Pros / Cons */}
              <div className="row__detail">
                <div className="row__poscon row__poscon--pros">
                  <div className="row__poscon-head"><span className="dot dot--pro">+</span> PROS</div>
                  <ul>
                    {(d.pros || []).slice(0, 3).map((p, j) => <li key={j}>{p}</li>)}
                  </ul>
                </div>
                <div className="row__poscon row__poscon--cons">
                  <div className="row__poscon-head"><span className="dot dot--con">−</span> CONS</div>
                  <ul>
                    {(d.cons || []).slice(0, 3).map((c, j) => <li key={j}>{c}</li>)}
                  </ul>
                </div>
                <div className="row__verdict">
                  <div className="row__verdict-head">OUR TAKE</div>
                  <p>
                    {d.bestFor && <>Best for <b>{d.bestFor.toLowerCase()}</b>. </>}
                    {d.notFor && <>Skip if you're <b>{d.notFor.toLowerCase()}</b>.</>}
                  </p>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <div className="results__footer">
        <div className="results__footer-q">Not the one? Try a different angle.</div>
        <div className="results__footer-actions">
          <button className="btn btn--ghost" onClick={onBack}>NEW SEARCH</button>
          <button className="btn btn--primary">SUBSCRIBE TO THIS COMPARISON</button>
        </div>
      </div>
    </div>
  );
}

window.Matchmaking = Matchmaking;
window.Compare = Compare;
