// ===== Optimierung → Reports & Analytics (Dashboard-Builder) =====
const { useState: useRpS, useEffect: useRpE } = React;

const RP_KEY = 'solver.reports';
// Datenquellen: Aufträge (A_ORDERS) + Shopfloor-Maßnahmen (SfStore)
const RP_SOURCES = {
  orders: { label: 'Aufträge', get: () => window.A_ORDERS || [],
    dims: [['system', 'Arbeitssystem'], ['kunde', 'Kunde'], ['abc', 'ABC'], ['status', 'Status'], ['produkt', 'Produkt']],
    measures: [['count', 'Anzahl'], ['istArbeit', 'Σ Ist-Arbeit [h]'], ['avgDLZ', 'Ø Durchlaufzeit [T]'], ['avgTA', 'Ø Terminabw. [T]'], ['spät', 'Verspätet']] },
  measures: { label: 'Maßnahmen', get: () => (window.SfStore ? window.SfStore.list : []),
    dims: [['cat', 'Kategorie'], ['owner', 'Verantwortlich'], ['status', 'Status'], ['ref', 'Bezug']],
    measures: [['count', 'Anzahl'], ['offen', 'Offen']] },
  comments: { label: 'Kommentare', get: () => (window.KkStore ? window.KkStore.list : []),
    dims: [['cat', 'Kategorie'], ['kind', 'Objekttyp']],
    measures: [['count', 'Anzahl']] },
};
const RP_PALETTE = [['bar', 'Balken', 'layers'], ['donut', 'Donut', 'target'], ['table', 'Tabelle', 'box']];
const RP_COLORS = ['#2A4D74', '#3269B4', '#5B8AC9', '#A7C2E7', '#E0A53B', '#8C8A85', '#9AA3AE', '#46586E'];

function rpVal(src, dim, r) {
  const v = r[dim];
  if (v == null || v === '') return '—';
  if (src === 'measures' && dim === 'cat') return (window.SF_CAT_LABELS && window.SF_CAT_LABELS[v]) || v;
  if (src === 'measures' && dim === 'status') return ({ offen: 'Offen', arbeit: 'In Arbeit', erledigt: 'Erledigt' })[v] || v;
  return String(v);
}
function rpMeasure(recs, src, measure) {
  const n = recs.length;
  if (measure === 'count') return n;
  if (measure === 'istArbeit') return Math.round(recs.reduce((s, r) => s + (r.istArbeit || 0), 0));
  if (measure === 'avgDLZ') { const d = recs.filter(r => r.istEnde); return d.length ? Math.round(d.reduce((s, r) => s + (r.istDLZ || 0), 0) / d.length * 10) / 10 : 0; }
  if (measure === 'avgTA') { const d = recs.filter(r => r.istEnde); return d.length ? Math.round(d.reduce((s, r) => s + (r.taAbgang || 0), 0) / d.length * 10) / 10 : 0; }
  if (measure === 'spät') return recs.filter(r => r.istEnde && r.taAbgang > 0).length;
  if (measure === 'offen') return recs.filter(r => r.status !== 'erledigt').length;
  return n;
}
function rpAgg(w) {
  const list = (RP_SOURCES[w.source].get() || []);
  const g = {};
  list.forEach(r => { const k = rpVal(w.source, w.dim, r); (g[k] = g[k] || []).push(r); });
  return Object.keys(g).map(k => ({ key: k, value: rpMeasure(g[k], w.source, w.measure) })).sort((a, b) => b.value - a.value);
}
function rpDefaults(viz) { return { id: 'w' + Date.now() + Math.floor(Math.random() * 99), viz, title: 'Neues Widget', source: 'orders', dim: 'system', measure: 'count', wide: viz === 'bar' }; }

function RpWidget({ w, onChange, onRemove }) {
  const data = rpAgg(w);
  const max = Math.max(1, ...data.map(d => d.value));
  const src = RP_SOURCES[w.source];
  const set = (k, v) => { const nw = { ...w, [k]: v }; if (k === 'source') { nw.dim = RP_SOURCES[v].dims[0][0]; nw.measure = RP_SOURCES[v].measures[0][0]; } onChange(nw); };
  const total = data.reduce((s, d) => s + d.value, 0) || 1;
  let acc = 0;
  const segs = data.slice(0, 8).map((d, i) => { const a0 = acc / total * 360; acc += d.value; const a1 = acc / total * 360; return { d, a0, a1, c: RP_COLORS[i % RP_COLORS.length] }; });
  const arc = (cx, cy, r, a0, a1) => { const p = (a) => [cx + r * Math.cos((a - 90) * Math.PI / 180), cy + r * Math.sin((a - 90) * Math.PI / 180)]; const [x0, y0] = p(a0), [x1, y1] = p(a1); const large = a1 - a0 > 180 ? 1 : 0; return `M ${cx} ${cy} L ${x0} ${y0} A ${r} ${r} 0 ${large} 1 ${x1} ${y1} Z`; };
  const sel = { height: 30, padding: '0 8px', borderRadius: 6, border: '1px solid var(--line-2)', background: 'var(--surface)', color: 'var(--ink)', fontSize: 12 };

  return (
    <div style={{ gridColumn: w.wide ? 'span 2' : 'span 1', background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 10, boxShadow: 'var(--shadow)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', borderBottom: '1px solid var(--line)' }}>
        <input value={w.title} onChange={e => set('title', e.target.value)} style={{ flex: 1, border: 'none', background: 'transparent', fontSize: 13.5, fontWeight: 600, color: 'var(--ink)', outline: 'none' }} />
        <button onClick={() => set('wide', !w.wide)} title="Breite" style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--muted)' }}><Icon name="expand" size={14} /></button>
        <button onClick={onRemove} title="Entfernen" style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--muted)' }}><Icon name="close" size={14} /></button>
      </div>
      <div style={{ display: 'flex', gap: 6, padding: '8px 12px', borderBottom: '1px solid var(--line)', flexWrap: 'wrap' }}>
        <select value={w.source} onChange={e => set('source', e.target.value)} style={sel}>{Object.keys(RP_SOURCES).map(k => <option key={k} value={k}>{RP_SOURCES[k].label}</option>)}</select>
        <select value={w.dim} onChange={e => set('dim', e.target.value)} style={sel}>{src.dims.map(d => <option key={d[0]} value={d[0]}>nach {d[1]}</option>)}</select>
        <select value={w.measure} onChange={e => set('measure', e.target.value)} style={sel}>{src.measures.map(m => <option key={m[0]} value={m[0]}>{m[1]}</option>)}</select>
      </div>
      <div style={{ padding: 12, flex: 1, minHeight: 150 }}>
        {data.length === 0 ? <div style={{ color: 'var(--muted)', fontSize: 12, textAlign: 'center', padding: 20 }}>Keine Daten</div>
          : w.viz === 'bar' ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              {data.slice(0, 10).map((d, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ width: 96, fontSize: 11.5, color: 'var(--ink-2)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} title={d.key}>{d.key}</span>
                  <span style={{ flex: 1, height: 14, background: 'var(--surface-2)', borderRadius: 3, overflow: 'hidden' }}><span style={{ display: 'block', height: '100%', width: (d.value / max * 100) + '%', background: '#3269B4', borderRadius: 3 }} /></span>
                  <span className="num" style={{ width: 52, textAlign: 'right', fontFamily: 'var(--mono)', fontSize: 11.5, fontWeight: 600 }}>{d.value.toLocaleString('de-DE')}</span>
                </div>
              ))}
            </div>
          ) : w.viz === 'donut' ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <svg viewBox="0 0 120 120" style={{ width: 120, height: 120, flex: '0 0 auto' }}>
                {segs.map((s, i) => <path key={i} d={arc(60, 60, 56, s.a0, s.a1)} fill={s.c} />)}
                <circle cx="60" cy="60" r="32" fill="var(--panel)" />
              </svg>
              <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 5 }}>
                {segs.map((s, i) => <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12 }}><span style={{ width: 10, height: 10, borderRadius: 2, background: s.c, flex: '0 0 auto' }} /><span style={{ flex: 1, color: 'var(--ink-2)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.d.key}</span><b className="num" style={{ fontFamily: 'var(--mono)' }}>{s.d.value.toLocaleString('de-DE')}</b></div>)}
              </div>
            </div>
          ) : (
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}><tbody>
              {data.map((d, i) => <tr key={i} style={{ borderBottom: '1px solid var(--line)' }}><td style={{ padding: '6px 8px', color: 'var(--ink)' }}>{d.key}</td><td className="num" style={{ padding: '6px 8px', textAlign: 'right', fontFamily: 'var(--mono)', fontWeight: 600 }}>{d.value.toLocaleString('de-DE')}</td></tr>)}
            </tbody></table>
          )}
      </div>
    </div>
  );
}

function ReportsView() {
  const [, force] = useRpS(0);
  useRpE(() => { const u1 = window.SfStore ? window.SfStore.sub(() => force(n => n + 1)) : null; const u2 = window.KkStore ? window.KkStore.sub(() => force(n => n + 1)) : null; return () => { u1 && u1(); u2 && u2(); }; }, []);
  const [widgets, setWidgets] = useRpS(() => { try { const s = JSON.parse(localStorage.getItem(RP_KEY) || 'null'); return Array.isArray(s) ? s : seedReports(); } catch (e) { return seedReports(); } });
  const save = (ws) => { setWidgets(ws); try { localStorage.setItem(RP_KEY, JSON.stringify(ws)); } catch (e) {} };
  const add = (viz) => save([...widgets, rpDefaults(viz)]);
  const change = (id, nw) => save(widgets.map(w => w.id === id ? nw : w));
  const remove = (id) => save(widgets.filter(w => w.id !== id));
  const [over, setOver] = useRpS(false);

  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 }}>Reports &amp; Analytics</span>
        <span className="label">Dashboard-Builder · live aus den Daten</span>
        {widgets.length > 0 && <button onClick={() => save([])} style={{ marginLeft: 'auto', height: 32, padding: '0 12px', borderRadius: 7, border: '1px solid var(--line-2)', background: 'var(--surface)', color: 'var(--ink-2)', fontSize: 12.5, cursor: 'pointer' }}>Alle entfernen</button>}
      </header>
      <main style={{ flex: 1, minHeight: 0, overflow: 'auto', padding: 14, display: 'flex', gap: 14 }}>
        <aside style={{ width: 168, flex: '0 0 auto' }}>
          <div className="label" style={{ marginBottom: 8 }}>Widgets</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {RP_PALETTE.map(p => (
              <div key={p[0]} draggable onDragStart={e => { e.dataTransfer.setData('text/plain', p[0]); e.dataTransfer.effectAllowed = 'copy'; }} onClick={() => add(p[0])}
                style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '10px 12px', borderRadius: 8, border: '1px solid var(--line-2)', background: 'var(--panel)', cursor: 'grab', fontSize: 13, fontWeight: 500 }}>
                <Icon name={p[2]} size={16} style={{ color: 'var(--accent-ink)' }} /> {p[1]}
              </div>
            ))}
          </div>
          <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 10, lineHeight: 1.4 }}>Ziehen oder klicken zum Hinzufügen</div>
        </aside>
        <section onDragOver={e => { e.preventDefault(); setOver(true); }} onDragLeave={() => setOver(false)} onDrop={e => { e.preventDefault(); setOver(false); const v = e.dataTransfer.getData('text/plain'); if (['bar', 'donut', 'table'].includes(v)) add(v); }}
          style={{ flex: 1, minWidth: 0, borderRadius: 10, outline: over ? '2px dashed var(--accent-ink)' : 'none', outlineOffset: -4 }}>
          {widgets.length === 0 ? (
            <div style={{ height: '100%', minHeight: 300, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8, color: 'var(--muted)', border: '2px dashed var(--line-2)', borderRadius: 10 }}>
              <Icon name="layers" size={28} /><b style={{ color: 'var(--ink-2)' }}>Leeres Dashboard</b><span style={{ fontSize: 12.5 }}>Widget aus der Leiste hierher ziehen — oder anklicken.</span>
            </div>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', gap: 14 }}>
              {widgets.map(w => <RpWidget key={w.id} w={w} onChange={nw => change(w.id, nw)} onRemove={() => remove(w.id)} />)}
            </div>
          )}
        </section>
      </main>
    </React.Fragment>
  );
}

function seedReports() {
  return [
    { id: 'r1', viz: 'bar', title: 'Aufträge je Arbeitssystem', source: 'orders', dim: 'system', measure: 'count', wide: true },
    { id: 'r2', viz: 'donut', title: 'Aufträge nach ABC', source: 'orders', dim: 'abc', measure: 'count', wide: false },
    { id: 'r3', viz: 'bar', title: 'Ø Terminabweichung je System', source: 'orders', dim: 'system', measure: 'avgTA', wide: false },
    { id: 'r4', viz: 'donut', title: 'Offene Maßnahmen nach Kategorie', source: 'measures', dim: 'cat', measure: 'offen', wide: false },
    { id: 'r5', viz: 'table', title: 'Σ Ist-Arbeit je Kunde', source: 'orders', dim: 'kunde', measure: 'istArbeit', wide: false },
  ];
}

Object.assign(window, { ReportsView });
