// 5-Schritt-Konfigurator + Bestätigungsseite
const { useState, useEffect, useMemo } = React;
const { Btn, navigate, PH, WFNote } = window.UI;
// Werte werden zur Render-Zeit aus window.SITE_DATA gelesen (vom Server geladen)
// Werte werden zur Render-Zeit aus window.SITE_DATA gelesen — Bootstrap
// (app.jsx) füllt SITE_DATA vor dem Render mit Server-Konfig.
const getSD       = () => window.SITE_DATA || {};
const getANL      = () => getSD().ANLAESSE          || [];
const getBAU      = () => getSD().BAUSTEINE         || {};
const getTLBau    = () => getSD().TIMELINE_BAUSTEINE || [];
const getTLVorlage = (anlassId) => {
  const v = getSD().TIMELINE_VORLAGEN || {};
  return (anlassId && v[anlassId]) || v.default || getSD().TIMELINE_VORLAGE || [];
};
const T = (k, fb='') => (getSD().TEXTE || {})[k] || fb;

// ============ State Hook (URL + localStorage persistent) ============
function useConfigState() {
  const initial = () => {
    // URL-Parameter (?anlass=hochzeit etc.) hat höchste Priorität — überschreibt localStorage
    let urlAnlass = '';
    try {
      const sp = new URLSearchParams(window.location.search);
      const v = (sp.get('anlass') || '').toLowerCase().trim();
      const validIds = (getANL() || []).map(a => a.id);
      if (v && validIds.includes(v)) urlAnlass = v;
    } catch {}
    try {
      const saved = JSON.parse(localStorage.getItem('onkelfinke_config') || 'null');
      if (saved) return urlAnlass ? { ...saved, anlass: urlAnlass } : saved;
    } catch {}
    return {
      anlass: urlAnlass, location: '', personen: 50, datum: '', plz: '',
      catering: '', getraenke: '', service: [], extras: [], beratung: 'unverbindlich',
      timeline: [...getTLVorlage(urlAnlass)],
      kontakt: { name: '', email: '', telefon: '', notiz: '' },
    };
  };
  const [state, setState] = useState(initial);
  useEffect(() => {
    localStorage.setItem('onkelfinke_config', JSON.stringify(state));
  }, [state]);
  const update = (patch) => setState(s => ({ ...s, ...patch }));
  const reset = () => { localStorage.removeItem('onkelfinke_config'); setState(initial); };
  return [state, update, reset];
}

// ============ Preisberechnung ============
function calc(state) {
  const p = Math.max(1, Number(state.personen) || 0);
  let total = 0;
  const lines = [];

  const find = (key, id) => (getBAU()[key]?.options || []).find(o => o.id === id);

  if (state.location) {
    const o = find('location', state.location);
    if (o) {
      const sum = (o.unit === 'p.P.') ? o.price * p : o.price;
      if (sum > 0) { total += sum; lines.push({ titel: 'Location · ' + o.label, sub: o.unit === 'p.P.' ? `${p} × ${o.price} €` : 'pauschal', sum }); }
      else lines.push({ titel: 'Location · ' + o.label, sub: 'inkl.', sum: 0 });
    }
  }
  if (state.catering) {
    const o = find('catering', state.catering);
    if (o) { const sum = o.price * p; total += sum; lines.push({ titel: 'Catering · ' + o.label, sub: `${p} × ${o.price} €`, sum }); }
  }
  if (state.getraenke) {
    const o = find('getraenke', state.getraenke);
    if (o && o.price > 0) { const sum = o.price * p; total += sum; lines.push({ titel: 'Getränke · ' + o.label, sub: `${p} × ${o.price} €`, sum }); }
    else if (o) { lines.push({ titel: 'Getränke · ' + o.label, sub: 'auf Verbrauch / pauschal', sum: 0 }); }
  }
  state.service.forEach(id => {
    const o = find('service', id);
    if (o) { total += o.price; lines.push({ titel: 'Service · ' + o.label, sub: o.unit, sum: o.price }); }
  });
  state.extras.forEach(id => {
    const o = find('extras', id);
    if (o) {
      const sum = o.unit === 'p.P.' ? o.price * p : o.price;
      total += sum;
      lines.push({ titel: 'Extra · ' + o.label, sub: o.unit === 'p.P.' ? `${p} × ${o.price} €` : 'pauschal', sum });
    }
  });
  if (state.beratung && state.beratung !== 'unverbindlich') {
    const o = find('beratung', state.beratung);
    if (o && o.price > 0) { total += o.price; lines.push({ titel: 'Beratung · ' + o.label, sub: 'pauschal', sum: o.price }); }
  }
  return { total, lines };
}

// ============ Schritt-Header ============
const STEPS = [
  { n: 1, t: 'Anlass'    },
  { n: 2, t: 'Location'  },
  { n: 3, t: 'Catering'  },
  { n: 4, t: 'Service'   },
  { n: 5, t: 'Timeline'  },
  { n: 6, t: 'Übersicht' },
];

function Stepper({ step, onJump }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const active = el.querySelector('[data-active="true"]');
    if (active && el.scrollWidth > el.clientWidth) {
      const target = active.offsetLeft - 16;
      el.scrollTo({ left: Math.max(0, target), behavior: 'smooth' });
    }
  }, [step]);
  return (
    <div ref={ref} className="of-stepper" style={{ display: 'flex', gap: 0, borderBottom: '1px solid var(--line-strong)', background: 'var(--paper)' }}>
      {STEPS.map((s, i) => (
        <button key={s.n} onClick={() => onJump(s.n)} disabled={s.n > step}
          data-active={s.n === step}
          style={{
            flex: 1, padding: '20px 16px', textAlign: 'left',
            background: s.n === step ? 'var(--navy)' : 'transparent',
            color: s.n === step ? 'var(--cream)' : (s.n < step ? 'var(--navy)' : 'var(--muted)'),
            border: 'none', borderRight: i < STEPS.length - 1 ? '1px solid var(--line-strong)' : 'none',
            cursor: s.n <= step ? 'pointer' : 'default',
            transition: 'all 200ms',
          }}>
          <div className="mono" style={{ fontSize: 10, opacity: 0.7, marginBottom: 4 }}>Schritt {s.n} / 6</div>
          <div className="serif of-stepper-t" style={{ fontSize: 18, fontWeight: 500, fontStyle: 'italic' }}>{s.t}</div>
        </button>
      ))}
    </div>
  );
}

// ============ Option Card ============
function OptionCard({ active, onClick, title, desc, price, unit, multi }) {
  return (
    <button onClick={onClick} style={{
      textAlign: 'left', width: '100%', padding: 20, borderRadius: 4,
      border: '1px solid ' + (active ? 'var(--navy)' : 'var(--line-strong)'),
      background: active ? 'var(--navy)' : 'var(--paper)',
      color: active ? 'var(--cream)' : 'inherit',
      cursor: 'pointer', display: 'grid', gridTemplateColumns: '24px 1fr auto', gap: 16, alignItems: 'center',
      transition: 'all 150ms',
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: multi ? 4 : 999,
        border: '1px solid ' + (active ? 'var(--cream)' : 'var(--line-strong)'),
        background: active ? 'var(--cream)' : 'transparent',
        display: 'grid', placeItems: 'center', color: 'var(--navy)', fontSize: 14, fontWeight: 700,
      }}>{active ? '✓' : ''}</div>
      <div>
        <div className="serif" style={{ fontSize: 18, fontWeight: 500, marginBottom: 4 }}>{title}</div>
        <div style={{ fontSize: 13, opacity: 0.75 }}>{desc}</div>
      </div>
      <div style={{ textAlign: 'right' }}>
        {price > 0 ? (
          <>
            <div className="serif" style={{ fontSize: 22, fontStyle: 'italic' }}>{price} €</div>
            <div className="mono" style={{ fontSize: 9, opacity: 0.6 }}>{unit}</div>
          </>
        ) : (
          <div className="mono" style={{ fontSize: 10, opacity: 0.6 }}>{unit || 'inkl.'}</div>
        )}
      </div>
    </button>
  );
}

// ============ Schritt 1: Anlass + Eckdaten ============
function Step1({ state, update }) {
  return (
    <div>
      <h2 className="serif of-step-h2" style={{ fontSize: 48, fontWeight: 500, lineHeight: 1.05, margin: '0 0 16px' }}>{T("step1_h", "Was feierst du?")}</h2>
      <p style={{ color: 'var(--muted)', fontSize: 16, marginBottom: 40, maxWidth: 600 }}>
        Wir richten alles auf deinen Anlass aus — sag uns als erstes, worum's geht.
      </p>
      <div className="of-step-anlass-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 48 }}>
        {getANL().map(a => (
          <button key={a.id} onClick={() => update({ anlass: a.id })} style={{
            border: '1px solid ' + (state.anlass === a.id ? 'var(--navy)' : 'var(--line-strong)'),
            background: state.anlass === a.id ? 'var(--navy)' : 'var(--paper)',
            color: state.anlass === a.id ? 'var(--cream)' : 'inherit',
            padding: 24, borderRadius: 4, cursor: 'pointer', textAlign: 'left',
          }}>
            <div style={{ fontSize: 36, marginBottom: 12 }}>{a.emoji}</div>
            <div className="serif" style={{ fontSize: 22, fontStyle: 'italic', fontWeight: 500, marginBottom: 4 }}>{a.label}</div>
            <div style={{ fontSize: 12, opacity: 0.7 }}>{a.desc}</div>
          </button>
        ))}
      </div>

      <h3 className="serif" style={{ fontSize: 28, fontWeight: 500, margin: '0 0 24px', fontStyle: 'italic' }}>Eckdaten</h3>
      <div className="of-eckdaten-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
        <Field label="Datum (geplant)">
          <input type="date" value={state.datum} onChange={e => update({ datum: e.target.value })} style={inputStyle} />
        </Field>
        <Field label="Anzahl Personen">
          <div className="of-pill-row" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <button onClick={() => update({ personen: Math.max(1, state.personen - 10) })} style={pillBtn}>−10</button>
            <input type="number" value={state.personen} onChange={e => update({ personen: Number(e.target.value) })} style={{ ...inputStyle, textAlign: 'center', flex: 1, minWidth: 0 }} />
            <button onClick={() => update({ personen: state.personen + 10 })} style={pillBtn}>+10</button>
          </div>
        </Field>
        <Field label="PLZ Veranstaltungsort">
          <input type="text" placeholder="47…" value={state.plz} onChange={e => update({ plz: e.target.value })} style={inputStyle} />
        </Field>
      </div>
    </div>
  );
}

// ============ Schritt 2: Location ============
function StepLocation({ state, update }) {
  const cat = getBAU().location;
  const options = (cat && cat.options) || [
    { id: 'eigene',     label: 'Ich habe eine eigene Location', price: 0,   unit: 'inkl.',    desc: 'Du hast bereits einen Saal, Garten oder eine Halle.' },
    { id: 'suchen',     label: 'Onkelfinke sucht eine Location', price: 180, unit: 'pauschal', desc: 'Wir finden die passende Location nach deinen Wünschen.' },
    { id: 'komplett',   label: 'Komplettpaket mit Location',     price: 0,   unit: 'auf Anfrage', desc: 'Location + Catering + Service — alles aus einer Hand.' },
  ];
  return (
    <div>
      <h2 className="serif of-step-h2" style={{ fontSize: 48, fontWeight: 500, lineHeight: 1.05, margin: '0 0 16px' }}>{T("step_location_h", "Wo soll's stattfinden?")}</h2>
      <p style={{ color: 'var(--muted)', fontSize: 16, marginBottom: 40, maxWidth: 600 }}>
        {T("step_location_p", "Hast du schon eine Location — oder sollen wir uns darum kümmern?")}
      </p>
      <div style={{ display: 'grid', gap: 12 }}>
        {options.map(o => (
          <OptionCard key={o.id}
            active={state.location === o.id}
            onClick={() => update({ location: state.location === o.id ? '' : o.id })}
            title={o.label} desc={o.desc} price={o.price} unit={o.unit} />
        ))}
      </div>
    </div>
  );
}

// ============ Schritt 3: Catering + Getränke ============
function Step2({ state, update }) {
  return (
    <div>
      <h2 className="serif of-step-h2" style={{ fontSize: 48, fontWeight: 500, lineHeight: 1.05, margin: '0 0 16px' }}>{T("step2_h", "Was kommt auf den Tisch?")}</h2>
      <p style={{ color: 'var(--muted)', fontSize: 16, marginBottom: 40, maxWidth: 600 }}>
        Catering und Getränke — wähle je eine Variante. Du kannst es später jederzeit ändern.
      </p>
      <div className="of-step-grid-2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32 }}>
        {['catering', 'getraenke'].map(key => {
          const cat = getBAU()[key]; if (!cat) return null;
          return (
            <div key={key}>
              <div className="mono" style={{ color: 'var(--muted)', marginBottom: 16 }}>{cat.title}</div>
              <div style={{ display: 'grid', gap: 8 }}>
                {cat.options.map(o => (
                  <OptionCard key={o.id}
                    active={state[key] === o.id}
                    onClick={() => update({ [key]: state[key] === o.id ? '' : o.id })}
                    title={o.label} desc={o.desc} price={o.price} unit={o.unit} />
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ============ Schritt 3: Service + Extras ============
function Step3({ state, update }) {
  const toggle = (key, id) => {
    const list = state[key];
    update({ [key]: list.includes(id) ? list.filter(x => x !== id) : [...list, id] });
  };
  return (
    <div>
      <h2 className="serif of-step-h2" style={{ fontSize: 48, fontWeight: 500, lineHeight: 1.05, margin: '0 0 16px' }}>{T("step3_h", "Wer macht's?")}</h2>
      <p style={{ color: 'var(--muted)', fontSize: 16, marginBottom: 40, maxWidth: 600 }}>
        Service und Extras — alles optional, alles dazubuchbar.
      </p>
      {['service', 'extras', 'beratung'].map(key => {
        const cat = getBAU()[key]; if (!cat) return null;
        return (
          <div key={key} style={{ marginBottom: 40 }}>
            <div className="mono" style={{ color: 'var(--muted)', marginBottom: 16 }}>{cat.title}</div>
            <div className="of-step-grid-2" style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
              {cat.options.map(o => {
                const active = cat.multi ? state[key].includes(o.id) : state[key] === o.id;
                return (
                  <OptionCard key={o.id}
                    active={active}
                    multi={cat.multi}
                    onClick={() => cat.multi ? toggle(key, o.id) : update({ [key]: state[key] === o.id ? '' : o.id })}
                    title={o.label} desc={o.desc} price={o.price} unit={o.unit} />
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ============ Schritt 4: Timeline (drag & drop) ============
function Step4({ state, update }) {
  const [dragId, setDragId] = useState(null);

  const onDragStart = (id) => (e) => {
    setDragId(id);
    e.dataTransfer.effectAllowed = 'move';
  };
  const onDragOver = (idx) => (e) => { e.preventDefault(); };
  const onDrop = (idx) => (e) => {
    e.preventDefault();
    if (!dragId) return;
    const list = [...state.timeline];
    const fromIdx = list.findIndex(x => x.id === dragId);
    if (fromIdx < 0) {
      // Aus Bausteinen ziehen
      const tpl = getTLBau().find(x => x.id === dragId);
      if (tpl) {
        list.splice(idx, 0, { ...tpl, id: tpl.id + '-' + Date.now(), zeit: '' });
      }
    } else {
      const [item] = list.splice(fromIdx, 1);
      list.splice(idx, 0, item);
    }
    update({ timeline: list });
    setDragId(null);
  };

  const removeItem = (id) => update({ timeline: state.timeline.filter(x => x.id !== id) });
  const updateItem = (id, patch) => update({ timeline: state.timeline.map(x => x.id === id ? { ...x, ...patch } : x) });

  return (
    <div>
      <h2 className="serif of-step-h2" style={{ fontSize: 48, fontWeight: 500, lineHeight: 1.05, margin: '0 0 16px' }}>{T("step4_h", "Wie soll der Tag laufen?")}</h2>
      <p style={{ color: 'var(--muted)', fontSize: 16, marginBottom: 40, maxWidth: 600 }}>
        Ein grober Plan — du kannst Bausteine reinziehen, Zeiten ändern, Reihenfolge anpassen. Wir machen daraus einen Ablauf.
      </p>
      <div className="of-timeline-config-grid" style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 32 }}>

        {/* Timeline */}
        <div>
          <div className="mono" style={{ color: 'var(--muted)', marginBottom: 16 }}>Dein Ablauf</div>
          <div style={{ background: 'var(--paper)', border: '1px solid var(--line-strong)', borderRadius: 4, padding: 16 }}>
            {state.timeline.map((item, idx) => (
              <div key={item.id}
                draggable onDragStart={onDragStart(item.id)} onDragOver={onDragOver(idx)} onDrop={onDrop(idx)}
                className="of-timeline-row"
                style={{
                  display: 'grid', gridTemplateColumns: '20px 80px 32px 1fr 32px', gap: 12, alignItems: 'center',
                  padding: '12px 8px', borderBottom: idx < state.timeline.length - 1 ? '1px dashed var(--line)' : 'none',
                  cursor: 'grab', background: dragId === item.id ? 'rgba(0,16,39,0.06)' : 'transparent',
                }}>
                <span style={{ color: 'var(--muted)', cursor: 'grab' }}>⋮⋮</span>
                <input type="time" value={item.zeit} onChange={e => updateItem(item.id, { zeit: e.target.value })}
                  className="mono of-timeline-time" style={{ ...inputStyle, padding: '6px 8px', fontSize: 11, textAlign: 'center' }} />
                <span style={{ fontSize: 18 }}>{item.icon}</span>
                <input value={item.label} onChange={e => updateItem(item.id, { label: e.target.value })}
                  style={{ ...inputStyle, padding: '6px 8px', fontSize: 14 }} />
                <button onClick={() => removeItem(item.id)} style={{ background: 'transparent', border: 'none', color: 'var(--muted)', cursor: 'pointer' }}>✕</button>
              </div>
            ))}
            <div onDragOver={onDragOver(state.timeline.length)} onDrop={onDrop(state.timeline.length)}
              style={{ marginTop: 12, padding: 16, border: '1px dashed var(--line-strong)', borderRadius: 4, textAlign: 'center', color: 'var(--muted)', fontSize: 12 }}
              className="mono">
              Hier Baustein ablegen ↓
            </div>
          </div>
        </div>

        {/* Bausteine */}
        <div>
          <div className="mono" style={{ color: 'var(--muted)', marginBottom: 16 }}>Bausteine zum Ziehen</div>
          <div style={{ display: 'grid', gap: 8 }}>
            {getTLBau().map(b => (
              <div key={b.id} draggable onDragStart={onDragStart(b.id)}
                style={{
                  padding: '12px 16px', border: '1px solid var(--line-strong)', borderRadius: 4,
                  background: 'var(--paper)', cursor: 'grab',
                  display: 'flex', alignItems: 'center', gap: 12,
                }}>
                <span style={{ fontSize: 20 }}>{b.icon}</span>
                <span style={{ fontSize: 14 }}>{b.label}</span>
                <span className="mono" style={{ marginLeft: 'auto', fontSize: 9, color: 'var(--muted)' }}>ziehen ⋮⋮</span>
              </div>
            ))}
          </div>
        </div>

      </div>
    </div>
  );
}

// ============ Schritt 5: Übersicht + Kontakt ============
function Step5({ state, update }) {
  const { total, lines } = calc(state);
  return (
    <div>
      <h2 className="serif of-step-h2" style={{ fontSize: 48, fontWeight: 500, lineHeight: 1.05, margin: '0 0 16px' }}>{T("step5_h", "Sieht das gut aus?")}</h2>
      <p style={{ color: 'var(--muted)', fontSize: 16, marginBottom: 40, maxWidth: 600 }}>
        Prüf deine Auswahl, sag uns wie wir dich erreichen — wir melden uns innerhalb von 24h mit einem persönlichen Angebot.
      </p>

      <div className="of-summary-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32 }}>
        {/* Kontaktformular */}
        <div>
          <div className="mono" style={{ color: 'var(--muted)', marginBottom: 16 }}>Deine Kontaktdaten</div>
          <div style={{ display: 'grid', gap: 16 }}>
            <Field label="Name *">
              <input value={state.kontakt.name} onChange={e => update({ kontakt: { ...state.kontakt, name: e.target.value } })} style={inputStyle} />
            </Field>
            <Field label="E-Mail *">
              <input type="email" value={state.kontakt.email} onChange={e => update({ kontakt: { ...state.kontakt, email: e.target.value } })} style={inputStyle} />
            </Field>
            <Field label="Telefon">
              <input value={state.kontakt.telefon} onChange={e => update({ kontakt: { ...state.kontakt, telefon: e.target.value } })} style={inputStyle} />
            </Field>
            <Field label="Anmerkungen / Wünsche">
              <textarea value={state.kontakt.notiz} onChange={e => update({ kontakt: { ...state.kontakt, notiz: e.target.value } })} rows={5} style={{ ...inputStyle, resize: 'vertical', fontFamily: 'inherit' }} />
            </Field>
          </div>
        </div>

        {/* Übersicht */}
        <div style={{ background: 'var(--paper)', border: '1px solid var(--navy)', borderRadius: 4, padding: 24, alignSelf: 'start' }}>
          <div className="mono" style={{ color: 'var(--muted)', marginBottom: 16 }}>Deine Konfiguration</div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, fontSize: 13, marginBottom: 20, paddingBottom: 20, borderBottom: '1px solid var(--line)' }}>
            <div><div className="mono" style={{ fontSize: 9, color: 'var(--muted)', marginBottom: 2 }}>Anlass</div>{getANL().find(a=>a.id===state.anlass)?.label || '—'}</div>
            <div><div className="mono" style={{ fontSize: 9, color: 'var(--muted)', marginBottom: 2 }}>Personen</div>{state.personen}</div>
            <div><div className="mono" style={{ fontSize: 9, color: 'var(--muted)', marginBottom: 2 }}>Datum</div>{state.datum || '—'}</div>
            <div><div className="mono" style={{ fontSize: 9, color: 'var(--muted)', marginBottom: 2 }}>PLZ</div>{state.plz || '—'}</div>
          </div>

          {lines.length === 0 && <div style={{ color: 'var(--muted)', fontSize: 13, textAlign: 'center', padding: 24 }}>Noch nichts ausgewählt</div>}
          {lines.map((l, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 12, padding: '10px 0', borderBottom: '1px dashed var(--line)' }}>
              <div>
                <div style={{ fontSize: 14 }}>{l.titel}</div>
                <div className="mono" style={{ fontSize: 9, color: 'var(--muted)' }}>{l.sub}</div>
              </div>
              <div className="serif" style={{ fontStyle: 'italic' }}>{l.sum > 0 ? l.sum.toLocaleString('de-DE') + ' €' : '—'}</div>
            </div>
          ))}

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 20, paddingTop: 20, borderTop: '1px solid var(--navy)' }}>
            <span className="mono">Geschätzte Summe</span>
            <span className="serif" style={{ fontSize: 36, fontStyle: 'italic', fontWeight: 500 }}>{total.toLocaleString('de-DE')} €</span>
          </div>
          <div className="mono" style={{ fontSize: 9, color: 'var(--muted)', marginTop: 8, textAlign: 'right' }}>
            zzgl. MwSt · Anfahrt nach Aufwand · unverbindlich
          </div>
        </div>
      </div>
    </div>
  );
}

// ============ Sticky Sidebar Summary (kompakte Live-Summe) ============
function StickySummary({ state }) {
  const { total } = calc(state);
  return (
    <div style={{
      position: 'sticky', top: 100, alignSelf: 'start',
      background: 'var(--paper)', border: '1px solid var(--line-strong)', borderRadius: 4, padding: 24,
    }}>
      <div className="mono" style={{ color: 'var(--muted)', marginBottom: 16 }}>Live-Vorschau</div>
      <div style={{ fontSize: 13, lineHeight: 1.8 }}>
        <Row k="Anlass" v={getANL().find(a=>a.id===state.anlass)?.label || '—'} />
        <Row k="Personen" v={state.personen} />
        <Row k="Datum" v={state.datum || '—'} />
      </div>
      <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--navy)' }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', marginBottom: 4 }}>Geschätzt</div>
        <div className="serif" style={{ fontSize: 36, fontStyle: 'italic', fontWeight: 500, lineHeight: 1 }}>
          {total.toLocaleString('de-DE')} €
        </div>
        <div className="mono" style={{ fontSize: 9, color: 'var(--muted)', marginTop: 6 }}>zzgl. MwSt · unverbindlich</div>
      </div>
    </div>
  );
}

// ============ Konfigurator-Container ============
function ConfiguratorPage() {
  const [state, update, reset] = useConfigState();
  const [step, setStep] = useState(1);

  // Anlass aus URL übernehmen
  useEffect(() => {
    const params = new URLSearchParams((window.location.hash.split('?')[1] || ''));
    const a = params.get('anlass');
    if (a && !state.anlass) update({ anlass: a });
  }, []);

  const next = () => { if (step < 6) setStep(step + 1); };
  const prev = () => { if (step > 1) setStep(step - 1); else navigate('/'); };

  const [submitting, setSubmitting] = useState(false);
  const [submitErr, setSubmitErr] = useState('');

  const submit = async () => {
    const k = state.kontakt || {};
    if (!k.name || !k.email) { setSubmitErr('Bitte Name und E-Mail angeben.'); return; }
    const { total } = calc(state);

    const payload = {
      anlass: state.anlass,
      personen: state.personen,
      datum: state.datum,
      plz: state.plz,
      catering: state.catering,
      getraenke: state.getraenke,
      service: state.service,
      extras: state.extras,
      beratung: state.beratung,
      timeline: state.timeline,
      summe: total,
      kontakt: k,
      _hp: '', // Honeypot
    };

    setSubmitting(true);
    setSubmitErr('');
    try {
      if (window.OF_API && window.OF_API.submit) {
        await window.OF_API.submit(payload);
        navigate('/konfigurator/danke');
        return;
      }
      throw new Error('API nicht verfügbar');
    } catch (e) {
      setSubmitErr('Konnte Anfrage nicht senden: ' + (e.message || e) + ' — bitte direkt info@onkelfinke.de schreiben.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <>
      <Stepper step={step} onJump={setStep} />

      <div style={{ maxWidth: 1320, margin: '0 auto', padding: '48px 32px 80px' }} className="of-config-grid-wrap">
        <div className="of-config-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 48 }}>
          <div>
            {step === 1 && <Step1 state={state} update={update} />}
            {step === 2 && <StepLocation state={state} update={update} />}
            {step === 3 && <Step2 state={state} update={update} />}
            {step === 4 && <Step3 state={state} update={update} />}
            {step === 5 && <Step4 state={state} update={update} />}
            {step === 6 && <Step5 state={state} update={update} />}

            <div className="of-config-nav" style={{ display: 'flex', justifyContent: 'space-between', marginTop: 64, paddingTop: 32, borderTop: '1px solid var(--line)' }}>
              <Btn variant="ghost" onClick={prev} icon={false}>← Zurück</Btn>
              <div style={{ display: 'flex', gap: 12 }}>
                <button onClick={reset} className="mono" style={{ background: 'transparent', border: 'none', color: 'var(--muted)', cursor: 'pointer', fontSize: 11 }}>Zurücksetzen</button>
                {step < 6 ? <Btn onClick={next}>Weiter</Btn> : <Btn onClick={submit} disabled={submitting}>{submitting ? 'Sende…' : 'Anfrage senden'}</Btn>}
              </div>
            </div>
            {submitErr && <div role="alert" style={{ marginTop: 16, padding: 12, background: '#fff3f1', border: '1px solid var(--danger)', borderRadius: 4, color: 'var(--danger)', fontSize: 13 }}>{submitErr}</div>}
          </div>
          <StickySummary state={state} />
        </div>
      </div>
    </>
  );
}

// ============ Bestätigungsseite ============
function DankePage() {
  const [state] = useConfigState();
  const { total, lines } = calc(state);
  return (
    <div className="of-danke-grid" style={{ maxWidth: 1100, margin: '0 auto', padding: '80px 32px 120px' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 64 }} className="of-summary-grid">
        <div>
          <div style={{ fontSize: 64, marginTop: 32, marginBottom: 16 }}>🥂</div>
          <h1 className="serif of-danke-h1" style={{ fontSize: 'clamp(56px, 7vw, 96px)', lineHeight: 1, fontWeight: 500, fontStyle: 'italic', margin: '0 0 32px' }}>
            Danke,<br/>{state.kontakt.name || 'du'}!
          </h1>
          <p style={{ fontSize: 18, lineHeight: 1.6, color: 'rgba(0,16,39,0.85)', marginBottom: 32 }}>
            Wir haben deine Anfrage bekommen und melden uns <strong>innerhalb von 24 Stunden</strong> mit einem persönlichen Angebot per Mail oder Telefon.
          </p>
          <div style={{ background: 'var(--paper)', border: '1px solid var(--line-strong)', borderRadius: 4, padding: 24, marginBottom: 32 }}>
            <div className="mono" style={{ color: 'var(--muted)', marginBottom: 8 }}>Was passiert jetzt?</div>
            <ol style={{ paddingLeft: 20, lineHeight: 1.8, color: 'rgba(0,16,39,0.85)' }}>
              <li>Wir prüfen deine Konfiguration und schauen uns das Datum an.</li>
              <li>Du bekommst ein detailliertes Angebot per Mail.</li>
              <li>Wir telefonieren, justieren wo nötig — und du buchst.</li>
            </ol>
          </div>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <Btn icon={false}>📄 PDF herunterladen</Btn>
            <Btn variant="ghost" onClick={() => navigate('/')}>Zur Startseite</Btn>
          </div>
        </div>

        {/* PDF-Vorschau */}
        <div>
          <div className="mono" style={{ color: 'var(--muted)', marginBottom: 12 }}>Vorschau · Anfrage-PDF</div>
          <div style={{
            background: 'var(--cream)', border: '1px solid var(--line-strong)', borderRadius: 4,
            boxShadow: '0 12px 40px rgba(0,16,39,0.12)', padding: 32, fontSize: 12,
            transform: 'rotate(0.3deg)',
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid var(--navy)', paddingBottom: 16, marginBottom: 24 }}>
              <div>
                <div className="serif" style={{ fontSize: 20, fontStyle: 'italic', fontWeight: 600 }}>Onkelfinke</div>
                <div className="mono" style={{ fontSize: 8, color: 'var(--muted)' }}>PARTYPLANER · CATERING</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="mono" style={{ fontSize: 9, color: 'var(--muted)' }}>Anfrage</div>
                <div className="mono">{new Date().toLocaleDateString('de-DE')}</div>
              </div>
            </div>

            <div style={{ marginBottom: 16 }}>
              <div className="mono" style={{ fontSize: 9, color: 'var(--muted)', marginBottom: 4 }}>Für</div>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{state.kontakt.name || '—'}</div>
              <div style={{ color: 'var(--muted)' }}>{state.kontakt.email || '—'}</div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, fontSize: 11, marginBottom: 24, padding: 12, background: 'var(--cream-2)', borderRadius: 4 }} className="of-pdf-info">
              <div><div className="mono" style={{ fontSize: 8, color: 'var(--muted)' }}>Anlass</div>{getANL().find(a=>a.id===state.anlass)?.label || '—'}</div>
              <div><div className="mono" style={{ fontSize: 8, color: 'var(--muted)' }}>Personen</div>{state.personen}</div>
              <div><div className="mono" style={{ fontSize: 8, color: 'var(--muted)' }}>Datum</div>{state.datum || '—'}</div>
            </div>

            <div className="mono" style={{ fontSize: 9, color: 'var(--muted)', marginBottom: 8 }}>Positionen</div>
            {lines.length === 0 && <div style={{ color: 'var(--muted)', fontSize: 11, textAlign: 'center', padding: 16 }}>—</div>}
            {lines.map((l, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 8, padding: '8px 0', borderBottom: '1px dashed var(--line)' }}>
                <div>
                  <div style={{ fontSize: 11 }}>{l.titel}</div>
                  <div className="mono" style={{ fontSize: 8, color: 'var(--muted)' }}>{l.sub}</div>
                </div>
                <div className="serif" style={{ fontStyle: 'italic', fontSize: 12 }}>{l.sum > 0 ? l.sum.toLocaleString('de-DE') + ' €' : '—'}</div>
              </div>
            ))}

            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--navy)' }}>
              <span className="mono" style={{ fontSize: 11 }}>Geschätzt</span>
              <span className="serif" style={{ fontSize: 22, fontStyle: 'italic', fontWeight: 600 }}>{total.toLocaleString('de-DE')} €</span>
            </div>
            <div className="mono" style={{ fontSize: 8, color: 'var(--muted)', marginTop: 4, textAlign: 'right' }}>zzgl. MwSt · unverbindlich</div>

            <div className="mono" style={{ fontSize: 8, color: 'var(--muted)', marginTop: 32, textAlign: 'center', borderTop: '1px solid var(--line)', paddingTop: 12 }}>
              Onkelfinke · Hauskoppelstieg 7 · 22111 Hamburg · info@onkelfinke.de · 0152 058 620 58
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// Helpers
const inputStyle = { width: '100%', padding: '12px 14px', border: '1px solid var(--line-strong)', borderRadius: 4, background: 'var(--paper)', fontSize: 14, color: 'var(--navy)' };
const pillBtn = { padding: '8px 14px', border: '1px solid var(--line-strong)', borderRadius: 999, background: 'var(--paper)', cursor: 'pointer', fontFamily: '"Roboto Mono", monospace', fontSize: 11 };

function Field({ label, children }) {
  return (
    <label style={{ display: 'block' }}>
      <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', marginBottom: 6 }}>{label}</div>
      {children}
    </label>
  );
}
function Row({ k, v }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px dashed var(--line)', padding: '6px 0' }}>
      <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>{k}</span>
      <span style={{ fontSize: 13 }}>{v}</span>
    </div>
  );
}

window.CONFIGURATOR = { ConfiguratorPage, DankePage };
