/* PAGE 3 — Performance by Metric
   RC-PAGE-021: Compare chart limited to 3 metrics max
   RC-PAGE-022: Monthly trend matrix (horizontally scanable) */

const PageByMetric = ({ reportType, comparison, changeMode, granularity, viewerDisabled }) => {
  const defaultCompare = reportType.compareRoster.slice(0, 3);
  const [compareMetrics, setCompareMetrics] = React.useState(defaultCompare);
  const [showPicker, setShowPicker] = React.useState(false);
  const [dragIdx, setDragIdx] = React.useState(null);
  const [hoverIdx, setHoverIdx] = React.useState(null);

  const toggleMetric = (m) => {
    if (compareMetrics.includes(m)) {
      if (compareMetrics.length > 1) setCompareMetrics(compareMetrics.filter(x => x !== m));
    } else {
      if (compareMetrics.length < 3) setCompareMetrics([...compareMetrics, m]);
    }
  };
  const reorderChip = (from, to) => {
    if (from === to || from == null || to == null) return;
    const next = [...compareMetrics];
    const [moved] = next.splice(from, 1);
    next.splice(to, 0, moved);
    setCompareMetrics(next);
  };

  return (
    <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Compare chart card */}
      <Card>
        <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--rc-border-soft)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <h3 style={{ margin: 0, fontSize: 13, fontWeight: 600, fontFamily: 'Poppins' }}>Metric Comparison</h3>
            <span style={{ fontSize: 11, color: 'var(--rc-text-sub)' }}>Up to 3 metrics · {compareMetrics.length}/3 selected</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', position: 'relative' }}>
            {compareMetrics.map((m, i) => {
              const isTarget = hoverIdx === i && dragIdx != null && dragIdx !== i;
              const insertBefore = isTarget && dragIdx > i;
              const insertAfter = isTarget && dragIdx < i;
              return (
              <span key={m}
                draggable={!viewerDisabled}
                onDragStart={(e) => { if (viewerDisabled) return; setDragIdx(i); e.dataTransfer.effectAllowed = 'move'; }}
                onDragOver={(e) => { if (dragIdx == null) return; e.preventDefault(); setHoverIdx(i); }}
                onDragLeave={() => { if (hoverIdx === i) setHoverIdx(null); }}
                onDrop={(e) => { e.preventDefault(); reorderChip(dragIdx, i); setDragIdx(null); setHoverIdx(null); }}
                onDragEnd={() => { setDragIdx(null); setHoverIdx(null); }}
                style={{
                  position: 'relative',
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  padding: '4px 8px 4px 6px',
                  background: isTarget
                    ? 'color-mix(in srgb, var(--rc-chart-1) 10%, var(--rc-subtle))'
                    : 'var(--rc-subtle)',
                  border: `1px ${isTarget ? 'dashed' : 'solid'} var(--rc-border)`,
                  borderRadius: 999,
                  fontSize: 11, fontWeight: 500, color: 'var(--rc-text)',
                  cursor: viewerDisabled ? 'default' : (dragIdx === i ? 'grabbing' : 'grab'),
                  opacity: dragIdx === i ? 0.35 : 1,
                  transform: dragIdx === i ? 'scale(0.96)' : 'scale(1)',
                  transition: 'background 0.12s, border-color 0.12s, opacity 0.12s, transform 0.12s',
                }}>
                {insertBefore && (
                  <span style={{
                    position: 'absolute', left: -5, top: 2, bottom: 2, width: 3,
                    background: 'var(--rc-chart-1)', borderRadius: 2, zIndex: 2,
                  }} />
                )}
                {insertAfter && (
                  <span style={{
                    position: 'absolute', right: -5, top: 2, bottom: 2, width: 3,
                    background: 'var(--rc-chart-1)', borderRadius: 2, zIndex: 2,
                  }} />
                )}
                <span style={{ width: 8, height: 8, borderRadius: 2, background: CHART_PALETTE[i] }} />
                {METRIC_LABELS[m]}
                {compareMetrics.length > 1 && (
                  <button onClick={() => toggleMetric(m)} style={{
                    border: 0, background: 'transparent', cursor: 'pointer',
                    color: 'var(--rc-text-mute)', padding: 0, display: 'inline-flex',
                  }}><Icon name="x" size={10} /></button>
                )}
              </span>
            );})}
            {compareMetrics.length < 3 && (
              <button onClick={() => setShowPicker(!showPicker)} style={{
                display: 'inline-flex', alignItems: 'center', gap: 4,
                padding: '4px 8px', background: 'var(--rc-card)',
                border: '1px dashed var(--rc-border)', borderRadius: 999,
                fontSize: 11, color: 'var(--rc-text-sub)', cursor: 'pointer', fontFamily: 'inherit',
              }}>
                <Icon name="plus" size={10} /> Add metric
              </button>
            )}
            {showPicker && (
              <Dropdown onClose={() => setShowPicker(false)} align="right" width={200}>
                {reportType.compareRoster.filter(m => !compareMetrics.includes(m)).map(m => (
                  <DropItem key={m} onClick={() => { toggleMetric(m); setShowPicker(false); }}>
                    {METRIC_LABELS[m]}
                  </DropItem>
                ))}
              </Dropdown>
            )}
          </div>
        </div>
        <div style={{ padding: '14px 14px 12px' }}>
          <CompareMetricsChart metrics={compareMetrics} height={240} />
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 40px 0', fontSize: 9, color: 'var(--rc-text-mute)' }}>
            {['Apr 01','Apr 05','Apr 09','Apr 13','Apr 17','Apr 21','Apr 25','Apr 29'].map(d => <span key={d}>{d}</span>)}
          </div>
        </div>
      </Card>

      {/* Monthly trend matrix — RC-PAGE-022 */}
      <Card>
        <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--rc-border-soft)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <h3 style={{ margin: 0, fontSize: 13, fontWeight: 600, fontFamily: 'Poppins' }}>Monthly Trend Matrix</h3>
            <span style={{ fontSize: 11, color: 'var(--rc-text-sub)' }}>Trailing 12 months · one row per metric</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Pill tone="default" size="sm">
              <Icon name="calendar" size={11} /> <span style={{ marginLeft: 4 }}>May 2025 → Apr 2026</span>
            </Pill>
            <IconBtn name="download" title="Export" />
          </div>
        </div>
        <TrendMatrix metrics={reportType.trendMatrixRows || reportType.scorecards} viewerDisabled={viewerDisabled} />
      </Card>
    </div>
  );
};

const CHART_PALETTE = ['var(--rc-chart-1)', 'var(--rc-chart-2)', 'var(--rc-chart-3)'];

const CompareMetricsChart = ({ metrics, height }) => {
  const W = 900, H = height, padL = 40, padR = 16, padT = 12, padB = 18;
  const series = metrics.map((m, i) => {
    const values = window.series(m, 30);
    const min = Math.min(...values), max = Math.max(...values);
    const range = max - min || 1;
    // normalize each series to 0..1 then scale
    const pts = values.map((v, idx) => {
      const x = padL + (idx / (values.length - 1)) * (W - padL - padR);
      const y = padT + (1 - (v - min) / range) * (H - padT - padB);
      return [x, y];
    });
    return { metric: m, color: CHART_PALETTE[i], pts };
  });

  const toPath = (pts) => {
    if (pts.length === 0) return '';
    let d = `M ${pts[0][0]} ${pts[0][1]}`;
    for (let i = 1; i < pts.length; i++) {
      const [x0, y0] = pts[i - 1], [x1, y1] = pts[i];
      const cx = (x0 + x1) / 2;
      d += ` C ${cx} ${y0}, ${cx} ${y1}, ${x1} ${y1}`;
    }
    return d;
  };

  return (
    <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ display: 'block' }} preserveAspectRatio="none">
      {/* gridlines */}
      {[0.25, 0.5, 0.75].map(r => (
        <line key={r} x1={padL} x2={W - padR} y1={padT + r * (H - padT - padB)} y2={padT + r * (H - padT - padB)}
          stroke="var(--rc-border-soft)" strokeDasharray="3 4" />
      ))}
      <line x1={padL} x2={W - padR} y1={H - padB} y2={H - padB} stroke="var(--rc-border)" />
      {/* Y axis labels (left) for first series only */}
      {[0, 0.5, 1].map(r => (
        <text key={r} x={padL - 6} y={padT + (1 - r) * (H - padT - padB) + 3} textAnchor="end"
          fontSize="9" fill="var(--rc-text-mute)" fontFamily="Inter">
          {(r * 100).toFixed(0)}
        </text>
      ))}
      {/* lines */}
      {series.map((s) => (
        <path key={s.metric} d={toPath(s.pts)} fill="none" stroke={s.color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      ))}
    </svg>
  );
};

/* RC-PAGE-022 trend matrix — one row per metric, 12 monthly columns.
   Column order: NEWEST → OLDEST (left → right) so the most recent month
   sits adjacent to Latest / vs PY. */
const MONTHS_12 = ['Apr','Mar','Feb','Jan','Dec','Nov','Oct','Sep','Aug','Jul','Jun','May'];
// year-suffix per month (Apr 26 .. May 25)
const MONTH_YEAR = { Apr:'26', Mar:'26', Feb:'26', Jan:'26',
                     Dec:'25', Nov:'25', Oct:'25', Sep:'25',
                     Aug:'25', Jul:'25', Jun:'25', May:'25' };

const TrendMatrix = ({ metrics: metricsProp, viewerDisabled }) => {
  const [metrics, setMetrics] = React.useState(metricsProp);
  React.useEffect(() => { setMetrics(metricsProp); }, [metricsProp.join('|')]);

  const [dragIdx, setDragIdx] = React.useState(null);
  const [hoverIdx, setHoverIdx] = React.useState(null);
  // RC-RPT-007 — change-display mode applies to each month cell (abs change vs same month prior year)
  const [matrixChangeMode, setMatrixChangeMode] = React.useState('pct'); // 'pct' | 'net' | 'off'
  const reorder = (from, to) => {
    if (from === to || from == null || to == null) return;
    const next = [...metrics];
    const [moved] = next.splice(from, 1);
    next.splice(to, 0, moved);
    setMetrics(next);
  };
  return (
    <div style={{ overflow: 'auto' }}>
      {/* RC-RPT-007 — change-display toggle for month cells */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'flex-end',
        gap: 6, padding: '0 0 8px',
      }}>
        <span style={{ fontSize: 10.5, color: 'var(--rc-text-mute)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
          Per-month change:
        </span>
        <Segmented
          tabs={[
            { value: 'pct', label: '%' },
            { value: 'net', label: 'Net' },
            { value: 'off', label: 'Off' },
          ]}
          active={matrixChangeMode} onChange={setMatrixChangeMode} size="sm" />
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11, fontFamily: 'Inter', fontVariantNumeric: 'tabular-nums' }}>
        <thead>
          <tr>
            <th style={{ ...matHead, textAlign: 'left', minWidth: 180 }}>Metric</th>
            <th style={{ ...matHead, textAlign: 'right', minWidth: 80 }}>Latest</th>
            <th style={{ ...matHead, textAlign: 'right', minWidth: 64 }}>vs PY</th>
            <th style={{ ...matHead, textAlign: 'left', minWidth: 110 }}>12-mo trend</th>
            {MONTHS_12.map(m => (
              <th key={m} style={{ ...matHead, textAlign: 'right', minWidth: 60 }}>
                {m} {MONTH_YEAR[m]}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {metrics.slice(0, 11).map((m, ri) => {
            // Generate 12 chronological months (index 0 = oldest, 11 = newest),
            // then reverse to match column order (newest at left).
            const chronological = Array.from({ length: 12 }, (_, i) => {
              const base = BASELINES[m] ?? 100;
              const factor = 0.7 + Math.sin((i + ri * 1.3) * 0.6) * 0.25 + i * 0.015;
              return base * factor;
            });
            const monthly = [...chronological].reverse(); // newest → oldest
            const latest = chronological[chronological.length - 1];
            const prior  = chronological[0];
            const dir = changeDirection(m, latest - prior);
            return (
              <tr key={m}
                draggable={!viewerDisabled}
                onDragStart={(e) => { if (viewerDisabled) return; setDragIdx(ri); e.dataTransfer.effectAllowed = 'move'; }}
                onDragOver={(e) => { if (dragIdx == null) return; e.preventDefault(); setHoverIdx(ri); }}
                onDragLeave={() => { if (hoverIdx === ri) setHoverIdx(null); }}
                onDrop={(e) => { e.preventDefault(); reorder(dragIdx, ri); setDragIdx(null); setHoverIdx(null); }}
                onDragEnd={() => { setDragIdx(null); setHoverIdx(null); }}
                style={{
                  borderTop: hoverIdx === ri && dragIdx != null && dragIdx > ri
                    ? '3px solid var(--rc-chart-1)'
                    : '1px solid var(--rc-border-soft)',
                  borderBottom: hoverIdx === ri && dragIdx != null && dragIdx < ri
                    ? '3px solid var(--rc-chart-1)'
                    : undefined,
                  opacity: dragIdx === ri ? 0.35 : 1,
                  transform: dragIdx === ri ? 'scale(0.995)' : 'scale(1)',
                  cursor: viewerDisabled ? 'default' : (dragIdx === ri ? 'grabbing' : 'grab'),
                  background: hoverIdx === ri && dragIdx != null && dragIdx !== ri
                    ? 'color-mix(in srgb, var(--rc-chart-1) 4%, transparent)' : 'transparent',
                  transition: 'opacity 0.12s, transform 0.12s',
                }}>
                <td style={{ ...matCell, textAlign: 'left', color: 'var(--rc-text)', fontWeight: 500 }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                    {!viewerDisabled && <Icon name="drag" size={11} color="var(--rc-text-mute)" />}
                    {METRIC_LABELS[m]}
                  </span>
                </td>
                <td style={{ ...matCell, textAlign: 'right', color: 'var(--rc-text)' }}>{formatValue(m, latest)}</td>
                <td style={{ ...matCell, textAlign: 'right' }}>
                  <Delta value={formatChange(m, latest, prior, 'pct')} direction={dir} size={10} />
                </td>
                <td style={{ ...matCell, textAlign: 'left' }}>
                  <Sparkline values={chronological} height={20} width={96} direction={dir} />
                </td>
                {monthly.map((v, mi) => {
                  const pctOfMax = v / Math.max(...monthly);
                  // monthly is newest→oldest: compute change vs the previous (older) month for per-cell delta.
                  const olderIdx = mi + 1;
                  const olderV = olderIdx < monthly.length ? monthly[olderIdx] : null;
                  const changeStr = (matrixChangeMode !== 'off' && olderV != null)
                    ? formatChange(m, v, olderV, matrixChangeMode)
                    : null;
                  const cellDir = olderV != null ? changeDirection(m, v - olderV) : 'neutral';
                  return (
                    <td key={mi} style={{
                      ...matCell, textAlign: 'right',
                      position: 'relative', lineHeight: 1.25,
                    }}>
                      <div style={{
                        position: 'absolute', inset: '2px 4px', borderRadius: 3,
                        background: `color-mix(in srgb, var(--rc-chart-1) ${Math.round(pctOfMax * 14)}%, transparent)`,
                      }} />
                      <div style={{ position: 'relative', color: 'var(--rc-text)' }}>
                        {formatValue(m, v, { compact: true })}
                      </div>
                      {changeStr && (
                        <div style={{
                          position: 'relative', fontSize: 9, marginTop: 1,
                          color: cellDir === 'good' ? 'var(--rc-green-ink)'
                            : cellDir === 'bad' ? 'var(--rc-negative)'
                            : 'var(--rc-text-mute)',
                          fontWeight: 500,
                        }}>{changeStr}</div>
                      )}
                    </td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

const matHead = { padding: '10px 10px', fontSize: 10, fontWeight: 500, color: 'var(--rc-text-sub)',
  background: 'var(--rc-subtle)', textTransform: 'uppercase', letterSpacing: '0.04em',
  borderBottom: '1px solid var(--rc-border)', whiteSpace: 'nowrap', position: 'sticky', top: 0 };
const matCell = { padding: '8px 10px', whiteSpace: 'nowrap' };

Object.assign(window, { PageByMetric, CompareMetricsChart, TrendMatrix, CHART_PALETTE });
