/* sections-a.jsx — Hero, Manifest, Weisst du noch, Neues Normal, Statement */

const { useState: useStateA } = React;

/* 1 — HERO */
function Hero({ motion, accent, onCta }) {
  return (
    <header className="section section--paper hero" data-screen-label="Hero">
      <Kinetic accent={accent} motion={motion} density={90} />
      <div className="wrap">
        <div className="hero__grid">
          <div>
            <div className="eyebrow" data-reveal>Die SuperApp für Deutschland</div>
            <h1 className="display h-hero" data-reveal style={{ '--reveal-delay': '.05s', marginTop: '22px' }}>
              Deutschland läuft<br />auf Papier.<br />
              <span className="accent-text">Du nicht mehr.</span>
            </h1>
            <p className="lede dim" data-reveal style={{ '--reveal-delay': '.12s', marginTop: '28px' }}>
              Eine App. Dein ganzes Leben in Deutschland. Kein Amt-Marathon, kein
              Passwort-Friedhof, kein „bitte ziehen Sie eine Nummer". Du tippst –
              Deutschland macht.
            </p>
            <div className="hero__cta" data-reveal style={{ '--reveal-delay': '.18s' }}>
              <button className="btn btn--primary btn--lg" onClick={onCta}>Ich bin dabei</button>
              <a href="#weisstdu" className="btn btn--ghost btn--lg btn--down">
                Zeig mir wie <span className="arrow">↓</span>
              </a>
            </div>
            <div className="hero__stat-row" data-reveal style={{ '--reveal-delay': '.24s' }}>
              <div className="stat"><div className="stat__num">1</div><div className="stat__label">Login für alles</div></div>
              <div className="stat"><div className="stat__num">0</div><div className="stat__label">Wartenummern</div></div>
              <div className="stat"><div className="stat__num">∞</div><div className="stat__label">Services, ein Zuhause</div></div>
            </div>
          </div>
          <div data-reveal style={{ '--reveal-delay': '.16s' }}>
            <div className="phone-wrap">
              <div className="phone-glow" aria-hidden="true"></div>
              <img className="hero__shot" src="hero-app.png" alt="DE-eins App auf dem Smartphone" />
            </div>
          </div>
        </div>
      </div>
    </header>
  );
}

/* 2 — MANIFEST */
const MANIFEST_NEGS = [
  { text: 'Dass dein Wochenende dem Bürgeramt gehört.', tag: 'Amt-Marathon' },
  { text: 'Dass „digital" 14 Logins bedeutet.', tag: 'Passwort-Friedhof' },
  { text: 'Dass Erwachsensein heißt, in Warteschleifen zu altern.', tag: 'Wartenummer' },
];

/* Interaktives Lösch-Deck: du wischst die Hürden selbst weg. */
function ManifestDeck() {
  const { useState, useRef } = React;
  const [gone, setGone] = useState([]);        // [{i, dir}]
  const [dx, setDx] = useState(0);             // live drag offset of top card
  const startX = useRef(null);
  const dragId = useRef(null);

  const goneIds = gone.map(g => g.i);
  const order = MANIFEST_NEGS.map((_, i) => i).filter(i => !goneIds.includes(i));
  const topId = order[0];
  const remaining = order.length;
  const cleared = remaining === 0;

  const remove = (i, dir = -1) => {
    setGone(g => g.some(x => x.i === i) ? g : [...g, { i, dir }]);
    setDx(0); startX.current = null; dragId.current = null;
  };
  const reset = () => { setGone([]); setDx(0); };

  const onDown = (e, i) => {
    if (i !== topId) return;
    startX.current = e.clientX; dragId.current = i;
    try { e.currentTarget.setPointerCapture(e.pointerId); } catch (err) {}
  };
  const onMove = (e) => {
    if (startX.current === null) return;
    setDx(e.clientX - startX.current);
  };
  const onUp = () => {
    if (startX.current === null) return;
    if (Math.abs(dx) > 110) remove(dragId.current, dx < 0 ? -1 : 1);
    else { setDx(0); startX.current = null; dragId.current = null; }
  };

  return (
    <div className="mf-deck">
      <div className="mf-stack">
        {MANIFEST_NEGS.map((card, i) => {
          const g = gone.find(x => x.i === i);
          const depth = order.indexOf(i);
          let style, cls = 'mf-card';
          if (g) {
            cls += ' is-gone';
            style = { transform: `translateX(${g.dir * 130}%) translateY(20px) rotate(${g.dir * 14}deg)`, zIndex: 1 };
          } else {
            const isTop = depth === 0;
            const live = isTop ? dx : 0;
            const rot = live * 0.04;
            style = {
              transform: `translateY(${depth * 16}px) scale(${1 - depth * 0.045}) translateX(${live}px) rotate(${rot}deg)`,
              opacity: depth > 2 ? 0 : 1,
              zIndex: 10 - depth,
            };
            if (isTop) cls += ' is-top';
            if (isTop && startX.current !== null) cls += ' is-dragging';
          }
          return (
            <div
              key={i}
              className={cls}
              style={style}
              onPointerDown={(e) => onDown(e, i)}
              onPointerMove={onMove}
              onPointerUp={onUp}
              onPointerCancel={onUp}
            >
              <div className="mf-card__top">
                <span className="mf-card__no">0{i + 1} / 03</span>
                <span className="mf-card__tag">{card.tag}</span>
              </div>
              <p className="mf-card__text">{card.text}</p>
              <button className="mf-card__del" onClick={() => remove(i, -1)} aria-label={'Löschen: ' + card.text}>
                <span className="mf-card__x" aria-hidden="true">✕</span> Aus meinem Leben löschen
              </button>
            </div>
          );
        })}

        <div className={'mf-reveal' + (cleared ? ' is-shown' : '')} aria-hidden={!cleared}>
          <span className="mf-reveal__chip"><span className="dot">✓</span> Alles weg, was dich aufhielt</span>
          <p className="mf-reveal__line">Dein Deutschland passt jetzt in <span className="hl">deine Hand.</span></p>
          <button className="mf-reveal__reset" onClick={reset}>↺ Nochmal ansehen</button>
        </div>
      </div>

      <div className={'mf-meter' + (cleared ? ' is-clear' : '')}>
        <span className="mf-meter__num">{remaining}</span>
        <span className="mf-meter__label">
          {cleared ? 'Hürden gelöscht. Keine übrig.' : (remaining === 1 ? 'Ding steht noch zwischen dir und deinem Leben' : 'Dinge stehen zwischen dir und deinem Leben')}
        </span>
        <div className="mf-meter__bar" aria-hidden="true">
          {MANIFEST_NEGS.map((_, i) => (
            <span key={i} className={'mf-meter__pip' + (goneIds.includes(i) ? ' is-clear' : '')}></span>
          ))}
        </div>
        <div className="mf-hint">
          {!cleared ? (
            <>
              <span className="mf-hint__txt">Wisch die Karte weg →</span>
              <button className="mf-hint__btn" onClick={() => setGone(MANIFEST_NEGS.map((_, i) => ({ i, dir: -1 })))}>Alle löschen</button>
            </>
          ) : (
            <span className="mf-hint__txt">Genau so einfach soll sich alles anfühlen.</span>
          )}
        </div>
      </div>
    </div>
  );
}

function Manifest({ accent = '#00e5b0', motion = true }) {
  return (
    <section className="section section--ink manifest" data-screen-label="Manifest">
      <div className="wrap-tight">
        <div className="eyebrow" data-reveal>Manifest</div>
        <h2 className="display h-lg" data-reveal style={{ '--reveal-delay': '.05s', marginTop: '18px', maxWidth: '20ch' }}>
          Drei Dinge stehen zwischen dir und deinem Leben. <span className="accent-text">Lösch sie.</span>
        </h2>

        <div data-reveal style={{ '--reveal-delay': '.1s' }}>
          <ManifestDeck />
        </div>

        <figure className="manifest__shot" data-reveal style={{ '--reveal-delay': '.1s' }}>
          <img src="manifest-img.jpg" alt="Eine Frau geht weiter — die Bürokratie hinter ihr löst sich in Partikel auf." loading="lazy" />
          <figcaption className="manifest__shot-cap">Was dich aufhielt, <span className="hl">löst sich auf.</span></figcaption>
        </figure>

        <div className="manifest__turn" data-reveal style={{ '--reveal-delay': '.1s' }}>
          <span className="tword">Das ist das Versprechen —</span>
          <span className="tline" aria-hidden="true"></span>
        </div>

        <div className="manifest__pos">
          <p className="m-pos" data-reveal>
            Alles, was dich aufhält, <span className="hl">gehört gelöscht.</span>
          </p>
        </div>

        <div className="manifest__kicker-wrap">
          <Kinetic accent={accent} motion={motion} density={60} />
          <div className="manifest__kicker">
            <span className="k-line" data-reveal>Ein Login.</span>
            <span className="k-line" data-reveal style={{ '--reveal-delay': '.08s' }}>Ein Leben.</span>
            <span className="k-line k-accent" data-reveal style={{ '--reveal-delay': '.16s' }}>Keine Ausreden mehr.</span>
          </div>
        </div>
      </div>
    </section>
  );
}

/* Interaktiver Vorher/Nachher-Slider: zieh dich vom Amt-Gestern ins 2026. */
function BeforeAfter() {
  const { useState, useRef, useEffect } = React;
  const [pos, setPos] = useState(60);   // % des "Früher"-Bildes von links
  const [touched, setTouched] = useState(false);
  const ref = useRef(null);
  const dragging = useRef(false);
  const teaser = useRef(null);

  const stopTeaser = () => { if (teaser.current) { clearInterval(teaser.current); teaser.current = null; } };
  const setFromX = (clientX) => {
    const el = ref.current; if (!el) return;
    const r = el.getBoundingClientRect();
    let p = ((clientX - r.left) / r.width) * 100;
    setPos(Math.max(3, Math.min(97, p)));
  };
  const onDown = (e) => {
    stopTeaser();
    dragging.current = true; setTouched(true); setFromX(e.clientX);
    try { e.currentTarget.setPointerCapture(e.pointerId); } catch (err) {}
  };
  const onMove = (e) => { if (dragging.current) setFromX(e.clientX); };
  const onUp = () => { dragging.current = false; };

  /* sanfter Auto-Teaser beim ersten Sichtbarwerden (bricht ab, sobald angefasst) */
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((es) => {
      es.forEach((en) => {
        if (en.isIntersecting && !touched && !teaser.current) {
          let v = 60; const tgt = 43;
          teaser.current = setInterval(() => {
            if (dragging.current) { stopTeaser(); return; }
            v -= 1.5; setPos(v);
            if (v <= tgt) stopTeaser();
          }, 16);
          io.disconnect();
        }
      });
    }, { threshold: 0.5 });
    io.observe(el);
    return () => { io.disconnect(); stopTeaser(); };
  }, [touched]);

  return (
    <div
      className={'ba' + (touched ? ' is-touched' : '')}
      ref={ref}
      onPointerDown={onDown} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}
      role="slider" aria-label="Vorher-Nachher: vom Amt-Wartezimmer ins Jetzt" aria-valuenow={Math.round(pos)}
    >
      <img className="ba__img ba__img--new" src="recall-new.jpg" alt="Entspannt zuhause auf dem Sofa, alles per App geregelt." draggable="false" loading="lazy" />
      <span className="ba__tag ba__tag--new"><span className="ba__dot"></span>Jetzt · 2026</span>

      <div className="ba__old" style={{ clipPath: 'inset(0 ' + (100 - pos) + '% 0 0)' }} aria-hidden="true">
        <img className="ba__img ba__img--old" src="recall-old.jpg" alt="" draggable="false" loading="lazy" />
        <span className="ba__tag ba__tag--old">Früher</span>
      </div>

      <div className="ba__handle" style={{ left: pos + '%' }} aria-hidden="true">
        <span className="ba__line"></span>
        <span className="ba__grip"><span className="ba__arr">‹</span><span className="ba__arr">›</span></span>
      </div>

      <span className="ba__hint" aria-hidden="true">Zieh dich ins Jetzt</span>
    </div>
  );
}

/* 3 — WEISST DU NOCH */
function Recall() {
  const items = [
    'Als „kurz zum Amt" ein halber Urlaubstag war.',
    'Als du 14 Passwörter hattest – und keins davon wusstest.',
    'Als ein Stempel drei Wochen und zwei Formulare kostete.',
    'Als jede Behörde, jede Kasse, jede App ihr eigenes Königreich war.',
  ];
  return (
    <section id="weisstdu" className="section section--paper" data-screen-label="Weisst du noch">
      <div className="wrap-tight">
        <div className="eyebrow" data-reveal>Rückblick</div>
        <h2 className="display h-xl" data-reveal style={{ '--reveal-delay': '.05s', marginTop: '20px', maxWidth: '16ch' }}>
          Weißt du noch, als das alles noch nervte?
        </h2>
        <div className="recall-list">
          {items.map((t, i) => (
            <div key={i} className="recall" data-reveal style={{ '--reveal-delay': (i * 0.05) + 's' }}>
              <span className="recall__no">0{i + 1}</span>
              <span className="recall__text"><span className="strike">{t}</span></span>
            </div>
          ))}
        </div>
        <div className="punch" data-reveal>
          <h3 className="display h-mega">
            Vorbei.<br /><span className="accent-text">Willkommen in 2026.</span>
          </h3>
        </div>

        <div data-reveal style={{ '--reveal-delay': '.08s' }}>
          <BeforeAfter />
        </div>
      </div>
    </section>
  );
}

/* 4 — DEIN NEUES NORMAL (staccato) */
function NeuesNormal() {
  const pairs = [
    ['Ausweisen?', 'Ein Tap.'],
    ['Bezahlen?', 'Schon passiert.'],
    ['Termin beim Amt?', 'Vom Bett aus.'],
    ['Ticket, Parken, losfahren?', 'Eine Bewegung.'],
    ['Gesundheit und Papierkram?', 'Geregelt.'],
    ['Der Rest deines Lebens?', 'Wartet nicht mehr.'],
  ];
  return (
    <section className="section section--paper" data-screen-label="Neues Normal" style={{ paddingTop: 0 }}>
      <div className="wrap-tight">
        <div className="eyebrow" data-reveal>Dein neues Normal</div>
        <h2 className="display h-xl" data-reveal style={{ '--reveal-delay': '.05s', marginTop: '20px', maxWidth: '14ch' }}>
          So fühlt sich dein Tag jetzt an.
        </h2>
        <div className="staccato">
          {pairs.map((p, i) => (
            <span key={i} className="chunk" data-reveal style={{ '--reveal-delay': (i * 0.04) + 's' }}>
              <span className="q">{p[0]} </span><span className="a">{p[1]}</span>
            </span>
          ))}
        </div>
      </div>
    </section>
  );
}

/* 5 — GROSSES STATEMENT */
function BigStatement() {
  return (
    <section className="section section--ink statement" data-screen-label="Statement">
      <div className="wrap">
        <p className="eyebrow" data-reveal style={{ justifyContent: 'center' }}>·</p>
        <h2 className="statement__big" data-reveal style={{ '--reveal-delay': '.06s', marginTop: '18px' }}>
          Tausend Apps wollten dein Leben organisieren.{' '}
          <span className="accent-text">Eine schafft's wirklich.</span>
        </h2>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, Manifest, Recall, NeuesNormal, BigStatement });
