// ---------- Shared course detail widget ----------
// Used both by the homepage course pills and by the All-Courses subpage.
// Exposes a global <WBCourseDetail course={...} onClose={...}/> so any
// React tree can mount the same modal — keeps look/behavior in one place.

const { useEffect: _wbUseEffect } = React;

const _wbCatById = (() => {
  const cats = window.WB_CATEGORIES || [];
  return Object.fromEntries(cats.map(c => [c.id, c]));
})();

const _DTerm = ({ children }) => (
  <dt style={{ color: 'var(--ink-50)', fontWeight: 500 }}>{children}</dt>
);
const _DDef = ({ children }) => (
  <dd style={{ color: 'var(--ink)', margin: 0 }}>{children}</dd>
);

// Soft fallback blurb when a course has no explicit `blurb` field — keeps the
// detail widget feeling fleshed-out without needing to rewrite all course data.
const _wbDefaultBlurb = (course, cat) => {
  const phrase = (cat && cat.title) || 'Angebot';
  return `Du erfährst hier mehr über ${course.title} — was dich erwartet, wie der Kurs aufgebaut ist und was du mitbringen solltest. Teil unseres Angebots im Bereich „${phrase}". Schreib uns bei Fragen jederzeit eine Nachricht.`;
};

const WBCourseDetail = ({ course, onClose }) => {
  _wbUseEffect(() => {
    if (!course) return undefined;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [course, onClose]);

  if (!course) return null;
  const cat = _wbCatById[course.cat] || { tone: { bg: '#5C4A3E', text: '#FAF6F1' }, title: 'Kurs' };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 2000,
      background: 'rgba(42,34,29,0.45)',
      backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24, animation: 'wbFadeIn 200ms ease',
    }}>
      <style>{`@keyframes wbFadeIn{from{opacity:0}to{opacity:1}}@keyframes wbPop{from{opacity:0;transform:translateY(12px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}`}</style>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: 'var(--offwhite)',
        borderRadius: 18,
        width: '100%', maxWidth: 560,
        maxHeight: 'calc(100vh - 48px)',
        overflowY: 'auto',
        boxShadow: '0 32px 80px rgba(42,34,29,0.32)',
        animation: 'wbPop 240ms var(--ease)',
        position: 'relative',
      }}>
        <div style={{
          background: cat.tone.bg, color: cat.tone.text,
          padding: '24px 28px 20px',
          borderRadius: '18px 18px 0 0',
          position: 'sticky', top: 0, zIndex: 2,
        }}>
          <div style={{
            display: 'flex', justifyContent: 'space-between',
            alignItems: 'center', marginBottom: 14,
          }}>
            <span style={{
              fontSize: 11, fontWeight: 600, letterSpacing: '0.12em',
              textTransform: 'uppercase', opacity: 0.85,
            }}>{cat.title}</span>
            <button type="button" onClick={onClose} aria-label="Schließen" style={{
              width: 32, height: 32, borderRadius: 999,
              background: 'rgba(255,255,255,0.2)',
              color: cat.tone.text, fontSize: 16,
              border: 'none', cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>×</button>
          </div>
          <h2 style={{
            fontFamily: 'Fraunces, serif', fontWeight: 400,
            fontSize: 'clamp(26px, 4vw, 32px)', lineHeight: 1.1,
            color: cat.tone.text,
            fontVariationSettings: '"opsz" 96, "SOFT" 60, "WONK" 1',
          }}>{course.title}</h2>
        </div>

        <div style={{ padding: '0 0 26px' }}>
          {/* Dummy hero image — replace with real photography later */}
          <div style={{
            width: '100%', aspectRatio: '16/9',
            background: cat.tone.bg,
            position: 'relative', overflow: 'hidden',
            marginBottom: 20,
          }}>
            <img
              src={`https://picsum.photos/seed/${encodeURIComponent('weiberei-' + course.id)}/720/405`}
              alt=""
              loading="lazy"
              style={{
                width: '100%', height: '100%', objectFit: 'cover', display: 'block',
                filter: 'saturate(0.85) contrast(0.96)',
              }}
              onError={(e) => { e.currentTarget.style.display = 'none'; }}
            />
            {/* Soft brand-tinted overlay so any image harmonises with the palette */}
            <div style={{
              position: 'absolute', inset: 0,
              background: `linear-gradient(180deg, transparent 40%, ${cat.tone.bg} 130%)`,
              mixBlendMode: 'multiply', opacity: 0.35,
            }} />
          </div>

          <div style={{ padding: '0 28px' }}>
            <p style={{
              fontFamily: 'Fraunces, serif',
              fontSize: 17, lineHeight: 1.5,
              color: 'var(--ink)',
              marginBottom: 14,
              fontVariationSettings: '"opsz" 36, "SOFT" 50, "WONK" 0',
            }}>{course.desc}</p>
            <p style={{
              fontSize: 14, lineHeight: 1.65,
              color: 'var(--ink-70)', marginBottom: 22,
            }}>{course.blurb || _wbDefaultBlurb(course, cat)}</p>

            <dl style={{
              display: 'grid', gridTemplateColumns: '120px 1fr',
              gap: '12px 16px', fontSize: 14, marginBottom: 26,
            }}>
              <_DTerm>Kursleitung</_DTerm>
              <_DDef>{course.leader}</_DDef>
              <_DTerm>Termine</_DTerm>
              <_DDef>{course.schedule}</_DDef>
              <_DTerm>Nächster Start</_DTerm>
              <_DDef>{course.nextStart}</_DDef>
              <_DTerm>Dauer</_DTerm>
              <_DDef>{course.duration}</_DDef>
              <_DTerm>Kosten</_DTerm>
              <_DDef><strong style={{ color: 'var(--ink)' }}>{course.price}</strong></_DDef>
            </dl>

            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              <button type="button"
                onClick={() => {
                  onClose();
                  if (window.__WB_INQUIRY_AVAILABLE) {
                    // Homepage: Formular direkt öffnen
                    window.dispatchEvent(new CustomEvent('wb-open-inquiry', {
                      detail: { title: course.title, kind: 'course' },
                    }));
                  } else {
                    // Subpage: zur Homepage navigieren, Formular öffnet sich dort
                    const params = new URLSearchParams({ kind: 'course', title: course.title });
                    window.location.href = 'Die Weiberei.html#anfrage?' + params.toString();
                  }
                }}
                className="btn btn-primary" style={{ flex: '1 1 auto' }}>
                Anfrage stellen →
              </button>
              <button type="button" onClick={onClose} className="btn btn-secondary"
                style={{ flex: '0 0 auto' }}>Zurück</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.WBCourseDetail = WBCourseDetail;
