// ===== Absatzprognose — Chart (Historie + ML-Prognose + Kundenabrufplan) =====
const { useState: useFcS, useMemo: useFcM } = React;

function ForecastChart({ article, history, forecast, abrufplan, compare }) {
  const W = 1000, H = 300, padL = 56, padR = 16, padT = 16, padB = 38;
  const plotW = W - padL - padR, plotH = H - padT - padB;

  const today = window.FC_TODAY;
  const allDates = [
    ...history.map(r => r.datum),
    ...forecast.points.map(p => p.datum),
    ...abrufplan.map(a => a.datum),
  ].map(d => new Date(d + 'T00:00:00Z').getTime());
  if (!allDates.length) return <div style={{ padding: 30, color: 'var(--muted)' }}>Keine Daten</div>;
  const tMin = Math.min(...allDates), tMax = Math.max(...allDates);
  const span = (tMax - tMin) || 1;
  const allQty = [
    ...history.map(r => r.menge),
    ...forecast.points.map(p => p.hi),
    ...abrufplan.map(a => a.menge),
  ];
  const qMax = Math.max(...allQty, 1) * 1.08;

  const x = (t) => padL + ((new Date(t + 'T00:00:00Z').getTime() - tMin) / span) * plotW;
  const y = (q) => padT + plotH * (1 - q / qMax);
  const xToday = x(window.fcIso(today));

  // Monatsachse
  const ticks = [];
  const d0 = new Date(tMin); d0.setUTCDate(1);
  for (let dt = new Date(d0); dt.getTime() <= tMax; dt.setUTCMonth(dt.getUTCMonth() + 2)) {
    ticks.push(new Date(dt));
  }

  // Prognoseband-Polygon (nur Zukunft)
  const fut = forecast.points.filter(p => p.future);
  let bandPath = '';
  if (fut.length) {
    const up = fut.map(p => `${x(p.datum).toFixed(1)},${y(p.hi).toFixed(1)}`);
    const dn = fut.slice().reverse().map(p => `${x(p.datum).toFixed(1)},${y(p.lo).toFixed(1)}`);
    bandPath = 'M' + up.join(' L') + ' L' + dn.join(' L') + ' Z';
  }
  const fcLine = forecast.points.map((p, i) => `${i ? 'L' : 'M'}${x(p.datum).toFixed(1)} ${y(p.menge).toFixed(1)}`).join(' ');

  const gridY = [0, 0.25, 0.5, 0.75, 1].map(f => Math.round(qMax * f / 500) * 500);

  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: H, minWidth: 680, display: 'block', fontFamily: 'var(--mono)' }}>
      {/* Gitter + y-Achse */}
      {gridY.map((q, i) => (
        <g key={i}>
          <line x1={padL} y1={y(q)} x2={W - padR} y2={y(q)} stroke="var(--line)" strokeWidth="1" />
          <text x={padL - 8} y={y(q) + 3} textAnchor="end" style={{ fontSize: 10, fill: 'var(--muted)' }}>{q.toLocaleString('de-DE')}</text>
        </g>
      ))}
      {/* x-Achse Monate */}
      {ticks.map((t, i) => {
        const xx = x(window.fcIso(t));
        return <g key={i}>
          <line x1={xx} y1={padT} x2={xx} y2={padT + plotH} stroke="var(--line)" strokeWidth="0.5" opacity="0.5" />
          <line x1={xx} y1={padT + plotH} x2={xx} y2={padT + plotH + 4} stroke="var(--muted)" strokeWidth="1" />
          <text x={xx} y={H - 22} textAnchor="middle" style={{ fontSize: 9, fill: 'var(--muted)' }}>{t.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: '2-digit' })}</text>
        </g>;
      })}

      {/* Heute-Linie */}
      <line x1={xToday} y1={padT} x2={xToday} y2={padT + plotH} stroke="var(--accent-ink)" strokeWidth="1.5" strokeDasharray="4 3" />
      <text x={xToday} y={padT - 4} textAnchor="middle" style={{ fontSize: 9, fill: 'var(--accent-ink)', fontWeight: 700 }}>heute</text>

      {/* Prognoseband */}
      {bandPath && <path d={bandPath} fill="color-mix(in oklch, var(--accent) 30%, transparent)" stroke="none" />}
      {/* ML-Prognoselinie */}
      <path d={fcLine} fill="none" stroke="var(--accent-ink)" strokeWidth="2" strokeDasharray={fut.length ? '0' : '0'} />

      {/* Historische Abrufe (Balken) */}
      {history.map((r, i) => (
        <g key={'h' + i}>
          <line x1={x(r.datum)} y1={y(0)} x2={x(r.datum)} y2={y(r.menge)} stroke="var(--ink-2)" strokeWidth="2" opacity="0.55" />
          <circle cx={x(r.datum)} cy={y(r.menge)} r="2.6" fill="var(--ink)" />
        </g>
      ))}

      {/* ML-Prognosepunkte (Zukunft) */}
      {fut.map((p, i) => <circle key={'f' + i} cx={x(p.datum)} cy={y(p.menge)} r="3" fill="var(--accent-ink)" stroke="#fff" strokeWidth="1" />)}

      {/* Kundenabrufplan */}
      {(compare ? compare.matches : abrufplan.map(c => ({ cust: c }))).map((m, i) => {
        const c = m.cust || m;
        const flagged = m.outOfBand || (m.within === false);
        const col = flagged ? 'var(--bad-ink)' : 'var(--warn-ink)';
        const dd = new Date(c.datum + 'T00:00:00Z');
        const lbl = dd.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit' });
        return (
          <g key={'c' + i}>
            <line x1={x(c.datum)} y1={y(0)} x2={x(c.datum)} y2={y(c.menge)} stroke={col} strokeWidth="2.5" />
            <rect x={x(c.datum) - 4} y={y(c.menge) - 4} width="8" height="8" transform={`rotate(45 ${x(c.datum)} ${y(c.menge)})`}
              fill={col} stroke="#fff" strokeWidth="1" />
            <text x={x(c.datum)} y={y(c.menge) - 9} textAnchor="middle" style={{ fontSize: 8.5, fill: col, fontWeight: 700 }}>{c.menge.toLocaleString('de-DE')}</text>
            <text x={x(c.datum)} y={y(0) + 11} textAnchor="middle" style={{ fontSize: 8, fill: col, fontWeight: 600 }}>{lbl}</text>
          </g>
        );
      })}
    </svg>
  );
}

function ChartLegend() {
  const item = (color, label, shape) => (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11, color: 'var(--ink-2)' }}>
      {shape === 'line' ? <span style={{ width: 18, height: 0, borderTop: `2px solid ${color}` }} />
        : shape === 'band' ? <span style={{ width: 18, height: 10, background: 'color-mix(in oklch, var(--accent) 30%, transparent)', borderRadius: 2 }} />
        : shape === 'diamond' ? <span style={{ width: 9, height: 9, background: color, transform: 'rotate(45deg)' }} />
        : <span style={{ width: 9, height: 9, borderRadius: 99, background: color }} />}
      {label}
    </span>
  );
  return (
    <div style={{ display: 'flex', gap: 18, flexWrap: 'wrap', padding: '8px 4px 0' }}>
      {item('var(--ink)', 'Historische Abrufe (Ist)', 'dot')}
      {item('var(--accent-ink)', 'ML-Prognose', 'line')}
      {item('', 'Prognoseband', 'band')}
      {item('var(--warn-ink)', 'Kundenabrufplan', 'diamond')}
      {item('var(--bad-ink)', 'Auffälliger Abruf', 'diamond')}
    </div>
  );
}

Object.assign(window, { ForecastChart, ChartLegend });
