// ---------- 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.`;
};

// Event-Datum nach ISO-String (yyyy-mm-dd) normalisieren. course-data.jsx
// reparst e.date in ein Date-OBJEKT (kursplan.jsx braucht das), unsere
// String-Vergleiche (d >= todayIso) laufen damit aber ins Leere. Lokale
// Datumsteile verwenden — toISOString() waere UTC und kippt in DE-Zeitzone
// auf den Vortag.
const _wbEventDateIso = (d) => {
  if (typeof d === 'string') return d.slice(0, 10);
  if (d instanceof Date && !Number.isNaN(d.getTime())) {
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
  }
  return '';
};
window._wbEventDateIso = _wbEventDateIso;

// Format „12. November 2026" — falls API mal kein vorformatiertes nextStart liefert.
const _fmtIsoDate = (iso) => {
  if (!iso) return '';
  try {
    const d = new Date(iso + 'T00:00:00');
    if (Number.isNaN(d.getTime())) return '';
    return d.toLocaleDateString('de-DE', { day: 'numeric', month: 'long', year: 'numeric' });
  } catch { return ''; }
};

const WBCourseDetail = ({ course, onClose }) => {
  // Inneres State, damit Klick auf einen „Weitere Termine"-Eintrag den
  // angezeigten Kursblock wechseln kann, ohne das Modal zu schließen.
  const [activeId, setActiveId] = React.useState(course?.id ?? null);
  React.useEffect(() => { setActiveId(course?.id ?? null); }, [course?.id]);

  // Wenn der Aufrufer einen alten Kurs übergibt, finden wir den aktuellen
  // Stand (und Geschwister) live aus dem globalen WB_COURSES.
  const allCourses = (typeof window !== 'undefined' && window.WB_COURSES) || [];
  const liveCourse = allCourses.find((c) => c.id === activeId) || course;

  _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 || !liveCourse) return null;
  const cat = _wbCatById[liveCourse.cat] || { tone: { bg: '#5C4A3E', text: '#FAF6F1' }, title: 'Kurs' };

  // Geschwister-Kursblöcke der gleichen Kursart, nur die mit Startdatum
  // ab heute, sortiert nach Startdatum aufsteigend.
  const todayIso = new Date().toISOString().slice(0, 10);
  const siblings = liveCourse.courseTypeId
    ? allCourses
        .filter((c) => c.courseTypeId === liveCourse.courseTypeId)
        .filter((c) => c.id !== liveCourse.id)
        .filter((c) => c.startDate && c.startDate >= todayIso)
        .sort((a, b) => String(a.startDate).localeCompare(String(b.startDate)))
    : [];

  // Alle Termine DIESES Kursblocks aus dem globalen Event-Cache rauslesen,
  // nur zukünftige zeigen. Wird unter „Termine" als kompakte Datums-Liste
  // gerendert, damit Nutzerinnen sehen, wann genau der Kurs läuft (statt
  // nur die Wiederholungs-Regel zu raten).
  const allEvents = (typeof window !== 'undefined' && window.WB_KURSPLAN_EVENTS) || [];
  const courseDates = allEvents
    .filter((e) => e.courseId === liveCourse.id)
    .map((e) => _wbEventDateIso(e.date))
    .filter((d) => d && d >= todayIso)
    .sort();
  // Format „6. Okt" (oder „6. Okt 2027" wenn Jahr abweicht vom aktuellen)
  const currentYear = new Date().getFullYear();
  const fmtShort = (iso) => {
    if (!iso) return '';
    const d = new Date(iso + 'T00:00:00');
    if (Number.isNaN(d.getTime())) return '';
    const day = d.getDate();
    const month = ['Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'][d.getMonth()];
    const yr = d.getFullYear();
    return yr === currentYear ? `${day}. ${month}` : `${day}. ${month} ${yr}`;
  };
  const dateListLabel = courseDates.map(fmtShort).filter(Boolean);

  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',
          }}>{liveCourse.title}</h2>
        </div>

        <div style={{ padding: '0 0 26px' }}>
          {/* Hero-Bild aus der Kursart (course_types.image_url). Wenn keins
              gepflegt ist, bleibt nur die brand-getönte Fläche stehen — kein
              Picsum-Phantombild mehr. */}
          <div style={{
            width: '100%', aspectRatio: '16/9',
            background: cat.tone.bg,
            position: 'relative', overflow: 'hidden',
            marginBottom: 20,
          }}>
            {liveCourse.imageUrl && (
              <img
                src={liveCourse.imageUrl}
                alt={liveCourse.imageAlt || ''}
                loading="lazy"
                style={{
                  width: '100%', height: '100%', objectFit: 'cover', display: 'block',
                  filter: 'saturate(0.92) contrast(0.98)',
                }}
                onError={(e) => { e.currentTarget.style.display = 'none'; }}
              />
            )}
            <div style={{
              position: 'absolute', inset: 0,
              background: `linear-gradient(180deg, transparent 40%, ${cat.tone.bg} 130%)`,
              mixBlendMode: 'multiply', opacity: liveCourse.imageUrl ? 0.35 : 0,
            }} />
          </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',
            }}>{liveCourse.desc}</p>
            {/* Langtext der Kursart (Admin: "Beschreibung"). Absaetze via
                pre-line erhalten — Admins tippen den Text mit Zeilenumbruechen. */}
            {liveCourse.longDesc && (
              <p style={{
                fontSize: 14, lineHeight: 1.7,
                color: 'var(--ink-70)', marginBottom: 22,
                whiteSpace: 'pre-line',
              }}>{liveCourse.longDesc}</p>
            )}
            {/* Wenn ueberhaupt keine Beschreibung existiert (weder Kurz noch
                Lang), zeigen wir einen dezenten Fallback. */}
            {!liveCourse.desc && !liveCourse.longDesc && (
              <p style={{
                fontSize: 14, lineHeight: 1.65,
                color: 'var(--ink-70)', marginBottom: 22,
              }}>{_wbDefaultBlurb(liveCourse, cat)}</p>
            )}

            <dl className="detail-dl" style={{
              display: 'grid', gridTemplateColumns: '120px 1fr',
              gap: '12px 16px', fontSize: 14, marginBottom: 26,
            }}>
              <_DTerm>Kursleitung</_DTerm>
              <_DDef>{liveCourse.leader || '—'}</_DDef>
              <_DTerm>Termine</_DTerm>
              <_DDef>
                {liveCourse.schedule || '—'}
                {dateListLabel.length > 0 && (
                  <div style={{
                    fontSize: 12.5,
                    color: 'var(--ink-50)',
                    marginTop: 4,
                    lineHeight: 1.55,
                  }}>
                    {dateListLabel.join(' · ')}
                  </div>
                )}
              </_DDef>
              <_DTerm>Nächster Start</_DTerm>
              <_DDef>{liveCourse.nextStart || _fmtIsoDate(liveCourse.startDate) || '—'}</_DDef>
              <_DTerm>Dauer</_DTerm>
              <_DDef>{liveCourse.duration || '—'}</_DDef>
              <_DTerm>Kosten</_DTerm>
              <_DDef>
                <strong style={{ color: 'var(--ink)' }}>{liveCourse.price || '—'}</strong>
                {liveCourse.kasseSubsidy && (
                  <div style={{
                    marginTop: 4,
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                    fontSize: 12, color: 'var(--sage-ink)',
                    background: 'var(--sage-tint)',
                    border: '1px solid var(--sage)',
                    borderRadius: 999, padding: '3px 10px',
                  }}>
                    <span>✓</span>
                    <span>Bezuschuss von der Krankenkasse je nach Kasse und Budget möglich</span>
                  </div>
                )}
              </_DDef>
            </dl>

            {siblings.length > 0 && (
              <div style={{
                background: 'var(--canvas)',
                border: '1px solid var(--sandstone)',
                borderRadius: 12,
                padding: '14px 16px 12px',
                marginBottom: 22,
              }}>
                <div style={{
                  fontSize: 11, fontWeight: 600, letterSpacing: '0.12em',
                  textTransform: 'uppercase', color: 'var(--ink-50)', marginBottom: 8,
                }}>Weitere Kursblöcke dieser Kursart · {siblings.length}</div>
                <p style={{ fontSize: 12.5, color: 'var(--ink-50)', marginBottom: 10, lineHeight: 1.5 }}>
                  Andere Termine — vielleicht passt einer besser zu deinem Zeitfenster.
                </p>
                <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {siblings.map((s) => (
                    <li key={s.id}>
                      <button type="button"
                        onClick={() => setActiveId(s.id)}
                        style={{
                          width: '100%',
                          background: 'var(--offwhite)',
                          border: '1px solid var(--sandstone)',
                          borderRadius: 10,
                          padding: '10px 12px',
                          textAlign: 'left',
                          fontFamily: 'inherit',
                          fontSize: 13.5,
                          cursor: 'pointer',
                          color: 'var(--ink)',
                          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
                          transition: 'background 140ms var(--ease), border-color 140ms var(--ease)',
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.background = 'var(--heather-subtle)';
                          e.currentTarget.style.borderColor = 'var(--heather-plum)';
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.background = 'var(--offwhite)';
                          e.currentTarget.style.borderColor = 'var(--sandstone)';
                        }}
                      >
                        <span>
                          <strong style={{ fontWeight: 600 }}>{s.nextStart || _fmtIsoDate(s.startDate)}</strong>
                          {s.leader && s.leader !== 'Team' && (
                            <span style={{ color: 'var(--ink-50)', fontSize: 12.5 }}>{' · '}{s.leader}</span>
                          )}
                          {s.title !== liveCourse.title && (
                            <span style={{ color: 'var(--ink-50)', fontSize: 12.5 }}>{' · '}{s.title}</span>
                          )}
                        </span>
                        <span style={{ color: 'var(--ink-50)', fontSize: 16, flexShrink: 0 }}>→</span>
                      </button>
                    </li>
                  ))}
                </ul>
              </div>
            )}

            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              {liveCourse.bookingUrl && (
                <a href={liveCourse.bookingUrl} target="_blank" rel="noopener noreferrer"
                  className="btn btn-primary"
                  style={{ flex: '1 1 200px', textAlign: 'center', textDecoration: 'none' }}>
                  Direkt buchen →
                </a>
              )}
              <button type="button"
                onClick={() => {
                  onClose();
                  if (window.__WB_INQUIRY_AVAILABLE) {
                    window.dispatchEvent(new CustomEvent('wb-open-inquiry', {
                      detail: { id: liveCourse.id, title: liveCourse.title, kind: 'course' },
                    }));
                  } else {
                    const params = new URLSearchParams({ kind: 'course', id: liveCourse.id, title: liveCourse.title });
                    window.location.href = 'Die Weiberei.html#anfrage?' + params.toString();
                  }
                }}
                className={liveCourse.bookingUrl ? 'btn btn-secondary' : 'btn btn-primary'}
                style={{ flex: '1 1 200px' }}>
                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;
