// ---------- Weib detail modal ----------
// Popup, das beim Klick auf eine Weib-Karte im „Die Weiber"-Karussell
// aufgeht. Zeigt Kurzvorstellung + längere Bio + aktuell angebotene
// Kurse und Behandlungen als klickbare Pills — Klick öffnet den
// jeweiligen Detail-Modal (WBCourseDetail / WBBehandlungDetail) via
// CustomEvent.

const { useEffect: _wbWeibUseEffect } = React;

const WBWeibDetail = ({ weib, onClose }) => {
  _wbWeibUseEffect(() => {
    if (!weib) 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;
    };
  }, [weib, onClose]);

  if (!weib) return null;

  // Hintergrundton aus der ersten zugewiesenen Kurs- oder Behandlungs-
  // Kategorie ableiten, sonst neutraler Sandstone-Ton.
  const allCats = [...(window.WB_CATEGORIES || []), ...(window.WB_BEHANDLUNG_CATEGORIES || [])];
  const findCat = (id) => allCats.find((c) => c.id === id);
  const firstCat =
    findCat(weib.courses?.[0]?.categoryId) ||
    findCat(weib.behandlungen?.[0]?.categoryId);
  const headerTone = firstCat
    ? { bg: firstCat.tone.bg, text: firstCat.tone.text }
    : { bg: '#5C4A3E', text: '#FAF6F1' };

  const openCourse = (id, title) => {
    onClose();
    setTimeout(() => {
      window.dispatchEvent(new CustomEvent('wb-open-course-by-id', { detail: { id, title } }));
    }, 50);
  };
  const openBehandlung = (id, title) => {
    onClose();
    setTimeout(() => {
      window.dispatchEvent(new CustomEvent('wb-open-behandlung-by-id', { detail: { id, title } }));
    }, 50);
  };

  const hasCourses = Array.isArray(weib.courses) && weib.courses.length > 0;
  const hasBehandlungen = Array.isArray(weib.behandlungen) && weib.behandlungen.length > 0;
  const longBio = weib.bio && weib.bio.trim().length > 0;
  const shortBio = weib.kurzvorstellung && weib.kurzvorstellung.trim().length > 0;

  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)}}.wb-weib-modal::-webkit-scrollbar{display:none}`}</style>
      <div onClick={(e) => e.stopPropagation()} className="wb-weib-modal" style={{
        background: 'var(--offwhite)',
        borderRadius: 18,
        width: '100%', maxWidth: 600,
        maxHeight: 'calc(100vh - 48px)',
        overflowY: 'auto',
        boxShadow: '0 32px 80px rgba(42,34,29,0.32)',
        animation: 'wbPop 240ms var(--ease)',
        position: 'relative',
        scrollbarWidth: 'none',
        msOverflowStyle: 'none',
      }}>
        <div style={{
          background: headerTone.bg, color: headerTone.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,
            }}>{weib.role || 'Die Weiber'}</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: headerTone.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: headerTone.text,
            fontVariationSettings: '"opsz" 96, "SOFT" 60, "WONK" 1',
          }}>{weib.name}</h2>
        </div>

        <div style={{ padding: '0 0 26px' }}>
          {weib.image && (
            <div style={{
              // Portrait 4:5 — matcht das Upload-Format (800×1000), damit
              // das Gesicht nie geschnitten wird. Höhe wird zusätzlich gedeckelt,
              // damit das Bild auf Desktop nicht das ganze Modal füllt.
              width: '100%', aspectRatio: '4 / 5',
              maxHeight: '60vh',
              background: headerTone.bg,
              position: 'relative', overflow: 'hidden',
              marginBottom: 20,
            }}>
              <img
                src={weib.image}
                alt={weib.name}
                loading="lazy"
                style={{
                  width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center top',
                  display: 'block', filter: 'saturate(0.94)',
                }}
                onError={(e) => { e.currentTarget.style.display = 'none'; }}
              />
              <div style={{
                position: 'absolute', inset: 0,
                background: `linear-gradient(180deg, transparent 60%, ${headerTone.bg} 140%)`,
                mixBlendMode: 'multiply', opacity: 0.25,
              }} />
            </div>
          )}

          <div style={{ padding: '0 28px' }}>
            {shortBio && (
              <p style={{
                fontFamily: 'Fraunces, serif',
                fontSize: 17, lineHeight: 1.5,
                color: 'var(--ink)',
                marginBottom: 14,
                fontVariationSettings: '"opsz" 36, "SOFT" 50, "WONK" 0',
              }}>{weib.kurzvorstellung}</p>
            )}
            {longBio && (
              <p style={{
                fontSize: 14, lineHeight: 1.7,
                color: 'var(--ink-70)', marginBottom: 22,
                whiteSpace: 'pre-wrap',
              }}>{weib.bio}</p>
            )}
            {!shortBio && !longBio && (
              <p style={{
                fontSize: 14, lineHeight: 1.65,
                color: 'var(--ink-50)', marginBottom: 22, fontStyle: 'italic',
              }}>
                Profil wird gerade gepflegt. Schau in Kürze nochmal vorbei.
              </p>
            )}

            {Array.isArray(weib.tags) && weib.tags.length > 0 && (
              <div style={{ marginBottom: 22 }}>
                <div style={{
                  fontSize: 11, fontWeight: 600, letterSpacing: '0.12em',
                  textTransform: 'uppercase', color: 'var(--ink-50)', marginBottom: 8,
                }}>Spezialisierungen</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {weib.tags.map((t) => (
                    <span key={t} style={{
                      background: 'var(--canvas)',
                      border: '1px solid var(--sandstone)',
                      borderRadius: 999, padding: '5px 11px',
                      fontSize: 12, color: 'var(--ink-70)', fontWeight: 500,
                    }}>{t}</span>
                  ))}
                </div>
              </div>
            )}

            {hasCourses && (
              <div style={{ marginBottom: 22 }}>
                <div style={{
                  fontSize: 11, fontWeight: 600, letterSpacing: '0.12em',
                  textTransform: 'uppercase', color: 'var(--ink-50)', marginBottom: 10,
                }}>Aktuelle Kurse · {weib.courses.length}</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {weib.courses.map((c) => {
                    const cat = findCat(c.categoryId);
                    const pill = cat?.pill;
                    return (
                      <button key={c.id} type="button"
                        onClick={() => openCourse(c.id, c.title)}
                        style={{
                          background: pill?.bg || 'var(--offwhite)',
                          color: pill?.text || 'var(--ink-70)',
                          border: '1px solid ' + (pill?.border || 'var(--sandstone)'),
                          borderRadius: 999, padding: '7px 13px',
                          fontSize: 12.5, fontWeight: 500,
                          cursor: 'pointer', fontFamily: 'inherit',
                          display: 'inline-flex', alignItems: 'center', gap: 6,
                          transition: 'transform 140ms var(--ease)',
                        }}
                        onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-1px)'; }}
                        onMouseLeave={(e) => { e.currentTarget.style.transform = 'translateY(0)'; }}
                      >
                        {pill && <span style={{
                          width: 6, height: 6, borderRadius: 999,
                          background: pill.text, opacity: 0.7,
                        }} />}
                        {c.title}
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            {hasBehandlungen && (
              <div style={{ marginBottom: 22 }}>
                <div style={{
                  fontSize: 11, fontWeight: 600, letterSpacing: '0.12em',
                  textTransform: 'uppercase', color: 'var(--ink-50)', marginBottom: 10,
                }}>Aktuelle Behandlungen · {weib.behandlungen.length}</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {weib.behandlungen.map((b) => {
                    const cat = findCat(b.categoryId);
                    const pill = cat?.pill;
                    return (
                      <button key={b.id} type="button"
                        onClick={() => openBehandlung(b.id, b.title)}
                        style={{
                          background: pill?.bg || 'var(--offwhite)',
                          color: pill?.text || 'var(--ink-70)',
                          border: '1px solid ' + (pill?.border || 'var(--sandstone)'),
                          borderRadius: 999, padding: '7px 13px',
                          fontSize: 12.5, fontWeight: 500,
                          cursor: 'pointer', fontFamily: 'inherit',
                          display: 'inline-flex', alignItems: 'center', gap: 6,
                          transition: 'transform 140ms var(--ease)',
                        }}
                        onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-1px)'; }}
                        onMouseLeave={(e) => { e.currentTarget.style.transform = 'translateY(0)'; }}
                      >
                        {pill && <span style={{
                          width: 6, height: 6, borderRadius: 999,
                          background: pill.text, opacity: 0.7,
                        }} />}
                        {b.title}
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            {!hasCourses && !hasBehandlungen && (
              <p style={{
                fontSize: 13, color: 'var(--ink-50)', fontStyle: 'italic',
                marginBottom: 22,
              }}>
                Aktuell sind dieser Frau noch keine Kurse oder Behandlungen
                zugewiesen.
              </p>
            )}

            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              {weib.website && (
                <a href={weib.website} target="_blank" rel="noopener noreferrer"
                  className="btn btn-primary"
                  style={{ flex: '1 1 200px', textAlign: 'center', textDecoration: 'none' }}>
                  Mehr Infos auf der eigenen Webseite →
                </a>
              )}
              <button type="button" onClick={onClose}
                className={weib.website ? 'btn btn-secondary' : 'btn btn-primary'}
                style={{ flex: '1 1 auto' }}>Schließen</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.WBWeibDetail = WBWeibDetail;
