// Floating inquiry CTA window — backend-wired.
//
// Datenfluss:
//   1. Beim ersten Öffnen wird /api/inquiries/options gefetcht — liefert
//      aktive Kurse (mit Starttermine) + Behandlungen aus dem Admin-Backend.
//      Ergebnis wird gecacht für die Session.
//   2. Drei Anfrage-Arten: 'general' / 'course' / 'behandlung'.
//   3. CTAs aus Karten/Detail-Seiten öffnen das Formular mit prefill={title, kind}.
//      Wir matchen den Titel gegen die Backend-Optionen — bei Treffer wird der
//      passende Eintrag vorausgewählt, sonst Fallback auf 'general' mit Notiz.
//   4. Submit POSTet an /api/inquiries → Backend mailt routet + speichert ins
//      Nachrichtenarchiv.

const { useState, useEffect, useMemo } = React;

// Backend-URL — später auf admin.dieweiberei.de umstellen.
const WB_API_BASE = 'https://project-zd7wa.vercel.app';

// In-memory Cache für die Options-Antwort. Erste Öffnung lädt, weitere nutzen Cache.
let _optionsCache = null;
let _optionsPromise = null;
const loadInquiryOptions = () => {
  if (_optionsCache) return Promise.resolve(_optionsCache);
  if (_optionsPromise) return _optionsPromise;
  _optionsPromise = fetch(WB_API_BASE + '/api/inquiries/options')
    .then((r) => r.ok ? r.json() : Promise.reject(new Error('Optionen konnten nicht geladen werden.')))
    .then((data) => { _optionsCache = data; return data; })
    .catch((err) => { _optionsPromise = null; throw err; });
  return _optionsPromise;
};

// ---------- Floating launcher button (always visible) ----------
const InquiryLauncher = ({ open, onToggle }) => {
  const isCoarse = typeof window !== 'undefined' &&
    window.matchMedia && window.matchMedia('(hover: none), (pointer: coarse)').matches;
  return (
    <button onClick={onToggle} className="inquiry-fab" style={{
      position: 'fixed',
      right: 'clamp(16px, 3vw, 32px)',
      bottom: 'clamp(16px, 3vw, 32px)',
      zIndex: 60,
      background: 'var(--heather-plum)',
      color: 'var(--offwhite)',
      borderRadius: 999,
      padding: '14px 22px',
      fontFamily: 'Figtree, sans-serif',
      fontSize: 14,
      fontWeight: 600,
      letterSpacing: '0.02em',
      boxShadow: 'var(--shadow-cta), 0 12px 32px rgba(42,34,29,0.18)',
      display: 'flex', alignItems: 'center', gap: 10,
      transition: isCoarse ? 'none' : 'all 220ms var(--ease)',
      cursor: 'pointer',
      transform: 'translateZ(0)',
      willChange: 'transform',
    }}
      onMouseEnter={isCoarse ? undefined : (e => { e.currentTarget.style.transform='translate3d(0,-3px,0)'; e.currentTarget.style.background='var(--heather-hover)'; })}
      onMouseLeave={isCoarse ? undefined : (e => { e.currentTarget.style.transform='translate3d(0,0,0)'; e.currentTarget.style.background='var(--heather-plum)'; })}
    >
      <span style={{
        width: 8, height: 8, borderRadius: 999, background: 'var(--rose-dust)',
        boxShadow: isCoarse ? 'none' : '0 0 0 0 rgba(201,166,166,0.7)',
        animation: isCoarse ? 'none' : 'pulseDot 2.4s ease-in-out infinite',
      }} />
      {open ? 'Schließen' : 'Anfragen'}
      <span style={{ fontSize: 16, marginLeft: 2 }}>{open ? '×' : '→'}</span>
    </button>
  );
};

// ---------- Form ----------
// prefill kommt von CTA-Klicks: { title: "Baby-Yoga", kind: "course"|"behandlung" }
const InquiryWindow = ({ open, onClose, prefill }) => {
  const [step, setStep] = useState(0); // 0=form, 1=sent
  const [options, setOptions] = useState({ courses: [], behandlungen: [], loading: true, error: null });

  // Formular-State
  const [kind, setKind] = useState('general');           // 'general' | 'course' | 'behandlung'
  const [courseId, setCourseId] = useState('');
  const [courseDate, setCourseDate] = useState('');
  const [behandlungId, setBehandlungId] = useState('');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [note, setNote] = useState('');
  const [phase, setPhase] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);

  // Optionen laden, sobald das Fenster erstmals geöffnet wird
  useEffect(() => {
    if (!open) return;
    if (_optionsCache) {
      setOptions({ ...options, courses: _optionsCache.courses ?? [], behandlungen: _optionsCache.behandlungen ?? [], loading: false, error: null });
      return;
    }
    setOptions((o) => ({ ...o, loading: true, error: null }));
    loadInquiryOptions().then(
      (data) => setOptions({ courses: data.courses ?? [], behandlungen: data.behandlungen ?? [], loading: false, error: null }),
      (err) => setOptions((o) => ({ ...o, loading: false, error: err.message })),
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  // Schließen-Animation: nach 400ms zurücksetzen
  useEffect(() => {
    if (!open) {
      const t = setTimeout(() => {
        setStep(0);
        setSubmitError(null);
      }, 400);
      return () => clearTimeout(t);
    }
  }, [open]);

  // Prefill verarbeiten: wenn beim Öffnen ein Titel mitkommt, versuchen
  // wir einen passenden Eintrag in den Optionen zu finden.
  useEffect(() => {
    if (!open || !prefill) return;
    if (options.loading) return; // warten bis Optionen da sind

    const wantedTitle = (prefill.title || '').trim().toLowerCase();
    const wantedKind = prefill.kind;

    if (wantedKind === 'course' && wantedTitle) {
      const match = options.courses.find(
        (c) => c.title.toLowerCase() === wantedTitle ||
               c.title.toLowerCase().includes(wantedTitle) ||
               wantedTitle.includes(c.title.toLowerCase()),
      );
      if (match) {
        setKind('course');
        setCourseId(match.id);
        return;
      }
    }
    if (wantedKind === 'behandlung' && wantedTitle) {
      const match = options.behandlungen.find(
        (b) => b.title.toLowerCase() === wantedTitle ||
               b.title.toLowerCase().includes(wantedTitle) ||
               wantedTitle.includes(b.title.toLowerCase()),
      );
      if (match) {
        setKind('behandlung');
        setBehandlungId(match.id);
        return;
      }
    }
    // Kein Match: bleibe bei 'general' und schreibe den Titel als Hinweis ins Note-Feld
    if (wantedTitle && !note) {
      setNote(`Interesse an: ${prefill.title}`);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, prefill, options.loading]);

  // Verfügbare Starttermine für den ausgewählten Kurs
  const selectedCourse = useMemo(
    () => options.courses.find((c) => c.id === courseId) || null,
    [options.courses, courseId],
  );

  // Wenn Kurs gewechselt wird: Datum zurücksetzen (alter Wert evtl. ungültig)
  useEffect(() => {
    setCourseDate('');
  }, [courseId]);

  // ---------- Submit ----------
  const submit = async (e) => {
    e.preventDefault();
    setSubmitError(null);

    // Pflichtfeld-Check
    if (!name.trim() || !email.trim()) {
      setSubmitError('Bitte Name und E-Mail ausfüllen.');
      return;
    }
    if (kind === 'course' && !courseId) {
      setSubmitError('Bitte einen Kurs wählen.');
      return;
    }
    if (kind === 'behandlung' && !behandlungId) {
      setSubmitError('Bitte eine Behandlung wählen.');
      return;
    }

    setSubmitting(true);
    try {
      const body = {
        kind,
        customerName: name.trim(),
        customerEmail: email.trim(),
        customerPhone: phone.trim() || null,
        customerPhase: phase || null,
        message: note.trim() || null,
      };
      if (kind === 'course') {
        body.courseId = courseId;
        if (courseDate) body.courseOccurrenceDate = courseDate;
      } else if (kind === 'behandlung') {
        body.behandlungId = behandlungId;
      }

      const res = await fetch(WB_API_BASE + '/api/inquiries', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok || !json.ok) {
        throw new Error(json.error || 'Anfrage konnte nicht gesendet werden.');
      }
      setStep(1);
    } catch (err) {
      setSubmitError(err.message || 'Unbekannter Fehler. Bitte später erneut versuchen.');
    } finally {
      setSubmitting(false);
    }
  };

  // ---------- Render ----------
  return (
    <>
      {/* backdrop */}
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0,
        background: 'rgba(42,34,29,0.32)',
        backdropFilter: 'blur(2px)',
        zIndex: 1900,
        opacity: open ? 1 : 0,
        pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity 220ms var(--ease)',
      }} />

      <aside role="dialog" aria-modal="true" aria-label="Anfrage" style={{
        position: 'fixed',
        right: 'clamp(16px, 3vw, 32px)',
        bottom: 'clamp(80px, 8vw, 100px)',
        width: 'min(440px, calc(100vw - 32px))',
        maxHeight: 'calc(100vh - 120px)',
        zIndex: 1950,
        background: 'var(--offwhite)',
        borderRadius: 16,
        boxShadow: '0 24px 64px rgba(42,34,29,0.22), 0 4px 12px rgba(42,34,29,0.08)',
        border: '1px solid var(--sandstone)',
        opacity: open ? 1 : 0,
        transform: open ? 'translateY(0) scale(1)' : 'translateY(12px) scale(0.98)',
        pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity 240ms var(--ease), transform 280ms var(--ease)',
        overflow: 'hidden',
        display: 'flex',
        flexDirection: 'column',
      }}>
        {/* Header */}
        <div style={{
          padding: '20px 24px 16px',
          borderBottom: '1px solid var(--sandstone)',
          display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
          gap: 16,
        }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 6, fontSize: 11 }}>Anfrage</div>
            <h3 style={{
              fontFamily: 'Fraunces, serif',
              fontSize: 22,
              fontWeight: 500,
              lineHeight: 1.2,
              letterSpacing: '-0.01em',
              fontVariationSettings: '"opsz" 96, "SOFT" 50',
            }}>
              {step === 0 ? 'Schön, dass du da bist.' : 'Danke dir.'}
            </h3>
          </div>
          <button onClick={onClose} aria-label="Schließen" style={{
            width: 36, height: 36, borderRadius: 999,
            background: 'var(--heather-subtle)',
            color: 'var(--ink)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 18, fontWeight: 500, flexShrink: 0,
            cursor: 'pointer', transition: 'background 180ms var(--ease)',
          }}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--rose-dust)'}
            onMouseLeave={e => e.currentTarget.style.background = 'var(--heather-subtle)'}
          >×</button>
        </div>

        {/* Body */}
        <div style={{ overflowY: 'auto', padding: 24 }}>
          {step === 0 ? (
            <form onSubmit={submit}>
              <p style={{ fontSize: 14.5, color: 'var(--ink-70)', lineHeight: 1.55, marginBottom: 20 }}>
                Sag uns kurz, wofür du dich interessierst. Wir melden uns persönlich bei dir – meist innerhalb von 1–2 Tagen.
              </p>

              {/* Anfrage-Art: Pills */}
              <Field label="Worum geht's?" required>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {[
                    { value: 'general', label: 'Allgemeine Anfrage' },
                    { value: 'course', label: 'Kurs' },
                    { value: 'behandlung', label: 'Behandlung' },
                  ].map((opt) => (
                    <button key={opt.value} type="button"
                      onClick={() => setKind(opt.value)}
                      style={{
                        padding: '8px 14px',
                        borderRadius: 999,
                        fontSize: 13, fontWeight: 500,
                        border: '1px solid ' + (kind === opt.value ? 'var(--heather-plum)' : 'var(--sandstone-border)'),
                        background: kind === opt.value ? 'var(--heather-subtle)' : 'transparent',
                        color: kind === opt.value ? 'var(--heather-hover)' : 'var(--ink-70)',
                        cursor: 'pointer',
                        transition: 'all 160ms var(--ease)',
                      }}>
                      {opt.label}
                    </button>
                  ))}
                </div>
              </Field>

              {/* Lade-Hinweis falls Optionen noch nicht da */}
              {options.loading && (kind === 'course' || kind === 'behandlung') && (
                <Field label="Lade Auswahl…">
                  <div style={{ ...inputStyle, color: 'var(--ink-50)' }}>Einen Moment…</div>
                </Field>
              )}

              {/* Fehler beim Laden */}
              {options.error && (kind === 'course' || kind === 'behandlung') && (
                <div style={{
                  fontSize: 13, color: '#9E5740',
                  background: 'rgba(181,104,74,0.08)',
                  border: '1px solid rgba(181,104,74,0.25)',
                  borderRadius: 8, padding: '10px 12px', marginBottom: 16,
                }}>
                  Auswahl konnte nicht geladen werden ({options.error}). Du kannst trotzdem eine allgemeine Anfrage schicken.
                </div>
              )}

              {/* Kurs-Auswahl */}
              {kind === 'course' && !options.loading && !options.error && (
                <>
                  <Field label="Welcher Kurs?" required>
                    <select value={courseId} onChange={(e) => setCourseId(e.target.value)} required style={inputStyle}>
                      <option value="">Bitte auswählen…</option>
                      {groupByCategory(options.courses).map((g) => (
                        <optgroup key={g.cat} label={g.cat}>
                          {g.items.map((c) => (
                            <option key={c.id} value={c.id}>{c.title}</option>
                          ))}
                        </optgroup>
                      ))}
                    </select>
                  </Field>

                  {selectedCourse && selectedCourse.occurrences && selectedCourse.occurrences.length > 0 && (
                    <Field label="Gewünschter Starttermin (optional)">
                      <select value={courseDate} onChange={(e) => setCourseDate(e.target.value)} style={inputStyle}>
                        <option value="">Egal / flexibel</option>
                        {selectedCourse.occurrences.map((iso) => (
                          <option key={iso} value={iso}>{formatGermanDate(iso)}</option>
                        ))}
                      </select>
                    </Field>
                  )}
                </>
              )}

              {/* Behandlung-Auswahl */}
              {kind === 'behandlung' && !options.loading && !options.error && (
                <Field label="Welche Behandlung?" required>
                  <select value={behandlungId} onChange={(e) => setBehandlungId(e.target.value)} required style={inputStyle}>
                    <option value="">Bitte auswählen…</option>
                    {groupByCategory(options.behandlungen).map((g) => (
                      <optgroup key={g.cat} label={g.cat}>
                        {g.items.map((b) => (
                          <option key={b.id} value={b.id}>{b.title}</option>
                        ))}
                      </optgroup>
                    ))}
                  </select>
                </Field>
              )}

              <Field label="Lebensphase (optional)">
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {['Schwanger', 'Wochenbett', 'Mit Kind', 'Zyklus / Wechsel', 'Andere'].map(p => (
                    <button key={p} type="button"
                      onClick={() => setPhase(phase === p ? '' : p)}
                      style={{
                        padding: '6px 12px',
                        borderRadius: 999,
                        fontSize: 12.5, fontWeight: 500,
                        border: '1px solid ' + (phase === p ? 'var(--heather-plum)' : 'var(--sandstone-border)'),
                        background: phase === p ? 'var(--heather-subtle)' : 'transparent',
                        color: phase === p ? 'var(--heather-hover)' : 'var(--ink-70)',
                        cursor: 'pointer',
                        transition: 'all 160ms var(--ease)',
                      }}>
                      {p}
                    </button>
                  ))}
                </div>
              </Field>

              <Field label="Dein Name" required>
                <input type="text" value={name} onChange={e => setName(e.target.value)} required style={inputStyle} placeholder="Vorname" />
              </Field>

              <Field label="E-Mail" required>
                <input type="email" value={email} onChange={e => setEmail(e.target.value)} required style={inputStyle} placeholder="du@beispiel.de" />
              </Field>

              <Field label="Telefon (optional)">
                <input type="tel" value={phone} onChange={e => setPhone(e.target.value)} style={inputStyle} placeholder="+49 …" />
              </Field>

              <Field label="Was möchtest du uns sagen? (optional)">
                <textarea value={note} onChange={e => setNote(e.target.value)} rows={3} style={{ ...inputStyle, resize: 'vertical', minHeight: 80 }} placeholder="Frage, Wunschtermin, ein Wort zu dir…" />
              </Field>

              {submitError && (
                <div style={{
                  fontSize: 13, color: '#9E5740',
                  background: 'rgba(181,104,74,0.08)',
                  border: '1px solid rgba(181,104,74,0.25)',
                  borderRadius: 8, padding: '10px 12px', marginBottom: 12,
                }}>
                  {submitError}
                </div>
              )}

              <button type="submit" className="btn btn-primary" disabled={submitting} style={{ width: '100%', justifyContent: 'center', marginTop: 8, opacity: submitting ? 0.7 : 1 }}>
                {submitting ? 'Sende…' : <>Anfrage senden <span>→</span></>}
              </button>

              <p style={{ fontSize: 11.5, color: 'var(--ink-50)', marginTop: 16, lineHeight: 1.5 }}>
                Mit dem Senden willigst du der Verarbeitung deiner Daten zur Bearbeitung der Anfrage zu.
              </p>
            </form>
          ) : (
            <div style={{ padding: '20px 0' }}>
              <div style={{
                width: 72, height: 72, borderRadius: 999,
                background: 'var(--sage-tint)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                marginBottom: 20,
              }}>
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="var(--sage-ink)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 12l5 5L20 7"/>
                </svg>
              </div>
              <h4 style={{ fontFamily: 'Fraunces, serif', fontSize: 20, fontWeight: 500, marginBottom: 12, lineHeight: 1.3 }}>
                Deine Anfrage ist bei uns angekommen.
              </h4>
              <p style={{ fontSize: 15, color: 'var(--ink-70)', lineHeight: 1.6, marginBottom: 24 }}>
                Wir melden uns innerhalb von 1–2 Tagen persönlich bei dir – an <strong style={{ color: 'var(--ink)' }}>{email}</strong>. Bis bald.
              </p>
              <button onClick={onClose} className="btn btn-secondary" style={{ width: '100%', justifyContent: 'center' }}>
                Schließen
              </button>
            </div>
          )}
        </div>
      </aside>
    </>
  );
};

// ---------- Helpers ----------

// Gruppiert eine flache Liste {id, title, categoryTitle} nach categoryTitle.
function groupByCategory(items) {
  const groups = new Map();
  for (const item of items) {
    const key = item.categoryTitle || 'Sonstige';
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key).push(item);
  }
  return Array.from(groups.entries()).map(([cat, items]) => ({ cat, items }));
}

// "2026-05-13" → "Mi, 13. Mai 2026"
function formatGermanDate(iso) {
  const [y, m, d] = iso.split('-').map(Number);
  const date = new Date(y, m - 1, d);
  return date.toLocaleDateString('de-DE', { weekday: 'short', day: '2-digit', month: 'short', year: 'numeric' });
}

const inputStyle = {
  width: '100%',
  padding: '11px 14px',
  background: 'var(--offwhite)',
  border: '1.5px solid var(--sandstone)',
  borderRadius: 8,
  fontFamily: 'Figtree, sans-serif',
  fontSize: 15,
  color: 'var(--ink)',
  outline: 'none',
  transition: 'border-color 160ms var(--ease), box-shadow 160ms var(--ease)',
};

const Field = ({ label, required, children }) => (
  <div style={{ marginBottom: 16 }}>
    <label style={{
      display: 'block',
      fontSize: 13, fontWeight: 600,
      color: 'var(--ink)',
      marginBottom: 6,
    }}>
      {label}{required && <span style={{ color: 'var(--heather-plum)' }}> *</span>}
    </label>
    {children}
  </div>
);

window.InquiryLauncher = InquiryLauncher;
window.InquiryWindow = InquiryWindow;
