/* global React, Recharts */
(function () {
const { useState, useMemo, useEffect, useRef } = React;
const {
  LineChart, Line, AreaChart, Area, BarChart, Bar, ComposedChart,
  PieChart, Pie, Cell,
  XAxis, YAxis, CartesianGrid, Tooltip, Legend, ReferenceLine,
  ResponsiveContainer,
} = Recharts;

const D = window.YUNO_DATA;

const C = {
  blue: '#3E4FE0', blue700: '#262F89', blue300: '#8F9AEA', blue100: '#DADEF8', blue50: '#EEF0FC',
  green: '#E0ED80', greenDark: '#A7B348',
  black: '#282A30', n400: '#8E93A8', n300: '#BDC1D3', n200: '#D9DCE8', n100: '#EFF1F6', n50: '#F7F8FB',
  good: '#2BA971', warn: '#E0A020', bad: '#D8434B',
  lilac: '#E8EAF5',
};
const REGION_COLOR = {
  LATAM: '#3E4FE0', EUROPE: '#262F89', APAC: '#8F9AEA', NA: '#A7B348', MENA: '#E0A020',
};

function CustomTooltip({ active, payload, label, format }) {
  if (!active || !payload || !payload.length) return null;
  return (
    <div className="tt">
      <div style={{ fontWeight: 700, marginBottom: 4 }}>{label}</div>
      {payload.map((p, i) => (
        <div key={i} className="tt-row">
          <span className="tt-label" style={{ color: p.color }}>● {p.name}</span>
          <span className="tt-val">{format ? D.fmt(p.value, format) : p.value}</span>
        </div>
      ))}
    </div>
  );
}

// Determine which regions a KPI applies to given filters
// region filter wins; if empty but owner filter is set, derive from owner
function effectiveRegions(filters) {
  if (filters.region && filters.region.length > 0) return filters.region;
  if (filters.owner && filters.owner.length > 0) {
    const set = new Set();
    filters.owner.forEach(o => (D.OWNER_REGIONS[o] || D.REGIONS).forEach(r => set.add(r)));
    return Array.from(set);
  }
  return D.REGIONS;
}

// Vertical mix → scaling factor. When filtering to verticals, we scale $-denominated
// metrics by the fraction of total mix they represent; rate metrics get a small
// additive perf offset from VERTICAL_PERF.
function verticalAggregate(filters) {
  const v = filters.vertical || [];
  if (!v.length) return { fraction: 1, rateOffset: 0 };
  let fraction = 0, rateSum = 0;
  v.forEach(name => {
    fraction += D.VERTICAL_MIX[name] || 0;
    rateSum += (D.VERTICAL_PERF[name]?.rateBoost || 0);
  });
  return { fraction: Math.max(0.01, fraction), rateOffset: rateSum / v.length };
}

// Compute filtered actual/target for a KPI
function computeFiltered(kpi, view, filters, kind /* 'actual' | 'target' */) {
  const regions = effectiveRegions(filters);
  const isAllRegions = regions.length === D.REGIONS.length;
  const targetField = view === 'qtd' ? 'q2Target' : 'q4Target';
  const actualField = view === 'qtd' ? 'q2Progress' : 'q1Actual';

  // Region-aware aggregation
  let actual = 0, target = 0;
  if (kpi.byRegion) {
    if (isAllRegions) {
      actual = view === 'qtd' ? (kpi.q2Progress != null ? kpi.q2Progress : kpi.q1Actual) : kpi.q1Actual + (kpi.q2Progress || 0);
      target = kpi[targetField];
    } else {
      let n = 0;
      for (const r of regions) {
        const row = kpi.byRegion[r];
        if (!row) continue;
        const a = row[actualField] != null ? row[actualField] : row.q1Actual;
        const t = row[targetField];
        // For rate metrics (pct, months, hours, score), average. For sums, sum.
        if (kpi.format === 'pct' || kpi.format === 'months' || kpi.format === 'days' || kpi.format === 'hours' || kpi.format === 'score10') {
          actual += a; target += t; n++;
        } else {
          actual += a; target += t;
        }
      }
      if ((kpi.format === 'pct' || kpi.format === 'months' || kpi.format === 'days' || kpi.format === 'hours' || kpi.format === 'score10') && n > 0) {
        actual /= n; target /= n;
      }
    }
  } else {
    actual = view === 'qtd' ? (kpi.q2Progress != null ? kpi.q2Progress : kpi.q1Actual) : kpi.q1Actual + (kpi.q2Progress || 0);
    target = kpi[targetField];
  }

  // Source filter — apply if KPI has bySource and source filter is set
  if (filters.source && filters.source.length > 0 && kpi.bySource) {
    let sa = 0, st = 0, n = 0;
    for (const s of filters.source) {
      const row = kpi.bySource[s];
      if (!row) continue;
      sa += row.current; st += row[targetField] != null ? row[targetField] : row.target;
      n++;
    }
    if (n > 0) {
      if (kpi.format === 'pct' || kpi.format === 'months' || kpi.format === 'hours') {
        actual = sa / n; target = st / n;
      } else {
        actual = sa; target = st;
      }
    }
  }

  // Stage filter — apply if KPI has byStage
  if (filters.stage && filters.stage.length > 0 && kpi.byStage) {
    let sa = 0, st = 0;
    for (const s of filters.stage) {
      const row = kpi.byStage[s];
      if (!row) continue;
      sa += row.current; st += row[targetField] != null ? row[targetField] : row.target;
    }
    actual = sa; target = st;
  }

  // Vertical filter — scale $ metrics by mix fraction; bump rate metrics by perf offset
  if (filters.vertical && filters.vertical.length > 0) {
    const { fraction, rateOffset } = verticalAggregate(filters);
    const isRate = kpi.format === 'pct' || kpi.format === 'months' || kpi.format === 'days'
                 || kpi.format === 'hours' || kpi.format === 'score10';
    if (isRate) {
      actual = actual + rateOffset;
    } else {
      actual = actual * fraction;
      target = target * fraction;
    }
  }

  return kind === 'target' ? target : actual;
}

function Sparkline({ data, color = C.blue, fill = true }) {
  return (
    <ResponsiveContainer width="100%" height="100%">
      <AreaChart data={data} margin={{ top: 4, right: 0, left: 0, bottom: 0 }}>
        <defs>
          <linearGradient id={`spark-${color.replace('#','')}`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity={0.3}/>
            <stop offset="100%" stopColor={color} stopOpacity={0}/>
          </linearGradient>
        </defs>
        <Area type="monotone" dataKey="actual" stroke={color} strokeWidth={1.8}
          fill={fill ? `url(#spark-${color.replace('#','')})` : 'none'} dot={false} isAnimationActive={false}/>
      </AreaChart>
    </ResponsiveContainer>
  );
}

function KpiCard({ kpi, view, filters, onClick }) {
  const value = computeFiltered(kpi, view, filters, 'actual');
  const target = computeFiltered(kpi, view, filters, 'target');
  const fyTarget = kpi.fyTarget || kpi.q4Target || target;
  const trend = D.trends[kpi.id] || [];
  const localStatus = D.health(value, target, kpi.higherIsBetter);
  const status = window.YUNO_KPI_STATUS ? window.YUNO_KPI_STATUS(kpi, localStatus) : localStatus;
  const pct = D.pctToTarget(value, target, kpi.higherIsBetter);

  // Arrow shows performance direction: ↑ = good performance, ↓ = poor performance
  const arrow = status === 'good' ? '↑' : '↓';
  const arrowColor = status === 'good' ? '#059669' : status === 'warn' ? '#D97706' : '#DC2626';

  // Map pillar to number and color for consistent styling
  const pillarNumber = kpi.pillar === 'Scalable Growth' ? 'P1' :
                     kpi.pillar === 'Operational Leverage' ? 'P2' :
                     kpi.pillar === 'Customer Value' ? 'P3' : 'P4';

  const pillarColor = kpi.pillar === 'Scalable Growth' ? '#3E4FE0' :
                    kpi.pillar === 'Operational Leverage' ? '#2B2A30' :
                    kpi.pillar === 'Customer Value' ? '#1726A6' : '#BDC3F6';

  const regions = effectiveRegions(filters);
  const scopeLabel = regions.length === D.REGIONS.length ? 'All regions' : regions.join(' + ');

  return (
    <div className="pillar-kpi-card" onClick={() => onClick && onClick(kpi)}>
      {/* Subtle pillar tag (P1/P2/P3/P4) — left corner */}
      <div style={{
        position: 'absolute',
        top: '10px',
        left: '10px',
        background: 'white',
        border: '1px solid #E2E8F0',
        color: '#94A3B8',
        padding: '1px 6px',
        borderRadius: '4px',
        fontSize: '9px',
        fontWeight: 600,
        letterSpacing: '0.04em',
        zIndex: 10
      }}>
        {pillarNumber}
      </div>

      {/* Sub-team owner — right corner, very light */}
      {(D.KPI_TO_TEAM && D.KPI_TO_TEAM[kpi.id]) && (
        <div style={{
          position: 'absolute',
          top: '12px',
          right: '12px',
          fontSize: 9,
          color: '#94A3B8',
          fontWeight: 500,
          letterSpacing: '0.02em',
          maxWidth: '60%',
          textAlign: 'right',
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          zIndex: 10
        }}>
          {D.KPI_TO_TEAM[kpi.id]}
        </div>
      )}

      {/* Centered KPI Name */}
      <div style={{
        textAlign: 'center',
        paddingTop: '8px',
        marginBottom: '8px',
        flexShrink: 0
      }}>
        <div className="kpi-name" style={{
          fontSize: '14px',
          fontWeight: '600',
          lineHeight: '1.2',
          color: '#1F2937',
          minHeight: '32px',
          maxHeight: '32px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          textAlign: 'center',
          overflow: 'hidden',
          wordWrap: 'break-word'
        }}>
          {kpi.name}
        </div>
      </div>

      {/* Main Value with Arrow */}
      <div style={{
        textAlign: 'center',
        marginBottom: '8px',
        flex: '1',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        minHeight: '40px'
      }}>
        <div style={{
          fontSize: '20px',
          fontWeight: 'bold',
          lineHeight: '1.1',
          color: arrowColor,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          gap: '4px'
        }}>
          {D.fmt(value, kpi.format)}
          <svg
            width="12"
            height="16"
            viewBox="0 0 12 16"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
            style={{
              transition: 'all 0.2s ease',
              flexShrink: 0,
              opacity: 0.9,
              transform: status === 'good' ? 'rotate(180deg)' : 'rotate(0deg)'
            }}
          >
            <path
              d="M6 2V14M6 14L2 10M6 14L10 10"
              stroke={arrowColor}
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        </div>
      </div>

      {/* Target and Delta Row */}
      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: '6px',
        flexShrink: 0
      }}>
        <span style={{
          fontSize: '11px',
          color: '#6B7280',
          fontWeight: '500',
          whiteSpace: 'nowrap'
        }}>
          TARGET: {D.fmt(target, kpi.format)}
        </span>
        <span style={{
          backgroundColor: pct >= 0 ? '#D1FAE5' : '#FEE2E2',
          color: pct >= 0 ? '#065F46' : '#991B1B',
          padding: '2px 6px',
          borderRadius: '4px',
          fontSize: '11px',
          fontWeight: '600',
          whiteSpace: 'nowrap',
          flexShrink: 0
        }}>
          {pct.toFixed(0)}%
        </span>
      </div>

      {/* Separator Line */}
      <div style={{
        height: '1px',
        backgroundColor: '#E5E7EB',
        marginBottom: '6px',
        flexShrink: 0
      }}></div>

      {/* FY Target Display */}
      <div style={{
        fontSize: '11px',
        color: '#6B7280',
        fontWeight: '500',
        textAlign: 'center',
        flexShrink: 0,
        paddingBottom: '4px'
      }}>
        FY Target: {D.fmt(fyTarget, kpi.format)}
      </div>
    </div>
  );
}

function KpiTile({ kpi, view, filters, onClick, dense }) {
  const value = computeFiltered(kpi, view, filters, 'actual');
  const target = computeFiltered(kpi, view, filters, 'target');
  const trend = D.trends[kpi.id] || [];
  // Pace-aware status for cumulative metrics in QTD view
  const pace = view === 'qtd' && (kpi.format === 'currencyMM' || kpi.format === 'currencyK')
    ? target * D.QUARTER_PROGRESS : target;
  const status = D.health(value, pace, kpi.higherIsBetter);
  const pct = D.pctToTarget(value, pace, kpi.higherIsBetter);

  // Arrow shows performance direction: ↑ = good performance, ↓ = poor performance
  const arrow = status === 'good' ? '↑' : '↓';
  const arrowColor = status === 'good' ? '#059669' : status === 'warn' ? '#D97706' : '#DC2626';
  const targetLabel = view === 'qtd' ? (kpi.format === 'currencyMM' || kpi.format === 'currencyK' ? 'pace' : 'Q2') : 'FY';
  return (
    <div className={`kpi-tile tile-${status} ${dense ? 'dense' : ''}`} onClick={() => onClick && onClick(kpi)}>
      <div className="tile-status-bar"/>
      <div className="tile-head">
        <div className="tile-name" title={kpi.name}>{kpi.name}</div>
        <span className="tile-delta" style={{
          color: arrowColor,
          fontWeight: '700',
          fontVariantNumeric: 'tabular-nums',
          display: 'flex',
          alignItems: 'center',
          gap: '4px'
        }}>
          <svg
            width="12"
            height="12"
            viewBox="0 0 24 24"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
            style={{
              transition: 'all 0.2s ease',
              transform: status === 'good' ? 'rotate(0deg)' : 'rotate(180deg)'
            }}
          >
            <path
              d="M7 14L12 9L17 14"
              stroke={arrowColor}
              strokeWidth="3"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
          {Math.abs(pct).toFixed(0)}%
        </span>
      </div>
      <div className={`tile-value number-${status}`}>{D.fmt(value, kpi.format, false, kpi.unit)}</div>
      <div className="tile-meta">
        <span className="tgt">vs {target} {targetLabel}</span>
      </div>
      <div className="tile-spark">
        <Sparkline data={trend} color={status === 'bad' ? C.bad : status === 'warn' ? C.warn : C.blue}/>
      </div>
    </div>
  );
}

// Expandable KPI tile — clicking a tile branches inline to show key derivatives.
// Click the value or chevron to expand; click the title or another tile to collapse.
function ExpandableKpiTile({ kpi, view, filters, onOpenDrawer, expanded, onToggle }) {
  const value = computeFiltered(kpi, view, filters, 'actual');
  const target = computeFiltered(kpi, view, filters, 'target');
  const trend = D.trends[kpi.id] || [];
  const pace = view === 'qtd' && (kpi.format === 'currencyMM' || kpi.format === 'currencyK')
    ? target * D.QUARTER_PROGRESS : target;
  const status = D.health(value, pace, kpi.higherIsBetter);
  const pct = D.pctToTarget(value, pace, kpi.higherIsBetter);

  // Arrow shows performance direction: ↑ = good performance, ↓ = poor performance
  const arrow = status === 'good' ? '↑' : '↓';
  const arrowColor = status === 'good' ? '#059669' : status === 'warn' ? '#D97706' : '#DC2626';
  const targetLabel = view === 'qtd' ? (kpi.format === 'currencyMM' || kpi.format === 'currencyK' ? 'pace' : 'Q2') : 'FY';
  const derivs = D.KPI_DERIVATIVES[kpi.id] || [];

  // Per-region mini bars (top contributors)
  const regionBars = kpi.byRegion ? D.REGIONS.map(r => {
    const row = kpi.byRegion[r];
    if (!row) return null;
    const a = view === 'qtd' ? (row.q2Progress ?? row.q1Actual) : row.q1Actual;
    const t = view === 'qtd' ? row.q2Target : row.q4Target;
    const p = D.pctToTarget(a, t, kpi.higherIsBetter);
    return { region: r, actual: a, target: t, pct: p, status: D.health(a, t, kpi.higherIsBetter) };
  }).filter(Boolean).sort((a, b) => b.actual - a.actual) : [];

  return (
    <div className={`kpi-tile-x tile-${status} ${expanded ? 'expanded' : ''}`}>
      <button className="kpi-tile-x-head" onClick={() => onToggle(kpi.id)}>
        <div className="tile-status-bar"/>
        <div className="tile-head">
          <div className="tile-name" title={kpi.name}>{kpi.name}</div>
          <span className="tile-delta" style={{
            color: arrowColor,
            fontWeight: '700',
            fontVariantNumeric: 'tabular-nums',
            display: 'flex',
            alignItems: 'center',
            gap: '4px'
          }}>
            <svg
              width="12"
              height="12"
              viewBox="0 0 24 24"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              style={{
                transition: 'all 0.2s ease',
                transform: status === 'good' ? 'rotate(0deg)' : 'rotate(180deg)'
              }}
            >
              <path
                d="M7 14L12 9L17 14"
                stroke={arrowColor}
                strokeWidth="3"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
            {Math.abs(pct).toFixed(0)}%
          </span>
        </div>
        <div className="tile-value-row">
          <div className={`tile-value number-${status}`}>{D.fmt(value, kpi.format, false, kpi.unit)}</div>
          <span className="tile-chevron">
            <svg
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              style={{
                transition: 'transform 0.2s ease',
                transform: expanded ? 'rotate(90deg)' : 'rotate(0deg)'
              }}
            >
              <path
                d="M9 18L15 12L9 6"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </span>
        </div>
        <div className="tile-meta">
          <span className="tgt">vs {D.fmt(target, kpi.format)} {targetLabel}</span>
          <span className="branches">{derivs.length} branches · {regionBars.length} regions</span>
        </div>
        <div className="tile-spark">
          <Sparkline data={trend} color={status === 'bad' ? C.bad : status === 'warn' ? C.warn : C.blue}/>
        </div>
      </button>

      {expanded && (
        <div className="kpi-branch">
          <div className="branch-section">
            <div className="branch-label">Drill across regions</div>
            <div className="branch-rows">
              {regionBars.map(rb => (
                <div key={rb.region} className="branch-row">
                  <span className={`dot status-${rb.status}`}/>
                  <span className="branch-name">{rb.region}</span>
                  <span className="branch-bar-track">
                    <span className={`branch-bar-fill ${rb.status}`} style={{ width: `${Math.min(100, Math.max(4, (rb.actual / Math.max(...regionBars.map(x=>x.actual))) * 100))}%` }}/>
                  </span>
                  <span className="branch-val">{D.fmt(rb.actual, kpi.format)}</span>
                  <span className={`branch-pct text-${rb.status === 'good' ? 'good' : rb.status === 'warn' ? 'warn' : 'bad'}`}>
                    {rb.pct >= 0 ? '+' : ''}{rb.pct.toFixed(0)}%
                  </span>
                </div>
              ))}
            </div>
          </div>

          {derivs.length > 0 && (
            <div className="branch-section">
              <div className="branch-label">Key derivative metrics</div>
              <div className="branch-derivs">
                {derivs.map(d => {
                  const dk = D.STRATEGIC.find(x => x.id === d.id) || D.CUSTOMER_VALUE.find(x => x.id === d.id);
                  if (!dk) return null;
                  const da = computeFiltered(dk, view, filters, 'actual');
                  const dt = computeFiltered(dk, view, filters, 'target');
                  const dpace = view === 'qtd' && (dk.format === 'currencyMM' || dk.format === 'currencyK') ? dt * D.QUARTER_PROGRESS : dt;
                  const ds = D.health(da, dpace, dk.higherIsBetter);
                  const dpct = D.pctToTarget(da, dpace, dk.higherIsBetter);
                  return (
                    <button key={d.id} className={`branch-deriv branch-${ds}`} onClick={(e) => { e.stopPropagation(); onOpenDrawer(dk); }}>
                      <div className="branch-deriv-head">
                        <span className={`dot status-${ds}`}/>
                        <span className="branch-deriv-name">{dk.name}</span>
                      </div>
                      <div className="branch-deriv-val">{D.fmt(da, dk.format)}</div>
                      <div className="branch-deriv-meta">
                        <span className={`text-${ds === 'good' ? 'good' : ds === 'warn' ? 'warn' : 'bad'}`} style={{ fontWeight: 700 }}>
                          {dpct >= 0 ? '+' : ''}{dpct.toFixed(0)}%
                        </span>
                        <span className="branch-deriv-why">{d.why}</span>
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          <div className="branch-actions">
            <button className="btn btn-secondary" onClick={(e) => { e.stopPropagation(); onOpenDrawer(kpi); }}>
              Open full deep-dive →
            </button>
            <span className="text-xs text-muted">Owner: <strong>{kpi.owner}</strong> · Source: {kpi._source?.split('·')[0] || 'Pending'}</span>
          </div>
        </div>
      )}
    </div>
  );
}

function RegionTile({ region, kpi, view, selected, onClick }) {
  const row = kpi.byRegion[region];
  if (!row) return null;
  const actual = view === 'qtd' ? (row.q2Progress != null ? row.q2Progress : row.q1Actual) : row.q1Actual;
  const target = view === 'qtd' ? row.q2Target : row.q4Target;
  const status = D.health(actual, target, kpi.higherIsBetter);
  const pct = D.pctToTarget(actual, target, kpi.higherIsBetter);
  const trend = (D.trends[kpi.id] || []).map((d) => ({
    ...d, actual: d.actual != null ? d.actual * (row.q4Target / kpi.q4Target || 0.2) : null,
  }));
  return (
    <div className={`region-tile region-${status} ${selected ? 'selected' : ''}`} onClick={onClick}>
      <div className="region-name">{region}</div>
      <div className="region-owner">Lead: {D.REGION_OWNERS[region]}</div>
      <div className="region-stat">
        <div className="label">{kpi.name}</div>
        <div className="val">{D.fmt(actual, kpi.format)}</div>
        <div className={`pct text-${status === 'good' ? 'good' : status === 'warn' ? 'warn' : 'bad'}`}>
          {pct >= 0 ? '+' : ''}{pct.toFixed(1)}% vs target
        </div>
      </div>
      <div className="region-mini">
        <Sparkline data={trend} color={status === 'bad' ? C.bad : status === 'warn' ? C.warn : C.blue}/>
      </div>
    </div>
  );
}

function TrendChart({ kpiId, format, height = 260, granularity = 'week', higherIsBetter = true }) {
  const raw = D.trends[kpiId] || [];
  const data = D.aggregateTrend(raw, granularity, higherIsBetter, kpiId);


  if (!data || data.length === 0) {
    return (
      <div style={{ height, width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f8f9fa', borderRadius: '8px' }}>
        <div style={{ color: '#666', fontSize: '14px' }}>No trend data available</div>
      </div>
    );
  }

  return (
    <div style={{ height, width: '100%', background: 'white', borderRadius: '8px', padding: '16px' }}>
      <ResponsiveContainer width="100%" height="100%">
        <ComposedChart data={data} margin={{ top: 20, right: 30, left: 20, bottom: 20 }}>
          <defs>
            <linearGradient id={`ga-${kpiId}`} x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#3E4FE0" stopOpacity={0.3}/>
              <stop offset="100%" stopColor="#3E4FE0" stopOpacity={0}/>
            </linearGradient>
          </defs>
          <CartesianGrid strokeDasharray="3 3" stroke="#E0E4E7" vertical={false}/>
          <XAxis dataKey="week" tick={{ fontSize: 12, fill: '#666' }} axisLine={false} tickLine={false}/>
          <YAxis tick={{ fontSize: 12, fill: '#666' }} axisLine={false} tickLine={false}
            tickFormatter={(v) => D.fmt(v, format)} width={80}/>
          <Tooltip content={<CustomTooltip format={format}/>}/>
          <Area type="monotone" dataKey="actual" name="Actual" stroke="#3E4FE0" strokeWidth={3}
            fill={`url(#ga-${kpiId})`} connectNulls={false}/>
          <Line type="monotone" dataKey="target" name="Target" stroke="#8E93A8" strokeWidth={2}
            strokeDasharray="5 4" dot={false}/>
          <Line type="monotone" dataKey="forecast" name="Forecast" stroke="#00C851" strokeWidth={2}
            strokeDasharray="2 3" dot={false}/>
          <Legend wrapperStyle={{ fontSize: 12, paddingTop: 16 }} iconType="line"/>
        </ComposedChart>
      </ResponsiveContainer>
    </div>
  );
}

function FunnelChart({ data }) {
  const maxCount = Math.max(...data.map(d => d.count), 1);
  return (
    <div>
      {data.map((s, i) => {
        const pct = (s.count / maxCount) * 100;
        const conv = i > 0 && data[i - 1].count > 0 ? ((s.count / data[i - 1].count) * 100).toFixed(1) : null;
        const color = i === data.length - 1 ? C.good
          : i >= data.length - 3 ? C.blue
          : C.blue300;
        return (
          <div key={s.stage} className="funnel-stage">
            <div className="stage-name">{s.stage}</div>
            <div style={{ position: 'relative' }}>
              <div className="stage-bar" style={{ width: `${Math.max(pct, 4)}%`, background: color, minWidth: 60 }}>
                {s.count.toLocaleString()}
              </div>
            </div>
            <div className="stage-count">{s.count.toLocaleString()}</div>
            <div className="stage-conv" style={{display: 'flex', alignItems: 'center', gap: '4px'}}>
              {conv ? (
                <>
                  {conv}%
                  <svg
                    width="12"
                    height="12"
                    viewBox="0 0 24 24"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M5 12H19"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                    <path
                      d="M12 5L19 12L12 19"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>
                </>
              ) : ''}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function ComparisonBar({ data, dataKey, targetKey, format, height = 220, color = C.blue }) {
  return (
    <div style={{ height, width: '100%' }}>
      <ResponsiveContainer>
        <BarChart data={data} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
          <CartesianGrid strokeDasharray="3 3" stroke={C.n100} vertical={false}/>
          <XAxis dataKey="name" tick={{ fontSize: 11, fill: C.n400 }} axisLine={false} tickLine={false}/>
          <YAxis tick={{ fontSize: 11, fill: C.n400 }} axisLine={false} tickLine={false}
            tickFormatter={(v) => D.fmt(v, format)} width={56}/>
          <Tooltip content={<CustomTooltip format={format}/>} cursor={{ fill: C.n50 }}/>
          <Bar dataKey={dataKey} name="Actual" fill={color} radius={[4, 4, 0, 0]} maxBarSize={48}/>
          {targetKey && <Bar dataKey={targetKey} name="Target" fill={C.n200} radius={[4, 4, 0, 0]} maxBarSize={48}/>}
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}

function DonutChart({ data, height = 200 }) {
  const COLORS = [C.blue, C.blue300, C.greenDark, C.warn, C.lilac];
  return (
    <div style={{ height, width: '100%' }}>
      <ResponsiveContainer>
        <PieChart>
          <Pie data={data} dataKey="value" nameKey="name" innerRadius={45} outerRadius={75}
            paddingAngle={2} stroke="white" strokeWidth={2}>
            {data.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]}/>)}
          </Pie>
          <Tooltip content={<CustomTooltip/>}/>
          <Legend verticalAlign="bottom" wrapperStyle={{ fontSize: 11 }} iconType="circle" iconSize={8}/>
        </PieChart>
      </ResponsiveContainer>
    </div>
  );
}

// ============================================================================
// NEW OVERVIEW COMPONENTS
// ============================================================================

function HeroKpiCard({ kpi, expanded, onToggle, onKpiClick }) {
  const statusColor = kpi.pctToTarget >= 100 ? C.good : kpi.pctToTarget >= 90 ? C.warn : C.bad;

  return (
    <div className="hero-kpi-card">
      <div className="hero-main" onClick={onToggle}>
        <div className="hero-header">
          <div className="hero-name">{kpi.name}</div>
          <div className="hero-status" style={{ color: statusColor }}>
            {D.fmt(kpi.pctToTarget, 'pct')} to target
          </div>
        </div>
        <div className="hero-value" style={{ color: statusColor }}>
          {D.fmt(kpi.value, kpi.format)}
        </div>
        <div className="hero-subtitle">
          Target: {D.fmt(kpi.target, kpi.format)} • Q2 performance tracking to exceed plan
        </div>
        <div className="expand-indicator" style={{display: 'flex', alignItems: 'center', gap: '4px', justifyContent: 'center'}}>
          <svg
            width="12"
            height="16"
            viewBox="0 0 12 16"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
            style={{
              transition: 'all 0.2s ease',
              transform: expanded ? 'rotate(180deg)' : 'rotate(0deg)'
            }}
          >
            <path
              d="M6 2V14M6 14L2 10M6 14L10 10"
              stroke="#6B7280"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
          {expanded ? 'Hide breakdown' : 'Show contributing KPIs'}
        </div>
      </div>
      {expanded && (
        <div className="hero-expansion">
          <div className="contributing-kpis">
            {kpi.contributing.map(contributingKpi => (
              <div key={contributingKpi.id} className="contributing-kpi"
                   onClick={() => onKpiClick(contributingKpi)}>
                <div className="contributing-name">{contributingKpi.name}</div>
                <div className="contributing-value">
                  {D.fmt(D.currentValue(contributingKpi, 'qtd'), contributingKpi.format)}
                </div>
                <div className="contributing-target">
                  {D.fmt(contributingKpi.q2Target, contributingKpi.format)} target
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function HeadlineCard({ headline }) {
  const statusColor = headline.status === 'good' ? C.good : headline.status === 'warn' ? C.warn : C.bad;

  return (
    <div className="headline-card">
      <div className="headline-label">{headline.label}</div>
      <div className="headline-value" style={{ color: statusColor }}>
        {headline.value}
      </div>
      <div className="headline-detail">{headline.detail}</div>
    </div>
  );
}

function KpiDistributionChart({ onSliceClick }) {
  const totalKPIs = Object.values(D.DEPARTMENT_KPI_DISTRIBUTION).reduce((sum, dept) => sum + dept.total, 0);
  const data = Object.entries(D.DEPARTMENT_KPI_DISTRIBUTION).map(([deptName, dept]) => ({
    name: deptName,
    value: dept.total,
    percentage: (dept.total / totalKPIs) * 100,
    color: D.DEPARTMENTS.find(d => d.label === deptName)?.color || C.blue,
    deptId: D.DEPARTMENTS.find(d => d.label === deptName)?.id || deptName
  }));

  const handleSliceClick = (data) => {
    onSliceClick(data.deptId);
  };

  return (
    <div style={{ height: 280, width: '100%' }}>
      <ResponsiveContainer>
        <PieChart>
          <Pie
            data={data}
            dataKey="value"
            nameKey="name"
            outerRadius={100}
            paddingAngle={2}
            stroke="white"
            strokeWidth={2}
            onClick={handleSliceClick}
            style={{ cursor: 'pointer' }}
          >
            {data.map((entry, i) => <Cell key={i} fill={entry.color}/>)}
          </Pie>
          <Tooltip content={({ active, payload }) => {
            if (!active || !payload || !payload.length) return null;
            const data = payload[0].payload;
            return (
              <div className="tt">
                <div style={{ fontWeight: 700, marginBottom: 4 }}>{data.name}</div>
                <div className="tt-row">
                  <span className="tt-label">KPIs:</span>
                  <span className="tt-val">{data.value} ({data.percentage.toFixed(1)}%)</span>
                </div>
                <div className="tt-hint">Click to filter</div>
              </div>
            );
          }}/>
          <Legend
            verticalAlign="bottom"
            wrapperStyle={{ fontSize: 11, paddingTop: 16 }}
            iconType="circle"
            iconSize={8}
            formatter={(value, entry) => `${value} (${entry.payload.percentage.toFixed(1)}%)`}
          />
        </PieChart>
      </ResponsiveContainer>
    </div>
  );
}

function EnhancedKpiPieChart({ onSliceClick }) {
  const [hoveredSlice, setHoveredSlice] = useState(null);
  const [activeSlice, setActiveSlice] = useState(null);
  const [showTooltip, setShowTooltip] = useState(false);
  const [hoverSource, setHoverSource] = useState(null); // Track if hover is from pie or legend

  // Calculate total KPIs across all departments
  const totalKPIs = Object.values(D.DEPARTMENT_KPI_DISTRIBUTION).reduce((sum, dept) => sum + dept.total, 0);

  // Process all departments with KPIs - exclude departments with 0 KPIs
  const data = Object.entries(D.DEPARTMENT_KPI_DISTRIBUTION)
    .filter(([deptName, dept]) => dept.total > 0) // Only include departments with active KPIs
    .map(([deptName, dept]) => {
    const department = D.DEPARTMENTS.find(d => d.label === deptName);
    const percentage = Math.round((dept.total / totalKPIs) * 100);

    return {
      name: deptName,
      value: dept.total,
      percentage: percentage,
      color: department?.color || '#3E4FE0',
      deptId: department?.id || deptName.toLowerCase().replace(/\s+/g, '_'),
      performanceSummary: `${dept.total} Strategic KPIs`,
      exceeding: dept.exceeding,
      onTrack: dept.onTrack,
      atRisk: dept.atRisk,
      performanceText: `${dept.exceeding} exceeding, ${dept.onTrack} on track, ${dept.atRisk} at risk`,
      q2Context: 'Q2 2026 performance tracking',
      trendIcon: dept.exceeding > dept.atRisk ? 'up' : dept.atRisk > dept.exceeding ? 'down' : 'stable',
      avgPerformance: Math.round((dept.exceeding / dept.total) * 100)
    };
  });

  const handleSliceClick = (data) => {
    setActiveSlice(data.deptId);
    onSliceClick(data.deptId);
    // Clear active state after a short time
    setTimeout(() => setActiveSlice(null), 200);
  };

  const handleChartMouseEnter = (data) => {
    setHoveredSlice(data.deptId);
    setShowTooltip(true);
    setHoverSource('pie');
  };

  const handleLegendMouseEnter = (data) => {
    setHoveredSlice(data.deptId);
    setShowTooltip(false); // Don't show tooltip for legend hover
    setHoverSource('legend');
  };

  const handleChartMouseLeave = () => {
    setHoveredSlice(null);
    setShowTooltip(false);
    setHoverSource(null);
  };

  const CustomTooltip = ({ active, payload }) => {
    if (active && payload && payload[0] && showTooltip && hoverSource === 'pie') {
      const data = payload[0].payload;
      return (
        <div className="custom-tooltip enhanced-pie-tooltip">
          <div className="tooltip-header">
            <strong>{data.name}</strong>
            <svg
              width="14"
              height="14"
              viewBox="0 0 24 24"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              style={{
                marginLeft: '6px',
                transform: data.trendIcon === 'up' ? 'rotate(-45deg)' : data.trendIcon === 'down' ? 'rotate(135deg)' : 'rotate(0deg)',
                transition: 'transform 0.2s ease'
              }}
            >
              <path
                d="M5 12H19"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
              <path
                d="M12 5L19 12L12 19"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </div>
          <div className="tooltip-content">
            <p><strong>{data.value} Strategic KPIs ({data.percentage}%)</strong></p>
            <p>{data.performanceText}</p>
            <p><em>Click to explore department details →</em></p>
          </div>
        </div>
      );
    }
    return null;
  };

  return (
    <div className="enhanced-pie-container">
      <div
        style={{ height: 300, width: '100%', position: 'relative' }}
        onMouseLeave={handleChartMouseLeave}
      >
        <ResponsiveContainer>
          <PieChart>
            <Pie
              data={data}
              dataKey="value"
              nameKey="name"
              outerRadius={140}
              innerRadius={0}
              paddingAngle={2}
              stroke="white"
              strokeWidth={2}
              onClick={handleSliceClick}
              onMouseEnter={handleChartMouseEnter}
              onMouseLeave={() => {}} // Handled by container
              style={{ cursor: 'pointer' }}
            >
              {data.map((entry, i) => {
                const isHovered = hoveredSlice === entry.deptId;
                const isActive = activeSlice === entry.deptId;

                // Calculate darker shade for active/clicked state
                const darkenColor = (color, factor = 0.8) => {
                  const hex = color.replace('#', '');
                  const r = parseInt(hex.substr(0, 2), 16) * factor;
                  const g = parseInt(hex.substr(2, 2), 16) * factor;
                  const b = parseInt(hex.substr(4, 2), 16) * factor;
                  return `rgb(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)})`;
                };

                let fillColor = entry.color;
                let cellOpacity = 1;
                let cellFilter = 'none';
                let strokeWidth = 2;

                if (isActive) {
                  fillColor = darkenColor(entry.color, 0.7); // Darker shade when clicked
                } else if (isHovered) {
                  if (hoverSource === 'legend') {
                    // More prominent highlighting when hovered from legend
                    cellOpacity = 0.9;
                    cellFilter = 'brightness(1.2) drop-shadow(0 0 8px rgba(0,0,0,0.3))';
                    strokeWidth = 3;
                  } else {
                    // Subtle highlighting when hovered directly
                    cellOpacity = 0.8;
                    cellFilter = 'brightness(1.1)';
                  }
                }

                return (
                  <Cell
                    key={i}
                    fill={fillColor}
                    stroke="white"
                    strokeWidth={strokeWidth}
                    opacity={cellOpacity}
                    filter={cellFilter}
                    style={{ outline: 'none' }} // Remove focus outline
                  />
                );
              })}
            </Pie>
            <Tooltip
              content={<CustomTooltip />}
              wrapperStyle={{
                pointerEvents: 'none',
                zIndex: 1000
              }}
            />
          </PieChart>
        </ResponsiveContainer>
      </div>

      {/* Legend with performance indicators */}
      <div className="pie-legend">
        {data.map((entry, i) => (
          <div
            key={i}
            className={`legend-item ${hoveredSlice === entry.deptId ? 'highlighted' : ''}`}
            onMouseEnter={() => handleLegendMouseEnter(entry)}
            onMouseLeave={handleChartMouseLeave}
            onClick={() => handleSliceClick(entry)}
          >
            <div className="legend-color" style={{ backgroundColor: entry.color }}></div>
            <div className="legend-text">
              <span className="legend-name">{entry.name}</span>
              <span className="legend-trend">
                <svg
                  width="12"
                  height="12"
                  viewBox="0 0 24 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                  style={{
                    transform: entry.trendIcon === 'up' ? 'rotate(-45deg)' : entry.trendIcon === 'down' ? 'rotate(135deg)' : 'rotate(0deg)',
                    transition: 'transform 0.2s ease'
                  }}
                >
                  <path
                    d="M5 12H19"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                  <path
                    d="M12 5L19 12L12 19"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </span>
            </div>
            <div className="legend-count">{entry.value} KPIs</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function HoverInsightTooltip({ children, insight }) {
  const [isVisible, setIsVisible] = useState(false);

  return (
    <div className="insight-wrapper" style={{ position: 'relative', display: 'inline-block' }}>
      <div
        onMouseEnter={() => setIsVisible(true)}
        onMouseLeave={() => setIsVisible(false)}
        style={{ cursor: 'pointer' }}
      >
        {children}
      </div>
      {isVisible && insight && (
        <div className="insight-tooltip">
          <div className="insight-title">{insight.title}</div>
          <div className="insight-content">{insight.content}</div>
          {insight.drivers && insight.drivers.length > 0 && (
            <div className="insight-drivers">
              <strong>Key drivers:</strong>
              <ul>
                {insight.drivers.map((driver, i) => (
                  <li key={i}>{driver}</li>
                ))}
              </ul>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function InsightIcon({ insight }) {
  const [isVisible, setIsVisible] = useState(false);

  return (
    <div className="insight-icon-wrapper" style={{ position: 'relative', display: 'inline-block' }}>
      <div
        className="insight-icon"
        onMouseEnter={() => setIsVisible(true)}
        onMouseLeave={() => setIsVisible(false)}
        title="Click for insights"
      >
        i
      </div>
      {isVisible && insight && (
        <div className="insight-tooltip">
          <div className="insight-title">{insight.title}</div>
          <div className="insight-content">{insight.content}</div>
          {insight.drivers && insight.drivers.length > 0 && (
            <div className="insight-drivers">
              <strong>Key drivers:</strong>
              <ul>
                {insight.drivers.map((driver, i) => (
                  <li key={i}>{driver}</li>
                ))}
              </ul>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// Enhanced insight generation engine
function generateKpiInsight(kpi, actual, target) {
  const pctToTarget = (actual / target) * 100;
  const status = D.health(actual, target, kpi.higherIsBetter);

  let title = '';
  let content = '';
  let drivers = [];

  if (status === 'good') {
    if (pctToTarget > 120) {
      title = 'Exceptional Performance';
      content = `${kpi.name} is performing ${Math.round(pctToTarget - 100)}% above target, indicating strong execution and favorable market conditions.`;
    } else if (pctToTarget > 105) {
      title = 'Strong Performance';
      content = `${kpi.name} is ${Math.round(pctToTarget - 100)}% ahead of target, showing solid momentum toward quarterly goals.`;
    } else {
      title = 'On Track';
      content = `${kpi.name} is meeting target expectations with ${Math.round(pctToTarget)}% achievement.`;
    }
  } else if (status === 'warn') {
    title = 'Moderate Concern';
    content = `${kpi.name} is ${Math.round(100 - pctToTarget)}% below target. Intervention may be needed to reach quarterly goals.`;
  } else {
    title = 'Critical Gap';
    content = `${kpi.name} is significantly below target at ${Math.round(pctToTarget)}%. Immediate action required.`;
  }

  // Add specific drivers based on KPI type
  if (kpi.id === 'new_logo_arr') {
    drivers = [
      `Pipeline health: ${D.fmt(D.STRATEGIC.find(k => k.id === 'qualified_pipeline')?.q2Progress || 0, 'currencyMM')}`,
      `Expansion rate: ${D.fmt(D.STRATEGIC.find(k => k.id === 'expansion_arr')?.q2Progress || 0, 'currencyMM')}`,
      `CAC payback: ${D.STRATEGIC.find(k => k.id === 'cac_payback_period')?.q2Progress || 0} months`
    ];
  } else if (kpi.id === 'qualified_pipeline') {
    drivers = [
      'Lead generation velocity',
      'Marketing qualified leads conversion',
      'Sales development efficiency'
    ];
  } else if (kpi.id === 'win_rate') {
    drivers = [
      'Deal qualification quality',
      'Competitive positioning',
      'Sales execution effectiveness'
    ];
  }

  return { title, content, drivers };
}


// Contextual Filter Component for Individual Charts
function ContextualFilters({ availableFilters, filters, setFilters, view, setView, granularity, setGranularity, kpi }) {
  const handleFilterChange = (dim, value) => {
    setFilters(prev => ({ ...prev, [dim]: value ? [value] : [] }));
  };

  const handleViewChange = (newView) => {
    setView(newView);
  };

  const handleGranularityChange = (newGranularity) => {
    if (setGranularity) setGranularity(newGranularity);
  };

  return (
    <div className="contextual-filters-clean">
      {availableFilters.includes('time') && (
        <div className="time-filter-group">
          <div className="filter-row">
            <div className="filter-section">
              <label className="filter-label">TIME PERIOD</label>
              <div className="time-filter-tabs">
                <button
                  className={`time-tab ${view === 'qtd' ? 'active' : ''}`}
                  onClick={() => handleViewChange('qtd')}
                >
                  Q2 2026
                </button>
                <button
                  className={`time-tab ${view === 'fy' ? 'active' : ''}`}
                  onClick={() => handleViewChange('fy')}
                >
                  YTD
                </button>
              </div>
            </div>
            {granularity && setGranularity && (
              <div className="filter-section">
                <label className="filter-label">CHART VIEW</label>
                <div className="granularity-tabs">
                  <button
                    className={`granularity-tab ${granularity === 'quarter' ? 'active' : ''}`}
                    onClick={() => handleGranularityChange('quarter')}
                  >
                    Quarterly
                  </button>
                  {kpi && kpi.supportsMonthlyData && (
                    <button
                      className={`granularity-tab ${granularity === 'month' ? 'active' : ''}`}
                      onClick={() => handleGranularityChange('month')}
                    >
                      Monthly
                    </button>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {availableFilters.includes('region') && (
        <div className="filter-group">
          <label className="filter-label">REGION</label>
          <div className="filter-tabs">
            <button
              className={`filter-tab ${(!filters.region || filters.region.length === 0) ? 'active' : ''}`}
              onClick={() => handleFilterChange('region', '')}
            >
              All Regions
            </button>
            <button
              className={`filter-tab ${(filters.region && filters.region[0] === 'LATAM') ? 'active' : ''}`}
              onClick={() => handleFilterChange('region', 'LATAM')}
            >
              LATAM
            </button>
            <button
              className={`filter-tab ${(filters.region && filters.region[0] === 'EUROPE') ? 'active' : ''}`}
              onClick={() => handleFilterChange('region', 'EUROPE')}
            >
              EUROPE
            </button>
            <button
              className={`filter-tab ${(filters.region && filters.region[0] === 'APAC') ? 'active' : ''}`}
              onClick={() => handleFilterChange('region', 'APAC')}
            >
              APAC
            </button>
            <button
              className={`filter-tab ${(filters.region && filters.region[0] === 'NA') ? 'active' : ''}`}
              onClick={() => handleFilterChange('region', 'NA')}
            >
              NA
            </button>
            <button
              className={`filter-tab ${(filters.region && filters.region[0] === 'MENA') ? 'active' : ''}`}
              onClick={() => handleFilterChange('region', 'MENA')}
            >
              MENA
            </button>
          </div>
        </div>
      )}

      {availableFilters.includes('source') && (
        <div className="filter-group">
          <label className="filter-label">SOURCE</label>
          <div className="filter-tabs">
            <button
              className={`filter-tab ${(!filters.source || filters.source.length === 0) ? 'active' : ''}`}
              onClick={() => handleFilterChange('source', '')}
            >
              All Sources
            </button>
            <button
              className={`filter-tab ${(filters.source && filters.source[0] === 'Inbound') ? 'active' : ''}`}
              onClick={() => handleFilterChange('source', 'Inbound')}
            >
              Inbound
            </button>
            <button
              className={`filter-tab ${(filters.source && filters.source[0] === 'Events') ? 'active' : ''}`}
              onClick={() => handleFilterChange('source', 'Events')}
            >
              Events
            </button>
            <button
              className={`filter-tab ${(filters.source && filters.source[0] === 'Outbound') ? 'active' : ''}`}
              onClick={() => handleFilterChange('source', 'Outbound')}
            >
              Outbound
            </button>
            <button
              className={`filter-tab ${(filters.source && filters.source[0] === 'Referral') ? 'active' : ''}`}
              onClick={() => handleFilterChange('source', 'Referral')}
            >
              Referral
            </button>
            <button
              className={`filter-tab ${(filters.source && filters.source[0] === 'Partnerships') ? 'active' : ''}`}
              onClick={() => handleFilterChange('source', 'Partnerships')}
            >
              Partnerships
            </button>
          </div>
        </div>
      )}

      {availableFilters.includes('stage') && (
        <div className="filter-group">
          <label className="filter-label">STAGE</label>
          <div className="filter-tabs">
            <button
              className={`filter-tab ${(!filters.stage || filters.stage.length === 0) ? 'active' : ''}`}
              onClick={() => handleFilterChange('stage', '')}
            >
              All Stages
            </button>
            <button
              className={`filter-tab ${(filters.stage && filters.stage[0] === 'Discovery') ? 'active' : ''}`}
              onClick={() => handleFilterChange('stage', 'Discovery')}
            >
              Discovery
            </button>
            <button
              className={`filter-tab ${(filters.stage && filters.stage[0] === 'Demo') ? 'active' : ''}`}
              onClick={() => handleFilterChange('stage', 'Demo')}
            >
              Demo
            </button>
            <button
              className={`filter-tab ${(filters.stage && filters.stage[0] === 'Negotiation') ? 'active' : ''}`}
              onClick={() => handleFilterChange('stage', 'Negotiation')}
            >
              Negotiation
            </button>
            <button
              className={`filter-tab ${(filters.stage && filters.stage[0] === 'Contracting') ? 'active' : ''}`}
              onClick={() => handleFilterChange('stage', 'Contracting')}
            >
              Contracting
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// SmartInsightsPanel + InteractiveDeepDiveCard were removed: both were
// exported but never rendered, and both contained hardcoded placeholder
// prose ("LATAM continues to drive…", "Maya Agent Core 25→45%", etc.) that
// had nothing to do with live data. Real per-KPI prose now lives in
// `cascade.insights` (see panels.jsx → KpiInsights / PillarInsightsDrillDown).
// If you need a region/department insights surface later, build it from
// `cascade.insights.byKpi` so it stays truthful — don't reintroduce static
// strings.

window.YUNO_COMPONENTS = {
  C, REGION_COLOR, KpiCard, KpiTile, ExpandableKpiTile, RegionTile, TrendChart, FunnelChart,
  ComparisonBar, DonutChart, Sparkline, CustomTooltip, computeFiltered, effectiveRegions, verticalAggregate,
  HeroKpiCard, HeadlineCard, KpiDistributionChart, EnhancedKpiPieChart, ContextualFilters,
  HoverInsightTooltip,
};
})();
