// Maison 57 — shared kit pieces: pinned horizontal type gallery + parallax full-bleed.
const {
  ImageCard: GImageCard, LineMask: GLineMask, Reveal: GReveal,
} = window.Maison57DesignSystem_40d525;

const REDUCE = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const MOBILE = () => window.matchMedia('(max-width: 760px)').matches;

/* Attach a handler to the page scroller; returns cleanup. */
function onPageScroll(fn) {
  const sc = window.__m57Scroller;
  if (!sc) return () => {};
  sc.addEventListener('scroll', fn, { passive: true });
  fn({ target: sc });
  return () => sc.removeEventListener('scroll', fn);
}

/**
 * FullBleed — full-width image section with subtle parallax (image moves
 * ~8% slower than the scroll) and a mask-revealed statement bottom-left.
 * The only place besides the hero where text may sit on an image.
 */
function FullBleed({ img, alt = '', height = '72vh', children, link }) {
  const ref = React.useRef(null);
  const imgRef = React.useRef(null);
  React.useEffect(() => {
    if (REDUCE()) return;
    return onPageScroll(() => {
      const el = ref.current, im = imgRef.current;
      if (!el || !im) return;
      const r = el.getBoundingClientRect();
      const vh = window.innerHeight || 800;
      if (r.bottom < 0 || r.top > vh) return;
      const center = r.top + r.height / 2 - vh / 2;
      im.style.transform = `translateY(${(-center * 0.08).toFixed(1)}px)`;
    });
  }, []);
  return (
    <section ref={ref} style={{ position: 'relative', height, overflow: 'hidden' }}>
      <img ref={imgRef} src={img} alt={alt}
        style={{ position: 'absolute', left: 0, top: '-8%', width: '100%', height: '116%', objectFit: 'cover', willChange: 'transform' }} />
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(24,30,24,0.55) 0%, rgba(24,30,24,0) 45%)' }}></div>
      <div className="m57-loc" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 'var(--space-8)', maxWidth: 'var(--content-max)', margin: '0 auto', padding: '0 var(--page-inset-lg) clamp(2.5rem, 5vw, 4rem)' }}>
        <div>{children}</div>
        {link && <div style={{ flex: 'none', paddingBottom: '0.4rem' }}>{link}</div>}
      </div>
    </section>
  );
}

/**
 * TypeGallery — the borderless horizontal gallery of the three apartment
 * types. Desktop: the section pins (position sticky) and vertical scroll
 * translates into horizontal glide. Mobile / reduced motion: native
 * horizontal scroll with snap. Below: counter + plain text arrows, left.
 */
function TypeGallery({ items, word = 'Wohnungen', intro, onOpen }) {
  const outer = React.useRef(null);
  const track = React.useRef(null);
  const [idx, setIdx] = React.useState(0);
  const [pin, setPin] = React.useState(false);

  React.useEffect(() => { setPin(!MOBILE() && !REDUCE()); }, []);

  React.useEffect(() => {
    if (!pin) return;
    return onPageScroll(() => {
      const o = outer.current, t = track.current;
      if (!o || !t) return;
      const vh = window.innerHeight || 800;
      const r = o.getBoundingClientRect();
      const range = r.height - vh;
      const p = Math.min(1, Math.max(0, -r.top / (range || 1)));
      const max = t.scrollWidth - t.parentElement.clientWidth;
      t.style.transform = `translateX(${(-p * max).toFixed(1)}px)`;
      t.style.setProperty('--gp', p.toFixed(3));
      setIdx(Math.min(items.length - 1, Math.round(p * (items.length - 1))));
    });
  }, [pin]);

  const arrow = (dir) => () => {
    if (pin) {
      const sc = window.__m57Scroller, o = outer.current;
      if (!sc || !o) return;
      const vh = window.innerHeight || 800;
      const step = (o.offsetHeight - vh) / (items.length - 1);
      sc.scrollBy({ top: dir * step, behavior: 'smooth' });
    } else if (track.current) {
      track.current.scrollBy({ left: dir * 340, behavior: 'smooth' });
    }
  };

  const cardW = 'clamp(230px, 23vw, 340px)';
  const inner = (
    <div style={{ paddingLeft: 'max(clamp(2rem, 6vw, 6rem), calc((100vw - 80rem) / 2 + 3rem))' }}>
      {intro}
      <div
        ref={track}
        className="m57-track"
        style={pin
          ? { display: 'flex', gap: 'clamp(1.25rem, 2.5vw, 2rem)', willChange: 'transform', width: 'max-content', paddingRight: '10vw' }
          : { display: 'flex', gap: '1.25rem', overflowX: 'auto', scrollSnapType: 'x mandatory', WebkitOverflowScrolling: 'touch', paddingRight: 'var(--page-inset-lg)', scrollbarWidth: 'none' }}
      >
        {items.map((it, j) => (
          <div key={it.label} style={{ width: cardW, flex: 'none', scrollSnapAlign: 'start',
            transform: pin ? `translateY(calc((1 - var(--gp, 0)) * ${j * 12}px))` : undefined,
            transition: 'transform 200ms linear' }}>
            <GImageCard image={it.img} label={it.label} meta={it.meta} sentence={it.sentence} ratio="4 / 5" onClick={(e) => { e.preventDefault(); if (onOpen) onOpen(it, j); }} />
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-6)', marginTop: 'clamp(1.5rem, 3vw, 2.5rem)' }}>
        <span className="tabular" style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-label)', color: 'var(--umbra-60)', fontVariantNumeric: 'tabular-nums' }}>
          0{idx + 1} / 0{items.length}
        </span>
        <button type="button" onClick={arrow(-1)} aria-label="Zurück" style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font-text)', fontSize: '1rem', color: 'var(--umbra)', padding: '0 0.25rem' }}>←</button>
        <button type="button" onClick={arrow(1)} aria-label="Weiter" style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font-text)', fontSize: '1rem', color: 'var(--umbra)', padding: '0 0.25rem' }}>→</button>
      </div>
    </div>
  );

  if (!pin) {
    return <section style={{ padding: '0 0 clamp(6rem, 11vw, 10rem)' }}><style>{`.m57-track::-webkit-scrollbar{display:none}`}</style>{inner}</section>;
  }
  return (
    <section ref={outer} style={{ height: '180vh', position: 'relative' }}>
      <div style={{ position: 'sticky', top: 0, height: '100vh', overflow: 'hidden', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
        {inner}
      </div>
    </section>
  );
}

/* TypeGrid — Kategorie-Karten nach fester Hierarchie (v4 §9): Bild, Serifen-
   Headline, ein bis zwei Zeilen Gefühl, Highlight-Zeile aus ultraleichten
   Linien-Icons mit Label, Button "Zum Wohnungsfinder" (Deep-Link, gefiltert). */
function TypeGrid({ items, intro, onOpen }) {
  const Rev = window.Maison57DesignSystem_40d525.Reveal;
  const Button = window.Maison57DesignSystem_40d525.Button;
  const LineIcon = window.LineIcon;
  return (
    <section style={{ maxWidth: 'var(--content-max)', margin: '0 auto', padding: '0 var(--page-inset-lg)' }}>
      {intro}
      <div className="m57-typegrid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 'clamp(2rem, 4.5vw, 4rem)' }}>
        {items.map((it, j) => (
          <Rev key={it.label} delay={j * 110}>
            <div className="m57-typecard" style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
              <div className="m57-typecard-img" style={{ aspectRatio: '4 / 5', overflow: 'hidden' }}>
                <img src={it.img} alt={it.label} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              </div>
              <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'clamp(1.5rem, 2vw, 1.75rem)', lineHeight: 1.1, letterSpacing: '-0.015em', color: 'var(--umbra)', borderTop: '1px solid var(--umbra)', marginTop: 'var(--space-5)', paddingTop: 'var(--space-4)', marginBottom: 'var(--space-2)' }}>{it.label}</h3>
              {it.sentence && <p style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', lineHeight: 1.6, color: 'var(--umbra-90)', margin: '0 0 var(--space-5)', maxWidth: '40ch' }}>{it.sentence}</p>}
              {it.highlights && (
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 'var(--space-4)', borderTop: '1px solid var(--sandstein)', paddingTop: 'var(--space-4)', marginTop: 'auto' }}>
                  {it.highlights.map((h) => (
                    <div key={h.label} style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: '0.45rem', color: 'var(--umbra)' }}>
                      {LineIcon ? <LineIcon name={h.icon} size={22} /> : null}
                      <span className="tabular" style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-micro)', color: 'var(--umbra-60)', fontVariantNumeric: 'tabular-nums', lineHeight: 1.3 }}>{h.label}</span>
                    </div>
                  ))}
                </div>
              )}
              <div style={{ marginTop: 'var(--space-5)' }}>
                <Button variant="outline" onClick={(e) => { e.preventDefault(); if (onOpen) onOpen(it, j); }}>Zum Wohnungsfinder</Button>
              </div>
            </div>
          </Rev>
        ))}
      </div>
      <style>{`
        .m57-typecard-img img { transition: transform 700ms var(--ease-reveal); }
        .m57-typecard:hover .m57-typecard-img img { transform: scale(1.04); }
      `}</style>
    </section>
  );
}

Object.assign(window, { FullBleed, TypeGallery, TypeGrid, onPageScroll });
