// Die Weiber — Kartendeck (gestapelt, swipebar)
// Inspired by Penteract: Active card in front, siblings rotate + scale + fade behind.
// Drag-swipe + Prev/Next + Keyboard arrows. Each Kursleiterin has her own card.

const { useState, useEffect, useRef, useCallback } = React;

// Backend-URL für Live-Daten — Profile pflegen sich Dina/Franzi selbst via
// /mein-profil. Wenn der Fetch fehlschlägt oder leer ist, nutzen wir Fallback.
const WB_API_BASE = 'https://project-zd7wa.vercel.app';

// Rotation für Karten-Hintergrundton, falls Backend kein Tone-Feld liefert.
const TONE_CYCLE = ['rose', 'sage', 'sandstone', 'heather'];

const WEIBER_FALLBACK = [
  {
    name: 'Franziska Helmbrecht',
    role: 'Hebamme · Gründerin',
    image: 'assets/franzi.png',
    tone: 'rose',
    tags: ['Hebamme', 'Geburtsvorbereitung', 'Wochenbett'],
    bio: 'Hebamme aus Leidenschaft. Begleitet Frauen vor, während und nach der Geburt — mit ruhiger Hand, klarer Sprache und ohne Schnörkel.',
    courses: ['Geburtsvorbereitung', 'Hebammensprechstunde', 'Wochenbettbetreuung'],
  },
  {
    name: 'Dina Stöcker',
    role: 'Sportwissenschaftlerin · Gründerin',
    image: 'assets/dina.png',
    tone: 'sage',
    tags: ['Rückbildung', 'Tupler®', 'Yoga'],
    bio: 'Sportwissenschaftlerin mit Fokus auf den weiblichen Körper nach der Geburt. Tupler®-zertifiziert, Yoga-Trainerin, Coaching für Mamas, die wieder ankommen wollen.',
    courses: ['Rückbildung Tupler®', 'Mama-Yoga', 'Coaching'],
  },
  {
    name: 'N.N.',
    role: 'Yogalehrerin',
    image: null,
    tone: 'sandstone',
    tags: ['Schwangeren-Yoga', 'Hatha', 'Yin'],
    bio: 'Bald hier — wir suchen die richtige Yogalehrerin für unsere Räume.',
    courses: ['Schwangeren-Yoga', 'Mama & Baby Yoga'],
  },
  {
    name: 'N.N.',
    role: 'Doula',
    image: null,
    tone: 'heather',
    tags: ['Geburtsbegleitung', 'Doula'],
    bio: 'Bald hier — eine Doula, die Geburten begleitet, ohne medizinische Rolle.',
    courses: ['Doula-Begleitung', 'Geburtsgespräch'],
  },
  {
    name: 'N.N.',
    role: 'Stillberaterin',
    image: null,
    tone: 'rose',
    tags: ['Stillen', 'IBCLC'],
    bio: 'Bald hier — Stillberatung für die ersten Wochen und alles, was danach kommt.',
    courses: ['Stillberatung', 'Beikost-Workshop'],
  },
];

const TONE_BG = {
  rose:      'var(--rose-tint)',
  sage:      'var(--sage-tint)',
  sandstone: 'var(--sandstone)',
  heather:   'var(--heather-subtle)',
};

const DieWeiber = () => {
  const ref = useReveal();
  const [active, setActive] = useState(0);
  const [drag, setDrag] = useState(0); // -1..1 normalized horizontal drag
  const dragRef = useRef({ startX: 0, active: false, width: 1 });

  // Weiber: erst Fallback, dann ggf. von API überschrieben
  const [weiber, setWeiber] = useState(WEIBER_FALLBACK);

  useEffect(() => {
    let stillMounted = true;
    fetch(WB_API_BASE + '/api/public/weiber')
      .then((r) => r.ok ? r.json() : Promise.reject(new Error('fetch failed')))
      .then((data) => {
        if (!stillMounted) return;
        if (Array.isArray(data.items) && data.items.length > 0) {
          // Backend liefert {id, name, role, image, bio, tags}.
          // Wir reichern um tone an (Rotation) und courses (leer — Backend hat
          // die Daten nicht in dieser Form; bleibt unsichtbar wenn leer).
          const mapped = data.items.map((w, i) => ({
            name: w.name,
            role: w.role,
            image: w.image,
            bio: w.bio,
            tags: Array.isArray(w.tags) ? w.tags.slice(0, 3) : [],
            courses: [],
            tone: TONE_CYCLE[i % TONE_CYCLE.length],
          }));
          setWeiber(mapped);
          setActive(0);
        }
      })
      .catch(() => { /* Fallback bleibt aktiv */ });
    return () => { stillMounted = false; };
  }, []);

  const total = weiber.length;

  // Mobile (≤720px): stack photo on top of text instead of side-by-side.
  const [isMobile, setIsMobile] = useState(() =>
    typeof window !== 'undefined' && window.matchMedia
      ? window.matchMedia('(max-width: 720px)').matches
      : false
  );
  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);
    };
  }, []);

  const next = useCallback(() => setActive(a => (a + 1) % total), [total]);
  const prev = useCallback(() => setActive(a => (a - 1 + total) % total), [total]);

  // Keyboard
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'ArrowRight') next();
      else if (e.key === 'ArrowLeft') prev();
    };
    // Only react when section is in viewport (light heuristic — listen always but it's fine)
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [next, prev]);

  // Pointer drag handlers
  const onPointerDown = (e) => {
    dragRef.current.active = true;
    dragRef.current.startX = e.clientX;
    dragRef.current.width = e.currentTarget.offsetWidth || 1;
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const onPointerMove = (e) => {
    if (!dragRef.current.active) return;
    const dx = e.clientX - dragRef.current.startX;
    const norm = Math.max(-1, Math.min(1, dx / (dragRef.current.width * 0.4)));
    setDrag(norm);
  };
  const onPointerUp = (e) => {
    if (!dragRef.current.active) return;
    dragRef.current.active = false;
    if (drag > 0.25) prev();
    else if (drag < -0.25) next();
    setDrag(0);
    try { e.currentTarget.releasePointerCapture(e.pointerId); } catch (_) {}
  };

  return (
    <section id="weiber" style={{ padding: 'clamp(56px, 8vw, 96px) 0 clamp(80px, 12vw, 128px)' }}>
      <div className="container">
        <div ref={ref} className="reveal" style={{ marginBottom: 32 }}>
          <div style={{ maxWidth: 640, marginBottom: 32 }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>Die Weiber</div>
            <h2 style={{ fontSize: 'clamp(36px, 5vw, 56px)', lineHeight: 1.1, letterSpacing: '-0.015em' }}>
              Die Frauen, die{' '}
              <em className="bacalisties" style={{ color: 'var(--heather-plum)' }}>halten</em>.
            </h2>
            <p className="lead" style={{ marginTop: 16 }}>
              Hebammen, Sportwissenschaftlerinnen, Yogalehrerinnen, Doulas, Beraterinnen — alle, die bei uns Kurse geben und Frauen begleiten.
            </p>
          </div>
        </div>

        {/* Deck Stage */}
        <div
          onPointerDown={onPointerDown}
          onPointerMove={onPointerMove}
          onPointerUp={onPointerUp}
          onPointerCancel={onPointerUp}
          style={{
            position: 'relative',
            height: isMobile ? 620 : 540,
            touchAction: 'pan-y',
            cursor: dragRef.current.active ? 'grabbing' : 'grab',
            userSelect: 'none',
          }}
        >
          {weiber.map((m, i) => {
            // Compute relative offset to active, with wrap-around (shortest direction)
            let offset = i - active;
            if (offset > total / 2) offset -= total;
            if (offset < -total / 2) offset += total;
            return (
              <DeckCard
                key={i}
                member={m}
                offset={offset}
                drag={offset === 0 ? drag : 0}
                isMobile={isMobile}
                onClick={() => { if (offset !== 0) setActive(i); }}
              />
            );
          })}
        </div>

        {/* Nav controls — under the deck */}
        <div style={{
          marginTop: 32,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16,
        }}>
          <button onClick={prev} aria-label="Vorherige" style={navBtn}>
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M12.5 4L6.5 10L12.5 16" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
          <span style={{
            fontFamily: 'Fraunces, serif', fontSize: 18,
            color: 'var(--ink-70)', minWidth: 72, textAlign: 'center',
            fontVariantNumeric: 'tabular-nums',
          }}>
            {String(active + 1).padStart(2, '0')} / {String(total).padStart(2, '0')}
          </span>
          <button onClick={next} aria-label="Nächste" style={navBtn}>
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M7.5 4L13.5 10L7.5 16" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
        </div>

        {/* Hint */}
        <div style={{
          marginTop: 16, textAlign: 'center',
          color: 'var(--ink-50)', fontSize: 13, letterSpacing: '0.06em', textTransform: 'uppercase',
          fontWeight: 600,
        }}>
          ← Ziehen oder Pfeiltasten →
        </div>
      </div>
    </section>
  );
};

const navBtn = {
  width: 44, height: 44, borderRadius: 999,
  border: '1.5px solid var(--sandstone-border)',
  background: 'transparent', color: 'var(--ink)',
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
  cursor: 'pointer',
  transition: 'background 180ms var(--ease), border-color 180ms var(--ease), transform 180ms var(--ease)',
};

const DeckCard = ({ member, offset, drag, onClick, isMobile }) => {
  const isActive = offset === 0;
  // Stack visualization: each step further away = smaller, more rotated, more transparent
  const stackStep = 56;        // px translate per step (sideways)
  const stackDepth = 14;       // px translate forward (down) per step
  const rotateStep = 4;        // deg
  const scaleStep = 0.06;
  const dragShift = drag * 80; // px when dragging the active card

  const abs = Math.abs(offset);
  const sign = Math.sign(offset);
  const visible = abs <= 2; // only render up to 2 cards on each side

  const transform = `
    translate3d(calc(-50% + ${sign * stackStep * abs + (isActive ? dragShift : 0)}px), ${stackDepth * abs}px, 0)
    rotate(${sign * rotateStep * abs - (isActive ? drag * 4 : 0)}deg)
    scale(${1 - scaleStep * abs})
  `;

  return (
    <article
      onClick={onClick}
      style={{
        position: 'absolute',
        top: 0, left: '50%',
        width: 'min(560px, 88%)',
        height: isMobile ? 600 : 500,
        transform,
        transformOrigin: 'center bottom',
        transition: 'transform 520ms cubic-bezier(0.2, 0.8, 0.2, 1), opacity 420ms var(--ease)',
        opacity: visible ? (isActive ? 1 : 1 - abs * 0.18) : 0,
        zIndex: 10 - abs,
        pointerEvents: visible ? 'auto' : 'none',
        cursor: isActive ? 'grab' : 'pointer',
        background: 'var(--offwhite)',
        border: '1px solid var(--sandstone)',
        borderRadius: 18,
        boxShadow: isActive
          ? '0 24px 64px rgba(42,34,29,0.18), 0 4px 12px rgba(42,34,29,0.08)'
          : '0 8px 24px rgba(42,34,29,0.10)',
        overflow: 'hidden',
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1fr 1.1fr',
        gridTemplateRows: isMobile ? '260px 1fr' : 'auto',
      }}
    >
      {/* Image / Portrait */}
      <div style={{
        background: TONE_BG[member.tone] || 'var(--sandstone)',
        position: 'relative',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        overflow: 'hidden',
      }}>
        {member.image ? (
          <img
            src={member.image}
            alt={member.name}
            draggable={false}
            style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center top', display: 'block' }}
          />
        ) : (
          <span style={{
            fontFamily: 'Fraunces, serif', fontSize: 96,
            color: 'var(--ink)', opacity: 0.25,
            fontVariationSettings: '"opsz" 144, "SOFT" 60, "WONK" 1',
          }}>
            {member.name.split(' ').map(p => p[0]).slice(0, 2).join('')}
          </span>
        )}
      </div>

      {/* Body */}
      <div style={{
        padding: isMobile ? '22px 22px 24px' : '36px 32px',
        display: 'flex', flexDirection: 'column',
        minHeight: 0,
        overflow: 'hidden',
      }}>
        <div className="eyebrow" style={{ color: 'var(--heather-plum)', marginBottom: 10 }}>
          {member.role}
        </div>
        <h3 style={{
          fontFamily: 'Fraunces, serif', fontSize: isMobile ? 24 : 30, fontWeight: 500,
          lineHeight: 1.15, marginBottom: 12, letterSpacing: '-0.01em',
        }}>
          {member.name}
        </h3>
        <p style={{ color: 'var(--ink-70)', fontSize: isMobile ? 14 : 15.5, lineHeight: 1.55, marginBottom: 16 }}>
          {member.bio}
        </p>

        <div style={{ marginTop: 'auto' }}>
          <div style={{
            fontSize: 11, fontWeight: 600, letterSpacing: '0.12em',
            textTransform: 'uppercase', color: 'var(--ink-50)', marginBottom: 10,
          }}>
            Kurse & Angebote
          </div>
          <ul style={{
            listStyle: 'none', padding: 0, margin: 0,
            display: 'flex', flexWrap: 'wrap', gap: 6,
          }}>
            {member.courses.map(c => (
              <li key={c} style={{
                background: 'var(--canvas)',
                border: '1px solid var(--sandstone)',
                borderRadius: 999, padding: '6px 12px',
                fontSize: 12.5, color: 'var(--ink-70)', fontWeight: 500,
              }}>{c}</li>
            ))}
          </ul>
        </div>
      </div>
    </article>
  );
};

Object.assign(window, { DieWeiber });
