// FFC presentation charts — refined ECharts modules (dark, restrained).
const { useRef: ffcUseRef, useEffect: ffcUseEffect } = React;

function readVar(name, fallback) {
  const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
  return v || fallback;
}

function isPrintMode() {
  return document.documentElement.classList.contains('ffc-printing') ||
    (window.matchMedia && window.matchMedia('print').matches);
}

function useEChart(buildOption, deps) {
  const ref = ffcUseRef(null);
  const inst = ffcUseRef(null);
  ffcUseEffect(() => {
    if (!ref.current || !window.echarts) return;
    inst.current = window.echarts.init(ref.current, null, { renderer: 'canvas' });
    const refresh = () => {
      if (!inst.current) return;
      inst.current.setOption(buildOption(), true);
      inst.current.resize();
    };
    refresh();
    const beforePrint = () => {
      document.documentElement.classList.add('ffc-printing');
      refresh();
      setTimeout(refresh, 40);
    };
    const afterPrint = () => {
      document.documentElement.classList.remove('ffc-printing');
      refresh();
      setTimeout(refresh, 40);
    };
    window.addEventListener('beforeprint', beforePrint);
    window.addEventListener('afterprint', afterPrint);
    const ro = new ResizeObserver(() => inst.current && inst.current.resize());
    ro.observe(ref.current);
    return () => {
      window.removeEventListener('beforeprint', beforePrint);
      window.removeEventListener('afterprint', afterPrint);
      ro.disconnect();
      inst.current && inst.current.dispose();
    };
    // eslint-disable-next-line
  }, deps || []);
  return ref;
}

const FFC_AXIS = () => {
  const print = isPrintMode();
  return {
    print,
    teal: print ? '#0f766e' : readVar('--ffc-teal-400', '#2aa194'),
    tealDeep: print ? '#115e59' : readVar('--ffc-teal-600', '#0e5f58'),
    gold: print ? '#8a5a00' : readVar('--ffc-gold-500', '#d4a23e'),
    forecast: print ? '#64748b' : 'rgba(148,164,174,0.55)',
    forecastBar: print ? '#cbd5e1' : 'rgba(148,164,174,0.35)',
    remaining: print ? '#e5e7eb' : 'rgba(255,255,255,0.05)',
    grid: print ? '#d7dee5' : 'rgba(255,255,255,0.06)',
    label: print ? '#4b5563' : readVar('--text-muted', '#738792'),
    text: print ? '#111827' : readVar('--text-secondary', '#aebcc5'),
    tooltipBg: print ? '#ffffff' : 'rgba(10,21,30,0.95)',
    tooltipText: print ? '#111827' : '#eef3f5',
    tooltipBorder: print ? '#cbd5e1' : 'rgba(255,255,255,0.1)',
    font: 'IBM Plex Mono, monospace',
  };
};

// Grouped bars: Actual vs Forecast across Weekly / MTD / YTD
function CompareChart({ rows }) {
  const ref = useEChart(() => {
    const c = FFC_AXIS();
    return {
      grid: { left: 6, right: 12, top: 30, bottom: 6, containLabel: true },
      legend: { data: ['Actual', '2026 FC'], right: 0, top: 0, textStyle: { color: c.text, fontFamily: c.font, fontSize: 11 }, itemWidth: 12, itemHeight: 12, icon: 'roundRect' },
      tooltip: { trigger: 'axis', backgroundColor: c.tooltipBg, borderColor: c.tooltipBorder, textStyle: { color: c.tooltipText, fontFamily: c.font, fontSize: 12 }, valueFormatter: (v) => '$' + Math.round(v).toLocaleString() },
      xAxis: { type: 'category', data: rows.map(r => r.k), axisLine: { lineStyle: { color: c.grid } }, axisTick: { show: false }, axisLabel: { color: c.label, fontFamily: c.font, fontSize: 11 } },
      yAxis: { type: 'value', splitLine: { lineStyle: { color: c.grid } }, axisLabel: { color: c.label, fontFamily: c.font, fontSize: 10, formatter: (v) => v >= 1e6 ? (v/1e6)+'M' : (v/1e3)+'K' } },
      series: [
        { name: 'Actual', type: 'bar', data: rows.map(r => r.actual), itemStyle: { color: c.teal, borderRadius: [3,3,0,0] }, barWidth: 22, animationDuration: 700, animationEasing: 'cubicOut' },
        { name: '2026 FC', type: 'bar', data: rows.map(r => r.fc), itemStyle: { color: c.forecastBar, borderRadius: [3,3,0,0] }, barWidth: 22, animationDuration: 700, animationEasing: 'cubicOut' },
      ],
    };
  }, [JSON.stringify(rows)]);
  return <div ref={ref} style={{ width: '100%', height: '100%' }} />;
}

// Trend: weekly actual vs forecast line over recent weeks
function TrendChart({ weeks }) {
  const ref = useEChart(() => {
    const c = FFC_AXIS();
    return {
      grid: { left: 6, right: 14, top: 28, bottom: 6, containLabel: true },
      legend: { data: ['Actual', 'Forecast'], right: 0, top: 0, textStyle: { color: c.text, fontFamily: c.font, fontSize: 11 }, itemWidth: 12, itemHeight: 12, icon: 'roundRect' },
      tooltip: { trigger: 'axis', backgroundColor: c.tooltipBg, borderColor: c.tooltipBorder, textStyle: { color: c.tooltipText, fontFamily: c.font, fontSize: 12 }, valueFormatter: (v) => '$' + Math.round(v).toLocaleString() },
      xAxis: { type: 'category', boundaryGap: false, data: weeks.map(w => 'W' + w.week_number), axisLine: { lineStyle: { color: c.grid } }, axisTick: { show: false }, axisLabel: { color: c.label, fontFamily: c.font, fontSize: 11 } },
      yAxis: { type: 'value', scale: true, splitLine: { lineStyle: { color: c.grid } }, axisLabel: { color: c.label, fontFamily: c.font, fontSize: 10, formatter: (v) => (v/1e3).toFixed(0)+'K' } },
      series: [
        { name: 'Actual', type: 'line', smooth: true, symbol: 'circle', symbolSize: 7, data: weeks.map(w => w.weekly_actual), lineStyle: { color: c.teal, width: 2.5 }, itemStyle: { color: c.teal }, areaStyle: { color: 'rgba(42,161,148,0.12)' }, animationDuration: 800 },
        { name: 'Forecast', type: 'line', smooth: true, symbol: 'none', data: weeks.map(w => w.weekly_fc), lineStyle: { color: c.forecast, width: 1.5, type: 'dashed' }, animationDuration: 800 },
      ],
    };
  }, [JSON.stringify(weeks)]);
  return <div ref={ref} style={{ width: '100%', height: '100%' }} />;
}

// Annual forecast progress gauge-style stacked bar
function AnnualChart({ ytdActual, annualFc }) {
  const ref = useEChart(() => {
    const c = FFC_AXIS();
    const pctDone = Math.min(100, (ytdActual / annualFc) * 100);
    return {
      grid: { left: 6, right: 16, top: 36, bottom: 6, containLabel: true },
      tooltip: { trigger: 'item', backgroundColor: c.tooltipBg, borderColor: c.tooltipBorder, textStyle: { color: c.tooltipText, fontFamily: c.font, fontSize: 12 }, valueFormatter: (v) => '$' + Math.round(v).toLocaleString() },
      xAxis: { type: 'value', max: annualFc, splitLine: { show: false }, axisLabel: { color: c.label, fontFamily: c.font, fontSize: 10, formatter: (v) => '$' + (v/1e6).toFixed(0) + 'M' } },
      yAxis: { type: 'category', data: ['YTD'], axisLine: { show: false }, axisTick: { show: false }, axisLabel: { color: c.text, fontFamily: c.font, fontSize: 12 } },
      title: { text: pctDone.toFixed(1) + '% of 2026 forecast', right: 0, top: 0, textStyle: { color: c.gold, fontFamily: c.font, fontSize: 12, fontWeight: 500 } },
      series: [
        { type: 'bar', stack: 't', data: [ytdActual], itemStyle: { color: c.tealDeep, borderRadius: [4,0,0,4] }, barWidth: 26, animationDuration: 800 },
        { type: 'bar', stack: 't', data: [annualFc - ytdActual], itemStyle: { color: c.remaining, borderRadius: [0,4,4,0] }, barWidth: 26 },
      ],
    };
  }, [ytdActual, annualFc]);
  return <div ref={ref} style={{ width: '100%', height: '100%' }} />;
}

Object.assign(window, { CompareChart, TrendChart, AnnualChart });
