// Maison 57 — v4 Module: Stat-Mosaik (6.1), Prozess (6.3), FAQ (6.2),
// "Das Haus lesen" Geschoss-Erklärgrafik (4.1).
const {
  Reveal: MReveal, LineMask: MLineMask, TextLink: MTextLink, CountUp: MCountUp,
} = window.Maison57DesignSystem_40d525;
const MIMG = '/assets/renderings/';

/* 6.1 · Stat-Mosaik — sechs Grid-Zellen, Hairline-getrennt: vier Zahl-Zellen
   (Zahl beweist, Satz erklärt), eine Bildzelle, eine gefüllte Waldgrün-Zelle
   mit Satz + Textlink. Dichteste Sektion der Seite. */
function StatMosaik({ onAusstattung }) {
  const cellBase = { padding: 'clamp(1.75rem, 3vw, 2.75rem)', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', minHeight: 'clamp(150px, 20vw, 210px)', borderTop: '1px solid var(--sandstein)', borderLeft: '1px solid var(--sandstein)' };
  const num = { fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'clamp(2.25rem, 3.6vw, 3.25rem)', lineHeight: 1, color: 'var(--umbra)' };
  const cap = { fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', color: 'var(--umbra-90)', lineHeight: 1.6, marginTop: 'var(--space-4)', maxWidth: '26ch' };
  const stats = [
    { el: <MCountUp value={31} />, t: 'Eigentumswohnungen in zwei Häusern mit Blick über Wien und ins Grüne.' },
    { el: <MCountUp value={100} suffix=" %" />, t: 'jede Einheit entweder mit Garten oder Terrasse.' },
    { el: <MCountUp value={300} suffix=" m" />, t: 'zu Fuß zum Wienerwald.' },
    { el: <MCountUp value={2028} prefix="Q1 " />, t: 'geplante Fertigstellung, erstes Quartal.' },
  ];
  return (
    <section style={{ maxWidth: 'var(--content-max)', margin: '0 auto', padding: '0 var(--page-inset-lg)' }}>
      <h2 style={{ overflow: 'hidden', margin: '0 0 clamp(1.75rem, 3vw, 2.5rem)', paddingBottom: '0.1em' }}>
        <MLineMask innerStyle={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'clamp(1.5rem, 2.4vw, 2.25rem)', letterSpacing: '-0.015em', color: 'var(--umbra)' }}>Im Überblick</MLineMask>
      </h2>
      <div className="m57-mosaik" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', borderRight: '1px solid var(--sandstein)', borderBottom: '1px solid var(--sandstein)' }}>
        {stats.slice(0, 2).map((s, i) => (
          <MReveal key={i} delay={i * 80}><div style={cellBase}><div style={num}>{s.el}</div><div style={cap}>{s.t}</div></div></MReveal>
        ))}
        {/* Bildzelle */}
        <MReveal delay={160}><div style={{ ...cellBase, padding: 0, overflow: 'hidden' }}><img src={MIMG + 'garden-firepit-sunset.jpg'} alt="Abend am Waldrand" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} /></div></MReveal>
        {stats.slice(2).map((s, i) => (
          <MReveal key={i + 2} delay={(i + 3) * 80}><div style={cellBase}><div style={num}>{s.el}</div><div style={cap}>{s.t}</div></div></MReveal>
        ))}
        {/* Waldgrün-Zelle */}
        <MReveal delay={400}>
          <div style={{ ...cellBase, background: 'var(--waldgruen)', gridColumn: 'span 1' }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'clamp(1.5rem, 2.2vw, 2rem)', lineHeight: 1.15, color: 'var(--creme)' }}>Gebaut für Generationen</div>
            <a onClick={(e) => { e.preventDefault(); onAusstattung(); }} href="#" style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', fontWeight: 500, color: 'var(--warmweiss)', textDecoration: 'none', borderBottom: '1px solid rgba(251,249,244,0.5)', paddingBottom: '0.15rem', alignSelf: 'flex-start', marginTop: 'var(--space-4)' }}>Zur Ausstattung →</a>
          </div>
        </MReveal>
      </div>
    </section>
  );
}

/* 6.3 · Prozess — fünf Spalten mit vertikalen Hairline-Trennern, nummeriert.
   Die Nummer ist die Grafik, kein Icon. */
function Prozess({ compact = true, onVormerkung }) {
  const steps = [
    ['01', 'Vormerkung anfragen', 'Unverbindlich und kostenlos, online in zwei Minuten.'],
    ['02', 'Persönliche Beratung', 'Ihre Ansprechpartnerin Viola Dollinger meldet sich binnen 24 Stunden.'],
    ['03', 'Besichtigung', 'Pläne, Ausstattung und Finanzierungsrahmen im Detail.'],
    ['04', 'Kaufvertrag', 'Beim Notar, mit treuhändischer Abwicklung.'],
    ['05', 'Übergabe Q1 2028', 'Schlüsselfertig, bezugsbereit, mit Willkommen.'],
  ];
  return (
    <section style={{ maxWidth: 'var(--content-max)', margin: '0 auto', padding: '0 var(--page-inset-lg)' }}>
      <h2 style={{ overflow: 'hidden', margin: '0 0 clamp(2rem, 3.5vw, 3rem)', paddingBottom: '0.1em' }}>
        <MLineMask innerStyle={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'clamp(1.5rem, 2.4vw, 2.25rem)', letterSpacing: '-0.015em', color: 'var(--umbra)' }}>In fünf Schritten</MLineMask>
      </h2>
      <div className="m57-prozess" style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', borderTop: '1px solid var(--sandstein)' }}>
        {steps.map((s, i) => (
          <MReveal key={s[0]} delay={i * 70}>
            <div style={{ padding: 'clamp(1.5rem, 2.5vw, 2.25rem) clamp(1rem, 1.8vw, 1.6rem) clamp(1.5rem, 2.5vw, 2.25rem) 0', borderLeft: i === 0 ? 'none' : '1px solid var(--sandstein)', paddingLeft: i === 0 ? 0 : 'clamp(1rem, 1.8vw, 1.6rem)', height: '100%', boxSizing: 'border-box' }}>
              <div className="tabular" style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(1.75rem, 2.8vw, 2.5rem)', color: 'var(--waldgruen)', lineHeight: 1, marginBottom: 'var(--space-4)' }}>{s[0]}</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: '1.1rem', color: 'var(--umbra)', marginBottom: '0.4rem' }}>{s[1]}</div>
              <div style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', lineHeight: 1.6, color: 'var(--umbra-60)' }}>{s[2]}</div>
            </div>
          </MReveal>
        ))}
      </div>
    </section>
  );
}

/* 6.2 · Nummeriertes FAQ-Akkordeon — Zeile öffnet per clip, Rest dimmt auf 60 %. */
function FAQ({ items }) {
  const [open, setOpen] = React.useState(null);
  const rows = items || [
    ['01', 'Wie läuft die Vormerkung ab', 'Sie senden das Formular, wir melden uns binnen 24 Stunden persönlich. Die Vormerkung ist unverbindlich und kostenlos, sie sichert Ihnen die frühzeitige Auswahl.'],
    ['02', 'Wann ist die Fertigstellung', 'Die Fertigstellung ist für das erste Quartal 2028 geplant, schlüsselfertig übergeben. Den genauen Termin nennen wir im Beratungsgespräch.'],
    ['03', 'Was ist die Flexizone', 'Ein Raum im eigenen Untergeschoss der vier Gartenwohnungen in Haus 7 (Top 1, 2+3, 4 und 5), je nach Wohnung 23 bis 31 m² groß. Mit Strom, Trink- und Schmutzwasserleitungen sind für eine spätere Nutzung vorbereitet, damit ist vom Spa über ein Gym mit Sauna bis zum Homeoffice vieles möglich.'],
    ['04', 'Wie funktioniert die Finanzierung', 'Wir stellen die Unterlagen für Ihre Bank zusammen und verweisen Sie an eine unabhängige Finanzierungsberatung. Eine verbindliche Beratung erfolgt im persönlichen Gespräch.'],
    ['05', 'Welche Nebenkosten fallen an', 'Es handelt sich um ein provisionspflichtiges Maklerangebot. Eine Provision fällt erst bei Abgabe eines verbindlichen Kaufanbots an. Sie erhalten mit dem Angebot eine Nebenkostenübersicht. Die Vertragserrichtung ist an eine Rechtsanwaltskanzlei gebunden.'],
  ];
  return (
    <section style={{ maxWidth: 'var(--content-max)', margin: '0 auto', padding: '0 var(--page-inset-lg)' }}>
      <h2 style={{ overflow: 'hidden', margin: '0 0 clamp(2rem, 3.5vw, 3rem)', paddingBottom: '0.1em' }}>
        <MLineMask innerStyle={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'clamp(1.5rem, 2.4vw, 2.25rem)', letterSpacing: '-0.015em', color: 'var(--umbra)' }}>Fragen</MLineMask>
      </h2>
      <div style={{ borderTop: '1px solid var(--sandstein)' }} onMouseLeave={() => {}}>
        {rows.map((r) => {
          const isOpen = open === r[0];
          const dim = open && !isOpen;
          return (
            <div key={r[0]} style={{ borderBottom: '1px solid var(--sandstein)', opacity: dim ? 0.6 : 1, transition: 'opacity 250ms ease' }}>
              <button onClick={() => setOpen(isOpen ? null : r[0])}
                style={{ width: '100%', background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left', display: 'flex', alignItems: 'baseline', gap: 'var(--space-5)', padding: 'clamp(1.1rem, 2vw, 1.6rem) 0' }}>
                <span className="tabular" style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-label)', color: 'var(--umbra-60)', flex: 'none', width: '2rem' }}>{r[0]}</span>
                <span style={{ flex: 1, fontFamily: 'var(--font-display)', fontSize: 'clamp(1.15rem, 1.8vw, 1.5rem)', color: 'var(--umbra)' }}>{r[1]}</span>
                <span aria-hidden="true" style={{ flex: 'none', fontSize: '1.2rem', color: 'var(--waldgruen)', transform: isOpen ? 'rotate(45deg)' : 'none', transition: 'transform 250ms var(--ease-reveal)' }}>+</span>
              </button>
              <div style={{ display: 'grid', gridTemplateRows: isOpen ? '1fr' : '0fr', transition: 'grid-template-rows 350ms var(--ease-reveal)' }}>
                <div style={{ overflow: 'hidden' }}>
                  <p style={{ margin: '0 0 clamp(1.1rem, 2vw, 1.6rem)', paddingLeft: 'calc(2rem + var(--space-5))', maxWidth: '60ch', fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', lineHeight: 1.7, color: 'var(--umbra-90)' }}>{r[2]}</p>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

/* 4.1 · "Das Haus lesen" — links fester Textblock, rechts stilisierter
   Geschossstapel beider Häuser (ON 7 links, ON 5 rechts, hangbedingt um ein
   Geschoss versetzt). Beim Scrollen füllt sich Ebene für Ebene in Waldgrün;
   eine Zeile nennt Inhalt + Einheitenzahl der aktiven Ebene. Klick auf eine
   Ebene setzt den Geschossfilter und scrollt zum Finder. */
function HausLesen({ units, onFloorSelect }) {
  const outer = React.useRef(null);
  const [p, setP] = React.useState(0);
  const [tapFloor, setTapFloor] = React.useState(null);
  const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const mobile = window.matchMedia('(max-width: 760px)').matches;
  const floorsUp = ['EG', '1.OG', '2.OG', 'DG']; // Füllreihenfolge unten→oben

  React.useEffect(() => {
    if (reduce || mobile) { setP(1); return; }
    const sc = window.__m57Scroller; if (!sc) { setP(1); return; }
    const onScroll = () => {
      const o = outer.current; if (!o) return;
      const vh = window.innerHeight || 800;
      const r = o.getBoundingClientRect();
      const range = r.height - vh;
      setP(Math.min(1, Math.max(0, -r.top / (range || 1))));
    };
    sc.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => sc.removeEventListener('scroll', onScroll);
  }, []);

  // aktive Ebene aus Scrollfortschritt (0..1 → EG..DG)
  const filledCount = Math.round(p * floorsUp.length);
  const activeIdx = Math.min(floorsUp.length - 1, Math.max(0, Math.ceil(p * floorsUp.length) - 1));
  const activeFloor = tapFloor || floorsUp[activeIdx];
  const content = window.M57_FLOOR_CONTENT[activeFloor] || {};
  const countOnFloor = units.filter((u) => u.geschoss === activeFloor).length;

  const isFilled = (fl) => {
    if (reduce) return true;
    const idx = floorsUp.indexOf(fl);
    return idx < filledCount || fl === activeFloor;
  };

  // SVG-Stapel: ON7 links (unten versetzt), ON5 rechts (höher).
  const cellH = 34, cellW = 120, gap = 4, off = cellH + gap;
  const rowsDown = ['DG', '2.OG', '1.OG', 'EG'];
  const stackH = rowsDown.length * (cellH + gap) + off;
  const SW = cellW * 2 + 20;
  const cell = (haus, fl, i) => {
    const filled = isFilled(fl) && (activeFloor === fl || isFilled(fl));
    const on = activeFloor === fl;
    const x = haus === 7 ? 0 : cellW + 20;
    const y = (haus === 7 ? off : 0) + i * (cellH + gap);
    const units2 = units.filter((u) => u.haus === haus && u.geschoss === fl);
    return (
      <g key={haus + fl} onClick={() => { setTapFloor(fl); onFloorSelect && onFloorSelect(fl); }} style={{ cursor: 'pointer' }}>
        <rect x={x} y={y} width={cellW} height={cellH}
          fill={isFilled(fl) ? 'var(--waldgruen)' : 'var(--warmweiss)'}
          stroke={on ? 'var(--umbra)' : (isFilled(fl) ? 'var(--waldgruen)' : 'var(--sandstein)')}
          strokeWidth={on ? 2 : 1}
          style={{ transition: 'fill 300ms var(--ease-reveal)' }} />
        <text x={x + 10} y={y + cellH / 2 + 4} fontFamily="var(--font-text)" fontSize="11" fill={isFilled(fl) ? 'var(--warmweiss)' : 'var(--umbra-60)'}>{fl}</text>
        <text x={x + cellW - 10} y={y + cellH / 2 + 4} textAnchor="end" fontFamily="var(--font-text)" fontSize="11" fill={isFilled(fl) ? 'rgba(251,249,244,0.75)' : 'var(--sandstein)'} style={{ fontVariantNumeric: 'tabular-nums' }}>{units2.length}</text>
      </g>
    );
  };

  const graphic = (
    <div>
      <svg viewBox={`0 0 ${SW} ${stackH + 18}`} width="100%" style={{ height: 'auto', display: 'block', maxWidth: 420 }} role="img" aria-label="Geschossstapel beider Häuser">
        {rowsDown.map((fl, i) => cell(7, fl, i))}
        {rowsDown.map((fl, i) => cell(5, fl, i))}
        <line x1="0" y1={stackH} x2={cellW} y2={stackH} stroke="var(--umbra)" strokeWidth="2" />
        <line x1={cellW + 20} y1={stackH - off} x2={SW} y2={stackH - off} stroke="var(--umbra)" strokeWidth="2" />
        <text x={cellW / 2} y={stackH + 14} textAnchor="middle" fontFamily="var(--font-text)" fontSize="10" fill="var(--umbra-60)">Haus 7</text>
        <text x={cellW + 20 + cellW / 2} y={stackH - off + 14 + rowsDown.length * (cellH + gap)} textAnchor="middle" fontFamily="var(--font-text)" fontSize="10" fill="var(--umbra-60)" style={{ display: 'none' }}>Haus 5</text>
      </svg>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 'var(--space-4)', marginTop: 'var(--space-5)', borderTop: '1px solid var(--sandstein)', paddingTop: 'var(--space-4)' }}>
        <span style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(1.15rem, 1.8vw, 1.5rem)', color: 'var(--umbra)' }}>{content.label}</span>
        <span className="tabular" style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-label)', color: 'var(--umbra-60)', fontVariantNumeric: 'tabular-nums' }}>{countOnFloor} Einheiten</span>
      </div>
      <p style={{ margin: '0.5rem 0 0', fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', color: 'var(--umbra-90)' }}>{content.text}</p>
      <p style={{ margin: '0.75rem 0 0', fontFamily: 'var(--font-text)', fontSize: 'var(--text-micro)', color: 'var(--umbra-60)' }}>Ebene wählen, um im Finder danach zu filtern.</p>
    </div>
  );

  const textBlock = (
    <div>
      <h2 style={{ overflow: 'hidden', margin: '0 0 clamp(1.25rem, 2.5vw, 2rem)', paddingBottom: '0.1em' }}>
        <MLineMask innerStyle={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'clamp(1.75rem, 3vw, 2.75rem)', letterSpacing: '-0.015em', lineHeight: 1.08, color: 'var(--umbra)' }}>Das Haus lesen</MLineMask>
      </h2>
      <p style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'clamp(1.25rem, 2vw, 1.7rem)', lineHeight: 1.35, color: 'var(--umbra)', margin: '0 0 var(--space-5)', maxWidth: '24ch' }}>
        Zwei Häuser, gestaffelt. Jedes Geschoss mit eigenem Blick über Wien.
      </p>
      <p style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', lineHeight: 1.8, color: 'var(--umbra-90)', margin: 0, maxWidth: '38ch' }}>
        Das Gelände versetzt die Häuser um ein Geschoss: das Erdgeschoss von Haus 5 liegt auf Höhe des ersten Untergeschosses von Haus 7. Aus dieser Besonderheit werden Gärten, Balkone und Dachterrassen, jede mit eigenem Blick.
      </p>
    </div>
  );

  if (reduce || mobile) {
    return (
      <section style={{ maxWidth: 'var(--content-max)', margin: '0 auto', padding: '0 var(--page-inset-lg)' }}>
        <div className="m57-cols2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'clamp(2rem, 5vw, 4rem)', alignItems: 'start' }}>
          {textBlock}{graphic}
        </div>
      </section>
    );
  }
  return (
    <section ref={outer} style={{ height: '220vh', position: 'relative' }}>
      <div style={{ position: 'sticky', top: 0, height: '100vh', display: 'flex', alignItems: 'center' }}>
        <div style={{ maxWidth: 'var(--content-max)', margin: '0 auto', padding: '0 var(--page-inset-lg)', width: '100%' }}>
          <div className="m57-cols2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'clamp(2rem, 5vw, 5rem)', alignItems: 'center' }}>
            {textBlock}{graphic}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { StatMosaik, Prozess, FAQ, HausLesen });
