// Tracker — W1 vs W2 Comparison View

function ComparisonView({ venueId, venueName, allowedVenueIds, onSelectVenue }) {
  const comparison = SEGMENT_DATA.getComparisonData(venueId, allowedVenueIds);
  const [chartMetric, setChartMetric] = React.useState('user_pct');

  if (!comparison || !comparison.segments) {
    return (
      <div className="card" style={{ padding: 40, textAlign: 'center', color: 'var(--ink-3)' }}>
        No comparison data available for this venue.
      </div>
    );
  }

  const segments = comparison.segments;
  const segOrder = [
    'DS1 - Experience Players', 'DS2 - Prize-Oriented Players',
    'Power Players', 'Social Squad', 'Holiday Heros', 'Casual',
    'Drifters', 'Budget', 'Dormant', 'Heavy Hitters', 'Prize Chasers', 'Outlier', 'Outliers'
  ];

  const orderedSegs = segOrder.filter(s => segments[s]).map(s => ({ name: s, ...segments[s] }));

  const REVERSED_SEGS = [
    'Drifters',
    'Budget',
    'Dormant',
    'Heavy Hitters',
    'Prize Chasers'
  ];

  const totals = {
    w1_users: orderedSegs.reduce((a, s) => a + s.w1_users, 0),
    w2_users: orderedSegs.reduce((a, s) => a + s.w2_users, 0),
    w1_revenue: orderedSegs.reduce((a, s) => a + s.w1_revenue, 0),
    w2_revenue: orderedSegs.reduce((a, s) => a + s.w2_revenue, 0),
    w1_profit: orderedSegs.reduce((a, s) => a + s.w1_profit, 0),
    w2_profit: orderedSegs.reduce((a, s) => a + s.w2_profit, 0),
    w1_redemption: orderedSegs.reduce((a, s) => a + s.w1_redemption, 0),
    w2_redemption: orderedSegs.reduce((a, s) => a + s.w2_redemption, 0),
    w1_vending: orderedSegs.reduce((a, s) => a + s.w1_vending, 0),
    w2_vending: orderedSegs.reduce((a, s) => a + s.w2_vending, 0),
    w1_liability: orderedSegs.reduce((a, s) => a + s.w1_liability, 0),
    w2_liability: orderedSegs.reduce((a, s) => a + s.w2_liability, 0),
    w1_total_cost: orderedSegs.reduce((a, s) => a + s.w1_total_cost, 0),
    w2_total_cost: orderedSegs.reduce((a, s) => a + s.w2_total_cost, 0),
  };

  const fmtrsTable = React.useMemo(() => {
    return {
      users: fmt.columnFormatter(orderedSegs.flatMap(s => [s.w1_users, s.w2_users]), 'num'),
      revenue: fmt.columnFormatter(orderedSegs.flatMap(s => [s.w1_revenue, s.w2_revenue]), 'idr'),
      profit: fmt.columnFormatter(orderedSegs.flatMap(s => [s.w1_profit, s.w2_profit]), 'idr'),
      cost: fmt.columnFormatter(orderedSegs.flatMap(s => [s.w1_total_cost, s.w2_total_cost]), 'idr'),
    };
  }, [orderedSegs]);

  const fUsr = (v) => fmtrsTable.users ? fmtrsTable.users(v) : fmt.num(v);
  const fRevTrk = (v) => fmtrsTable.revenue ? fmtrsTable.revenue(v) : fmt.idr(v);
  const fPrf = (v) => fmtrsTable.profit ? fmtrsTable.profit(v) : fmt.idr(v);
  const fCst = (v) => fmtrsTable.cost ? fmtrsTable.cost(v) : fmt.idr(v);

  const fmtrsCost = React.useMemo(() => {
    return {
      red: fmt.columnFormatter(orderedSegs.flatMap(s => [s.w1_redemption, s.w2_redemption]), 'idr'),
      vend: fmt.columnFormatter(orderedSegs.flatMap(s => [s.w1_vending, s.w2_vending]), 'idr'),
      liab: fmt.columnFormatter(orderedSegs.flatMap(s => [s.w1_liability, s.w2_liability]), 'idr'),
    };
  }, [orderedSegs]);

  const fRedCost = (v) => fmtrsCost.red ? fmtrsCost.red(v) : fmt.idr(v);
  const fVendCost = (v) => fmtrsCost.vend ? fmtrsCost.vend(v) : fmt.idr(v);
  const fLiabCost = (v) => fmtrsCost.liab ? fmtrsCost.liab(v) : fmt.idr(v);

  // Compute % for chart
  function getChartData(seg) {
    if (chartMetric === 'user_pct') {
      return {
        w1: totals.w1_users > 0 ? (seg.w1_users / totals.w1_users) * 100 : 0,
        w2: totals.w2_users > 0 ? (seg.w2_users / totals.w2_users) * 100 : 0,
        label: 'User %'
      };
    } else if (chartMetric === 'revenue_pct') {
      return {
        w1: totals.w1_revenue > 0 ? (seg.w1_revenue / totals.w1_revenue) * 100 : 0,
        w2: totals.w2_revenue > 0 ? (seg.w2_revenue / totals.w2_revenue) * 100 : 0,
        label: 'Revenue %'
      };
    } else {
      return {
        w1: seg.w1_profit_pct || 0,
        w2: seg.w2_profit_pct || 0,
        label: 'Profit %'
      };
    }
  }

  const chartData = orderedSegs.map(s => ({ name: s.name, ...getChartData(s) }));
  const chartMax = Math.max(...chartData.map(d => Math.max(Math.abs(d.w1), Math.abs(d.w2))), 1);

  function DeltaCell({ v1, v2, isCurrency, segmentName, formatter, isDetailed }) {
    const delta = v2 - v1;
    const isReversed = segmentName && REVERSED_SEGS.includes(segmentName);
    
    let color = 'var(--ink-3)';
    if (delta > 0) {
      color = isReversed ? '#dc2626' : '#059669';
    } else if (delta < 0) {
      color = isReversed ? '#059669' : '#dc2626';
    }
    
    const arrow = delta > 0 ? '↑' : delta < 0 ? '↓' : '—';
    const absD = Math.abs(delta);
    
    let formattedD = '';
    if (formatter) {
      formattedD = formatter(absD);
    } else if (isDetailed) {
      formattedD = isCurrency ? fmt.idr2(absD) : fmt.num2(absD);
    } else {
      formattedD = isCurrency ? fmt.idr(absD) : fmt.num(absD);
    }

    return (
      <span style={{ color, fontSize: 11, fontWeight: 600 }}>
        {arrow} {formattedD}
      </span>
    );
  }

  function PctDelta({ v1, v2, segmentName }) {
    const delta = v2 - v1;
    const isReversed = segmentName && REVERSED_SEGS.includes(segmentName);
    
    let color = 'var(--ink-3)';
    if (delta > 0) {
      color = isReversed ? '#dc2626' : '#059669';
    } else if (delta < 0) {
      color = isReversed ? '#059669' : '#dc2626';
    }
    
    const arrow = delta > 0 ? '↑' : delta < 0 ? '↓' : '';
    return (
      <span style={{ color, fontSize: 11, fontWeight: 600 }}>
        {arrow}{delta.toFixed(1)}pp
      </span>
    );
  }

  return (
    <div>
      <div className="section-head">
        <h2>Wave 1 vs Wave 2 Tracker</h2>
        <div className="meta">{venueName} — Key indicators side by side (W1: Jan–Dec 2025 vs W2: May 2025 – Apr 2026)</div>
      </div>

      {/* Summary KPIs */}
      <div className="grid grid-4" style={{ marginBottom: 24 }}>
        <div className="kpi">
          <div className="kpi-label">Total Users</div>
          <div className="kpi-value">{fmt.num2(totals.w2_users)}</div>
          <div className="kpi-foot"><DeltaCell v1={totals.w1_users} v2={totals.w2_users} isDetailed /> vs W1 ({fmt.num2(totals.w1_users)})</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Total Revenue</div>
          <div className="kpi-value">{fmt.idr2(totals.w2_revenue)}</div>
          <div className="kpi-foot"><DeltaCell v1={totals.w1_revenue} v2={totals.w2_revenue} isCurrency isDetailed /> vs W1</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Total Profit</div>
          <div className="kpi-value">{fmt.idr2(totals.w2_profit)}</div>
          <div className="kpi-foot"><DeltaCell v1={totals.w1_profit} v2={totals.w2_profit} isCurrency isDetailed /> vs W1</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Total Cost</div>
          <div className="kpi-value">{fmt.idr2(totals.w2_total_cost)}</div>
          <div className="kpi-foot"><DeltaCell v1={totals.w1_total_cost} v2={totals.w2_total_cost} isCurrency isDetailed /> vs W1</div>
        </div>
      </div>

      {/* Grouped bar chart — W1 vs W2 */}
      <div className="card seg-col-card" style={{ marginBottom: 16 }}>
        <div className="card-head">
          <div>
            <div className="card-title">Segment share comparison</div>
            <div className="card-sub">W1 (navy: Jan–Dec 2025) vs W2 (red: May 2025 – Apr 2026) — side by side</div>
          </div>
          <div className="card-controls">
            <div className="metric-toggle">
              <button className={chartMetric === 'user_pct' ? 'active' : ''} onClick={() => setChartMetric('user_pct')}>User %</button>
              <button className={chartMetric === 'revenue_pct' ? 'active' : ''} onClick={() => setChartMetric('revenue_pct')}>Revenue %</button>
              <button className={chartMetric === 'profit_pct' ? 'active' : ''} onClick={() => setChartMetric('profit_pct')}>Profit %</button>
            </div>
          </div>
        </div>
        <div style={{ padding: '8px 0 0 0', overflowX: 'auto' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 4, minWidth: orderedSegs.length * 110, height: 340, padding: '0 16px' }}>
            {chartData.map((d, i) => {
              const h1 = chartMax > 0 ? (Math.abs(d.w1) / chartMax) * 200 : 0;
              const h2 = chartMax > 0 ? (Math.abs(d.w2) / chartMax) * 200 : 0;
              const isNeg1 = d.w1 < 0;
              const isNeg2 = d.w2 < 0;
              const delta = d.w2 - d.w1;
              
              const isReversed = REVERSED_SEGS.includes(d.name);
              let deltaColor = '#6b7280';
              if (delta > 0) {
                deltaColor = isReversed ? '#dc2626' : '#059669';
              } else if (delta < 0) {
                deltaColor = isReversed ? '#059669' : '#dc2626';
              }
              const deltaArrow = delta > 0 ? '▲' : delta < 0 ? '▼' : '—';
              return (
                <div key={d.name} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', minWidth: 90 }}>
                  <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 230 }}>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                      <div style={{ fontSize: 11, fontWeight: 600, color: '#1a2a5e', marginBottom: 3, fontFamily: "'JetBrains Mono', monospace" }}>
                        {Math.abs(d.w1).toFixed(1)}%
                      </div>
                      <div style={{
                        width: 28, height: Math.max(h1, 2), borderRadius: '4px 4px 0 0',
                        background: isNeg1 ? 'rgba(26,42,94,0.3)' : '#1a2a5e',
                        border: isNeg1 ? '1px dashed #1a2a5e' : 'none'
                      }} />
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                      <div style={{ fontSize: 11, fontWeight: 600, color: '#e63329', marginBottom: 3, fontFamily: "'JetBrains Mono', monospace" }}>
                        {Math.abs(d.w2).toFixed(1)}%
                      </div>
                      <div style={{
                        width: 28, height: Math.max(h2, 2), borderRadius: '4px 4px 0 0',
                        background: isNeg2 ? 'rgba(230,51,41,0.3)' : '#e63329',
                        border: isNeg2 ? '1px dashed #e63329' : 'none'
                      }} />
                    </div>
                  </div>
                  {/* Delta indicator */}
                  <div style={{ fontSize: 11, fontWeight: 700, color: deltaColor, marginTop: 8, fontFamily: "'JetBrains Mono', monospace", textAlign: 'center' }}>
                    {deltaArrow} {Math.abs(delta).toFixed(1)}pp
                  </div>
                  {/* Full segment name */}
                  <div style={{ fontSize: 11, marginTop: 6, color: 'var(--ink-2)', textAlign: 'center', lineHeight: 1.3, fontWeight: 500, maxWidth: 100, wordWrap: 'break-word' }}>
                    {d.name}
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{ display: 'flex', gap: 20, justifyContent: 'center', padding: '12px 0 8px', fontSize: 11 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <div style={{ width: 14, height: 10, borderRadius: 2, background: '#1a2a5e' }} />
              <span>W1</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <div style={{ width: 14, height: 10, borderRadius: 2, background: '#e63329' }} />
              <span>W2</span>
            </div>
          </div>
        </div>
      </div>

      {/* Detailed table with % columns */}
      <div className="card seg-col-card">
        <div className="card-head">
          <div>
            <div className="card-title">Segment-level comparison</div>
            <div className="card-sub">W1 (Jan–Dec 2025) vs W2 (May 2025 – Apr 2026)</div>
          </div>
        </div>
        <div className="seg-chart-table-wrap" style={{ overflowX: 'auto' }}>
          <table className="seg-chart-table" style={{ whiteSpace: 'nowrap', fontSize: 12 }}>
            <thead>
              <tr>
                <th rowSpan="2" style={{ verticalAlign: 'bottom', position: 'sticky', left: 0, background: '#fff', zIndex: 2 }}>Segment</th>
                <th colSpan="5" style={{ textAlign: 'center', borderBottom: '2px solid var(--navy)', color: 'var(--navy)' }}>Users</th>
                <th colSpan="5" style={{ textAlign: 'center', borderBottom: '2px solid var(--gold)', color: 'var(--gold-dark)' }}>Revenue (IDR)</th>
                <th colSpan="3" style={{ textAlign: 'center', borderBottom: '2px solid #059669', color: '#059669' }}>Profit (IDR)</th>
                <th colSpan="2" style={{ textAlign: 'center', borderBottom: '2px solid var(--red)', color: 'var(--red)' }}>Profit %</th>
                <th colSpan="2" style={{ textAlign: 'center', borderBottom: '2px solid #9ca3af', color: '#6b7280' }}>Total Cost</th>
              </tr>
              <tr>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W1</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W2</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>Δ</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W1%</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W2%</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W1</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W2</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>Δ</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W1%</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W2%</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W1</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W2</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>Δ</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W1</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W2</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W1</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W2</th>
              </tr>
            </thead>
            <tbody>
              {orderedSegs.map(s => {
                const w1UserPct = totals.w1_users > 0 ? (s.w1_users / totals.w1_users * 100) : 0;
                const w2UserPct = totals.w2_users > 0 ? (s.w2_users / totals.w2_users * 100) : 0;
                const w1RevPct = totals.w1_revenue > 0 ? (s.w1_revenue / totals.w1_revenue * 100) : 0;
                const w2RevPct = totals.w2_revenue > 0 ? (s.w2_revenue / totals.w2_revenue * 100) : 0;
                return (
                  <tr key={s.name}>
                    <td style={{ position: 'sticky', left: 0, background: SEG_PASTEL_COLORS[s.name] || '#fff', zIndex: 1 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <div style={{ width: 4, height: 18, borderRadius: 2, background: SEG_COLORS[s.name] || '#ccc' }} />
                        <span style={{ fontWeight: 500 }}>{s.name}</span>
                      </div>
                    </td>
                    <td className="num">{fUsr(s.w1_users)}</td>
                    <td className="num">{fUsr(s.w2_users)}</td>
                    <td className="num"><DeltaCell v1={s.w1_users} v2={s.w2_users} segmentName={s.name} formatter={fmtrsTable.users} /></td>
                    <td className="num" style={{ color: '#6b7280' }}>{w1UserPct.toFixed(1)}%</td>
                    <td className="num" style={{ color: '#6b7280' }}>{w2UserPct.toFixed(1)}%</td>
                    <td className="num">{fRevTrk(s.w1_revenue)}</td>
                    <td className="num">{fRevTrk(s.w2_revenue)}</td>
                    <td className="num"><DeltaCell v1={s.w1_revenue} v2={s.w2_revenue} isCurrency segmentName={s.name} formatter={fmtrsTable.revenue} /></td>
                    <td className="num" style={{ color: '#6b7280' }}>{w1RevPct.toFixed(1)}%</td>
                    <td className="num" style={{ color: '#6b7280' }}>{w2RevPct.toFixed(1)}%</td>
                    <td className="num">{fPrf(s.w1_profit)}</td>
                    <td className="num">{fPrf(s.w2_profit)}</td>
                    <td className="num"><DeltaCell v1={s.w1_profit} v2={s.w2_profit} isCurrency segmentName={s.name} formatter={fmtrsTable.profit} /></td>
                    <td className="num">{fmt.pctRaw(s.w1_profit_pct)}</td>
                    <td className="num">{fmt.pctRaw(s.w2_profit_pct)}</td>
                    <td className="num">{fCst(s.w1_total_cost)}</td>
                    <td className="num">{fCst(s.w2_total_cost)}</td>
                  </tr>
                );
              })}
              <tr className="grand-total-row" style={{ fontWeight: 700, borderTop: '2px solid var(--ink-1)' }}>
                <td style={{ position: 'sticky', left: 0, background: '#f3f4f6', zIndex: 1 }}><strong>TOTAL</strong></td>
                <td className="num"><strong>{fUsr(totals.w1_users)}</strong></td>
                <td className="num"><strong>{fUsr(totals.w2_users)}</strong></td>
                <td className="num"><DeltaCell v1={totals.w1_users} v2={totals.w2_users} formatter={fmtrsTable.users} /></td>
                <td className="num"><strong>100%</strong></td>
                <td className="num"><strong>100%</strong></td>
                <td className="num"><strong>{fRevTrk(totals.w1_revenue)}</strong></td>
                <td className="num"><strong>{fRevTrk(totals.w2_revenue)}</strong></td>
                <td className="num"><DeltaCell v1={totals.w1_revenue} v2={totals.w2_revenue} isCurrency formatter={fmtrsTable.revenue} /></td>
                <td className="num"><strong>100%</strong></td>
                <td className="num"><strong>100%</strong></td>
                <td className="num"><strong>{fPrf(totals.w1_profit)}</strong></td>
                <td className="num"><strong>{fPrf(totals.w2_profit)}</strong></td>
                <td className="num"><DeltaCell v1={totals.w1_profit} v2={totals.w2_profit} isCurrency formatter={fmtrsTable.profit} /></td>
                <td className="num"><strong>{totals.w1_revenue > 0 ? fmt.pctRaw(totals.w1_profit / totals.w1_revenue * 100) : '—'}</strong></td>
                <td className="num"><strong>{totals.w2_revenue > 0 ? fmt.pctRaw(totals.w2_profit / totals.w2_revenue * 100) : '—'}</strong></td>
                <td className="num"><strong>{fCst(totals.w1_total_cost)}</strong></td>
                <td className="num"><strong>{fCst(totals.w2_total_cost)}</strong></td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      {/* Cost breakdown */}
      <div className="card seg-col-card" style={{ marginTop: 16 }}>
        <div className="card-head">
          <div>
            <div className="card-title">Cost breakdown by segment</div>
            <div className="card-sub">Redemption, Vending Cost, Liability</div>
          </div>
        </div>
        <div className="seg-chart-table-wrap" style={{ overflowX: 'auto' }}>
          <table className="seg-chart-table" style={{ whiteSpace: 'nowrap', fontSize: 12 }}>
            <thead>
              <tr>
                <th style={{ position: 'sticky', left: 0, background: '#fff', zIndex: 2 }}>Segment</th>
                <th colSpan="3" style={{ textAlign: 'center' }}>Redemption</th>
                <th colSpan="3" style={{ textAlign: 'center' }}>Vending Cost</th>
                <th colSpan="3" style={{ textAlign: 'center' }}>Liability</th>
              </tr>
              <tr>
                <th style={{ position: 'sticky', left: 0, background: '#fff', zIndex: 2 }}></th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W1</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W2</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>Δ</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W1</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W2</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>Δ</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W1</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>W2</th>
                <th style={{ textAlign: 'right', fontSize: 10 }}>Δ</th>
              </tr>
            </thead>
            <tbody>
              {orderedSegs.map(s => (
                <tr key={s.name}>
                  <td style={{ position: 'sticky', left: 0, background: SEG_PASTEL_COLORS[s.name] || '#fff', zIndex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <div style={{ width: 4, height: 18, borderRadius: 2, background: SEG_COLORS[s.name] || '#ccc' }} />
                      <span style={{ fontWeight: 500 }}>{s.name}</span>
                    </div>
                  </td>
                  <td className="num">{fRedCost(s.w1_redemption)}</td>
                  <td className="num">{fRedCost(s.w2_redemption)}</td>
                  <td className="num"><DeltaCell v1={s.w1_redemption} v2={s.w2_redemption} isCurrency formatter={fmtrsCost.red} /></td>
                  <td className="num">{fVendCost(s.w1_vending)}</td>
                  <td className="num">{fVendCost(s.w2_vending)}</td>
                  <td className="num"><DeltaCell v1={s.w1_vending} v2={s.w2_vending} isCurrency formatter={fmtrsCost.vend} /></td>
                  <td className="num">{fLiabCost(s.w1_liability)}</td>
                  <td className="num">{fLiabCost(s.w2_liability)}</td>
                  <td className="num"><DeltaCell v1={s.w1_liability} v2={s.w2_liability} isCurrency formatter={fmtrsCost.liab} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* 2x2 Venue Portfolio Shift Matrix */}
      {(() => {
        if (!allowedVenueIds || allowedVenueIds.filter(id => id !== 'ALL').length <= 1) return null;
        
        const individualIds = allowedVenueIds.filter(id => id !== 'ALL');
        const greenSegKeys = ['DS1 - Experience Players', 'DS2 - Prize-Oriented Players', 'Power Players', 'Social Squad', 'Holiday Heros'];
        const redSegKeys = ['Casual', 'Drifters', 'Dormant', 'Budget', 'Heavy Hitters', 'Prize Chasers'];

        const venuesList = individualIds.map(vId => {
          const comp = window.COMPARISON_DATA && window.COMPARISON_DATA[vId];
          if (!comp || !comp.segments) return null;

          // Sum green segments
          let w1_green = 0, w2_green = 0;
          greenSegKeys.forEach(k => {
            const s = comp.segments[k];
            if (s) {
              w1_green += (s.w1_users || 0);
              w2_green += (s.w2_users || 0);
            }
          });

          // Sum red segments
          let w1_red = 0, w2_red = 0;
          redSegKeys.forEach(k => {
            const s = comp.segments[k];
            if (s) {
              w1_red += (s.w1_users || 0);
              w2_red += (s.w2_users || 0);
            }
          });

          // Sum total revenue
          let w1_rev = 0, w2_rev = 0;
          Object.keys(comp.segments).forEach(k => {
            const s = comp.segments[k];
            if (s) {
              w1_rev += (s.w1_revenue || 0);
              w2_rev += (s.w2_revenue || 0);
            }
          });

          const greenGrowth = w1_green > 0 ? ((w2_green - w1_green) / w1_green) * 100 : 0;
          const redGrowth = w1_red > 0 ? ((w2_red - w1_red) / w1_red) * 100 : 0;
          const revGrowth = w1_rev > 0 ? ((w2_rev - w1_rev) / w1_rev) * 100 : 0;

          const name = window.VENUE_METADATA[vId]?.name || `Venue ${vId}`;

          return {
            id: vId,
            name,
            greenGrowth,
            redGrowth,
            revGrowth
          };
        }).filter(Boolean);

        // Group into 4 quadrants
        const q1 = []; // Expanding (Green +, Red +)
        const q2 = []; // Pivot (Green +, Red <= 0)
        const q3 = []; // Contraction (Green <= 0, Red <= 0)
        const q4 = []; // Dilution Risk (Green <= 0, Red +)

        venuesList.forEach(v => {
          if (v.greenGrowth > 0 && v.redGrowth > 0) {
            q1.push(v);
          } else if (v.greenGrowth > 0 && v.redGrowth <= 0) {
            q2.push(v);
          } else if (v.greenGrowth <= 0 && v.redGrowth <= 0) {
            q3.push(v);
          } else if (v.greenGrowth <= 0 && v.redGrowth > 0) {
            q4.push(v);
          }
        });

        // Sort by absolute revenue growth descending
        const sortByRev = (arr) => arr.sort((a, b) => b.revGrowth - a.revGrowth);
        sortByRev(q1);
        sortByRev(q2);
        sortByRev(q3);
        sortByRev(q4);

        // Render Quadrant Card
        const QuadrantCard = ({ list, title, badgeColor, borderColor, description, emptyMsg, onSelectVenue }) => {
          const [expanded, setExpanded] = React.useState(false);
          const visibleList = expanded ? list : list.slice(0, 5);

          return (
            <div className="card" style={{ display: 'flex', flexDirection: 'column', border: `2px solid ${borderColor}`, borderRadius: '12px', padding: '16px 20px', background: '#fff', boxShadow: 'var(--shadow-sm)' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12, flexWrap: 'wrap', gap: 8 }}>
                <div>
                  <div style={{ font: "700 14px 'Space Grotesk', sans-serif", color: badgeColor, display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ width: 6, height: 14, background: badgeColor, borderRadius: 2 }} />
                    {title}
                  </div>
                  <div style={{ fontSize: '11px', color: 'var(--ink-3)', marginTop: 4, fontWeight: 500 }}>{description}</div>
                </div>
                <span style={{ fontSize: '11px', fontWeight: 700, background: 'var(--navy-50)', color: 'var(--navy)', padding: '2px 8px', borderRadius: 10 }}>
                  {list.length} venues
                </span>
              </div>
              
              <div style={{ flex: 1, overflowX: 'auto' }}>
                {visibleList.length > 0 ? (
                  <table className="seg-chart-table" style={{ fontSize: '11px', whiteSpace: 'nowrap' }}>
                    <thead>
                      <tr>
                        <th>Venue</th>
                        <th style={{ textAlign: 'right' }}>Green Growth</th>
                        <th style={{ textAlign: 'right' }}>Yellow & Red Growth</th>
                        <th style={{ textAlign: 'right' }}>Total Revenue Growth</th>
                      </tr>
                    </thead>
                    <tbody>
                      {visibleList.map(v => {
                        const revColor = v.revGrowth > 0 ? '#059669' : v.revGrowth < 0 ? '#dc2626' : 'var(--ink-2)';
                        const greenColor = v.greenGrowth > 0 ? '#059669' : v.greenGrowth < 0 ? '#dc2626' : 'var(--ink-3)';
                        const redColor = v.redGrowth > 0 ? '#dc2626' : v.redGrowth < 0 ? '#059669' : 'var(--ink-3)'; // Red growth is bad, so green if negative, red if positive
                        
                        return (
                          <tr key={v.id} onClick={() => onSelectVenue && onSelectVenue(v.id)} style={{ borderBottom: '1px solid var(--line-2)', cursor: onSelectVenue ? 'pointer' : 'default' }}>
                            <td style={{ padding: '8px 4px', maxWidth: 160, overflow: 'hidden', textOverflow: 'ellipsis' }}>
                              <div style={{ fontWeight: 600, color: 'var(--navy)' }}>{v.name}</div>
                              <div style={{ fontSize: '10px', color: 'var(--ink-3)' }}>ID: {v.id}</div>
                            </td>
                            <td className="num" style={{ color: greenColor, fontWeight: 600 }}>
                              {v.greenGrowth > 0 ? '▲' : v.greenGrowth < 0 ? '▼' : ''} {Math.abs(v.greenGrowth).toFixed(1)}%
                            </td>
                            <td className="num" style={{ color: redColor, fontWeight: 600 }}>
                              {v.redGrowth > 0 ? '▲' : v.redGrowth < 0 ? '▼' : ''} {Math.abs(v.redGrowth).toFixed(1)}%
                            </td>
                            <td className="num" style={{ padding: '8px 4px' }}>
                              <span style={{ background: v.revGrowth > 0 ? '#ecfdf5' : v.revGrowth < 0 ? '#fef2f2' : 'var(--navy-50)', color: revColor, fontWeight: 700, padding: '2px 6px', borderRadius: 4, fontSize: '10.5px' }}>
                                {v.revGrowth > 0 ? '▲' : v.revGrowth < 0 ? '▼' : ''} {Math.abs(v.revGrowth).toFixed(1)}%
                              </span>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                ) : (
                  <div style={{ textAlign: 'center', padding: '40px 0', color: 'var(--ink-4)', fontSize: '12px', fontStyle: 'italic' }}>
                    {emptyMsg}
                  </div>
                )}
              </div>

              {list.length > 5 && (
                <div style={{ display: 'flex', justifyContent: 'center', marginTop: 12 }}>
                  <button 
                    className="logout-btn" 
                    style={{ background: 'var(--navy-50)', color: 'var(--navy)', border: '1px solid var(--line)', padding: '4px 12px', fontSize: '11px', fontWeight: 600 }}
                    onClick={() => setExpanded(!expanded)}
                  >
                    {expanded ? 'Show Less' : `Show More (+${list.length - 5})`}
                  </button>
                </div>
              )}
            </div>
          );
        };

        return (
          <div style={{ marginTop: 24 }}>
            <div className="section-head">
              <h2>Venue Portfolio Shift Matrix</h2>
              <div className="meta">Analysing Green User Growth (Desirable) vs Yellow & Red User Growth (Undesirable) across individual venues</div>
            </div>

            <div className="grid grid-2" style={{ gap: 20 }}>
              {/* Quadrant II: Premium Restructure */}
              <QuadrantCard 
                onSelectVenue={onSelectVenue}
                list={q2} 
                title="Premium Restructure (Green ▲, Yellow & Red ▼)" 
                badgeColor="#047857" 
                borderColor="#a7f3d0" 
                description="Losing low-value users while gaining loyal, high-value ones. Highest-efficiency restructure."
                emptyMsg="No venues are currently undergoing premium restructures."
              />

              {/* Quadrant I: General Expansion */}
              <QuadrantCard 
                onSelectVenue={onSelectVenue}
                list={q1} 
                title="Double Expansion (Green ▲, Yellow & Red ▲)" 
                badgeColor="#1d4ed8" 
                borderColor="#bfdbfe" 
                description="Gaining footprint in both premium and casual segments. Strong overall expansion."
                emptyMsg="No venues are undergoing double segment expansion."
              />

              {/* Quadrant IV: Low-Value Dilution */}
              <QuadrantCard 
                onSelectVenue={onSelectVenue}
                list={q4} 
                title="Portfolio Dilution (Green ▼, Yellow & Red ▲)" 
                badgeColor="#dc2626" 
                borderColor="#fca5a5" 
                description="Losing loyal VIPs while being flooded with casual/low-value users. High margin risk."
                emptyMsg="No venues are showing low-value portfolio dilution risk."
              />

              {/* Quadrant III: Contraction */}
              <QuadrantCard 
                onSelectVenue={onSelectVenue}
                list={q3} 
                title="General Contraction (Green ▼, Yellow & Red ▼)" 
                badgeColor="#4b5563" 
                borderColor="#e5e7eb" 
                description="Shrinking guest base across all categories. High operational priority."
                emptyMsg="No venues are currently in contraction."
              />
            </div>
          </div>
        );
      })()}
    </div>
  );
}

window.ComparisonView = ComparisonView;
