// ===== Absatzprognose — Hauptansicht =====
const { useState: useAbS, useMemo: useAbM } = React;

const PATTERN_TINT = {
  'regelmäßig': 'var(--good)', 'saisonal': 'var(--accent)', 'erratisch': 'var(--bad)',
  'wachsend': 'var(--good)', 'fallend': 'var(--warn)', 'hochvolumig': 'var(--accent)',
};
const fmtN = (v) => Math.round(v).toLocaleString('de-DE');
const fmtDe = (s) => { const d = new Date(s + 'T00:00:00Z'); return d.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: '2-digit' }); };

function AbsatzView({ onCreatePA, paList }) {
  const articles = window.FC_ARTICLES;
  const [selId, setSel] = useAbS(articles[0].id);
  const [plans, setPlans] = useAbS(() => {
    const o = {}; articles.forEach(a => { o[a.id] = window.FC_ABRUFPLAN[a.id].map(r => ({ ...r })); }); return o;
  });
  const [horizon, setHorizon] = useAbS(270);

  const article = articles.find(a => a.id === selId);
  const history = window.FC_RAW[selId];
  const abrufplan = plans[selId] || [];

  const forecast = useAbM(() => window.forecastArticle(history, { horizonDays: horizon }), [selId, horizon]);
  const compare = useAbM(() => window.comparePlan(forecast, abrufplan), [forecast, abrufplan]);

  // Plan-Editor
  const setPlan = (rows) => setPlans(p => ({ ...p, [selId]: rows }));
  const addRow = () => {
    const last = abrufplan.length ? abrufplan[abrufplan.length - 1].datum : window.fcIso(window.FC_TODAY);
    const nd = window.fcAddDays(new Date(last + 'T00:00:00Z'), Math.round(article.intervalMean));
    setPlan([...abrufplan, { datum: window.fcIso(nd), menge: article.qtyMean, id: selId + '-c-' + Date.now() }]);
  };
  const updRow = (id, patch) => setPlan(abrufplan.map(r => r.id === id ? { ...r, ...patch } : r));
  const delRow = (id) => setPlan(abrufplan.filter(r => r.id !== id));
  const applyFc = () => {
    // ML-Prognose als Abrufplan übernehmen
    const fut = forecast.points.filter(p => p.future);
    setPlan(fut.map((p, i) => ({ datum: p.datum, menge: p.menge, id: selId + '-fc-' + i })));
  };
  // Plan-Spalte (separat von der Kundenabrufmenge) auf die Prognose setzen
  const takeAllFc = () => setPlan(compare.matches.map(m => ({ ...m.cust, plan: m.fc ? m.fc.menge : m.cust.menge })));

  const st = forecast.stats;

  return (
    <React.Fragment>
      <header style={{ flex: '0 0 auto', display: 'flex', alignItems: 'center', gap: 14, padding: '0 18px', height: 56, background: 'var(--panel)', borderBottom: '1px solid var(--line-2)' }}>
        <span style={{ fontSize: 14.5, fontWeight: 600 }}>Absatzprognose</span>
        <span className="label">ML-Mustererkennung · Kundenabruf-Validierung</span>
        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 10 }}>
          <span className="label">Horizont</span>
          {[90, 180, 270, 365].map(h => (
            <button key={h} onClick={() => setHorizon(h)} style={{ height: 30, padding: '0 10px', borderRadius: 6, fontFamily: 'var(--mono)', fontSize: 11.5, fontWeight: 600, cursor: 'pointer',
              border: '1px solid ' + (horizon === h ? 'var(--accent-ink)' : 'var(--line-2)'), background: horizon === h ? 'var(--accent)' : 'var(--surface)', color: horizon === h ? 'var(--accent-ink)' : 'var(--ink-2)' }}>{h} T</button>
          ))}
        </div>
      </header>

      <main style={{ flex: 1, minHeight: 0, display: 'flex' }}>
        {/* Artikelliste */}
        <div style={{ width: 268, flex: '0 0 auto', borderRight: '1px solid var(--line)', overflow: 'auto', background: 'var(--surface)' }}>
          <div className="label" style={{ padding: '12px 14px 6px' }}>Artikel · {articles.length}</div>
          {articles.map(a => {
            const on = a.id === selId;
            const hist = window.FC_RAW[a.id];
            const sa = window.analyzeArticle(hist);
            return (
              <button key={a.id} onClick={() => setSel(a.id)} onContextMenu={e => window.kikiMenu(e, { id: a.id, label: `${a.id} · ${a.name}`, kind: 'Artikel' })} style={{ display: 'block', width: '100%', textAlign: 'left', padding: '11px 14px', cursor: 'pointer',
                border: 'none', borderBottom: '1px solid var(--line)', borderLeft: '3px solid ' + (on ? 'var(--accent-ink)' : 'transparent'),
                background: on ? 'var(--accent)' : 'transparent' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 3 }}>
                  <span className="num" style={{ fontFamily: 'var(--mono)', fontSize: 11.5, fontWeight: 700, color: 'var(--ink)' }}>{a.id}</span>
                  <span style={{ fontSize: 9.5, padding: '1px 6px', borderRadius: 99, fontWeight: 600,
                    background: `color-mix(in oklch, ${PATTERN_TINT[a.pattern]} 50%, var(--surface))`, color: 'var(--ink-2)' }}>{a.pattern}</span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--ink-2)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.name}</div>
                <div className="num" style={{ fontFamily: 'var(--mono)', fontSize: 9.5, color: 'var(--muted)', marginTop: 2 }}>
                  {a.kunde} · {hist.length} Abrufe · cv {(sa.ivCv).toFixed(2)}
                </div>
              </button>
            );
          })}
        </div>

        {/* Detail */}
        <div style={{ flex: 1, minWidth: 0, overflow: 'auto', padding: 14, display: 'flex', flexDirection: 'column', gap: 12 }}>
          {/* Chart-Panel */}
          <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 8, boxShadow: 'var(--shadow)', overflow: 'hidden' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderBottom: '1px solid var(--line)' }}>
              <span style={{ fontWeight: 600, fontSize: 13.5 }}>{article.name}</span>
              <span className="label">{article.id} · {article.kunde}</span>
              <div style={{ marginLeft: 'auto', display: 'flex', gap: 16 }}>
                <Kpi label="Ø Intervall" value={`${st.ivMeanAll.toFixed(0)} T`} sub={`cv ${st.ivCv.toFixed(2)}`} />
                <Kpi label="Ø Menge" value={fmtN(st.qtyMeanAll)} sub={`cv ${st.qtyCv.toFixed(2)}`} />
                <Kpi label="Trend/Abruf" value={`${st.qtySlope >= 0 ? '+' : ''}${fmtN(st.qtySlope)}`} tone={st.qtySlope >= 0 ? 'var(--good-ink)' : 'var(--bad-ink)'} />
              </div>
            </div>
            <div style={{ padding: '12px 14px 6px' }}>
              <div style={{ maxHeight: 248, overflow: 'auto', border: '1px solid var(--line)', borderRadius: 6 }}>
                <ForecastChart article={article} history={history} forecast={forecast} abrufplan={abrufplan} compare={compare} />
              </div>
              <ChartLegend />
            </div>
          </div>

          {/* Gegenüberstellung */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {/* Kundenabrufplan (editierbar) */}
            <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 8, boxShadow: 'var(--shadow)', display: 'flex', flexDirection: 'column' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px', borderBottom: '1px solid var(--line)' }}>
                <Icon name="box" size={15} style={{ color: 'var(--ink-2)' }} />
                <span style={{ fontWeight: 600, fontSize: 13 }}>Kundenabrufplan</span>
                <span className="label">{abrufplan.length} Abrufe</span>
                <div style={{ marginLeft: 'auto', display: 'flex', gap: 7 }}>
                  <button onClick={takeAllFc} title="Prognose als Plan für alle Zeilen übernehmen" style={{ ...miniBtn, color: 'var(--accent-ink)', borderColor: 'var(--accent-line)' }}>Plan = Prognose (alle)</button>
                  <button onClick={addRow} style={miniBtn}>+ Abruf</button>
                </div>
              </div>
              <div style={{ overflow: 'auto', maxHeight: 240 }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
                  <thead><tr>
                    {['Datum', 'Abrufmenge', 'Prognose', 'Plan', 'vs. Prog.', ''].map((h, i) => <th key={i} style={{ ...window.thStyle, textAlign: i >= 1 && i <= 3 ? 'right' : 'left' }}>{h}</th>)}
                  </tr></thead>
                  <tbody>
                    {compare.matches.map((m, i) => {
                      const flagged = m.outOfBand || m.within === false;
                      const fcQty = m.fc ? m.fc.menge : null;
                      const planVal = m.cust.plan != null ? m.cust.plan : m.cust.menge;
                      return (
                        <tr key={m.cust.id} onContextMenu={e => window.kikiMenu(e, { id: article.id, label: `${article.id} · Abruf ${window.fcIso ? '' : ''}${m.cust.datum}`, kind: 'Kundenabruf' })} style={{ borderBottom: '1px solid var(--line)', background: flagged ? 'color-mix(in oklch, var(--bad) 14%, transparent)' : 'transparent' }}>
                          <td style={{ padding: '5px 10px' }}>
                            <input type="date" value={m.cust.datum} onChange={e => updRow(m.cust.id, { datum: e.target.value })} style={inp} />
                          </td>
                          <td style={{ padding: '5px 10px', textAlign: 'right' }}>
                            <input type="number" value={m.cust.menge} step="50" onChange={e => updRow(m.cust.id, { menge: +e.target.value })} style={{ ...inp, width: 74, textAlign: 'right' }} />
                          </td>
                          <td style={{ padding: '5px 10px', textAlign: 'right' }}>
                            {fcQty != null ? <span className="num" style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--accent-ink)', fontWeight: 600 }}>{fmtN(fcQty)}</span> : <span style={{ color: 'var(--muted)' }}>—</span>}
                          </td>
                          <td style={{ padding: '5px 10px', textAlign: 'right', whiteSpace: 'nowrap' }}>
                            <input type="number" value={planVal} step="50" onChange={e => updRow(m.cust.id, { plan: +e.target.value })} style={{ ...inp, width: 74, textAlign: 'right' }} />
                            <button onClick={() => updRow(m.cust.id, { plan: fcQty != null ? fcQty : m.cust.menge })} title="Prognose in Plan übernehmen" disabled={fcQty == null}
                              style={{ marginLeft: 4, width: 24, height: 26, verticalAlign: 'middle', border: '1px solid var(--line-2)', borderRadius: 5, background: 'var(--surface)', color: 'var(--accent-ink)', cursor: fcQty == null ? 'not-allowed' : 'pointer', opacity: fcQty == null ? 0.4 : 1, display: 'inline-grid', placeItems: 'center' }}><Icon name="trend" size={13} /></button>
                          </td>
                          <td style={{ padding: '5px 10px' }}>
                            {m.fc ? <span className="num" style={{ fontFamily: 'var(--mono)', fontSize: 11.5, color: Math.abs(m.qtyDev) > 0.25 ? 'var(--bad-ink)' : 'var(--ink-2)' }}>
                              {m.qtyDev >= 0 ? '+' : ''}{(m.qtyDev * 100).toFixed(0)}%{m.dateDeltaDays ? ` · ${m.dateDeltaDays > 0 ? '+' : ''}${m.dateDeltaDays}T` : ''}
                            </span> : <span style={{ color: 'var(--muted)' }}>—</span>}
                          </td>
                          <td style={{ padding: '5px 6px', textAlign: 'right', whiteSpace: 'nowrap' }}>
                            {(() => {
                              const created = paList && paList.find(p => p.source === 'prognose' && p._row === m.cust.id);
                              return (
                                <button onClick={() => { if (onCreatePA && !created) { const planVal = m.cust.plan != null ? m.cust.plan : m.cust.menge; const nr = onCreatePA({ ...article, _row: m.cust.id }, m.cust.datum, planVal); } }}
                                  title={created ? 'Planauftrag erstellt' : 'Planauftrag erzeugen → Feinplanung'} disabled={!!created}
                                  style={{ height: 24, padding: '0 8px', borderRadius: 5, fontFamily: 'var(--mono)', fontSize: 10.5, fontWeight: 700,
                                    border: '1px solid ' + (created ? '#B9A8D8' : 'var(--accent-line)'), background: created ? '#E2D8F0' : 'var(--surface)', color: created ? '#7A5BB0' : 'var(--accent-ink)', cursor: created ? 'default' : 'pointer' }}>
                                  {created ? '✓ PA' : 'PA'}
                                </button>
                              );
                            })()}
                            <button onClick={() => delRow(m.cust.id)} style={{ marginLeft: 4, border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--muted)', padding: 2, verticalAlign: 'middle' }}><Icon name="trash" size={14} /></button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                  <tfoot>
                    <tr style={{ borderTop: '2px solid var(--line-2)', background: 'var(--surface-2)' }}>
                      <td style={{ padding: '7px 10px', fontWeight: 600, fontSize: 11.5, color: 'var(--ink-2)' }}>Σ Zeitraum</td>
                      <td style={{ padding: '7px 10px', textAlign: 'right' }} className="num"><span style={{ fontFamily: 'var(--mono)', fontWeight: 700, fontSize: 12.5 }}>{fmtN(compare.matches.reduce((s, m) => s + (m.cust.menge || 0), 0))}</span></td>
                      <td style={{ padding: '7px 10px', textAlign: 'right' }} className="num"><span style={{ fontFamily: 'var(--mono)', fontWeight: 700, fontSize: 12.5, color: 'var(--accent-ink)' }}>{fmtN(compare.matches.reduce((s, m) => s + (m.fc ? m.fc.menge : 0), 0))}</span></td>
                      <td style={{ padding: '7px 10px', textAlign: 'right' }} className="num"><span style={{ fontFamily: 'var(--mono)', fontWeight: 700, fontSize: 12.5 }}>{fmtN(compare.matches.reduce((s, m) => s + (m.cust.plan != null ? m.cust.plan : m.cust.menge), 0))}</span></td>
                      <td colSpan={2}></td>
                    </tr>
                  </tfoot>
                </table>
              </div>
            </div>

            {/* Validierung / Flags */}
            <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 8, boxShadow: 'var(--shadow)', display: 'flex', flexDirection: 'column' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px', borderBottom: '1px solid var(--line)' }}>
                <Icon name="trend" size={15} style={{ color: 'var(--ink-2)' }} />
                <span style={{ fontWeight: 600, fontSize: 13 }}>Validierung gegen ML-Prognose</span>
              </div>
              <div style={{ padding: 14 }}>
                <div style={{ display: 'flex', gap: 18, marginBottom: 12 }}>
                  <Kpi label="Σ Kunde" value={fmtN(compare.totalCust)} />
                  <Kpi label="Σ Prognose" value={fmtN(compare.totalFc)} />
                  <Kpi label="Abweichung" value={`${compare.devPct >= 0 ? '+' : ''}${compare.devPct.toFixed(0)}%`} tone={Math.abs(compare.devPct) > 15 ? 'var(--bad-ink)' : 'var(--good-ink)'} />
                </div>
                {compare.flags.length === 0 ? (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', background: 'color-mix(in oklch, var(--good) 18%, var(--surface))', border: '1px solid color-mix(in oklch, var(--good) 40%, var(--line))', borderRadius: 7, fontSize: 12, color: 'var(--good-ink)' }}>
                    <Icon name="check" size={15} /> Abrufplan plausibel — keine Auffälligkeiten zur Prognose.
                  </div>
                ) : (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                    <div className="label">{compare.flags.length} Auffälligkeit{compare.flags.length > 1 ? 'en' : ''}</div>
                    {compare.flags.map((f, i) => (
                      <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: '7px 10px', background: 'color-mix(in oklch, var(--bad) 12%, var(--surface))', border: '1px solid color-mix(in oklch, var(--bad) 35%, var(--line))', borderRadius: 7 }}>
                        <Icon name={f.type === 'menge' ? 'box' : 'clock'} size={13} style={{ color: 'var(--bad-ink)', flex: '0 0 auto', marginTop: 1 }} />
                        <div style={{ minWidth: 0 }}>
                          <span className="num" style={{ fontFamily: 'var(--mono)', fontSize: 10.5, color: 'var(--bad-ink)', fontWeight: 600 }}>{fmtDe(f.datum)}</span>
                          <div style={{ fontSize: 11.5, color: 'var(--ink-2)' }}>{f.msg}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Rohdaten-Historie */}
          <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 8, boxShadow: 'var(--shadow)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px', borderBottom: '1px solid var(--line)' }}>
              <Icon name="layers" size={15} style={{ color: 'var(--ink-2)' }} />
              <span style={{ fontWeight: 600, fontSize: 13 }}>Rohdaten — Abruf-Historie</span>
              <span className="label">{history.length} Abrufe · 2 Jahre</span>
            </div>
            <div style={{ overflow: 'auto', maxHeight: 220 }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
                <thead><tr>
                  {['#', 'Abrufdatum', 'Menge', 'Intervall', 'Δ Vormonat'].map((h, i) => <th key={i} style={{ ...window.thStyle, textAlign: i === 0 || i >= 2 ? 'right' : 'left' }}>{h}</th>)}
                </tr></thead>
                <tbody>
                  {history.slice().reverse().map((r, ri) => {
                    const idx = history.length - ri;
                    const prev = history[idx - 2];
                    const iv = prev ? Math.round((new Date(r.datum) - new Date(prev.datum)) / 86400000) : null;
                    return (
                      <tr key={ri} style={{ borderBottom: '1px solid var(--line)' }}>
                        <td style={{ ...window.tdNum, color: 'var(--muted)' }}>{idx}</td>
                        <td style={{ padding: '5px 10px', fontFamily: 'var(--mono)', fontSize: 12 }}>{fmtDe(r.datum)}</td>
                        <td style={window.tdNum}>{fmtN(r.menge)}</td>
                        <td style={window.tdNum}>{iv != null ? iv + ' T' : '—'}</td>
                        <td style={window.tdNum}>{prev ? `${r.menge - prev.menge >= 0 ? '+' : ''}${fmtN(r.menge - prev.menge)}` : '—'}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </main>
    </React.Fragment>
  );
}

function Kpi({ label, value, sub, tone }) {
  return (
    <div style={{ textAlign: 'right' }}>
      <div className="num" style={{ fontFamily: 'var(--mono)', fontSize: 14, fontWeight: 600, color: tone || 'var(--ink)' }}>{value}</div>
      <div className="label" style={{ fontSize: 9 }}>{label}{sub ? ` · ${sub}` : ''}</div>
    </div>
  );
}

const miniBtn = { height: 28, padding: '0 10px', borderRadius: 6, border: '1px solid var(--line-2)', background: 'var(--surface)', color: 'var(--ink-2)', fontSize: 11.5, fontWeight: 500, cursor: 'pointer' };
const inp = { height: 28, padding: '0 7px', boxSizing: 'border-box', fontFamily: 'var(--mono)', fontSize: 12, border: '1px solid var(--line-2)', borderRadius: 5, background: 'var(--surface)', color: 'var(--ink)' };

Object.assign(window, { AbsatzView });
