/* Comparison View (Screen D) — Our Ranking vs External 21-List */

function fmtFollowers(n) { return n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e3 ? (n / 1e3).toFixed(1) + 'K' : String(n); }

/* Simple score from available Phase-1 data (proxy until Phase 2 scoring) */
function computeProxyScore(m) {
  var s = 0;
  s += Math.min(1, Math.log10(Math.max(1, m.followers)) / 5.5) * 0.40;
  s += (m.bio ? 0.20 : 0);
  s += (m.verified ? 0.15 : 0);
  s += (m.mentions && m.mentions.length > 0 ? 0.15 : 0);
  s += (m.url ? 0.10 : 0);
  return Math.round(s * 100) / 100;
}

/* ── Stat Card ── */
function CompStatCard({ label, value, color }) {
  return (
    <div style={{ background: 'var(--bg-card)', border: '1px solid var(--border-subtle)', borderRadius: 12, padding: '14px 18px', flex: 1, textAlign: 'center' }}>
      <div style={{ fontSize: 26, fontWeight: 700, fontFamily: 'var(--mono)', color: color, fontFeatureSettings: "'tnum' 1", lineHeight: 1.1 }}>{value}</div>
      <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginTop: 4 }}>{label}</div>
    </div>
  );
}

/* ── Row in either column ── */
function CompPersonRow({ person, rank, side, isOverlap, isHovered, onHover, height }) {
  var [localHov, setLocalHov] = React.useState(false);
  var highlighted = isHovered || localHov;
  var bg = highlighted ? 'var(--bg-elevated)' : isOverlap ? 'rgba(249,115,22,0.04)' : 'transparent';
  return (
    <div
      onMouseEnter={function () { setLocalHov(true); onHover(person.handle); }}
      onMouseLeave={function () { setLocalHov(false); onHover(null); }}
      style={{
        display: 'flex', alignItems: 'center', gap: 8, height: height,
        padding: '0 10px', borderRadius: 6, background: bg,
        borderLeft: (isOverlap && side === 'left') ? '3px solid var(--amber)' : '3px solid transparent',
        borderRight: (isOverlap && side === 'right') ? '3px solid var(--amber)' : '3px solid transparent',
        transition: 'background .12s', cursor: 'default',
      }}>
      {/* Rank */}
      <div style={{ width: 22, fontSize: 11, fontFamily: 'var(--mono)', color: 'var(--text-tertiary)', textAlign: 'right', fontFeatureSettings: "'tnum' 1", flexShrink: 0 }}>{rank}</div>
      {/* Avatar */}
      <Avatar name={person.name} handle={person.handle} size={26} />
      {/* Info */}
      <div style={{ flex: 1, minWidth: 0, overflow: 'hidden' }}>
        <div style={{ fontSize: 12, fontFamily: 'var(--mono)', color: 'var(--text-primary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', fontWeight: 500 }}>@{person.handle}</div>
        {person.name && <div style={{ fontSize: 11, color: 'var(--text-tertiary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{person.name}</div>}
      </div>
      {/* Right metric */}
      {side === 'left' && (
        <div style={{ fontSize: 12, fontFamily: 'var(--mono)', color: 'var(--text-secondary)', fontFeatureSettings: "'tnum' 1", flexShrink: 0, textAlign: 'right' }}>
          <div>{fmtFollowers(person.followers)}</div>
          <div style={{ fontSize: 10, color: person._tier === 1 ? 'var(--accent)' : 'var(--text-tertiary)', fontFamily: 'var(--mono)' }}>{typeof person._proxyScore === 'number' ? person._proxyScore.toFixed(2) : person._proxyScore}{person._tier ? ' · T' + person._tier : ''}</div>
        </div>
      )}
      {side === 'right' && person.external && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
          <TierBadge tier={person.external.tier} />
          <span style={{ fontSize: 11, fontFamily: 'var(--mono)', color: 'var(--text-secondary)', fontFeatureSettings: "'tnum' 1" }}>{person.external.priority}</span>
        </div>
      )}
    </div>
  );
}

/* ── Column Header ── */
function CompColumnHeader({ title, subtitle, color }) {
  return (
    <div style={{ padding: '12px 10px 10px', borderBottom: '1px solid var(--border-subtle)', marginBottom: 4 }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: color || 'var(--text-primary)' }}>{title}</div>
      {subtitle && <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 }}>{subtitle}</div>}
    </div>
  );
}

/* ═══════ MAIN COMPARISON VIEW ═══════ */
function ComparisonView() {
  var [hoveredHandle, setHoveredHandle] = React.useState(null);
  var members = window.COHORT.members;

  /* Our ranking: top 30 by real priority score */
  var ourRanking = React.useMemo(function () {
    var SC = window.SCORING.getDefault();
    return SC.scored.slice(0, 30).map(function (s) { return Object.assign({}, s.m, { _proxyScore: s.priorityScore, _tier: s.tier }); });
  }, []);

  /* External list sorted by priority */
  var externalList = React.useMemo(function () {
    return members.filter(function (m) { return m.external; })
      .sort(function (a, b) { return b.external.priority - a.external.priority; });
  }, []);

  /* Overlap set */
  var overlapHandles = React.useMemo(function () {
    var extSet = new Set(externalList.map(function (m) { return m.handle; }));
    var s = new Set();
    ourRanking.forEach(function (m) { if (extSet.has(m.handle)) s.add(m.handle); });
    return s;
  }, [ourRanking, externalList]);

  var overlapCount = overlapHandles.size;
  var uniqueOurs = ourRanking.length - overlapCount;
  var uniqueExt = externalList.length - overlapCount;

  /* Connector lines */
  var ROW_H = 44;
  var HEADER_H = 54;
  var connectors = React.useMemo(function () {
    var ourIdx = {};
    ourRanking.forEach(function (m, i) { ourIdx[m.handle] = i; });
    var result = [];
    externalList.forEach(function (m, ei) {
      if (ourIdx[m.handle] !== undefined) {
        result.push({
          handle: m.handle,
          y1: HEADER_H + ourIdx[m.handle] * ROW_H + ROW_H / 2,
          y2: HEADER_H + ei * ROW_H + ROW_H / 2,
        });
      }
    });
    return result;
  }, [ourRanking, externalList]);

  var svgH = Math.max(ourRanking.length, externalList.length) * ROW_H + HEADER_H + 20;

  function bezier(c) {
    return 'M 0,' + c.y1 + ' C 50,' + c.y1 + ' 70,' + c.y2 + ' 120,' + c.y2;
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      {/* Stats */}
      <div style={{ padding: '16px 28px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', gap: 12, flexShrink: 0 }}>
        <CompStatCard label="Overlap" value={overlapCount} color="var(--accent)" />
        <CompStatCard label="Unique to Ours" value={uniqueOurs} color="var(--text-primary)" />
        <CompStatCard label="Unique to External" value={uniqueExt} color="var(--text-secondary)" />
        <div style={{ flex: 2, background: 'var(--bg-card)', border: '1px solid var(--border-subtle)', borderRadius: 12, padding: '14px 18px', fontSize: 12, color: 'var(--text-tertiary)', lineHeight: 1.55 }}>
          Left column ranks by our 3-layer <strong style={{ color: 'var(--text-secondary)' }}>priority_score</strong> (Light + Heavy). Adjust the weights in the <strong style={{ color: 'var(--accent)' }}>Methodology</strong> tab to see this reflow. Hover any row to trace its connection.
        </div>
      </div>

      {/* Comparison columns */}
      <div style={{ flex: 1, overflow: 'auto', padding: '0 28px 28px' }}>
        <div style={{ display: 'flex', gap: 0 }}>
          {/* Our Ranking */}
          <div style={{ flex: 1 }}>
            <CompColumnHeader title="Our Ranking" subtitle={'Top ' + ourRanking.length + ' by priority_score'} color="var(--text-primary)" />
            {ourRanking.map(function (m, i) {
              return <CompPersonRow key={m.handle} person={m} rank={i + 1} side="left"
                isOverlap={overlapHandles.has(m.handle)}
                isHovered={hoveredHandle === m.handle}
                onHover={setHoveredHandle} height={ROW_H} />;
            })}
          </div>

          {/* SVG Connectors */}
          <div style={{ width: 120, flexShrink: 0, position: 'relative' }}>
            <svg width="120" height={svgH} style={{ display: 'block' }}>
              {connectors.map(function (c) {
                var active = !hoveredHandle || hoveredHandle === c.handle;
                return <path key={c.handle} d={bezier(c)}
                  fill="none" stroke="var(--accent)"
                  strokeWidth={hoveredHandle === c.handle ? 2.5 : 1.5}
                  opacity={active ? 0.6 : 0.08}
                  style={{ transition: 'opacity .2s, stroke-width .15s' }} />;
              })}
              {/* Dots at endpoints */}
              {connectors.map(function (c) {
                var active = !hoveredHandle || hoveredHandle === c.handle;
                return (
                  <React.Fragment key={c.handle + '-dots'}>
                    <circle cx="2" cy={c.y1} r={active ? 4 : 3} fill="var(--accent)" opacity={active ? 0.8 : 0.15} style={{ transition: 'opacity .2s' }} />
                    <circle cx="118" cy={c.y2} r={active ? 4 : 3} fill="var(--accent)" opacity={active ? 0.8 : 0.15} style={{ transition: 'opacity .2s' }} />
                  </React.Fragment>
                );
              })}
            </svg>
          </div>

          {/* External 21 */}
          <div style={{ flex: 1 }}>
            <CompColumnHeader title="External 21-List" subtitle={externalList.length + ' people · sorted by priority'} color="var(--accent)" />
            {externalList.map(function (m, i) {
              return <CompPersonRow key={m.handle} person={m} rank={i + 1} side="right"
                isOverlap={overlapHandles.has(m.handle)}
                isHovered={hoveredHandle === m.handle}
                onHover={setHoveredHandle} height={ROW_H} />;
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

window.ComparisonView = ComparisonView;
