// Main app: login screen, sidebar, mobile header, sections, floating CTA

const { useState, useEffect, useRef } = React;

function LoginScreen({ onUnlock, prefillName, token }) {
  const [pw, setPw] = useState('');
  const [shake, setShake] = useState(false);
  const [unlocking, setUnlocking] = useState(false);
  const [err, setErr] = useState('');

  const fail = (msg) => {
    setErr(msg);
    setUnlocking(false);
    setShake(true);
    setTimeout(() => setShake(false), 400);
  };

  const submit = async (e) => {
    e.preventDefault();
    setErr('');
    if (pw.trim().length === 0) { fail('Bitte gib dein Passwort ein.'); return; }
    if (!token) {
      fail('Kein gültiger Zugang. Bitte öffne den persönlichen Link aus deiner E-Mail.');
      return;
    }
    setUnlocking(true);
    try {
      const res = await fetch('/api/login', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ token, password: pw }),
      });
      if (!res.ok) { fail('Passwort falsch. Bitte prüfe deine Zugangs-E-Mail.'); return; }
      const data = await res.json();
      setTimeout(() => onUnlock(data.name), 600);
    } catch {
      fail('Verbindung fehlgeschlagen. Bitte versuch es gleich nochmal.');
    }
  };

  return (
    <div className="login-screen">
      <div className="login-bg-glow" />
      <div className="login-card" style={{ animation: shake ? 'shake 0.4s ease' : undefined, opacity: unlocking ? 0 : 1, transition: 'opacity 0.5s ease' }}>
        {/* Logo mark */}
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 12, marginBottom: 36 }}>
          <div style={{ width: 48, height: 48, background: 'var(--lime)', color: 'var(--forest-deep)', borderRadius: 12, display: 'grid', placeItems: 'center', fontFamily: 'Epilogue, sans-serif', fontWeight: 900, fontSize: 22 }}>RB</div>
          <div style={{ textAlign: 'left' }}>
            <div style={{ fontFamily: 'Epilogue, sans-serif', fontWeight: 900, fontSize: 17, letterSpacing: '-0.01em' }}>ROOM BOOM</div>
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.1em', color: 'rgba(248,247,242,0.5)' }}>VAULT · V1.0</div>
          </div>
        </div>

        <h1>Willkommen{prefillName ? `, ${prefillName}` : ''}.</h1>
        <p>
          Bitte gib das Passwort ein, das du per E-Mail erhalten hast.
        </p>

        <form onSubmit={submit}>
          <input
            type="password"
            className="login-input"
            placeholder="Vault-Passwort"
            value={pw}
            onChange={e => setPw(e.target.value)}
            autoFocus
          />
          <button type="submit" className="btn btn-lime" style={{ width: '100%', justifyContent: 'center', padding: '16px 22px' }}>
            {unlocking ? 'Öffne Vault…' : 'Vault öffnen →'}
          </button>
        </form>

        <div className="footer-note">
          Kein Passwort? Schreib Nils auf WhatsApp: <a href="#">+49 173 ···</a>
        </div>

        {err && (
          <div style={{ marginTop: 18, fontSize: 13, color: '#E06B5C', lineHeight: 1.4 }}>
            {err}
          </div>
        )}
      </div>
      <style>{`
        @keyframes shake {
          0%, 100% { transform: translateX(0); }
          25% { transform: translateX(-8px); }
          75% { transform: translateX(8px); }
        }
      `}</style>
    </div>
  );
}

function Sidebar({ active, visited, total, onNavigate }) {
  const sections = window.RBData.SECTIONS;
  return (
    <aside className="sidebar grain">
      <div className="sidebar-logo">
        <div className="mark">RB</div>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <span>ROOM BOOM</span>
          <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, letterSpacing: '0.1em', color: 'rgba(248,247,242,0.5)', fontWeight: 400 }}>VAULT</span>
        </div>
      </div>

      <nav>
        {sections.map(s => (
          <a
            key={s.id}
            href={`#${s.id}`}
            onClick={(e) => { e.preventDefault(); onNavigate(s.id); }}
            className={[active === s.id ? 'active' : '', visited.has(s.id) ? 'visited' : ''].join(' ')}
          >
            <span className="num">{s.num}</span>
            <span style={{ flex: 1 }}>{s.label}</span>
            <span className="check">✓</span>
          </a>
        ))}
      </nav>

      <div className="sidebar-progress">
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <span style={{ fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em' }}>FORTSCHRITT</span>
          <span className="mono">{visited.size}/{total}</span>
        </div>
        <div className="bar"><div className="fill" style={{ width: `${(visited.size / total) * 100}%` }} /></div>
      </div>
    </aside>
  );
}

function MobileHeader({ onOpenMenu, visited, total }) {
  return (
    <header className="mobile-header">
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 28, height: 28, background: 'var(--lime)', color: 'var(--forest-deep)', borderRadius: 8, display: 'grid', placeItems: 'center', fontFamily: 'Epilogue, sans-serif', fontWeight: 900, fontSize: 12 }}>RB</div>
        <div style={{ fontFamily: 'Epilogue, sans-serif', fontWeight: 900, fontSize: 14 }}>ROOM BOOM VAULT</div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: 'rgba(248,247,242,0.6)' }}>{visited.size}/{total}</span>
        <button onClick={onOpenMenu} style={{ width: 36, height: 36, borderRadius: 8, background: 'rgba(255,255,255,0.06)', color: 'var(--off)', display: 'grid', placeItems: 'center' }}>
          <svg width="18" height="14" viewBox="0 0 18 14"><path d="M0 1 H18 M0 7 H18 M0 13 H18" stroke="currentColor" strokeWidth="1.5" /></svg>
        </button>
      </div>
    </header>
  );
}

function MobileMenu({ open, onClose, onNavigate, visited, active }) {
  const sections = window.RBData.SECTIONS;
  if (!open) return null;
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 80,
      background: 'var(--forest-deep)', color: 'var(--off)',
      display: 'flex', flexDirection: 'column',
      padding: 24,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 36 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 32, height: 32, background: 'var(--lime)', color: 'var(--forest-deep)', borderRadius: 8, display: 'grid', placeItems: 'center', fontFamily: 'Epilogue, sans-serif', fontWeight: 900, fontSize: 14 }}>RB</div>
          <div style={{ fontFamily: 'Epilogue, sans-serif', fontWeight: 900, fontSize: 16 }}>VAULT</div>
        </div>
        <button onClick={onClose} style={{ width: 40, height: 40, borderRadius: 10, background: 'rgba(255,255,255,0.06)', color: 'var(--off)', display: 'grid', placeItems: 'center', fontSize: 18 }}>✕</button>
      </div>
      <nav style={{ display: 'flex', flexDirection: 'column', gap: 4, flex: 1 }}>
        {sections.map(s => (
          <a
            key={s.id}
            href={`#${s.id}`}
            onClick={(e) => { e.preventDefault(); onNavigate(s.id); onClose(); }}
            style={{
              display: 'flex', alignItems: 'center', gap: 14,
              padding: '16px 14px',
              borderRadius: 12,
              background: active === s.id ? 'rgba(168,224,98,0.08)' : 'transparent',
              color: active === s.id ? 'var(--lime)' : (visited.has(s.id) ? 'var(--off)' : 'rgba(248,247,242,0.6)'),
              borderLeft: active === s.id ? '2px solid var(--lime)' : '2px solid transparent',
            }}
          >
            <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 12, opacity: 0.6, minWidth: 22 }}>{s.num}</span>
            <span style={{ flex: 1, fontSize: 16 }}>{s.label}</span>
            {visited.has(s.id) && <span style={{ color: 'var(--lime)', fontSize: 12 }}>✓</span>}
          </a>
        ))}
      </nav>
    </div>
  );
}

function FloatingCTA({ onClick, hidden }) {
  return (
    <button
      className={`floating-cta ${hidden ? 'hidden' : ''}`}
      onClick={onClick}
      data-track="booking"
      data-track-label="floating-cta"
    >
      <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor"><circle cx="7" cy="7" r="6" fill="none" stroke="currentColor" strokeWidth="1.5" /><path d="M7 3 V7 L10 9" stroke="currentColor" strokeWidth="1.5" fill="none" /></svg>
      Call mit Nils buchen
      <span style={{ marginLeft: 2 }}>→</span>
    </button>
  );
}

function App() {
  const bootToken = (typeof window !== 'undefined' && window.__RB_TOKEN__) || '';
  const bootName = (typeof window !== 'undefined' && window.__RB_NAME__) || '';

  const [unlocked, setUnlocked] = useState(false);
  const [firstName, setFirstName] = useState(bootName || 'Maurice');
  const [active, setActive] = useState('welcome');
  const [visited, setVisited] = useState(new Set(['welcome']));
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [ctaHidden, setCtaHidden] = useState(false);

  const sections = window.RBData.SECTIONS;
  const total = sections.length;

  const beginSession = (name) => {
    if (name) setFirstName(name);
    setUnlocked(true);
    if (window.RBTrack && bootToken) window.RBTrack.start(bootToken);
  };

  // Auto-unlock returning visitors that still have a valid session cookie
  useEffect(() => {
    let cancelled = false;
    fetch('/api/me')
      .then(r => (r.ok ? r.json() : null))
      .then(d => { if (!cancelled && d && d.name) beginSession(d.name); })
      .catch(() => {});
    return () => { cancelled = true; };
  }, []);

  // Intersection observer to track which section is active and visited
  useEffect(() => {
    if (!unlocked) return;
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const id = entry.target.id;
            setActive(id);
            setVisited(prev => {
              if (prev.has(id)) return prev;
              const next = new Set(prev);
              next.add(id);
              return next;
            });
            // Hide CTA when in last section
            setCtaHidden(id === 'nextstep');
          }
        });
      },
      { threshold: 0.35, rootMargin: '-100px 0px -50% 0px' }
    );

    sections.forEach(s => {
      const el = document.getElementById(s.id);
      if (el) observer.observe(el);
    });
    return () => observer.disconnect();
  }, [unlocked]);

  const navigate = (id) => {
    const el = document.getElementById(id);
    if (el) {
      el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

  if (!unlocked) {
    return <LoginScreen onUnlock={beginSession} prefillName={firstName} token={bootToken} />;
  }

  return (
    <div className="vault-enter">
      <Sidebar active={active} visited={visited} total={total} onNavigate={navigate} />
      <MobileHeader onOpenMenu={() => setMobileMenuOpen(true)} visited={visited} total={total} />
      <MobileMenu open={mobileMenuOpen} onClose={() => setMobileMenuOpen(false)} onNavigate={navigate} visited={visited} active={active} />

      <main className="main">
        <WelcomeSection
          firstName={firstName}
          scrollProgress={{ seen: visited.size, total }}
          onNavigate={navigate}
        />
        <CockpitSection />
        <KarteSection />
        <PropertiesSection />
        <BusinessCaseSection />
        <ProzessSection />
        <TeamSection />
        <AufgabenSection />
        <FAQsSection />
        <DownloadsSection />
        <NextStepSection firstName={firstName} />
      </main>

      <FloatingCTA onClick={() => navigate('nextstep')} hidden={ctaHidden} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
