// ---------- Behandlungen ----------
// 1:1 sessions and treatments offered in the Weiberei. Tile grid styled to
// match the rest of the homepage (warm sandstone, Heather Plum accents,
// Fraunces headings). Pulled from the live Weiberei site, Sandra Roland's
// services intentionally excluded per request.

// Treatments are categorised the same way as the courses — pulled from
// window.WB_CATEGORIES so the pill colors stay in sync if categories change.
// Data itself lives in behandlung-data.jsx so the Alle-Behandlungen subpage
// can reuse it.
const WB_BEHANDLUNGEN = window.WB_BEHANDLUNGEN || [];


const BehandlungTile = ({ item, onOpen }) => {
  const ref = useReveal();
  const cat = (window.WB_CATEGORIES || []).find((c) => c.id === item.cat) || {};
  const pill = cat.pill || { bg: 'var(--heather-subtle)', text: 'var(--heather-plum)', border: '#D4BCC6' };
  const accent = cat.tone && cat.tone.solid || 'var(--heather-plum)';
  return (
    <article ref={ref} className="reveal" role="button" tabIndex={0}
      onClick={() => onOpen(item)}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onOpen(item); } }}
      style={{
        background: 'var(--offwhite)',
        border: '1px solid ' + pill.border,
        borderTop: `4px solid ${accent}`,
        borderRadius: 14,
        padding: '22px 24px 24px',
        display: 'flex', flexDirection: 'column', gap: 10,
        transition: 'all 200ms var(--ease)',
        boxShadow: '0 1px 3px rgba(42,34,29,0.04)',
        cursor: 'pointer',
        textAlign: 'left',
      }}
      onMouseEnter={(e) => {
        e.currentTarget.style.transform = 'translateY(-3px)';
        e.currentTarget.style.boxShadow = '0 12px 28px rgba(42,34,29,0.12)';
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.transform = 'translateY(0)';
        e.currentTarget.style.boxShadow = '0 1px 3px rgba(42,34,29,0.04)';
      }}>
      
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 7,
        fontSize: 11, fontWeight: 600, letterSpacing: '0.12em', textTransform: 'uppercase',
        color: pill.text,
        background: pill.bg,
        border: '1px solid ' + pill.border,
        alignSelf: 'flex-start',
        padding: '4px 10px', borderRadius: 999
      }}>
        <span style={{ width: 6, height: 6, borderRadius: 999, background: pill.text }} />
        {cat.title || 'Behandlung'}
      </span>

      <h3 style={{
        fontFamily: 'Fraunces, serif', fontWeight: 400,
        fontSize: 24, lineHeight: 1.15, color: 'var(--ink)',
        fontVariationSettings: '"opsz" 96, "SOFT" 50, "WONK" 1'
      }}>{item.title}</h3>

      <div style={{
        fontSize: 12.5, color: 'var(--ink-50)',
        fontStyle: 'italic'
      }}>mit {item.leader}</div>

      <p style={{
        fontSize: 14, lineHeight: 1.55, color: 'var(--ink-70)',
        flex: 1, marginTop: 2
      }}>{item.body}</p>

      <div style={{
        marginTop: 8, paddingTop: 12,
        borderTop: '1px dashed rgba(42,34,29,0.12)',
        fontSize: 12, color: 'var(--ink-70)'
      }}>
        <strong style={{ color: 'var(--ink)', fontWeight: 600 }}>Kontakt:</strong> {item.contact}
      </div>
    </article>);

};

const Behandlungen = ({ onOpenInquiry }) => {
  const headRef = useReveal();
  const [openItem, setOpenItem] = React.useState(null);

  // Mobile (≤720px): tiles are grouped by category and each group is a
  // collapsible accordion, all collapsed by default. Desktop keeps the flat
  // auto-fill grid so nothing changes there.
  const [isMobile, setIsMobile] = React.useState(() =>
    typeof window !== 'undefined' && window.matchMedia
      ? window.matchMedia('(max-width: 720px)').matches
      : false
  );
  React.useEffect(() => {
    if (typeof window === 'undefined' || !window.matchMedia) return undefined;
    const mq = window.matchMedia('(max-width: 720px)');
    const onChange = (e) => setIsMobile(e.matches);
    onChange(mq);
    mq.addEventListener ? mq.addEventListener('change', onChange) : mq.addListener(onChange);
    return () => {
      mq.removeEventListener ? mq.removeEventListener('change', onChange) : mq.removeListener(onChange);
    };
  }, []);

  // Group items in the same order they appear in WB_CATEGORIES so the section
  // mirrors the rest of the site (Hebamme → Schwangerschaft → … → Baby).
  const cats = window.WB_CATEGORIES || [];
  const groups = cats
    .map(cat => ({ cat, items: WB_BEHANDLUNGEN.filter(b => b.cat === cat.id) }))
    .filter(g => g.items.length > 0);

  // openCats: Set of cat ids currently expanded; starts empty per request.
  const [openCats, setOpenCats] = React.useState(() => new Set());
  const toggleCat = (id) => {
    setOpenCats(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };

  return (
    <>
    <section id="behandlungen" style={{ padding: 'clamp(56px, 8vw, 96px) 0 clamp(40px, 6vw, 64px)' }}>
      <div className="container">
        <div ref={headRef} className="reveal" style={{
          marginBottom: 40, display: 'flex', alignItems: 'flex-end',
          justifyContent: 'space-between', gap: 24, flexWrap: 'wrap'
        }}>
          <div style={{ maxWidth: 720 }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>Behandlungen</div>
            <h2 style={{
              fontSize: 'clamp(36px, 5vw, 56px)', lineHeight: 1.1, letterSpacing: '-0.015em',
              marginBottom: 20,
              fontVariationSettings: '"opsz" 96, "SOFT" 50, "WONK" 1'
            }}>
              Individuelle Betreuung, ganz nach{' '}
              <em className="bacalisties" style={{ color: 'var(--heather-plum)' }}>deinen Bedürfnissen</em>.
            </h2>
            <p className="lead" style={{ maxWidth: 600 }}>
              Persönliche Begleitung in unseren Räumen — von Osteopathie bis Eltern-Coaching.
              Termine direkt mit der jeweiligen Frau, ganz in deinem Tempo.
            </p>
          </div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
            <a href="Alle%20Behandlungen.html"
              className="btn btn-secondary"
              style={{ textDecoration: 'none', whiteSpace: 'nowrap' }}>
              Alle Behandlungen <span style={{ fontSize: 17, marginLeft: 2 }}>→</span>
            </a>
            <button type="button" onClick={onOpenInquiry}
              className="btn btn-secondary"
              style={{ whiteSpace: 'nowrap' }}>
              Allgemeine Anfrage <span style={{ fontSize: 17, marginLeft: 2 }}>→</span>
            </button>
          </div>
        </div>

        {isMobile ? (
          <div id="behandlungen-grid" style={{ display: 'flex', flexDirection: 'column', gap: 10, scrollMarginTop: 88 }}>
            {groups.map(({ cat, items }) => {
              const isOpen = openCats.has(cat.id);
              const pill = cat.pill || { bg: 'var(--heather-subtle)', text: 'var(--heather-plum)', border: '#D4BCC6' };
              const accent = (cat.tone && cat.tone.solid) || 'var(--heather-plum)';
              return (
                <div key={cat.id} style={{
                  background: 'var(--offwhite)',
                  border: '1px solid ' + pill.border,
                  borderLeft: `4px solid ${accent}`,
                  borderRadius: 12,
                  overflow: 'hidden',
                }}>
                  <button type="button"
                    onClick={() => toggleCat(cat.id)}
                    aria-expanded={isOpen}
                    aria-controls={`bh-grp-${cat.id}`}
                    style={{
                      width: '100%',
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                      gap: 12, padding: '14px 16px',
                      background: 'transparent', border: 'none',
                      fontFamily: 'inherit', cursor: 'pointer', color: 'var(--ink)',
                      textAlign: 'left',
                    }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                      <span aria-hidden="true" style={{
                        width: 8, height: 8, borderRadius: 999,
                        background: accent, flexShrink: 0,
                      }} />
                      <span style={{
                        fontFamily: 'Fraunces, serif',
                        fontSize: 18, lineHeight: 1.15,
                        fontVariationSettings: '"opsz" 96, "SOFT" 50, "WONK" 1',
                      }}>{cat.title}</span>
                      <span style={{
                        fontSize: 11.5, fontWeight: 600,
                        padding: '2px 8px', borderRadius: 999,
                        background: pill.bg, color: pill.text,
                        border: '1px solid ' + pill.border,
                        lineHeight: 1.4,
                      }}>{items.length}</span>
                    </span>
                    <span aria-hidden="true" style={{
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      width: 24, height: 24,
                      fontSize: 11, color: 'var(--ink-50)',
                      transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)',
                      transition: 'transform 220ms var(--ease)',
                    }}>▼</span>
                  </button>

                  <div id={`bh-grp-${cat.id}`}
                    aria-hidden={!isOpen}
                    style={{
                      display: 'grid',
                      gridTemplateRows: isOpen ? '1fr' : '0fr',
                      transition: 'grid-template-rows 280ms var(--ease)',
                    }}>
                    <div style={{ overflow: 'hidden', minHeight: 0 }}>
                      <div style={{
                        display: 'flex', flexDirection: 'column', gap: 12,
                        padding: '4px 12px 14px',
                      }}>
                        {items.map(item =>
                          <BehandlungTile key={item.id} item={item} onOpen={setOpenItem} />
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          <div id="behandlungen-grid" style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
            gap: 16,
            scrollMarginTop: 88,
          }}>
            {WB_BEHANDLUNGEN.map((item) =>
            <BehandlungTile key={item.id} item={item} onOpen={setOpenItem} />
            )}
          </div>
        )}
      </div>
    </section>
    {(() => {
      const Detail = window.WBBehandlungDetail;
      return openItem && Detail ? (
        <Detail item={openItem} onClose={() => setOpenItem(null)} />
      ) : null;
    })()}
    </>);

};

window.Behandlungen = Behandlungen;