// Aktuelles — full-bleed tile carousel
// -------------------------------------
// Backend-pflegbar: das `AKTUELLES_ITEMS`-Array unten wird später aus dem CMS
// geliefert. Items haben einen `kind`:
//   - 'flyer' → einzelnes Bild (Canva-Export, hoch oder quer)
//   - 'reel'  → Video-Reel (Canva → mp4); poster wird vor Play angezeigt
// Optional pro Item:
//   - eyebrow, title, body, cta {label, href}
// Layout: Track läuft full-bleed durch den Viewport, Kacheln scrollen
// horizontal vorbei. Jede Kachel ist eine eigenständige Karte mit fester
// Größe. Keine Hero-Slides, kein Crossfade — echtes Tile-Carousel.

// Backend-URL für Live-Daten. Wenn der Fetch fehlschlägt oder die DB leer ist,
// nutzen wir den Fallback unten — so bleibt die Seite immer mit Inhalten.
const WB_API_BASE = 'https://project-zd7wa.vercel.app';

const AKTUELLES_FALLBACK = [
  {
    id: 'sommer-kreis',
    kind: 'flyer',
    src: `https://picsum.photos/seed/${encodeURIComponent('weiberei-flyer-sommer')}/720/960`,
    eyebrow: 'NEUER KURS',
    title: 'Sommer-Frauenkreis',
    body: 'Sechs Abende ab 14. Juli. Anmeldung offen.',
    cta: { label: 'Plätze sichern', href: '#kursplan' },
  },
  {
    id: 'rueckbildung-reel',
    kind: 'reel',
    // Beispiel-Video; in Produktion durch Canva-Export-MP4 ersetzen.
    src: 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4',
    poster: `https://picsum.photos/seed/${encodeURIComponent('weiberei-reel-rueckbildung')}/720/960`,
    eyebrow: 'EINBLICK',
    title: 'So fühlt sich Rückbildung bei uns an',
    body: '90 Sekunden Studio-Atmosphäre.',
  },
  {
    id: 'workshop-papa',
    kind: 'flyer',
    src: `https://picsum.photos/seed/${encodeURIComponent('weiberei-flyer-papa')}/720/960`,
    eyebrow: 'WORKSHOP',
    title: 'Geburtsvorbereitung für Paare',
    body: 'Ein Samstag, ein Paar Stunden, ein gemeinsames Bild der Geburt.',
    cta: { label: 'Mehr erfahren', href: '#kursplan' },
  },
  {
    id: 'team-news',
    kind: 'flyer',
    src: `https://picsum.photos/seed/${encodeURIComponent('weiberei-flyer-team')}/720/960`,
    eyebrow: 'TEAM',
    title: 'Neu: Mira, Osteopathin',
    body: 'Termine ab Mitte August.',
    cta: { label: 'Behandlungen', href: '#behandlungen' },
  },
  {
    id: 'reel-frauenkreis',
    kind: 'reel',
    src: 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4',
    poster: `https://picsum.photos/seed/${encodeURIComponent('weiberei-reel-frauenkreis')}/720/960`,
    eyebrow: 'REEL',
    title: 'Frauenkreis: ein Abend',
    body: 'Teaser zum monatlichen Kreis.',
  },
  {
    id: 'flyer-yoga',
    kind: 'flyer',
    src: `https://picsum.photos/seed/${encodeURIComponent('weiberei-flyer-yoga')}/720/960`,
    eyebrow: 'NEU IM KURSPLAN',
    title: 'Schwangerenyoga, Donnerstag',
    body: 'Acht Termine, kleine Gruppe.',
    cta: { label: 'Zum Kursplan', href: '#kursplan' },
  },
];

const Aktuelles = () => {
  const headRef = (typeof useReveal === 'function') ? useReveal() : { current: null };
  const trackRef = React.useRef(null);
  const videoRefs = React.useRef({});
  const [canPrev, setCanPrev] = React.useState(false);
  const [canNext, setCanNext] = React.useState(true);
  // Items: erst Fallback, dann ggf. von API überschrieben
  const [items, setItems] = React.useState(AKTUELLES_FALLBACK);

  React.useEffect(() => {
    let active = true;
    fetch(WB_API_BASE + '/api/public/aktuelles')
      .then((r) => r.ok ? r.json() : Promise.reject(new Error('fetch failed')))
      .then((data) => {
        if (!active) return;
        if (Array.isArray(data.items) && data.items.length > 0) {
          setItems(data.items);
        }
      })
      .catch(() => { /* Fallback bleibt aktiv */ });
    return () => { active = false; };
  }, []);

  useDragScroll(trackRef);

  const updateEdges = React.useCallback(() => {
    const el = trackRef.current;
    if (!el) return;
    const { scrollLeft, scrollWidth, clientWidth } = el;
    setCanPrev(scrollLeft > 4);
    setCanNext(scrollLeft + clientWidth < scrollWidth - 4);
  }, []);

  React.useEffect(() => {
    const el = trackRef.current;
    if (!el) return undefined;
    updateEdges();
    el.addEventListener('scroll', updateEdges, { passive: true });
    window.addEventListener('resize', updateEdges);
    return () => {
      el.removeEventListener('scroll', updateEdges);
      window.removeEventListener('resize', updateEdges);
    };
  }, [updateEdges]);

  const scrollByCards = (dir) => {
    const el = trackRef.current;
    if (!el) return;
    // Scroll by ~80% of viewport so users always see one familiar card on the next page
    const amount = Math.max(320, el.clientWidth * 0.8) * dir;
    el.scrollBy({ left: amount, behavior: 'smooth' });
  };

  return (
    <section
      id="aktuelles"
      style={{
        padding: 'clamp(56px, 8vw, 96px) 0 clamp(72px, 10vw, 112px)',
        position: 'relative',
        zIndex: 1,
      }}>
      {/* Section header — sits inside container width */}
      <div className="container" style={{ marginBottom: 'clamp(28px, 4vw, 48px)' }}>
        <div ref={headRef} className="reveal" style={{
          display: 'flex',
          gap: 32,
          alignItems: 'flex-end',
          justifyContent: 'space-between',
          flexWrap: 'wrap',
        }}>
          <div style={{ maxWidth: 640 }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>AKTUELLES</div>
            <h2 style={{
              fontSize: 'clamp(32px, 4.5vw, 48px)',
              lineHeight: 1.1,
              letterSpacing: '-0.015em',
              marginBottom: 16,
            }}>
              Was gerade in der<br />Weiberei passiert.
            </h2>
            <p className="lead" style={{ maxWidth: 520 }}>
              Neue Kurse, kleine Filme, Plakate. Alles auf einen Blick.
            </p>
          </div>
        </div>
      </div>

      {/* Container-bound scroll track — cards stay within page container width */}
      <div className="container" style={{ position: 'relative' }}>
          {/* Side arrows — same pattern as the other tile carousels */}
          <SideArrow direction="prev" disabled={!canPrev} onClick={() => scrollByCards(-1)} />
          <SideArrow direction="next" disabled={!canNext} onClick={() => scrollByCards(1)} />

        <div
          ref={trackRef}
          className="aktuelles-track"
          style={{
            display: 'flex',
            gap: 'clamp(16px, 1.6vw, 24px)',
            overflowX: 'auto',
            overflowY: 'hidden',
            // Proximity (not mandatory) — track scrolls freely and only snaps
            // softly near a card edge. Combined with smooth-scroll on arrow
            // clicks this reads as one continuous glide, not discrete jumps.
            scrollSnapType: 'x proximity',
            // (No CSS scrollBehavior:smooth — that would lag drag-scrolling.
            // Smooth scroll on arrow clicks is opt-in via scrollBy({behavior:'smooth'}).)
            paddingBottom: 12,
            scrollbarWidth: 'none',
            msOverflowStyle: 'none',
            WebkitOverflowScrolling: 'touch',
            // Prevent browser default text/image selection while dragging
            userSelect: 'none',
            WebkitUserSelect: 'none',
            // Allow horizontal pan (touch-swipe) AND vertical page scroll
            touchAction: 'pan-x pan-y',
          }}>
          {items.map((item) => (
            <AktuellesTile
              key={item.id}
              item={item}
              videoRefs={videoRefs}
            />
          ))}
        </div>

        {/* Right-edge fade hint */}
        <div aria-hidden="true" style={{
          position: 'absolute',
          top: 0, bottom: 12, right: 0,
          width: 80,
          background: 'linear-gradient(to left, rgba(252,248,242,0.85), rgba(252,248,242,0))',
          pointerEvents: 'none',
          opacity: canNext ? 1 : 0,
          transition: 'opacity 240ms var(--ease, ease)',
          borderTopRightRadius: 14,
          borderBottomRightRadius: 14,
        }} />
        <div aria-hidden="true" style={{
          position: 'absolute',
          top: 0, bottom: 12, left: 0,
          width: 80,
          background: 'linear-gradient(to right, rgba(252,248,242,0.85), rgba(252,248,242,0))',
          pointerEvents: 'none',
          opacity: canPrev ? 1 : 0,
          transition: 'opacity 240ms var(--ease, ease)',
          borderTopLeftRadius: 14,
          borderBottomLeftRadius: 14,
        }} />
      </div>

      <style>{`
        .aktuelles-track::-webkit-scrollbar { display: none; }
      `}</style>
    </section>
  );
};

const AktuellesTile = ({ item, videoRefs }) => {
  const [playing, setPlaying] = React.useState(false);

  const togglePlay = (e) => {
    e.preventDefault();
    const v = videoRefs.current[item.id];
    if (!v) return;
    if (v.paused) {
      v.play();
      setPlaying(true);
    } else {
      v.pause();
      setPlaying(false);
    }
  };

  return (
    <article
      style={{
        flex: '0 0 auto',
        width: 'clamp(260px, 28vw, 340px)',
        scrollSnapAlign: 'start',
        background: 'var(--paper, #fcf8f2)',
        border: '1px solid rgba(196, 169, 143, 0.55)',
        borderRadius: 14,
        overflow: 'hidden',
        boxShadow: '0 16px 36px rgba(42,34,29,0.12)',
        display: 'flex',
        flexDirection: 'column',
      }}>
      {/* Media — 3:4 portrait, matches Canva flyer/reel ratio */}
      <div style={{
        position: 'relative',
        aspectRatio: '3 / 4',
        background: 'var(--sage-tint, #e9efe6)',
        overflow: 'hidden',
      }}>
        {item.kind === 'reel' ? (
          <>
            <video
              ref={(el) => { videoRefs.current[item.id] = el; }}
              src={item.src}
              poster={item.poster}
              playsInline
              muted
              loop
              draggable="false"
              preload="none"
              onPlay={() => setPlaying(true)}
              onPause={() => setPlaying(false)}
              style={{
                position: 'absolute', inset: 0,
                width: '100%', height: '100%',
                objectFit: 'cover',
              }}
            />
            <button
              type="button"
              onClick={togglePlay}
              aria-label={playing ? 'Pause' : 'Abspielen'}
              style={{
                position: 'absolute',
                inset: 0,
                width: '100%', height: '100%',
                background: 'transparent',
                border: 'none',
                cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                padding: 0,
              }}>
              <span style={{
                width: 64, height: 64, borderRadius: '50%',
                background: 'rgba(252, 248, 242, 0.95)',
                border: '1px solid rgba(42,34,29,0.12)',
                boxShadow: '0 14px 28px rgba(42,34,29,0.28)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: 'var(--ink, #2a221d)',
                opacity: playing ? 0 : 1,
                transition: 'opacity 220ms var(--ease, ease)',
              }}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                  <path d="M8 5v14l11-7z" />
                </svg>
              </span>
            </button>
            <span style={{
              position: 'absolute',
              top: 12, left: 12,
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '4px 10px',
              borderRadius: 999,
              background: 'rgba(252, 248, 242, 0.92)',
              border: '1px solid rgba(196, 169, 143, 0.55)',
              fontSize: 11,
              letterSpacing: '0.06em',
              color: 'var(--heather-plum, #7d5a6e)',
              fontWeight: 600,
            }}>
              <span style={{
                width: 6, height: 6, borderRadius: '50%',
                background: 'var(--heather-plum, #7d5a6e)',
              }} />
              REEL
            </span>
          </>
        ) : (
          <>
            <img
              src={item.src}
              alt={item.title || ''}
              loading="lazy"
              draggable="false"
              style={{
                position: 'absolute', inset: 0,
                width: '100%', height: '100%',
                objectFit: 'cover',
              }}
            />
            <span style={{
              position: 'absolute',
              top: 12, left: 12,
              padding: '4px 10px',
              borderRadius: 999,
              background: 'rgba(252, 248, 242, 0.92)',
              border: '1px solid rgba(196, 169, 143, 0.55)',
              fontSize: 11,
              letterSpacing: '0.06em',
              color: 'var(--ink, #2a221d)',
              fontWeight: 600,
            }}>
              FLYER
            </span>
          </>
        )}
      </div>

      {/* Caption */}
      <div style={{
        padding: '20px 22px 22px',
        display: 'flex',
        flexDirection: 'column',
        gap: 8,
        flex: 1,
      }}>
        {item.eyebrow && (
          <div className="eyebrow" style={{ fontSize: 11 }}>{item.eyebrow}</div>
        )}
        {item.title && (
          <h3 style={{
            fontSize: 'clamp(18px, 1.6vw, 22px)',
            lineHeight: 1.2,
            letterSpacing: '-0.005em',
            margin: 0,
          }}>
            {item.title}
          </h3>
        )}
        {item.body && (
          <p style={{
            fontSize: 14,
            lineHeight: 1.5,
            color: 'var(--ink-soft, #5b504a)',
            margin: 0,
          }}>
            {item.body}
          </p>
        )}
        {item.cta && (
          <a
            href={item.cta.href}
            style={{
              marginTop: 'auto',
              paddingTop: 12,
              fontSize: 14,
              fontWeight: 600,
              color: 'var(--heather-plum, #7d5a6e)',
              textDecoration: 'none',
              alignSelf: 'flex-start',
              display: 'inline-flex',
              alignItems: 'center',
              gap: 6,
            }}>
            {item.cta.label} <span aria-hidden="true">→</span>
          </a>
        )}
      </div>
    </article>
  );
};

const SideArrow = ({ direction, onClick, disabled }) => {
  const isPrev = direction === 'prev';
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled}
      aria-label={isPrev ? 'Zurück' : 'Weiter'}
      style={{
        position: 'absolute',
        top: '50%',
        [isPrev ? 'left' : 'right']: 'clamp(12px, 2vw, 28px)',
        transform: 'translateY(-50%)',
        zIndex: 5,
        width: 48, height: 48,
        borderRadius: 999,
        background: 'rgba(250, 246, 241, 0.9)',
        backdropFilter: 'blur(8px)',
        WebkitBackdropFilter: 'blur(8px)',
        border: '1px solid rgba(196, 169, 143, 0.5)',
        color: 'var(--ink, #2a221d)',
        boxShadow: '0 8px 18px rgba(42,34,29,0.12)',
        cursor: disabled ? 'default' : 'pointer',
        opacity: disabled ? 0.35 : 1,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        transition: 'all 160ms var(--ease, ease)',
      }}
      onMouseEnter={(e) => {
        if (disabled) return;
        e.currentTarget.style.background = 'var(--heather-plum, #7d5a6e)';
        e.currentTarget.style.color = 'var(--offwhite, #fcf8f2)';
        e.currentTarget.style.borderColor = 'var(--heather-plum, #7d5a6e)';
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.background = 'rgba(250, 246, 241, 0.9)';
        e.currentTarget.style.color = 'var(--ink, #2a221d)';
        e.currentTarget.style.borderColor = 'rgba(196, 169, 143, 0.5)';
      }}>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        {isPrev
          ? <polyline points="15 18 9 12 15 6" />
          : <polyline points="9 18 15 12 9 6" />}
      </svg>
    </button>
  );
};

const TileArrow = null; // deprecated — replaced by SideArrow

Object.assign(window, { Aktuelles });
