// ===== Losgrößenberechnung nach Andler (Popup) =====
const { useState: useLS } = React;

function AndlerPopup({ op, onClose, onApply }) {
  const SD = window.STAMMDATEN;
  const stueckwertDefault = window.TEILEWERT[op.mat] ?? 10;
  // editierbare Felder, vorbelegt aus Stammdaten
  const [jahresbedarf, setJB] = useLS(op.jahresbedarf || op.menge * 24);
  const [stueckwert, setSW] = useLS(stueckwertDefault);
  const [zinssatz, setZins] = useLS(SD.zinssatz);
  const [lohn, setLohn] = useLS(SD.lohnkosten);
  const [msSatz, setMsSatz] = useLS(SD.maschinenstundensatz);

  const setupH = op.setupBaseMin != null ? op.setupBaseMin / 60 : 25 / 60; // Rüstdauer (h) — Schätzung
  const ruestH = (op._setupMin != null ? op._setupMin : 25) / 60;
  // Rüstkosten je Los = Rüstdauer × (Maschinenstundensatz + Lohnkosten)
  const ruestkosten = ruestH * (Number(msSatz) + Number(lohn));

  const { q: qOpt, ch } = window.andlerOptimum({ jahresbedarf: +jahresbedarf, ruestkosten, stueckwert: +stueckwert, zinssatz: +zinssatz });
  const kostenAt = (q) => window.losKosten(q, { jahresbedarf: +jahresbedarf, ruestkosten, ch });
  const kOpt = kostenAt(qOpt);
  const losProJahr = qOpt > 0 ? (+jahresbedarf / qOpt) : 0;

  // manuell überschreibbare Losgröße (vorbelegt mit dem berechneten Optimum)
  const [losInput, setLos] = useLS('');
  const losVal = losInput === '' ? Math.round(qOpt) : Math.max(1, Math.round(+losInput));

  const euro = (v) => '€ ' + (Math.round(v)).toLocaleString('de-DE');
  const fmt0 = (v) => Math.round(v).toLocaleString('de-DE');

  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(63,62,61,.34)', zIndex: 60, animation: 'rowIn .15s' }} />
      <div role="dialog" style={{ position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', zIndex: 61,
        width: 720, maxWidth: '94vw', maxHeight: '92vh', overflow: 'auto', background: 'var(--surface)', borderRadius: 12,
        border: '1px solid var(--line-2)', boxShadow: '0 24px 64px rgba(63,62,61,.28)', animation: 'rowIn .18s' }}>
        {/* Kopf */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '15px 20px', borderBottom: '1px solid var(--line)' }}>
          <span style={{ display: 'grid', placeItems: 'center', width: 26, height: 26, borderRadius: 6, background: 'var(--accent)', color: 'var(--accent-ink)' }}><Icon name="calc" size={16} /></span>
          <div>
            <div style={{ fontWeight: 600, fontSize: 14.5 }}>Losgrößenberechnung — Andler</div>
            <div className="num" style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>{op.nr} · {op.kurz} · {window.MATERIALS[op.mat].id}</div>
          </div>
          <button onClick={onClose} style={{ marginLeft: 'auto', width: 30, height: 30, border: '1px solid var(--line-2)', borderRadius: 6, background: 'var(--surface)', display: 'grid', placeItems: 'center', color: 'var(--ink-2)', cursor: 'pointer' }}><Icon name="close" size={15} /></button>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0 }}>
          {/* Eingaben */}
          <div style={{ padding: '16px 20px', borderRight: '1px solid var(--line)' }}>
            <div className="label" style={{ marginBottom: 10 }}>Parameter · aus Stammdaten</div>
            <Field label="Jahresbedarf" unit="Stück/Jahr" value={jahresbedarf} onChange={setJB} />
            <Field label="Teilewert" unit="€/Stück" value={stueckwert} onChange={setSW} step="0.1" hint={`Stammdaten ${window.MATERIALS[op.mat].id}`} />
            <Field label="Zins-/Lagersatz" unit="% p.a." value={zinssatz} onChange={setZins} />
            <Field label="Lohnkosten" unit="€/h" value={lohn} onChange={setLohn} />
            <Field label="Maschinenstundensatz" unit="€/h" value={msSatz} onChange={setMsSatz} />
            <div style={{ marginTop: 12, padding: '10px 12px', background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 8 }}>
              <Row2 k="Rüstdauer / Los" v={ruestH.toFixed(2).replace('.', ',') + ' h'} />
              <Row2 k="Rüstkosten / Los" v={euro(ruestkosten)} sub="= Rüstdauer × (Masch. + Lohn)" />
              <Row2 k="Lagerkostensatz" v={euro(ch) + ' /Stück·a'} sub="= Zinssatz × Teilewert" />
            </div>
          </div>

          {/* Ergebnis + Grafik */}
          <div style={{ padding: '16px 20px' }}>
            <div className="label" style={{ marginBottom: 10 }}>Optimale Losgröße</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
              <span className="num" style={{ fontFamily: 'var(--mono)', fontSize: 34, fontWeight: 700, color: 'var(--accent-ink)' }}>{fmt0(qOpt)}</span>
              <span style={{ fontSize: 13, color: 'var(--muted)' }}>Stück / Los</span>
            </div>
            <div style={{ display: 'flex', gap: 18, marginTop: 4, marginBottom: 12 }}>
              <span style={{ fontSize: 12, color: 'var(--ink-2)' }}>≈ <b className="num">{losProJahr.toFixed(1).replace('.', ',')}</b> Lose/Jahr</span>
              <span style={{ fontSize: 12, color: 'var(--ink-2)' }}>Gesamtkosten <b className="num">{euro(kOpt)}</b>/a</span>
            </div>
            <CostChart jahresbedarf={+jahresbedarf} ruestkosten={ruestkosten} ch={ch} qOpt={qOpt} aktuell={op.menge} kostenAt={kostenAt} />
            <div style={{ display: 'flex', gap: 14, marginTop: 8, fontSize: 11, color: 'var(--muted)', flexWrap: 'wrap' }}>
              <Leg2 c="var(--accent-ink)" t="Gesamtkosten" />
              <Leg2 c="var(--warn-ink)" t="Rüstkosten" dash />
              <Leg2 c="var(--good-ink)" t="Lagerkosten" dash />
            </div>
            {/* manuell übernehmen */}
            <div style={{ marginTop: 12, padding: '11px 12px', background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 8 }}>
              <div className="label" style={{ marginBottom: 7 }}>Losgröße übernehmen</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <input type="number" value={losInput} placeholder={String(Math.round(qOpt))} onChange={e => setLos(e.target.value)}
                  style={{ width: 110, height: 34, padding: '0 10px', boxSizing: 'border-box', fontFamily: 'var(--mono)', fontSize: 15, fontWeight: 700, color: 'var(--ink)',
                    border: '1px solid var(--line-2)', borderRadius: 6, background: 'var(--surface)' }} />
                <span style={{ fontSize: 11.5, color: 'var(--muted)' }}>Stück</span>
                <button onClick={() => setLos(String(Math.round(qOpt)))} title="Optimum einsetzen"
                  style={{ height: 30, padding: '0 11px', borderRadius: 6, border: '1px solid var(--line-2)', background: 'var(--surface)', color: 'var(--accent-ink)', fontSize: 11.5, fontWeight: 600, whiteSpace: 'nowrap', cursor: 'pointer' }}>Optimum</button>
                <button onClick={() => onApply && onApply(op.nr, losVal)}
                  style={{ marginLeft: 'auto', height: 34, padding: '0 16px', borderRadius: 6, border: '1px solid var(--accent-ink)', background: 'var(--accent-ink)', color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Übernehmen</button>
              </div>
              <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 6 }}>Kosten bei {losVal} Stück: <b className="num" style={{ color: 'var(--ink-2)' }}>{euro(kostenAt(losVal))}/a</b></div>
            </div>
            <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '9px 12px', background: 'color-mix(in oklch, var(--accent) 16%, var(--surface))', border: '1px solid var(--accent-line)', borderRadius: 8 }}>
              <span style={{ fontSize: 12.5 }}>Aktuelle Losgröße <b className="num">{op.menge}</b> → Kosten <b className="num">{euro(kostenAt(op.menge))}</b>/a</span>
              {Math.abs(op.menge - qOpt) > qOpt * 0.1 && <span style={{ fontSize: 11.5, color: 'var(--bad-ink)', fontWeight: 600 }}>+{euro(kostenAt(op.menge) - kOpt)}/a</span>}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

function Field({ label, unit, value, onChange, step = '1', hint }) {
  return (
    <div style={{ marginBottom: 10 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <label style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{label}</label>
        <span style={{ fontSize: 10.5, color: 'var(--muted)', fontFamily: 'var(--mono)' }}>{unit}</span>
      </div>
      <input type="number" value={value} step={step} onChange={e => onChange(e.target.value)}
        style={{ width: '100%', height: 32, marginTop: 3, padding: '0 10px', boxSizing: 'border-box', fontFamily: 'var(--mono)', fontSize: 13, fontWeight: 600,
          border: '1px solid var(--line-2)', borderRadius: 6, background: 'var(--surface)', color: 'var(--ink)' }} />
      {hint && <div style={{ fontSize: 10, color: 'var(--muted)', marginTop: 2 }}>{hint}</div>}
    </div>
  );
}

function Row2({ k, v, sub }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '3px 0' }}>
      <span style={{ fontSize: 11.5, color: 'var(--muted)' }}>{k}{sub && <span style={{ fontSize: 9.5, display: 'block', color: 'var(--line-2)' }}>{sub}</span>}</span>
      <span className="num" style={{ fontFamily: 'var(--mono)', fontSize: 12.5, fontWeight: 600, color: 'var(--ink)' }}>{v}</span>
    </div>
  );
}

function Leg2({ c, t, dash }) {
  return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
    <span style={{ width: 16, height: 0, borderTop: `2px ${dash ? 'dashed' : 'solid'} ${c}` }} />{t}
  </span>;
}

// Kostenkurve (Rüst-, Lager-, Gesamtkosten) über die Losgröße mit Optimum-Markierung
function CostChart({ jahresbedarf, ruestkosten, ch, qOpt, aktuell, kostenAt }) {
  const W = 320, H = 168, padL = 6, padR = 6, padT = 8, padB = 18;
  const plotW = W - padL - padR, plotH = H - padT - padB;
  const qMax = Math.max(qOpt * 2.6, aktuell * 1.2, 10);
  const N = 60;
  const pts = [];
  let kMax = 0;
  for (let i = 1; i <= N; i++) {
    const q = (qMax / N) * i;
    const kR = (jahresbedarf / q) * ruestkosten;
    const kL = (q / 2) * ch;
    const kG = kR + kL;
    pts.push({ q, kR, kL, kG });
    kMax = Math.max(kMax, kG);
  }
  kMax = Math.min(kMax, kostenAt(qMax / N) * 1.05); // y-Skala vom linken Rand bündeln
  kMax = Math.max(kMax, kostenAt(qOpt) * 2.4);
  const x = (q) => padL + (q / qMax) * plotW;
  const y = (k) => padT + plotH * (1 - Math.min(k, kMax) / kMax);
  const path = (sel) => pts.map((p, i) => `${i ? 'L' : 'M'}${x(p.q).toFixed(1)} ${y(sel(p)).toFixed(1)}`).join(' ');

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }}>
      {/* Achsen */}
      <line x1={padL} y1={padT} x2={padL} y2={padT + plotH} stroke="var(--line-2)" strokeWidth="1" />
      <line x1={padL} y1={padT + plotH} x2={W - padR} y2={padT + plotH} stroke="var(--line-2)" strokeWidth="1" />
      {/* Optimum-Linie */}
      <line x1={x(qOpt)} y1={padT} x2={x(qOpt)} y2={padT + plotH} stroke="var(--accent-ink)" strokeWidth="1" strokeDasharray="3 3" opacity="0.6" />
      {/* aktuelle Losgröße */}
      {aktuell > 0 && aktuell < qMax && <line x1={x(aktuell)} y1={padT} x2={x(aktuell)} y2={padT + plotH} stroke="var(--muted)" strokeWidth="1" strokeDasharray="2 3" opacity="0.7" />}
      {/* Kurven */}
      <path d={path(p => p.kR)} fill="none" stroke="var(--warn-ink)" strokeWidth="1.4" strokeDasharray="4 3" />
      <path d={path(p => p.kL)} fill="none" stroke="var(--good-ink)" strokeWidth="1.4" strokeDasharray="4 3" />
      <path d={path(p => p.kG)} fill="none" stroke="var(--accent-ink)" strokeWidth="2" />
      {/* Optimum-Punkt */}
      <circle cx={x(qOpt)} cy={y(kostenAt(qOpt))} r="3.5" fill="var(--accent-ink)" stroke="#fff" strokeWidth="1.5" />
      <text x={x(qOpt)} y={padT + plotH + 13} textAnchor="middle" style={{ fontSize: 9, fill: 'var(--accent-ink)', fontWeight: 700, fontFamily: 'var(--mono)' }}>q* {Math.round(qOpt)}</text>
      {aktuell > 0 && aktuell < qMax && <text x={x(aktuell)} y={padT + plotH + 13} textAnchor="middle" style={{ fontSize: 9, fill: 'var(--muted)', fontFamily: 'var(--mono)' }}>ist {aktuell}</text>}
      <text x={W - padR} y={padT + 8} textAnchor="end" style={{ fontSize: 8.5, fill: 'var(--muted)', fontFamily: 'var(--mono)' }}>€/Jahr</text>
    </svg>
  );
}

Object.assign(window, { AndlerPopup });
