// Wraps the existing App with a Tweaks panel that swaps the accent color live.
// Reads/writes the EDITMODE block in Die Weiberei.html for persistence.

const TWEAK_DEFAULTS = window.__TWEAK_DEFAULTS;

const accentSwatches = [
  { name: 'Heather Plum', value: '#8B6E7E', hover: '#6F5663', subtle: '#EFE3E7' },
  { name: 'Rose Dust',    value: '#B07A8A', hover: '#8E5E6F', subtle: '#F2E1E1' },
  { name: 'Terracotta',   value: '#B5684A', hover: '#9E5740', subtle: '#F2DDD1' },
  { name: 'Honey',        value: '#B0824A', hover: '#8B6B3E', subtle: '#F0DCB9' },
  { name: 'Sage',         value: '#6F7E63', hover: '#4A5544', subtle: '#D8DFD1' },
  { name: 'Ink Brown',    value: '#5C4A3E', hover: '#2A221D', subtle: '#E8D5C0' },
];

// Convert hex → "r, g, b" for rgba() compositions
const hexToRgb = (hex) => {
  const h = hex.replace('#', '');
  return [parseInt(h.slice(0,2),16), parseInt(h.slice(2,4),16), parseInt(h.slice(4,6),16)].join(', ');
};

// Mix two hexes (default 50/50) — for derived hover/subtle when custom
const mix = (a, b, t = 0.5) => {
  const ah = a.replace('#',''), bh = b.replace('#','');
  const ar=parseInt(ah.slice(0,2),16), ag=parseInt(ah.slice(2,4),16), ab=parseInt(ah.slice(4,6),16);
  const br=parseInt(bh.slice(0,2),16), bg=parseInt(bh.slice(2,4),16), bb=parseInt(bh.slice(4,6),16);
  const r = Math.round(ar*(1-t) + br*t);
  const g = Math.round(ag*(1-t) + bg*t);
  const bl= Math.round(ab*(1-t) + bb*t);
  const h = (n) => n.toString(16).padStart(2,'0');
  return '#' + h(r) + h(g) + h(bl);
};

const SwatchRow = ({ value, onChange }) => {
  return (
    <div className="twk-row">
      <div className="twk-lbl"><span>Akzentfarbe</span></div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 2 }}>
        {accentSwatches.map(s => {
          const active = s.value.toLowerCase() === value.toLowerCase();
          return (
            <button key={s.name} type="button" title={s.name}
              onClick={() => onChange(s)}
              style={{
                width: 28, height: 28, borderRadius: 999,
                background: s.value,
                border: active ? '2px solid #29261b' : '1.5px solid rgba(0,0,0,0.1)',
                boxShadow: active ? '0 0 0 2px rgba(255,255,255,0.9), 0 0 0 3px ' + s.value : '0 1px 2px rgba(0,0,0,0.1)',
                cursor: 'pointer',
                padding: 0,
                transition: 'transform 120ms ease',
              }}
              onMouseEnter={e => e.currentTarget.style.transform = 'scale(1.08)'}
              onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
            />
          );
        })}
      </div>
      <div style={{ marginTop: 8, fontSize: 10.5, color: 'rgba(41,38,27,0.5)' }}>
        Hinweis: Heather Plum ist der definierte Marken-CTA.
      </div>
    </div>
  );
};

// Apply tokens to :root so existing components pick them up automatically.
const applyAccent = (s) => {
  const root = document.documentElement;
  root.style.setProperty('--heather-plum', s.value);
  root.style.setProperty('--heather-hover', s.hover);
  root.style.setProperty('--heather-subtle', s.subtle);
  root.style.setProperty('--shadow-cta', `0 4px 12px rgba(${hexToRgb(s.value)}, 0.25)`);
};

const TweakedApp = () => {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [inquiryOpen, setInquiryOpen] = React.useState(false);
  // prefill = { title, kind } — wird gesetzt, wenn ein CTA das Formular mit
  // vorgemerktem Kurs/Behandlung öffnen will.
  const [inquiryPrefill, setInquiryPrefill] = React.useState(null);
  const openInquiry = React.useCallback((prefill) => {
    // Defensiv: wenn die Funktion direkt als onClick-Handler genutzt wird,
    // bekommen wir ein SyntheticEvent statt eines Prefill-Objekts.
    const cleanPrefill =
      prefill && typeof prefill === 'object' && (prefill.title || prefill.kind)
        ? prefill
        : null;
    setInquiryPrefill(cleanPrefill);
    setInquiryOpen(true);
  }, []);

  // Globaler Event-Bus: Detail-Modals (course-detail, behandlung-detail), die
  // außerhalb des Komponenten-Trees gemountet sind, dispatchen einen
  // 'wb-open-inquiry'-Event mit { title, kind } im detail. Wir hören hier
  // mit und öffnen das Formular entsprechend.
  //
  // Flag __WB_INQUIRY_AVAILABLE signalisiert den Detail-Modals, dass das
  // Formular auf dieser Seite verfügbar ist — Subpages (Alle Kurse, Alle
  // Behandlungen) laden app.jsx nicht und fallback'en dann auf URL-Navigation.
  React.useEffect(() => {
    window.__WB_INQUIRY_AVAILABLE = true;
    const handler = (ev) => openInquiry(ev.detail || null);
    window.addEventListener('wb-open-inquiry', handler);

    // Initialer Hash-Check: Wenn die Seite über einen Subpage-Link mit
    // ?kind=...&title=... geladen wurde, Formular gleich öffnen.
    const hash = window.location.hash;
    if (hash.startsWith('#anfrage')) {
      const qs = hash.includes('?') ? hash.slice(hash.indexOf('?') + 1) : '';
      const params = new URLSearchParams(qs);
      const title = params.get('title');
      const kind = params.get('kind');
      if (title || kind) {
        // Kleines Delay, damit Optionen-Fetch starten kann
        setTimeout(() => openInquiry({ title: title || '', kind: kind || 'general' }), 50);
        history.replaceState(null, '', window.location.pathname);
      }
    }

    return () => {
      window.removeEventListener('wb-open-inquiry', handler);
      window.__WB_INQUIRY_AVAILABLE = false;
    };
  }, [openInquiry]);

  // Apply on mount + whenever accent changes
  React.useEffect(() => {
    const swatch = accentSwatches.find(s => s.value.toLowerCase() === (t.accent || '').toLowerCase());
    if (swatch) {
      applyAccent(swatch);
    } else if (t.accent) {
      // custom hex — derive hover (darker 25%) and subtle (lighter 85% mixed with canvas)
      applyAccent({
        value: t.accent,
        hover: mix(t.accent, '#000000', 0.20),
        subtle: mix(t.accent, '#FAF6F1', 0.85),
      });
    }
  }, [t.accent]);

  const onPickSwatch = (s) => {
    setTweak('accent', s.value);
  };

  return (
    <>
      <BackgroundCanvas />
      <Nav onOpenInquiry={openInquiry} />
      <main>
        <Hero onOpenInquiry={openInquiry} />
        <Kursplan onOpenInquiry={openInquiry} />
        <SectionDivider />
        <Behandlungen onOpenInquiry={openInquiry} />
        <SectionDivider />
        <CourseCarousel onOpenInquiry={openInquiry} />
        <SectionDivider />
        <Erfahrungen />
        <SectionDivider />
        <DieWeiber />
        <SectionDivider />
        <Bauchschmiede />
        <SectionDivider />
        <Ort onOpenInquiry={openInquiry} />
        <SectionDivider />
        <Aktuelles />
      </main>
      <Footer />
      <InquiryLauncher open={inquiryOpen} onToggle={() => { if (inquiryOpen) setInquiryOpen(false); else openInquiry(); }} />
      <InquiryWindow open={inquiryOpen} onClose={() => setInquiryOpen(false)} prefill={inquiryPrefill} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Marken-Akzent" />
        <SwatchRow value={t.accent} onChange={onPickSwatch} />
        <TweakColor
          label="Eigene Farbe"
          value={t.accent}
          onChange={(v) => setTweak('accent', v)}
        />
      </TweaksPanel>
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<TweakedApp />);
