// All-Behandlungen subpage app.
// Mirrors all-courses.jsx: filter bar (category chips + leader select + search)
// → treatment tile grid grouped & color-coded by category → floating
// detail widget on tile click. Detail widget is shared with the homepage.

const { useState: useStateBh, useMemo: useMemoBh, useEffect: useEffectBh } = React;

const bhCats = window.WB_CATEGORIES;
const bhItems = window.WB_BEHANDLUNGEN;
const bhLeaders = window.WB_BEHANDLUNG_LEADERS;
const bhCatById = Object.fromEntries(bhCats.map((c) => [c.id, c]));

// True if a treatment is led by `name` — strings are split on " & " so
// multi-person entries match each individual.
const bhHasLeader = (item, name) => {
  return String(item.leader)
    .split(/\s*&\s*/)
    .map((s) => s.trim())
    .includes(name);
};

// ---------- Filter bar ----------
const BhFilterBar = ({ activeCat, setActiveCat, leader, setLeader, query, setQuery, count }) => {
  const [isMobile, setIsMobile] = React.useState(
    typeof window !== 'undefined' && window.innerWidth <= 720
  );
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    const onResize = () => setIsMobile(window.innerWidth <= 720);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  const expanded = !isMobile || open;

  const activeCatObj = activeCat === 'all' ? null : bhCats.find((c) => c.id === activeCat);
  const activeChips = [];
  if (activeCatObj) activeChips.push({ key: 'cat', label: activeCatObj.title, tone: activeCatObj, onClear: () => setActiveCat('all') });
  if (leader !== 'all') activeChips.push({ key: 'leader', label: leader, tone: null, onClear: () => setLeader('all') });
  if (query.trim()) activeChips.push({ key: 'q', label: '„' + query + '"', tone: null, onClear: () => setQuery('') });

  return (
    <div style={{
      position: 'sticky', top: 72, zIndex: 30,
      background: 'rgba(242, 228, 206, 0.88)',
      backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)',
      borderBottom: '1px solid rgba(196, 169, 143, 0.4)',
      padding: isMobile ? '12px 0' : '20px 0',
    }}>
      <div className="container" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {isMobile && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
            <button type="button" onClick={() => setOpen((o) => !o)}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '9px 14px', borderRadius: 999,
                background: 'var(--offwhite)',
                border: '1px solid var(--sandstone)',
                fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
                color: 'var(--ink)', cursor: 'pointer',
                minHeight: 38,
              }}>
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
                <path d="M1 3h12M3 7h8M5 11h4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
              </svg>
              Filter
              {activeChips.length > 0 && (
                <span style={{
                  background: 'var(--heather-plum)', color: 'var(--offwhite)',
                  borderRadius: 999, minWidth: 18, height: 18,
                  fontSize: 11, fontWeight: 700,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  padding: '0 5px',
                }}>{activeChips.length}</span>
              )}
              <span style={{ fontSize: 10, opacity: 0.6, marginLeft: 2 }}>{open ? '▲' : '▼'}</span>
            </button>

            <span style={{ marginLeft: 'auto', fontSize: 13, color: 'var(--ink-70)', fontWeight: 500 }}>
              {count} {count === 1 ? 'Behandlung' : 'Behandlungen'}
            </span>

            {!open && activeChips.length > 0 && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, width: '100%', marginTop: 2 }}>
                {activeChips.map((chip) => (
                  <button key={chip.key} type="button" onClick={chip.onClear}
                    style={{
                      display: 'inline-flex', alignItems: 'center', gap: 6,
                      padding: '5px 10px', borderRadius: 999,
                      background: chip.tone ? chip.tone.tone.bg : 'var(--ink)',
                      color: chip.tone ? chip.tone.tone.text : 'var(--offwhite)',
                      border: 'none',
                      fontSize: 12, fontWeight: 500, fontFamily: 'inherit',
                      cursor: 'pointer',
                    }}>
                    {chip.label}
                    <span style={{ fontSize: 14, lineHeight: 1, opacity: 0.7 }}>×</span>
                  </button>
                ))}
                {activeChips.length > 1 && (
                  <button type="button"
                    onClick={() => { setActiveCat('all'); setLeader('all'); setQuery(''); }}
                    style={{
                      padding: '5px 10px', borderRadius: 999,
                      background: 'transparent', border: '1px dashed var(--sandstone-border)',
                      fontSize: 12, color: 'var(--ink-70)', fontFamily: 'inherit',
                      cursor: 'pointer',
                    }}>
                    Alles zurücksetzen
                  </button>
                )}
              </div>
            )}
          </div>
        )}

        {expanded && (
          <>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
              <BhCatChip active={activeCat === 'all'} onClick={() => setActiveCat('all')}
                label="Alle Kategorien" tone={null} count={bhItems.length} />
              {bhCats.map((c) => {
                const n = bhItems.filter((x) => x.cat === c.id).length;
                if (n === 0) return null;
                return (
                  <BhCatChip key={c.id} active={activeCat === c.id}
                    onClick={() => setActiveCat(c.id)}
                    label={c.title} tone={c} count={n} />
                );
              })}
            </div>

            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center' }}>
              <div style={{ position: 'relative', flex: '1 1 240px', maxWidth: 360 }}>
                <input type="text" value={query} onChange={(e) => setQuery(e.target.value)}
                  placeholder="Behandlung suchen…"
                  style={{
                    width: '100%', padding: '11px 14px 11px 38px',
                    background: 'var(--offwhite)',
                    border: '1px solid var(--sandstone)', borderRadius: 10,
                    fontSize: 14, fontFamily: 'inherit', color: 'var(--ink)',
                    outline: 'none',
                  }} />
                <span style={{
                  position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)',
                  fontSize: 14, opacity: 0.5,
                }}>⌕</span>
              </div>

              <div style={{ position: 'relative', flex: isMobile ? '1 1 100%' : '0 0 auto', minWidth: isMobile ? 0 : 240 }}>
                <select value={leader} onChange={(e) => setLeader(e.target.value)}
                  style={{
                    width: '100%',
                    appearance: 'none', WebkitAppearance: 'none', MozAppearance: 'none',
                    padding: '11px 38px 11px 14px',
                    borderRadius: 10,
                    background: 'var(--offwhite)',
                    border: '1px solid var(--sandstone)',
                    fontSize: 14, fontFamily: 'inherit', color: 'var(--ink)',
                    fontWeight: 500, lineHeight: 1.4,
                    cursor: 'pointer', outline: 'none',
                  }}>
                  <option value="all">Alle Behandlerinnen</option>
                  {bhLeaders.map((n) => <option key={n} value={n}>{n}</option>)}
                </select>
                <span style={{
                  position: 'absolute', right: 14, top: '50%',
                  transform: 'translateY(-50%)',
                  fontSize: 10, color: 'var(--ink-50)',
                  pointerEvents: 'none', lineHeight: 1,
                }}>▼</span>
              </div>

              {!isMobile && (
                <span style={{ marginLeft: 'auto', fontSize: 13, color: 'var(--ink-70)' }}>
                  {count} {count === 1 ? 'Behandlung' : 'Behandlungen'}
                </span>
              )}
            </div>

            {isMobile && (
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
                <button type="button"
                  onClick={() => { setActiveCat('all'); setLeader('all'); setQuery(''); }}
                  style={{
                    padding: '8px 14px', borderRadius: 8,
                    background: 'transparent', border: '1px solid var(--sandstone)',
                    fontSize: 13, color: 'var(--ink-70)', fontFamily: 'inherit',
                    cursor: 'pointer',
                  }}>
                  Zurücksetzen
                </button>
                <button type="button" onClick={() => setOpen(false)}
                  className="btn btn-primary"
                  style={{ padding: '8px 18px', minHeight: 38, fontSize: 13 }}>
                  {count} {count === 1 ? 'Behandlung' : 'Behandlungen'} ansehen
                </button>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

const BhCatChip = ({ active, onClick, label, tone, count }) => {
  const baseBg = tone ? tone.pill.bg : '#FAF6F1';
  const baseText = tone ? tone.pill.text : 'var(--ink-70)';
  const baseBorder = tone ? tone.pill.border : 'var(--sandstone)';
  return (
    <button type="button" onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '8px 14px', borderRadius: 999,
      background: active && tone ? tone.tone.bg : (active ? 'var(--ink)' : baseBg),
      color: active ? (tone ? tone.tone.text : '#FAF6F1') : baseText,
      border: '1px solid ' + (active ? 'transparent' : baseBorder),
      fontSize: 13, fontWeight: 500, fontFamily: 'inherit',
      cursor: 'pointer', transition: 'all 160ms var(--ease)',
      whiteSpace: 'nowrap',
    }}>
      {tone && <span style={{
        width: 8, height: 8, borderRadius: 999,
        background: active ? 'rgba(255,255,255,0.9)' : tone.tone.solid,
      }} />}
      {label}
      <span style={{
        fontSize: 11, fontWeight: 600,
        opacity: active ? 0.7 : 0.55,
        marginLeft: 2,
      }}>{count}</span>
    </button>
  );
};

// ---------- Category group ----------
const BhCategoryGroup = ({ cat, list, onOpen, forceOpen }) => {
  const [open, setOpen] = React.useState(!!forceOpen);
  React.useEffect(() => { if (forceOpen) setOpen(true); }, [forceOpen]);
  return (
    <div style={{ marginBottom: 28 }}>
      <button type="button" onClick={() => setOpen((o) => !o)}
        aria-expanded={open}
        style={{
          width: '100%', textAlign: 'left',
          display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap',
          padding: '14px 0 12px',
          background: 'transparent', border: 'none', cursor: 'pointer',
          borderBottom: '1px solid rgba(42,34,29,0.08)',
          fontFamily: 'inherit',
        }}>
        <span style={{
          fontSize: 11, fontWeight: 600, letterSpacing: '0.12em',
          textTransform: 'uppercase', color: cat.pill.text,
          background: cat.pill.bg,
          padding: '4px 10px', borderRadius: 999,
          border: '1px solid ' + cat.pill.border,
          flexShrink: 0,
        }}>{cat.eyebrow}</span>
        <h2 style={{
          fontFamily: 'Fraunces, serif', fontWeight: 400,
          fontSize: 'clamp(22px, 3vw, 32px)', lineHeight: 1.1,
          color: 'var(--ink)',
          fontVariationSettings: '"opsz" 96, "SOFT" 50',
          margin: 0,
        }}>{cat.title}</h2>
        <span style={{ fontSize: 13, color: 'var(--ink-50)', marginLeft: 'auto', flexShrink: 0 }}>
          {list.length} {list.length === 1 ? 'Behandlung' : 'Behandlungen'}
        </span>
        <span style={{
          width: 28, height: 28, borderRadius: 999,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          background: 'var(--offwhite)', border: '1px solid var(--sandstone)',
          fontSize: 11, color: 'var(--ink-70)',
          transform: open ? 'rotate(180deg)' : 'none',
          transition: 'transform 220ms var(--ease)',
          flexShrink: 0,
        }}>▼</span>
      </button>
      {open && (
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
          gap: 16,
          paddingTop: 20,
        }}>
          {list.map((b) => (
            <BhTreatmentTile key={b.id} item={b} onOpen={onOpen} />
          ))}
        </div>
      )}
    </div>
  );
};

// ---------- Tile ----------
const BhTreatmentTile = ({ item, onOpen }) => {
  const cat = bhCatById[item.cat];
  return (
    <button type="button" onClick={() => onOpen(item)}
      style={{
        textAlign: 'left',
        background: 'var(--offwhite)',
        border: '1px solid ' + cat.pill.border,
        borderTopWidth: 4, borderTopColor: cat.tone.solid,
        borderRadius: 14,
        padding: '20px 22px 22px',
        fontFamily: 'inherit',
        cursor: 'pointer',
        transition: 'all 200ms var(--ease)',
        boxShadow: '0 1px 3px rgba(42,34,29,0.04)',
        display: 'flex', flexDirection: 'column', gap: 10,
        minHeight: 220,
      }}
      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: 6,
        fontSize: 11, fontWeight: 600, letterSpacing: '0.1em',
        textTransform: 'uppercase',
        color: cat.pill.text,
        alignSelf: 'flex-start',
        background: cat.pill.bg,
        padding: '4px 10px', borderRadius: 999,
      }}>
        <span style={{ width: 6, height: 6, borderRadius: 999, background: cat.tone.solid }} />
        {cat.title}
      </span>

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

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

      <div style={{
        display: 'flex', flexDirection: 'column', gap: 4,
        fontSize: 12.5, color: 'var(--ink-70)',
        borderTop: '1px dashed rgba(42,34,29,0.12)',
        paddingTop: 10, marginTop: 4,
      }}>
        <span><strong style={{ color: 'var(--ink)', fontWeight: 600 }}>Mit:</strong> {item.leader}</span>
        <span><strong style={{ color: 'var(--ink)', fontWeight: 600 }}>Kontakt:</strong> {item.contact}</span>
      </div>

      <span style={{
        fontSize: 12, fontWeight: 600,
        color: cat.pill.text,
        marginTop: 4,
        display: 'inline-flex', alignItems: 'center', gap: 4,
      }}>Details ansehen →</span>
    </button>
  );
};

// ---------- Detail widget ----------
// Use the shared widget defined in behandlung-detail.jsx so the homepage tile
// and this page open the exact same modal.
const BhDetailWidget = (props) => {
  const Comp = window.WBBehandlungDetail;
  return Comp ? <Comp {...props} /> : null;
};

// ---------- Page ----------
const AllBehandlungenPage = () => {
  // Clear any leftover scroll lock — see all-courses.jsx for rationale.
  useEffectBh(() => {
    document.body.style.overflow = '';
  }, []);

  const [activeCat, setActiveCat] = useStateBh(() => {
    const m = (typeof location !== 'undefined' ? location.hash : '').match(/cat=([\w-]+)/);
    if (m && bhCats.some((c) => c.id === m[1])) return m[1];
    return 'all';
  });
  const [leader, setLeader] = useStateBh('all');
  const [query, setQuery] = useStateBh('');
  const [openItem, setOpenItem] = useStateBh(null);

  const filtered = useMemoBh(() => {
    const q = query.trim().toLowerCase();
    return bhItems.filter((b) => {
      if (activeCat !== 'all' && b.cat !== activeCat) return false;
      if (leader !== 'all' && !bhHasLeader(b, leader)) return false;
      if (q && !(b.title.toLowerCase().includes(q) || b.body.toLowerCase().includes(q) || b.leader.toLowerCase().includes(q))) return false;
      return true;
    });
  }, [activeCat, leader, query]);

  const grouped = useMemoBh(() => {
    const order = activeCat === 'all' ? bhCats : bhCats.filter((c) => c.id === activeCat);
    return order.map((c) => ({
      cat: c,
      list: filtered.filter((x) => x.cat === c.id),
    })).filter((g) => g.list.length > 0);
  }, [filtered, activeCat]);

  return (
    <>
      <header style={{
        position: 'sticky', top: 0, zIndex: 50,
        background: 'rgba(242, 228, 206, 0.85)',
        backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)',
        borderBottom: '1px solid rgba(196, 169, 143, 0.4)',
        padding: '18px 0',
      }}>
        <div className="container" style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <a href="Die%20Weiberei.html" aria-label="Die Weiberei — zur Startseite" style={{
            display: 'inline-flex', alignItems: 'center', height: 52,
          }}>
            <img src="assets/logo-weiberei.png" alt="Die Weiberei"
              style={{ height: 52, width: 'auto', display: 'block' }} />
          </a>
          <a href="Die%20Weiberei.html" style={{
            fontSize: 13, color: 'var(--ink-70)', textDecoration: 'none',
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>← Zur Startseite</a>
        </div>
      </header>

      <main>
        <section style={{ padding: 'clamp(48px, 7vw, 80px) 0 32px' }}>
          <div className="container" style={{ maxWidth: 720 }}>
            <span className="eyebrow" style={{ marginBottom: 14, display: 'inline-block' }}>● Alle Behandlungen</span>
            <h1 style={{
              fontSize: 'clamp(40px, 6vw, 64px)', lineHeight: 1.05, letterSpacing: '-0.02em',
              fontVariationSettings: '"opsz" 96, "SOFT" 50, "WONK" 1', marginTop: 12, marginBottom: 18,
            }}>
              Individuelle Begleitung, ganz nach <em className="bacalisties" style={{ color: 'var(--heather-plum)' }}>deinen Bedürfnissen</em>.
            </h1>
            <p className="lead">
              {bhItems.length} 1:1-Behandlungen und Sprechstunden — sortiert nach Lebensphase.
              Filter nach Kategorie oder Behandlerin. Klick auf eine Kachel für Details und Anfrage.
            </p>
          </div>
        </section>

        <BhFilterBar
          activeCat={activeCat} setActiveCat={setActiveCat}
          leader={leader} setLeader={setLeader}
          query={query} setQuery={setQuery}
          count={filtered.length}
        />

        <section style={{ padding: '32px 0 96px' }}>
          <div className="container">
            {grouped.length === 0 ? (
              <div style={{
                textAlign: 'center', padding: '80px 20px',
                color: 'var(--ink-70)',
              }}>
                <div style={{ fontSize: 32, marginBottom: 12, fontFamily: 'Fraunces, serif' }}>Nichts gefunden.</div>
                <p style={{ marginBottom: 20 }}>Versuche eine andere Kategorie oder Behandlerin.</p>
                <button type="button" className="btn btn-secondary"
                  onClick={() => { setActiveCat('all'); setLeader('all'); setQuery(''); }}>
                  Filter zurücksetzen
                </button>
              </div>
            ) : grouped.map(({ cat, list }) => (
              <BhCategoryGroup key={cat.id} cat={cat} list={list} onOpen={setOpenItem} forceOpen={activeCat !== 'all'} />
            ))}
          </div>
        </section>
      </main>

      <BhDetailWidget item={openItem} onClose={() => setOpenItem(null)} />
    </>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<AllBehandlungenPage />);
