// Sections 1-3: Welcome, Live-Cockpit, Deutschlandkarte

// ====== Hook: count-up when in viewport ======
function useCountUp(target, duration = 1500, startTrigger = true) {
  const [val, setVal] = React.useState(0);
  React.useEffect(() => {
    if (!startTrigger) return;
    let raf;
    const start = performance.now();
    const tick = (t) => {
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(Math.round(target * eased));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, duration, startTrigger]);
  return val;
}

function useInView(ref, opts = { threshold: 0.2 }) {
  const [inView, setInView] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current || inView) return;
    const io = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) setInView(true);
    }, opts);
    io.observe(ref.current);
    return () => io.disconnect();
  }, [ref, inView]);
  return inView;
}

// ====== Section 1: Welcome Hub ======
function WelcomeSection({ firstName, scrollProgress, onNavigate }) {
  const ref = React.useRef(null);
  const seen = scrollProgress.seen;
  const total = scrollProgress.total;

  return (
    <section id="welcome" className="sect forest-bg grain" style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', padding: '120px 0 100px' }} data-screen-label="01 Welcome">
      <div className="container" style={{ position: 'relative', zIndex: 2, width: '100%' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 60, gap: 32, flexWrap: 'wrap' }}>
          <div>
            <span className="eyebrow">Vault · Persönlich für dich</span>
          </div>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.08em', color: 'rgba(248,247,242,0.55)', textAlign: 'right' }}>
            ERSTELLT AM<br />14.05.2026
          </div>
        </div>

        <h1 style={{ fontSize: 'clamp(48px, 8vw, 110px)', lineHeight: 0.96, letterSpacing: '-0.03em', marginBottom: 36, maxWidth: 1100 }}>
          Willkommen im<br />
          ROOM BOOM Vault, <span style={{ color: 'var(--lime)' }}>{firstName}</span>.
        </h1>

        <p style={{ fontSize: 'clamp(18px, 1.8vw, 22px)', maxWidth: 680, color: 'rgba(248,247,242,0.75)', lineHeight: 1.5, marginBottom: 56 }}>
          Hier findest du alles, was du wissen musst — bevor wir gemeinsam dein Franchise aufbauen.
          15 Minuten Lesezeit. Keine PDFs. Keine Sales-Tricks.
        </p>

        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(320px, 1.4fr) 1fr', gap: 32, marginBottom: 64 }} className="welcome-grid">
          {/* Loom placeholder */}
          <div style={{
            position: 'relative',
            aspectRatio: '16 / 9',
            borderRadius: 18,
            overflow: 'hidden',
            border: '1px solid var(--rule)',
            cursor: 'pointer',
            background: 'linear-gradient(135deg, #122620, #1C3A2D 50%, #25503e)',
          }}>
            <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(circle at 30% 40%, rgba(168,224,98,0.15), transparent 60%)' }} />
            {/* Faux video frame */}
            <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'flex-end', padding: 24, color: 'var(--off)' }}>
              <div>
                <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, letterSpacing: '0.1em', color: 'var(--lime)', marginBottom: 6 }}>
                  60 SEKUNDEN · MAURICE SCHOENEWOLF
                </div>
                <div style={{ fontFamily: 'Epilogue, sans-serif', fontWeight: 800, fontSize: 22 }}>
                  „Schön, dass du da bist, {firstName}."
                </div>
              </div>
            </div>
            {/* Play button */}
            <div style={{
              position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
              width: 72, height: 72, borderRadius: '50%',
              background: 'var(--lime)',
              display: 'grid', placeItems: 'center',
              boxShadow: '0 16px 40px -10px rgba(168,224,98,0.5)',
              transition: 'transform 0.25s ease',
            }}>
              <svg width="22" height="24" viewBox="0 0 22 24" fill="var(--forest-deep)" style={{ marginLeft: 4 }}>
                <path d="M0 0 L22 12 L0 24 Z" />
              </svg>
            </div>
            {/* Loom-style chip */}
            <div style={{ position: 'absolute', top: 18, left: 18, background: 'rgba(18,38,32,0.7)', backdropFilter: 'blur(8px)', padding: '6px 12px', borderRadius: 999, fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.1em', color: 'var(--off)' }}>
              ● REC · LOOM
            </div>
          </div>

          {/* Progress card */}
          <div style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid var(--rule)', borderRadius: 18, padding: 28, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 18 }}>Dein Fortschritt</div>
              <div style={{ fontFamily: 'Epilogue, sans-serif', fontWeight: 900, fontSize: 56, lineHeight: 1, marginBottom: 4 }}>
                {seen}<span style={{ color: 'rgba(248,247,242,0.4)', fontSize: 36 }}>/{total}</span>
              </div>
              <div style={{ fontSize: 13, color: 'rgba(248,247,242,0.6)', marginBottom: 22 }}>
                {seen === 0 ? 'Sektionen entdeckt' : seen === total ? 'Alle Sektionen entdeckt' : 'Sektionen entdeckt'}
              </div>
              <div style={{ height: 6, background: 'rgba(255,255,255,0.08)', borderRadius: 6, overflow: 'hidden', marginBottom: 16 }}>
                <div style={{ height: '100%', width: `${(seen / total) * 100}%`, background: 'var(--lime)', transition: 'width 0.6s ease', borderRadius: 6 }} />
              </div>
            </div>
            <div style={{ fontSize: 12, color: 'rgba(248,247,242,0.5)', lineHeight: 1.6 }}>
              Bei jeder Sektion, die du erreichst, füllt sich dieser Balken.
              Pause? Komm jederzeit zurück — der Vault merkt sich, wo du warst.
            </div>
          </div>
        </div>

        {/* Quick CTAs */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 16 }}>
          {[
            { to: 'cockpit', label: 'Starte mit dem Live-Cockpit', sub: 'Zahlen, heute, jetzt' },
            { to: 'karte', label: 'Springe zur Deutschlandkarte', sub: 'Ist deine Region frei?' },
            { to: 'businesscase', label: 'Direkt zum Business Case', sub: 'ROI-Rechner & Szenarien' },
          ].map((cta, i) => (
            <a
              key={i}
              href={`#${cta.to}`}
              onClick={(e) => { e.preventDefault(); onNavigate(cta.to); }}
              style={{
                display: 'block',
                padding: '22px 24px',
                background: 'rgba(255,255,255,0.03)',
                border: '1px solid var(--rule)',
                borderRadius: 14,
                transition: 'all 0.2s ease',
                cursor: 'pointer',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.background = 'rgba(168,224,98,0.06)'; e.currentTarget.style.borderColor = 'var(--lime)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = 'rgba(255,255,255,0.03)'; e.currentTarget.style.borderColor = 'var(--rule)'; e.currentTarget.style.transform = 'translateY(0)'; }}
            >
              <div style={{ fontSize: 11, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em', color: 'rgba(248,247,242,0.5)', marginBottom: 8 }}>
                {String(i + 1).padStart(2, '0')} · {cta.sub.toUpperCase()}
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
                <span style={{ fontWeight: 600, fontSize: 16 }}>{cta.label}</span>
                <span style={{ color: 'var(--lime)' }}>→</span>
              </div>
            </a>
          ))}
        </div>
      </div>
      <style>{`
        @media (max-width: 768px) {
          .welcome-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

// ====== Section 2: Live-Cockpit ======
function CockpitCard({ item, animate, idx }) {
  const value = useCountUp(item.value, 1400 + idx * 120, animate);
  const formatted = new Intl.NumberFormat('de-DE').format(value);
  return (
    <div className="grain" style={{
      position: 'relative',
      background: 'var(--forest)',
      border: '1px solid var(--rule)',
      borderRadius: 18,
      padding: '36px 28px',
      overflow: 'hidden',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 32, position: 'relative', zIndex: 2 }}>
        <span className="live-dot" />
        <span className="mono" style={{ fontSize: 11, letterSpacing: '0.1em', color: 'var(--lime)' }}>LIVE</span>
      </div>
      <div className="mono" style={{
        fontSize: 'clamp(48px, 5.6vw, 84px)',
        fontWeight: 700,
        lineHeight: 1,
        color: 'var(--off)',
        letterSpacing: '-0.04em',
        marginBottom: 18,
        position: 'relative', zIndex: 2,
      }}>
        {formatted}
      </div>
      <div style={{ position: 'relative', zIndex: 2 }}>
        <div style={{ fontWeight: 600, fontSize: 15, color: 'var(--off)', marginBottom: 4 }}>
          {item.label}
        </div>
        <div style={{ fontSize: 13, color: 'rgba(248,247,242,0.5)' }}>
          {item.sub}
        </div>
      </div>
    </div>
  );
}

function CockpitSection() {
  const ref = React.useRef(null);
  const inView = useInView(ref);
  const data = window.RBData.COCKPIT;
  const now = new Date().toLocaleString('de-DE', { hour: '2-digit', minute: '2-digit', day: '2-digit', month: '2-digit' });

  return (
    <section id="cockpit" className="sect forest-deep-bg grain" ref={ref} data-screen-label="02 Live-Cockpit">
      <div className="container" style={{ position: 'relative', zIndex: 2 }}>
        <div className="section-head" style={{ marginBottom: 56 }}>
          <span className="eyebrow">Sektion 02 · Live aus dem Netzwerk</span>
          <h2 style={{ color: 'var(--off)' }}>
            ROOM BOOM in Zahlen — <span style={{ color: 'var(--lime)' }}>heute, jetzt, live.</span>
          </h2>
          <p style={{ color: 'rgba(248,247,242,0.7)' }}>
            Keine geschönten Stichtags-Zahlen. Was du hier siehst, ist live aus Guesty und unserem
            Partner-System. Aktualisiert alle 6 Stunden.
          </p>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 16 }}>
          {data.map((item, i) => <CockpitCard key={i} item={item} idx={i} animate={inView} />)}
        </div>

        <div style={{ marginTop: 28, display: 'flex', flexWrap: 'wrap', gap: 16, justifyContent: 'space-between', alignItems: 'center', color: 'rgba(248,247,242,0.5)', fontSize: 12, fontFamily: 'JetBrains Mono, monospace' }}>
          <span>DATEN AUS GUESTY · SUPABASE · STRIPE</span>
          <span>LETZTE AKTUALISIERUNG: {now.toUpperCase()} UHR</span>
        </div>
      </div>
    </section>
  );
}

// ====== Section 3: Deutschlandkarte ======
function KarteSection() {
  const [hoveredLand, setHoveredLand] = React.useState(null);
  const [selectedRegion, setSelectedRegion] = React.useState('');
  const [pinModal, setPinModal] = React.useState(null);
  const [listings, setListings] = React.useState([]);
  const [heat, setHeat] = React.useState({});
  const data = window.RBData;
  React.useEffect(() => {
    let c = false;
    window.RBListings.load().then(d => {
      if (!c) { setListings(d.listings || []); setHeat(d.heat || {}); }
    });
    return () => { c = true; };
  }, []);
  const properties = listings;
  const mapPins = properties.filter(p => typeof p.lat === 'number' && typeof p.lng === 'number');
  const availability = selectedRegion ? data.REGION_AVAILABILITY[selectedRegion] : null;
  const activeBLCount = new Set(properties.map(p => p.bundesland).filter(Boolean)).size;

  const statusColor = (status) => status === 'green' ? '#A8E062' : status === 'yellow' ? '#E0C962' : '#E06B5C';
  const statusIcon = (status) => status === 'green' ? '●' : status === 'yellow' ? '◐' : '○';

  return (
    <section id="karte" className="sect" style={{ background: 'var(--off)' }} data-screen-label="03 Karte">
      <div className="container">
        <div className="section-head" style={{ marginBottom: 56 }}>
          <span className="eyebrow dark">Sektion 03 · Wo wir sind</span>
          <h2>
            {properties.length || ''} Standorte. <br />
            <span style={{ color: 'var(--forest)' }}>Eine Karte, die wächst.</span>
          </h2>
          <p>
            Klick auf einen Pin für Details. Wähle dein Bundesland unten — wir zeigen dir,
            ob deine Region noch frei ist.
          </p>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.1fr) minmax(280px, 1fr)', gap: 48, alignItems: 'start' }} className="karte-grid">
          {/* Map */}
          <div style={{ position: 'relative' }}>
            <div style={{
              background: 'var(--forest-deep)',
              border: '1px solid rgba(28,58,45,0.15)',
              borderRadius: 24,
              padding: 24,
              position: 'relative',
              overflow: 'hidden',
            }} className="grain">
              <div style={{ position: 'absolute', top: 18, left: 24, fontFamily: 'JetBrains Mono, monospace', fontSize: 11, letterSpacing: '0.1em', color: 'rgba(248,247,242,0.5)' }}>
                DEUTSCHLAND · 16 BUNDESLÄNDER · {properties.length} STANDORTE
              </div>
              <div style={{ paddingTop: 20 }}>
                <GermanyMap
                  properties={mapPins}
                  heat={heat}
                  hoveredLand={hoveredLand}
                  onLandHover={setHoveredLand}
                  onPinClick={setPinModal}
                  selectedRegion={selectedRegion}
                />
              </div>
              {/* Legend */}
              <div style={{ display: 'flex', gap: 18, alignItems: 'center', flexWrap: 'wrap', marginTop: 8, padding: '14px 16px', borderTop: '1px solid var(--rule)', color: 'rgba(248,247,242,0.55)', fontSize: 11, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.06em' }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ width: 22, height: 8, background: 'linear-gradient(90deg, #1c3a2d, #5a8847)', borderRadius: 2 }} />
                  NETZWERK-DICHTE
                </span>
                <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ width: 8, height: 8, background: 'var(--lime)', borderRadius: '50%', boxShadow: '0 0 0 2px rgba(168,224,98,0.2)' }} />
                  STANDORT
                </span>
              </div>
            </div>
          </div>

          {/* Info Panel */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20, position: 'sticky', top: 24 }}>
            {/* Region tool */}
            <div className="card" style={{ background: 'var(--forest)', color: 'var(--off)', borderColor: 'transparent' }}>
              <div className="eyebrow" style={{ marginBottom: 16 }}>Verfügbarkeits-Check</div>
              <h3 style={{ fontSize: 24, color: 'var(--off)', marginBottom: 18 }}>
                Ist deine Region noch frei?
              </h3>
              <select
                value={selectedRegion}
                onChange={e => setSelectedRegion(e.target.value)}
                style={{
                  width: '100%',
                  background: 'rgba(255,255,255,0.06)',
                  color: 'var(--off)',
                  border: '1px solid var(--rule)',
                  borderRadius: 10,
                  padding: '14px 16px',
                  fontSize: 15,
                  fontFamily: 'inherit',
                  marginBottom: 16,
                }}
              >
                <option value="">Wähle dein Bundesland...</option>
                {data.BUNDESLAENDER.map(b => <option key={b} value={b} style={{ background: '#122620' }}>{b}</option>)}
              </select>

              {availability && (
                <div style={{
                  padding: '16px 18px',
                  borderRadius: 12,
                  background: 'rgba(0,0,0,0.18)',
                  borderLeft: `3px solid ${statusColor(availability.status)}`,
                  display: 'flex', alignItems: 'flex-start', gap: 12,
                }}>
                  <span style={{ color: statusColor(availability.status), fontSize: 22, lineHeight: 1 }}>{statusIcon(availability.status)}</span>
                  <div>
                    <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, letterSpacing: '0.1em', color: statusColor(availability.status), marginBottom: 4, textTransform: 'uppercase' }}>
                      {availability.status === 'green' ? 'Frei' : availability.status === 'yellow' ? 'Begrenzt' : 'Voll'}
                    </div>
                    <div style={{ fontSize: 14, color: 'var(--off)', lineHeight: 1.4 }}>
                      {availability.label}
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* Stats */}
            <div className="card" style={{ padding: 24 }}>
              <div className="eyebrow dark" style={{ marginBottom: 16 }}>In Zahlen</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
                {[
                  { v: `${properties.length}`, l: 'Standorte' },
                  { v: `${activeBLCount}`, l: 'Bundesländer' },
                  { v: `${new Set(properties.map(p => p.type).filter(Boolean)).size}`, l: 'Objekt-Typen' },
                  { v: `${properties.reduce((a, p) => a + (p.capacity || 0), 0)}`, l: 'Gäste-Kapazität' },
                ].map((s, i) => (
                  <div key={i}>
                    <div className="mono" style={{ fontSize: 28, fontWeight: 700, color: 'var(--forest)', marginBottom: 2 }}>{s.v}</div>
                    <div style={{ fontSize: 12, color: 'var(--muted-dark)' }}>{s.l}</div>
                  </div>
                ))}
              </div>
            </div>

            <div style={{ fontSize: 12, color: 'var(--muted-dark)', lineHeight: 1.5 }}>
              Hinweis: Genaue Adressen aus Konkurrenzschutz nicht öffentlich.
              Im Erstcall mit Nils zeigen wir dir die Listings.
            </div>
          </div>
        </div>
      </div>

      {/* Pin Modal — property snapshot */}
      {pinModal && (() => {
        const palettes = [
          ['#122620', '#1C3A2D', '#5a8847'],
          ['#1C3A2D', '#25503e', '#76a85a'],
          ['#25503e', '#3d6b4e', '#a8e062'],
          ['#122620', '#2e5a3f', '#76a85a'],
        ];
        const seed = String(pinModal.id || '').split('').reduce((a, c) => a + c.charCodeAt(0), 0);
        const pal = palettes[seed % palettes.length];
        return (
        <div className="modal-backdrop" onClick={() => setPinModal(null)}>
          <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 540 }}>
            <button className="modal-close" onClick={() => setPinModal(null)}>✕</button>
            <div style={{
              aspectRatio: '16 / 9',
              background: `linear-gradient(135deg, ${pal[0]}, ${pal[1]} 60%, ${pal[2]} 130%)`,
              borderRadius: '24px 24px 0 0',
              position: 'relative',
              overflow: 'hidden',
            }}>
              {pinModal.picture && (
                <img src={pinModal.picture} alt={pinModal.name} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
              )}
              <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to bottom, rgba(18,38,32,0.1) 40%, rgba(18,38,32,0.72) 100%)' }} />
              <div style={{ position: 'absolute', top: 20, left: 24, color: 'var(--off)', fontFamily: 'JetBrains Mono, monospace', fontSize: 11, letterSpacing: '0.1em' }}>
                {String(pinModal.type || '').toUpperCase()} · LIVE
              </div>
              <div style={{ position: 'absolute', bottom: 20, left: 24, color: 'var(--off)' }}>
                <div style={{ fontFamily: 'Epilogue, sans-serif', fontWeight: 900, fontSize: 32, lineHeight: 1, marginBottom: 6 }}>{pinModal.name}</div>
                <div style={{ fontSize: 14, color: 'rgba(248,247,242,0.7)' }}>{pinModal.city}{pinModal.region ? ` · ${pinModal.region}` : ''}</div>
              </div>
            </div>
            <div style={{ padding: 32 }}>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 22 }}>
                <div>
                  <div style={{ fontSize: 10, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em', color: 'var(--muted-dark)', marginBottom: 4 }}>GÄSTE</div>
                  <div className="mono" style={{ fontSize: 20, fontWeight: 700 }}>{pinModal.capacity}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em', color: 'var(--muted-dark)', marginBottom: 4 }}>ONLINE SEIT</div>
                  <div className="mono" style={{ fontSize: 20, fontWeight: 700 }}>{pinModal.since}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em', color: 'var(--muted-dark)', marginBottom: 4 }}>SCHLAFZ.</div>
                  <div className="mono" style={{ fontSize: 20, fontWeight: 700 }}>{pinModal.bedrooms || '–'}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em', color: 'var(--muted-dark)', marginBottom: 4 }}>BÄDER</div>
                  <div className="mono" style={{ fontSize: 20, fontWeight: 700 }}>{pinModal.bathrooms || '–'}</div>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 22 }}>
                {(pinModal.tags || []).map(t => <span key={t} className="chip dark">{t}</span>)}
              </div>
              <a href="#partner" className="btn btn-ghost-dark" style={{ width: '100%', justifyContent: 'center' }} onClick={() => setPinModal(null)}>
                Alle Unterkünfte ansehen →
              </a>
            </div>
          </div>
        </div>
        );
      })()}

      <style>{`
        @media (max-width: 900px) {
          .karte-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

Object.assign(window, { WelcomeSection, CockpitSection, KarteSection, useInView, useCountUp });
