// WakeMeBot landing page — sections composed top to bottom.
// Content tuned to match what shipped: $9.99/mo or $39.99/yr, 7-day trial,
// 3 free alarms, AI suggestions from Apple + Google Calendar, five
// ElevenLabs studio voices (Mark free + four Plus). The landing page
// showcases three of the Plus voices: Cassidy, Eva, Austin.

const { useState, useRef, useEffect } = React;
const { SunDisc, Wordmark, GlassCard, AppStorePill, TextCTA, Waveform, Eyebrow,
  PhoneFrame, PhoneCalendarScreen, PhoneVoiceScreen } = window;

// ─── Shared layout helpers ────────────────────────────────────────────────
const Container = ({ children, style }) =>
  <div style={{ maxWidth: 1240, margin: '0 auto', padding: '0 32px', ...style }}>{children}</div>;


// ─── Nav ──────────────────────────────────────────────────────────────────
const Nav = () =>
  <Container style={{ paddingTop: 28, paddingBottom: 0, display: 'flex', alignItems: 'center', gap: 28 }}>
    <a href="#top" style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
      <SunDisc size={32} halo={false} hover={false} />
      <Wordmark size={20} />
    </a>
    <nav style={{ display: 'flex', gap: 28, marginLeft: 'auto',
      fontSize: 14, fontWeight: 500, color: 'var(--ink-2)' }}>
      <a href="#how">How it works</a>
      <a href="#voices">Voices</a>
      <a href="#calendar">Smart alarms</a>
      <a href="#faq">FAQ</a>
    </nav>
    <a href="#download" style={{
      fontSize: 14, fontWeight: 600, padding: '9px 16px', borderRadius: 999,
      background: 'var(--ink)', color: '#FFF6E4', letterSpacing: '-0.01em'
    }}>Download</a>
  </Container>;


// ─── 1 · Hero ─────────────────────────────────────────────────────────────
const Hero = () =>
  <Container style={{ paddingTop: 60, paddingBottom: 120, position: 'relative' }}>
    <div style={{ display: 'grid', gridTemplateColumns: '0.95fr 1.05fr', gap: 64, alignItems: 'center' }}>
      <div style={{ animation: 'wmbFloat 7s ease-in-out infinite', textAlign: 'center' }}>
        <SunDisc size={420} />
      </div>
      <div>
        <h1>
          <Wordmark size="inherit" weight={600} />
        </h1>
        <p style={{ fontSize: 34, marginTop: 22, letterSpacing: '-0.025em',
          fontWeight: 500, color: 'var(--ink)', lineHeight: 1.12, maxWidth: 540 }}>
          Alarms that<br />
          <span style={{ fontStyle: 'italic', fontWeight: 500 }}>know why.</span>
        </p>
        <p style={{ fontSize: 18, marginTop: 24, color: 'var(--ink-mute)', maxWidth: 520, lineHeight: 1.5 }}>
          WakeMeBot reads your calendar, picks the moments that matter, and wakes you
          with a voice line that names the day's anchor — not just another buzz.
        </p>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, marginTop: 36 }}>
          <AppStorePill />
          <TextCTA href="#how">How it works</TextCTA>
        </div>
        <div style={{ display: 'flex', gap: 22, marginTop: 32, color: 'var(--ink-faint)', fontSize: 13, fontWeight: 500 }}>
          <span>iOS 26 · iPhone</span>
          <span style={{ opacity: 0.5 }}>·</span>
          <span>7-day free trial of WakeMeBot Plus</span>
        </div>
      </div>
    </div>
  </Container>;


// ─── 2 · Voice prompt demo ────────────────────────────────────────────────
const VoiceDemo = () =>
  <Container style={{ paddingBottom: 140 }}>
    <GlassCard pad={56} radius={36} style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 48, alignItems: 'center' }}>
      <div>
        <Eyebrow>Just say it</Eyebrow>
        <h2 style={{ marginTop: 18 }}>Speak the reason.<br />Sleep on the rest.</h2>
        <p style={{ fontSize: 17, marginTop: 22, color: 'var(--ink-mute)', maxWidth: 480, lineHeight: 1.55 }}>
          One sentence in plain English. WakeMeBot picks the time, the tone, and
          the voice — and reads it back to you at sunrise.
        </p>

        <div style={{ marginTop: 30, display: 'flex', flexDirection: 'column', gap: 14, maxWidth: 520 }}>
          <div style={{
            alignSelf: 'flex-end', maxWidth: '88%',
            padding: '14px 18px', borderRadius: '22px 22px 6px 22px',
            background: 'var(--ink)', color: '#FFF6E4',
            fontSize: 15, lineHeight: 1.45, letterSpacing: '-0.01em',
            boxShadow: '0 10px 26px -14px rgba(42, 26, 18, 0.5)'
          }}>
            "Wake me at 7 tomorrow — I'm pitching investors at 9."
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, alignSelf: 'flex-start' }}>
            <div style={{
              padding: '14px 18px', borderRadius: '22px 22px 22px 6px',
              background: 'rgba(255,251,241,0.7)',
              boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.8)',
              fontSize: 15, lineHeight: 1.45, letterSpacing: '-0.01em',
              maxWidth: 360
            }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em',
                textTransform: 'uppercase', color: 'var(--coral)', marginBottom: 6 }}>
                Alarm · 7:00 AM
              </div>
              "Pitch deck on the table, coffee in the kitchen — board meeting in two hours."
            </div>
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'center' }}>
        <PhoneFrame width={300} height={620}>
          <PhoneVoiceScreen />
        </PhoneFrame>
      </div>
    </GlassCard>
  </Container>;


// ─── 3 · How it works ─────────────────────────────────────────────────────
const HowItWorks = () => {
  const steps = [
    { n: '01', title: 'Speak or type', body: 'Tell WakeMeBot what tomorrow holds. A flight, a pitch, a long run — anything.', glyph: '◐' },
    { n: '02', title: 'Or let AI suggest', body: 'WakeMeBot reads your calendar and proposes smart alarms for flights, pitches, and the events that actually matter.', glyph: '◍' },
    { n: '03', title: 'You wake up knowing why', body: 'No buzz. A real voice tells you the reason — out loud, the moment your eyes open.', glyph: '◔' }];

  return (
    <Container style={{ paddingBottom: 140 }}>
      <div id="how" style={{ textAlign: 'center', marginBottom: 56 }}>
        <Eyebrow>How it works</Eyebrow>
        <h2 style={{ marginTop: 18, maxWidth: 800, margin: '18px auto 0' }}>
          Three steps. None of them feel like setting an alarm.
        </h2>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 22 }}>
        {steps.map((s) =>
          <GlassCard key={s.n} pad={32} radius={28}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 500,
                letterSpacing: '0.14em', color: 'var(--coral)' }}>{s.n}</div>
              <div style={{ fontSize: 22, color: 'var(--coral)' }}>{s.glyph}</div>
            </div>
            <h3 style={{ marginTop: 28 }}>{s.title}</h3>
            <p style={{ marginTop: 14, color: 'var(--ink-mute)', fontSize: 15.5, lineHeight: 1.55, maxWidth: 320 }}>
              {s.body}
            </p>
          </GlassCard>
        )}
      </div>
    </Container>);
};


// ─── 4 · Smart calendar alarms ────────────────────────────────────────────
const CalendarSection = () =>
  <Container style={{ paddingBottom: 140 }}>
    <div id="calendar" style={{ display: 'grid', gridTemplateColumns: '1fr 0.95fr', gap: 80, alignItems: 'center' }}>
      <div>
        <Eyebrow>Smart alarms</Eyebrow>
        <h2 style={{ marginTop: 18 }}>It reads your calendar<br />so you don't have to.</h2>
        <p style={{ fontSize: 17, marginTop: 22, color: 'var(--ink-mute)', maxWidth: 480, lineHeight: 1.55 }}>
          Connect Apple Calendar or Google Calendar once. WakeMeBot suggests alarms for the events that actually matter — pitches, flights, doctor's appointments, the morning before a wedding. Approve them in a tap.
        </p>
        <ul style={{ listStyle: 'none', padding: 0, marginTop: 28, display: 'flex',
          flexDirection: 'column', gap: 14, maxWidth: 460 }}>
          {[
            ['✈', 'Travel-aware', 'Flights and trains get a longer lead time — security plus traffic.'],
            ['◐', 'Real wake-ups', "A 9 AM pitch wakes you at 7, not at 8:35 — enough time to actually wake up."],
            ['◍', 'Routine-immune', 'Skips daily standup, lunch, focus blocks. Surfaces the things that matter.']].
          map(([icon, t, d]) =>
            <li key={t} style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
              <span style={{ width: 30, height: 30, borderRadius: 8, flexShrink: 0,
                background: 'rgba(255,255,255,0.6)',
                boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.8)',
                color: 'var(--coral)', display: 'inline-flex', alignItems: 'center',
                justifyContent: 'center', fontSize: 16 }}>{icon}</span>
              <span style={{ paddingTop: 3 }}>
                <span style={{ fontWeight: 600, letterSpacing: '-0.01em' }}>{t}</span>
                <span style={{ color: 'var(--ink-mute)' }}> — {d}</span>
              </span>
            </li>
          )}
        </ul>
      </div>
      <div style={{ display: 'flex', justifyContent: 'center' }}>
        <PhoneFrame>
          <PhoneCalendarScreen />
        </PhoneFrame>
      </div>
    </div>
  </Container>;


// ─── 5 · Voice personalities ──────────────────────────────────────────────
const Voices = () => {
  // Three of the four Plus voices in the iOS app. Audio files are static
  // MP3s under /voices/ — no ElevenLabs call from the public site.
  // Drop file -> auto-detected at load time; missing file -> play button
  // hidden for that voice.
  const voices = [
    { name: 'Cassidy', tag: 'Warm & conversational', audio: '/voices/cassidy.mp3',
      sample: '"Pitch deck on the table, coffee in the kitchen — board meeting in two hours."',
      accent: '#E8732C' },
    { name: 'Eva',     tag: 'Cute robot voice',      audio: '/voices/eva.mp3',
      sample: '"Calculating optimal wake-up sequence. Coffee status: critical. Good morning, human."',
      accent: '#C95018' },
    { name: 'Austin',  tag: 'Texan cowboy',          audio: '/voices/austin.mp3',
      sample: '"Mornin’, partner. Sun’s up, coffee’s hot. Saddle up — your nine o’clock ain’t gonna wait."',
      accent: '#C98B2B' }];

  const [playing, setPlaying] = useState(null);     // currently-playing voice name
  const [available, setAvailable] = useState({});   // { [name]: bool } once HEAD probe completes
  const audioRefs = useRef({});

  // Probe each MP3 on mount. If the file 404s (e.g. user hasn't uploaded
  // it yet), hide the play button for that voice. Avoids broken play UI.
  useEffect(() => {
    let cancelled = false;
    Promise.all(voices.map((v) =>
      fetch(v.audio, { method: 'HEAD' })
        .then((r) => [v.name, r.ok])
        .catch(() => [v.name, false])
    )).then((pairs) => {
      if (cancelled) return;
      setAvailable(Object.fromEntries(pairs));
    });
    return () => { cancelled = true; };
  }, []);

  const toggle = (name) => {
    const el = audioRefs.current[name];
    if (!el) return;
    if (playing && playing !== name) {
      const other = audioRefs.current[playing];
      if (other) { other.pause(); other.currentTime = 0; }
    }
    if (playing === name) {
      el.pause();
      el.currentTime = 0;
      setPlaying(null);
    } else {
      el.play().then(() => setPlaying(name)).catch(() => setPlaying(null));
    }
  };

  return (
    <Container style={{ paddingBottom: 140 }}>
      <div id="voices" style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
        gap: 32, marginBottom: 40, flexWrap: 'wrap' }}>
        <div>
          <Eyebrow>Pick a voice</Eyebrow>
          <h2 style={{ marginTop: 18 }}>Studio voices.<br />Not stock library.</h2>
        </div>
        <p style={{ fontSize: 16, color: 'var(--ink-mute)', maxWidth: 360, lineHeight: 1.55 }}>
          Four studio voices on Plus, with more arriving over the next few releases. Or stay with Mark, our clean wake-up voice on the free tier.
        </p>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 18 }}>
        {voices.map((v) => {
          const canPlay = available[v.name];
          const isPlaying = playing === v.name;
          return (
            <GlassCard key={v.name} pad={26} radius={24}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 500,
                  letterSpacing: '0.12em', textTransform: 'uppercase', color: v.accent }}>{v.tag}</div>
                {canPlay && (
                  <button onClick={() => toggle(v.name)} style={{
                    width: 36, height: 36, borderRadius: '50%', border: 'none', cursor: 'pointer',
                    background: v.accent, color: '#FFF6E4',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    boxShadow: '0 8px 16px -6px rgba(184, 63, 24, 0.55)'
                  }} aria-label={`${isPlaying ? 'Pause' : 'Play'} ${v.name} sample`}>
                    {isPlaying ? (
                      <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
                        <rect x="2" y="1" width="3" height="10" />
                        <rect x="7" y="1" width="3" height="10" />
                      </svg>
                    ) : (
                      <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
                        <path d="M2 1l9 5-9 5z" />
                      </svg>
                    )}
                  </button>
                )}
              </div>
              <h3 style={{ marginTop: 18, fontSize: 26 }}>{v.name}</h3>
              <p style={{ marginTop: 10, color: 'var(--ink-mute)', fontSize: 14, lineHeight: 1.5, minHeight: 80 }}>
                {v.sample}
              </p>
              <Waveform bars={22} height={28} color={v.accent} />
              {canPlay && (
                <audio
                  ref={(el) => { audioRefs.current[v.name] = el; }}
                  src={v.audio}
                  preload="none"
                  onEnded={() => setPlaying(null)}
                />
              )}
            </GlassCard>
          );
        })}
      </div>
      <p style={{ marginTop: 22, color: 'var(--ink-faint)', fontSize: 13, textAlign: 'center' }}>
        More voices coming soon.
      </p>
    </Container>);
};


// ─── 6 · FAQ ──────────────────────────────────────────────────────────────
const FAQItem = ({ q, a, defaultOpen = false }) => {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div style={{ borderTop: '0.5px solid var(--hair)' }}>
      <button onClick={() => setOpen(!open)} style={{
        width: '100%', textAlign: 'left', padding: '24px 4px', cursor: 'pointer',
        background: 'transparent', border: 'none', display: 'flex', alignItems: 'center',
        justifyContent: 'space-between', gap: 24, color: 'var(--ink)'
      }}>
        <span style={{ fontSize: 19, fontWeight: 500, letterSpacing: '-0.02em' }}>{q}</span>
        <span style={{ flexShrink: 0, width: 28, height: 28, borderRadius: '50%',
          background: open ? 'var(--ink)' : 'rgba(255,255,255,0.55)',
          color: open ? '#FFF6E4' : 'var(--ink)',
          boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.7)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 18, lineHeight: 1, transform: open ? 'rotate(45deg)' : 'none',
          transition: 'all 180ms ease' }}>+</span>
      </button>
      {open &&
        <div style={{ paddingBottom: 24, paddingRight: 60, color: 'var(--ink-mute)',
          fontSize: 16, lineHeight: 1.6, letterSpacing: '-0.005em' }}>
          {a}
        </div>
      }
    </div>);
};
const FAQ = () =>
  <Container style={{ paddingBottom: 140, maxWidth: 880 }}>
    <div id="faq" style={{ textAlign: 'center', marginBottom: 40 }}>
      <Eyebrow>FAQ</Eyebrow>
      <h2 style={{ marginTop: 18 }}>Common questions.</h2>
    </div>
    <div style={{ borderBottom: '0.5px solid var(--hair)' }}>
      <FAQItem defaultOpen
        q="Does WakeMeBot work when the app is closed?"
        a="Yes. Alarms are delivered through Apple's notification system so they fire even when the app isn't running. The first time you set one, iOS asks for notification permission — grant it once and you're set." />
      <FAQItem
        q="Will it work without my calendar?"
        a="Yes — you can set alarms manually like any clock app. Connecting Apple or Google Calendar adds the AI suggestions on top." />
      <FAQItem
        q="What happens to my calendar data?"
        a="Event titles, times, and locations briefly flow through our private server to generate the suggestion + wake line, then they're gone. They're never sold, never used to train AI models, and never stored on our servers beyond a tiny per-event decision cache. Full detail on the privacy page." />
      <FAQItem
        q="How much does it cost?"
        a="Free for up to 3 active alarms with Mark, our clean wake-up voice. WakeMeBot Plus is $9.99/month or $39.99/year (with a 7-day free trial) and unlocks unlimited alarms, the AI calendar suggestions, and four additional studio-quality wake-up voices." />
      <FAQItem
        q="Android?"
        a="Not yet — iOS only for now." />
    </div>
  </Container>;


// ─── 7 · Final CTA + footer ───────────────────────────────────────────────
const FinalCTA = () =>
  <Container style={{ paddingBottom: 100 }}>
    <div id="download" style={{
      position: 'relative', overflow: 'hidden',
      borderRadius: 40, padding: '80px 56px', textAlign: 'center',
      background: 'linear-gradient(180deg, #FFD7A8 0%, #F0A055 40%, #E8732C 100%)',
      boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.6), 0 30px 60px -24px rgba(184, 63, 24, 0.4)',
      color: 'var(--ink)'
    }}>
      <div style={{ position: 'absolute', top: -120, left: '50%', transform: 'translateX(-50%)', opacity: 0.85 }}>
        <SunDisc size={260} hover />
      </div>
      <div style={{ marginTop: 80 }}>
        <h2 style={{ fontSize: 'clamp(38px, 5vw, 64px)' }}>Tomorrow morning,<br />you'll know why you're up.</h2>
        <div style={{ display: 'inline-flex', gap: 12, marginTop: 32, flexWrap: 'wrap', justifyContent: 'center' }}>
          <AppStorePill />
          <TextCTA href="#voices" arrow={false}>Listen to voices</TextCTA>
        </div>
        <div style={{ marginTop: 24, fontSize: 13, color: 'rgba(42,26,18,0.65)' }}>
          Free up to 3 alarms · Plus from $9.99/mo · 7-day free trial · iOS 26+
        </div>
      </div>
    </div>
  </Container>;


const Footer = () =>
  <Container style={{ paddingBottom: 56 }}>
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      gap: 24, flexWrap: 'wrap',
      padding: '32px 0', borderTop: '0.5px solid var(--hair)',
      fontSize: 13, color: 'var(--ink-mute)' }}>
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
        <SunDisc size={22} halo={false} hover={false} />
        <Wordmark size={15} />
        <span style={{ marginLeft: 6, opacity: 0.7 }}>© 2026</span>
      </div>
      <nav style={{ display: 'flex', gap: 22 }}>
        <a href="/privacy">Privacy</a>
        <a href="/terms">Terms</a>
        <a href="/support">Support</a>
        <a href="mailto:hello@wakemebot.app">hello@wakemebot.app</a>
      </nav>
    </div>
  </Container>;


// ─── Page ─────────────────────────────────────────────────────────────────
const LandingPage = () =>
  <main id="top">
    <Nav />
    <Hero />
    <VoiceDemo />
    <HowItWorks />
    <CalendarSection />
    <Voices />
    <FAQ />
    <FinalCTA />
    <Footer />
  </main>;


window.LandingPage = LandingPage;
