// Anzeigenkette — day-of-life sticky scroller
// Globals: window.DaySection

const { useEffect: useEffectD, useRef: useRefD, useState: useStateD } = React;

/* ---------------- Phone slides (4 platforms) ---------------- */

function StatusBar({ time, dark }) {
  return (
    <div className="status-bar" style={{ color: dark ? '#fff' : '#000' }}>
      <div>{time}</div>
      <div className="icons">
        <div className="bars"><i /><i /><i /><i /></div>
        <span style={{ fontSize: 11, fontWeight: 600 }}>5G</span>
        <div className="battery"><i /></div>
      </div>
    </div>
  );
}

function slideStyle(progress) {
  // progress: -1 (entering from below) → 0 (centered) → 1 (leaving up)
  // when not active, progress is 0 from caller, but we also fade by active flag in className
  const ty = progress * -30;
  const op = 1 - Math.min(1, Math.abs(progress) * 0.6);
  return {
    transform: `translateY(${ty}px)`,
    opacity: op,
    transition: 'transform 200ms var(--ease-out), opacity 400ms var(--ease-out)',
  };
}

function WeatherSlide({ active, progress = 0 }) {
  return (
    <div className={'phone-slide s-weather' + (active ? ' active' : '')} style={active ? slideStyle(progress) : null}>
      <StatusBar time="6:47" dark />
      <div className="weather-body">
        <div className="weather-loc">Aalen</div>
        <div className="weather-temp">14°</div>
        <div className="weather-cond">Regnerisch</div>
        <div className="weather-hi">H:16°  T:9°</div>
        <div className="weather-hours">
          <div>jetzt<b>14°</b></div>
          <div>8<b>13°</b></div>
          <div>9<b>12°</b></div>
          <div>10<b>13°</b></div>
          <div>11<b>14°</b></div>
        </div>
        <div className="weather-ad-slot">
          <div className="ad-banner">
            <span className="ad-tag-mini">Anzeige</span>
            <window.ThemeBadge hook="aufstieg" style={{ position: 'absolute', top: -10, right: 12 }} />
            <div className="av">E</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <h5>Teamleitung Bußgeldstelle (m/w/d)</h5>
              <p>Wartest Du auf eine Leitungsstelle? Stadt Ellwangen.</p>
            </div>
            <div className="cta-mini">Bewerben</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function InstagramSlide({ active, progress = 0 }) {
  return (
    <div className={'phone-slide s-ig' + (active ? ' active' : '')} style={active ? slideStyle(progress) : null}>
      <StatusBar time="12:34" />
      <div className="ig-header">
        <div className="ig-logo">Instagram</div>
        <div style={{ display: 'flex', gap: 14, fontSize: 18 }}>
          <span>♡</span><span>✉</span>
        </div>
      </div>
      <div className="ig-stories">
        {['lena_b', 'aalen.fc', 'mama', 'jonas', 'kant.tine'].map((n, i) => (
          <div key={i} className="ig-story">
            <div className="ring"><div style={{ background: ['#caa', '#dca', '#aac', '#cac', '#aca'][i] }} /></div>
            <span>{n}</span>
          </div>
        ))}
      </div>
      <div className="ig-feed">
        <div className="ig-post">
          <div className="ig-post-head">
            <div className="av" />
            <div className="meta">
              <b>stadt.ellwangen</b>
              <span>Gesponsert</span>
            </div>
            <div style={{ fontSize: 16, color: '#888' }}>⋯</div>
          </div>
          <div className="ig-post-img">
            <div className="ad-square">
              <window.ThemeBadge hook="entwicklung" style={{ position: 'absolute', top: 12, right: 12 }} />
              <div className="ribbon">Stadt Ellwangen</div>
              <div>
                <h5>Teamleitung der Bußgeldstelle (m/w/d) gesucht</h5>
                <div className="opener">Monatelang für den Fachwirt gebüffelt. Wochenenden in der Verwaltungsschule. Endlich den AII in der Tasche. Und jetzt?</div>
              </div>
              <div className="meta-row">
                <div className="from">Stadt Ellwangen · Karriere</div>
                <div className="cta-mini" style={{ background: '#fff', color: '#002a3c' }}>Bewerben</div>
              </div>
              <svg style={{ position: 'absolute', inset: 0, opacity: 0.15, pointerEvents: 'none' }} viewBox="0 0 300 300" preserveAspectRatio="none">
                <path d="M0,260 L40,260 L40,210 L70,210 L70,225 L100,225 L100,170 L130,170 L130,140 L150,140 L150,120 L165,120 L165,140 L185,140 L185,90 L195,90 L195,140 L215,140 L215,170 L260,170 L260,200 L300,200 L300,300 L0,300 Z" fill="#fff" />
              </svg>
            </div>
          </div>
          <div className="ig-post-actions">
            <span>♡</span><span>💬</span><span>↗</span>
          </div>
        </div>
      </div>
    </div>
  );
}

function ReelSlide({ active, progress = 0 }) {
  return (
    <div className={'phone-slide s-reel' + (active ? ' active' : '')} style={active ? slideStyle(progress) : null}>
      <StatusBar time="16:12" dark />
      <div className="reel-stage">
        <div className="ad-reel">
          <div className="bg-blob" />
          <div className="bg-blob-2" />
          <window.ThemeBadge hook="alltag" style={{ position: 'absolute', top: 14, right: 14, zIndex: 4 }} />
          <div className="top-strip">
            <span /><span /><span /><span />
          </div>
          <div className="ad-label">Anzeige · Stadt Ellwangen</div>
          <div className="hook">
            Die Akte mit dem schwierigen Fahrverbot auf dem Tisch.
            <br /><span className="hl">Deine finale Unterschrift</span> darunter.
            <br />Ohne drei Rücksprachen bei der Amtsleitung.
          </div>
          <div className="caption">Teamleitung Bußgeldstelle · Stadt Ellwangen</div>
          <div className="cta-pill">Mehr erfahren →</div>
          <div className="reel-side">
            <div className="ic">♡<small>2,1k</small></div>
            <div className="ic">💬<small>184</small></div>
            <div className="ic">↗<small>52</small></div>
          </div>
        </div>
      </div>
    </div>
  );
}

function YoutubeSlide({ active, progress = 0 }) {
  return (
    <div className={'phone-slide s-yt' + (active ? ' active' : '')} style={active ? slideStyle(progress) : null}>
      <StatusBar time="21:15" dark />
      <div className="yt-header">
        <div className="yt-logo">You<span>Tube</span></div>
        <div style={{ display: 'flex', gap: 12, fontSize: 13, color: '#aaa' }}>⌕ ◉</div>
      </div>
      <div className="yt-player">
        <div className="ad-yt">
          <div className="city-line" />
          <window.ThemeBadge hook="einwand" style={{ position: 'absolute', top: 10, right: 10, zIndex: 4 }} />
          <div>
            <div className="top-line">Anzeige</div>
            <div className="badge" style={{ marginTop: 6 }}>Stadt Ellwangen</div>
          </div>
          <div>
            <div className="hook">
              Plötzlich eine neue Verwaltung, ein anderes Team, unbekannte Hierarchien… allein die Vorstellung, die Sicherheit der aktuellen Stelle zu riskieren, löst Verunsicherungen aus.
            </div>
            <div className="sub">Wir nehmen Dir die Sorge.</div>
          </div>
        </div>
        <div className="yt-ad-tag">Anzeige</div>
        <div className="yt-skip">Überspringen ⏭</div>
        <div className="yt-progress" style={{ position: 'absolute', bottom: 0, left: 0, right: 0 }}>
          <div />
        </div>
      </div>
      <div className="yt-meta">
        <h4>Tagesschau in 100 Sekunden — 6. Mai 2026</h4>
        <p>tagesschau · 142 Tsd. Aufrufe · vor 2 Stunden</p>
      </div>
    </div>
  );
}

/* ---------------- Day section ---------------- */

const STATIONS = [
  {
    time: '06:47',
    label: 'Morgens',
    title: 'Erster Blick aufs Wetter.',
    body: 'Erster Griff zum Handy noch vor dem Aufstehen. Die Wetter-App zeigt 14 Grad und Regen — und unten in der App eine kleine Anzeige.',
    creative: 'In-Feed-Banner · 6:5',
    hook: 'Wartest Du darauf, dass in Deinem aktuellen Amt endlich eine Leitungsstelle frei wird?',
    sunPos: 18, // % from top of rail
    sunMode: '',
  },
  {
    time: '12:34',
    label: 'Mittags',
    title: 'Mittagspause, Instagram-Feed.',
    body: 'In der Pause scrollt sie kurz durch Stories und Posts. Ein gesponserter Square-Post taucht zwischen den Beiträgen ihrer Freunde auf.',
    creative: 'Square 1:1 · Instagram Feed',
    hook: 'Monatelang für den Fachwirt gebüffelt. Wochenenden in der Verwaltungsschule. Endlich den AII in der Tasche. Und jetzt?',
    sunPos: 38,
    sunMode: '',
  },
  {
    time: '16:12',
    label: 'Nachmittags',
    title: 'Reel-Pause vor Feierabend.',
    body: 'Vier Reels später kommt eines, das anders aussieht. Ein direkter Hook, kein Hochglanz — sondern ein konkretes Bild aus ihrem Berufsalltag.',
    creative: 'Story 9:16 · Instagram Reel',
    hook: 'Die Akte mit dem schwierigen Fahrverbot auf dem Tisch. Deine finale Unterschrift darunter.',
    sunPos: 62,
    sunMode: 'evening',
  },
  {
    time: '21:15',
    label: 'Abends',
    title: 'Letzte Tagesschau auf YouTube.',
    body: 'Vor dem Schlafen läuft auf dem Tablet die Tagesschau. Davor: ein Pre-Roll, der diesmal die Sorgen anspricht, statt mit Versprechen zu locken.',
    creative: 'Story 9:16 · YouTube In-Stream',
    hook: 'Allein die Vorstellung, die Sicherheit der aktuellen Stelle zu riskieren, löst Verunsicherungen aus.',
    sunPos: 88,
    sunMode: 'night',
  },
];

function DaySection() {
  const sectionRef = useRefD(null);
  const [activeIdx, setActiveIdx] = useStateD(0);
  // continuous progress 0..1 across the full day track (smooth, not stepped)
  const [progress, setProgress] = useStateD(0);
  // local sub-progress within the current station (0..1) for the phone parallax
  const [stationProgress, setStationProgress] = useStateD(0);

  useEffectD(() => {
    if (!sectionRef.current) return;
    const items = sectionRef.current.querySelectorAll('.station');
    let raf = 0;
    const tick = () => {
      raf = 0;
      const center = window.innerHeight / 2;
      let best = 0, bestDist = Infinity;
      let bestRect = null;
      items.forEach((el, i) => {
        const r = el.getBoundingClientRect();
        const elCenter = r.top + r.height / 2;
        const d = Math.abs(elCenter - center);
        if (d < bestDist) { bestDist = d; best = i; bestRect = r; }
      });
      setActiveIdx(best);
      // sub progress within this station: -1 (just entering) → 0 (centered) → 1 (leaving)
      if (bestRect) {
        const local = (center - (bestRect.top + bestRect.height / 2)) / bestRect.height;
        setStationProgress(Math.max(-1, Math.min(1, local)));
      }
      // overall day progress for the sun rail
      const trackRect = sectionRef.current.getBoundingClientRect();
      const total = trackRect.height - window.innerHeight;
      const scrolled = -trackRect.top;
      const p = Math.max(0, Math.min(1, scrolled / total));
      setProgress(p);
    };
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(tick);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    tick();
    return () => { window.removeEventListener('scroll', onScroll); if (raf) cancelAnimationFrame(raf); };
  }, []);

  const station = STATIONS[activeIdx];
  // continuous sun position: blend across the 4 stations using progress
  const sunY = 10 + progress * 84; // 10% → 94%
  const sunModeContinuous = progress > 0.78 ? 'night' : progress > 0.5 ? 'evening' : '';
  // phone tilt + lift based on station sub-progress
  const phoneTilt = stationProgress * -3; // deg
  const phoneLift = stationProgress * 18;  // px
  const phoneScale = 1 - Math.abs(stationProgress) * 0.02;

  return (
    <section className="day-section" ref={sectionRef} data-day="0">
      <div className="day-intro">
        <div className="eyebrow-mark">Ein Tag · 4 Plattformen · 1 Stelle</div>
        <h2>Ein typischer Tag — vier Begegnungen mit derselben Stelle.</h2>
        <p>Sticky-Phone links, Stationen rechts. Scrollt mit.</p>
      </div>

      <div className="day-track">
        {/* sun rail */}
        <div className="sun-rail">
          <div className="sun-rail-inner">
            <div
              className={'sun-rail-marker ' + sunModeContinuous}
              style={{ top: `calc(${sunY}% - 18px)`, transition: 'background 600ms var(--ease-out), box-shadow 600ms var(--ease-out)' }}
            >
              <div className="sun-rail-time">
                {station.time}
                <small>{station.label}</small>
              </div>
            </div>
          </div>
        </div>

        {/* phone */}
        <div className="phone-col">
          <div
            className="phone"
            style={{
              transform: `perspective(1200px) translateY(${phoneLift}px) rotate(${phoneTilt}deg) scale(${phoneScale})`,
              transition: 'transform 200ms var(--ease-out)',
            }}
          >
            <div className="phone-notch" />
            <div className="phone-screen">
              <WeatherSlide active={activeIdx === 0} progress={activeIdx === 0 ? stationProgress : 0} />
              <InstagramSlide active={activeIdx === 1} progress={activeIdx === 1 ? stationProgress : 0} />
              <ReelSlide active={activeIdx === 2} progress={activeIdx === 2 ? stationProgress : 0} />
              <YoutubeSlide active={activeIdx === 3} progress={activeIdx === 3 ? stationProgress : 0} />
            </div>
            <div className="phone-glare" style={{ opacity: 0.5 + Math.abs(stationProgress) * 0.3 }} />
          </div>
        </div>

        {/* stations text */}
        <div className="day-text">
          {STATIONS.map((s, i) => (
            <div
              className={'station' + (i === activeIdx ? ' in' : '')}
              key={i}
              data-tp
              data-day-tp="0"
              data-hook={['aufstieg','entwicklung','alltag','einwand'][i]}
            >
              <div className="time-tag">{s.time} · {s.label}</div>
              <h3>{s.title}</h3>
              <p>{s.body}</p>
              <div className="quote">„{s.hook}"</div>
              <dl className="creative-meta">
                <dt>Format</dt><dd>{s.creative}</dd>
                <dt>Plattform</dt><dd>{['Wetter-App In-Feed', 'Instagram Feed', 'Instagram Reels', 'YouTube In-Stream'][i]}</dd>
                <dt>Absender</dt><dd>Stadt Ellwangen</dd>
              </dl>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

window.DaySection = DaySection;
