/* global React */
const { useState: useStateS, useEffect: useEffectS, useRef: useRefS } = React;

/* shared viewport hook for scaling the heavy MacBook/island scenes responsively */
function useViewportWidth() {
  const [vw, setVw] = useStateS(typeof window !== 'undefined' ? window.innerWidth : 1200);
  useEffectS(() => {
    let raf = null;
    const onResize = () => {
      if (raf) return;
      raf = window.requestAnimationFrame(() => {
        raf = null;
        setVw(window.innerWidth);
      });
    };
    window.addEventListener('resize', onResize, { passive: true });
    return () => window.removeEventListener('resize', onResize);
  }, []);
  return vw;
}

/* ============================================================
   HOMEPAGE SECTIONS — 10 total
   ============================================================ */

/* ---------- 1. NAV ---------- */
function Navbar({ theme, setTheme, density, setDensity, lang, setLang }) {
  const [scrolled, setScrolled] = useStateS(false);
  const { t } = useT();
  useEffectS(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="container nav-inner">
        <a href="#top" className="nav-brand">
          <img src="assets/vibepet-logo.png" alt="VibePet" className="brand-logo-img" />
          <span className="brand-word">VibePet</span>
        </a>
        <div className="nav-links">
          <a href="#pets">{t('nav.pets')}</a>
          <a href="#sounds">{t('nav.sounds')}</a>
          <SocialLinks variant="icons" />
          <span className="nav-sep" />
          <div className="lang-toggle" role="group" aria-label="Language">
            <button
              className={`lang-btn ${lang === 'en' ? 'active' : ''}`}
              onClick={() => setLang('en')}
              aria-pressed={lang === 'en'}>EN</button>
            <button
              className={`lang-btn ${lang === 'zh' ? 'active' : ''}`}
              onClick={() => setLang('zh')}
              aria-pressed={lang === 'zh'}>中</button>
          </div>
          <button
            className="nav-icon-btn"
            onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
            aria-label="Toggle theme"
            title={`Switch to ${theme === 'dark' ? 'light' : 'dark'}`}>
            
            {theme === 'dark' ?
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4">
                <circle cx="8" cy="8" r="3" />
                <path d="M8 1v2M8 13v2M1 8h2M13 8h2M2.8 2.8l1.4 1.4M11.8 11.8l1.4 1.4M2.8 13.2l1.4-1.4M11.8 4.2l1.4-1.4" />
              </svg> :

            <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                <path d="M9 1a7 7 0 1 0 6 10.4A6 6 0 0 1 9 1z" />
              </svg>
            }
          </button>
          <a
            href="https://download.vibepet.ai/latest/vibepet-macos-arm64.dmg"
            className="btn btn-primary nav-cta"
            download>{t('nav.download')}</a>
        </div>
      </div>
    </nav>);

}

/* ---------- 2. HERO ---------- */
function Hero({ capsuleShape, heroCopy }) {
  const { t } = useT();
  const vw = useViewportWidth();
  // Hero scene is 1040 wide by default; scale to fit the viewport (container padding is 24/32px).
  const heroAvail = Math.max(280, Math.min(vw - 32, 1080));
  const heroScale = Math.min(1, heroAvail / 1040);
  const copies = {
    a: {
      h1: [t('hero.titleA1'), " ", <span key="alive" className="hero-accent">{t('hero.titleA2')}</span>],
      sub: t('hero.subA')
    },
    b: {
      h1: [t('hero.titleB1'), <br key="br" />, <span key="agents" className="hero-accent">{t('hero.titleB2')}</span>],
      sub: t('hero.subB')
    },
    c: {
      h1: [t('hero.titleC1'), <br key="br" />, <span key="rest" className="hero-accent">{t('hero.titleC2')}</span>],
      sub: t('hero.subC')
    }
  };
  const copy = copies[heroCopy] || copies.a;

  return (
    <section className="s hero" id="top">
      <div className="container">
        <h1 className="h-hero hero-h1">{copy.h1}</h1>
        <p className="sub hero-sub">{copy.sub}</p>

        <div className="hero-cta row gap-3 flex-wrap items-center">
          <DownloadCommand variant="dmg" primary label={t('hero.download')} />
        </div>

        <div className="hero-meta row gap-6 mono">
          <div className="row items-center gap-2"><span className="dot mint" /><span>{t('hero.stat.mem')}</span></div>
          <div className="row items-center gap-2"><span className="dot blue" /><span>{t('hero.stat.cpu')}</span></div>
        </div>

        <div className="hero-stage hero-stage-hifi">
          <HfMacBookScene
            width={1040}
            height={640}
            scale={heroScale}
            islandState="running"
            caption={t('hero.caption')}
            variant="pet+ticker"
            showChips={true}
            hoverEnabled={true}
            demo={true} />
          
          <div className="hero-stage-caption mono muted">
            <span className="dot blue" />
            {t('hero.hint')}
          </div>
        </div>
      </div>
    </section>);

}

/* ---------- 3. CHAOS → CALM ---------- */
function ChaosToCalm() {
  const { t } = useT();
  const vw = useViewportWidth();
  // HfExpandedIsland is 540px wide. Scale down when the available column is narrower.
  const chaosAvail = vw < 980 ? Math.max(280, vw - 48) : Math.max(360, Math.min(560, (vw - 96) / 2));
  const calmScale = Math.min(1, chaosAvail / 560);
  const cards = [
  { tool: 'claude-code', status: 'waitingInput', title: t('chaos.card.1.title'), body: t('chaos.card.1.body'), time: "32s", angle: -6, x: -8, y: -10 },
  { tool: 'codex', status: 'rateLimit', title: t('chaos.card.2.title'), body: t('chaos.card.2.body'), time: "1m", angle: 4, x: 4, y: -16 },
  { tool: 'gemini', status: 'error', title: t('chaos.card.3.title'), body: t('chaos.card.3.body'), time: "2m", angle: -3, x: -12, y: 14 },
  { tool: 'cursor', status: 'done', title: t('chaos.card.4.title'), body: t('chaos.card.4.body'), time: "4m", angle: 5, x: 10, y: 6 },
  { tool: 'factory', status: 'done', title: t('chaos.card.5.title'), body: t('chaos.card.5.body'), time: "7m", angle: -2, x: -2, y: 22 },
  { tool: 'opencode', status: 'waitingInput', title: t('chaos.card.6.title'), body: t('chaos.card.6.body'), time: "9m", angle: 3, x: 14, y: -2 }];


  return (
    <section className="s chaos">
      <div className="container">
        <SectionHeading
          eyebrow={t('chaos.eyebrow')}
          title={<>{t('chaos.title.pre')} <span className="muted-strike">{t('chaos.title.zero')}</span> {t('chaos.title.post')}</>}
          sub={t('chaos.sub')} />
        

        <div className="chaos-stage">
          <div className="chaos-left">
            <div className="chaos-label mono muted"><span className="dot coral" /> {t('chaos.left')}</div>
            <div className="chaos-cards">
              {cards.map((c, i) =>
              <div
                key={i}
                className="chaos-card-pos"
                style={{
                  transform: `translate(${c.x}px, ${c.y}px) rotate(${c.angle}deg)`,
                  animationDelay: `${i * 0.12}s`
                }}>
                
                  <MessageCard tool={c.tool} status={c.status} title={c.title} body={c.body} time={c.time} drift />
                </div>
              )}
            </div>
          </div>

          <div className="chaos-arrow mono muted" aria-hidden="true">
            <div className="chaos-arrow-line" />
            <div className="chaos-arrow-word">{t('chaos.arrow')}</div>
            <div className="chaos-arrow-line" />
          </div>

          <div className="chaos-right">
            <div className="chaos-label mono muted"><span className="dot mint" /> {t('chaos.right')}</div>
            <div className="chaos-right-stage">
              <div
                className="chaos-calm-scaler"
                style={{
                  '--calm-scale': calmScale,
                  width: `calc(540px * var(--calm-scale))`,
                }}>
                <div className="chaos-calm-inner">
                  <HfExpandedIsland headerState="approval" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

/* ---------- 4. HOW IT WORKS + FOOTPRINT ---------- */
function HowItWorks() {
  const { t } = useT();
  const vw = useViewportWidth();
  // On desktop the 3-col grid gives each card ~340px; on mobile a single column gets ~full container.
  // Mini scene natural width is 520; pick a scale so it fits the column.
  let howScale = 0.62;
  if (vw < 900) howScale = Math.min(0.72, Math.max(0.42, (vw - 64) / 520));
  const steps = [
  {
    n: "01",
    title: t('how.01.title'),
    body: t('how.01.body'),
    state: "idle",
    expanded: false,
    caption: t('how.01.caption')
  },
  {
    n: "02",
    title: t('how.02.title'),
    body: t('how.02.body'),
    state: "rate",
    expanded: false,
    caption: t('how.02.caption')
  },
  {
    n: "03",
    title: t('how.03.title'),
    body: t('how.03.body'),
    state: "approval",
    expanded: true,
    caption: t('how.03.caption')
  }];


  return (
    <section className="s how" id="how">
      <div className="container">
        <SectionHeading
          eyebrow={t('how.eyebrow')}
          title={t('how.title')}
          sub={t('how.sub')} />

        <div className="how-grid hifi">
          {steps.map((s) =>
          <div key={s.n} className="how-step hifi">
              <div className="how-step-head mono muted">{s.n} · {s.title}</div>
              <div className="how-step-stage hifi" data-expanded={s.expanded}>
                <HfMacBookScene
                width={520}
                height={s.expanded ? 560 : 320}
                scale={howScale}
                size="mini"
                islandState={s.state}
                defaultExpanded={s.expanded}
                hoverEnabled={false}
                showChips={false}
                caption={s.caption}
                showDock={!s.expanded}
                showCodeWindow={!s.expanded}
                variant="pet+ticker" />
              
              </div>
              <div className="how-step-body">{s.body}</div>
            </div>
          )}
        </div>

        <div className="footprint-strip">
          <FootprintStat n="< 60" unit="MB" label={t('how.footprint.mem')} tint="mint" />
          <FootprintStat n="< 0.5" unit="%" label={t('how.footprint.cpu')} tint="blue" />
          <FootprintStat n="1" unit="binary" label={t('how.footprint.binary')} tint="purple" />
        </div>
      </div>
    </section>);

}

function FootprintStat({ n, unit, label, tint }) {
  return (
    <div className="footprint-stat">
      <div className="footprint-n">
        <span className="footprint-num" style={{ color: `var(--accent-${tint})` }}>{n}</span>
        <span className="footprint-unit mono">{unit}</span>
      </div>
      <div className="footprint-label">{label}</div>
    </div>);

}

/* ---------- 5. EIGHT TOOLS ---------- */
function EightTools() {
  const [hovered, setHovered] = useStateS(null);
  const { t } = useT();
  const examples = {
    "claude-code": { status: "waitingInput", title: "Edit src/db.ts · 3 lines", body: "Approve write to project root?", time: "27s ago" },
    "codex": { status: "rateLimit", title: "Quota cooldown · 6 min", body: "27 messages queued. Resume at 15:30.", time: "2m ago" },
    "cursor": { status: "done", title: "Review ready", body: "6 files · 3 suggestions, 1 risk.", time: "4m ago" },
    "gemini": { status: "error", title: "Auth expired", body: "Re-authorize gemini-cli.", time: "12m ago" },
    "trae": { status: "running", title: "Planning step 4/9", body: "Drafting migration plan.", time: "now" },
    "copilot-cli": { status: "done", title: "Completion accepted", body: "Inserted in pkg/server/index.ts.", time: "1m ago" },
    "factory": { status: "running", title: "Droid running · feat/onboard", body: "17 commits · 4 tests passing.", time: "now" },
    "opencode": { status: "waitingInput", title: "Shell write requested", body: "Allow writes to ~/.config/?", time: "8m ago" }
  };
  const activeTool = hovered || "claude-code";
  const ex = examples[activeTool];

  return (
    <section className="s tools" id="tools">
      <div className="container">
        <SectionHeading
          eyebrow={t('tools.eyebrow')}
          title={t('tools.title')}
          sub={t('tools.sub')} />
        

        <div className="tools-layout">
          <div className="tools-grid">
            {TOOL_KEYS.map((key) =>
            <button
              key={key}
              className={`tool-tile ${hovered === key ? 'active' : ''}`}
              onMouseEnter={() => setHovered(key)}
              onFocus={() => setHovered(key)}
              onMouseLeave={() => setHovered(null)}>
              
                <div className="tool-tile-head">
                  <span className="tool-mark lg" style={{ background: TOOLS[key].tint }}>
                    {TOOLS[key].icon
                      ? <img src={TOOLS[key].icon} alt="" />
                      : <span style={{ color: textForBg(TOOLS[key].tint) }}>{TOOLS[key].mark}</span>}
                  </span>
                  <span className={`dot ${
                examples[key].status === 'running' ? 'mint' :
                examples[key].status === 'error' ? 'coral' :
                examples[key].status === 'rateLimit' ? 'amber' :
                examples[key].status === 'waitingInput' ? 'coral' : 'mint'}`
                } />
                </div>
                <div className="tool-tile-name">{TOOLS[key].name}</div>
                <div className="tool-tile-purpose mono muted">{t(`tools.purpose.${key}`)}</div>
              </button>
            )}
          </div>

          <aside className="tools-preview">
            <div className="tools-preview-head mono muted">
              {hovered ? t('tools.preview.active') : t('tools.preview.idle')}
            </div>
            <div className="tools-preview-stage">
              <MessageCard
                tool={activeTool}
                status={ex.status}
                title={ex.title}
                body={ex.body}
                time={ex.time} />
              
            </div>
            <div className="tools-preview-foot mono muted">
              {t('tools.footer')}
            </div>
          </aside>
        </div>
      </div>
    </section>);

}

/* ---------- 6. PET PERSONALITY ---------- */
function PetPersonality() {
  const { t } = useT();
  const states = [
  { key: "idle", label: t('pets.state.idle'), tint: "mint", pet: "capy" },
  { key: "running", label: t('pets.state.running'), tint: "mint", pet: "capy" },
  { key: "waitingInput", label: t('pets.state.waitingInput'), tint: "coral", pet: "capy" },
  { key: "approval", label: t('pets.state.approval'), tint: "coral", pet: "capy" },
  { key: "review", label: t('pets.state.review'), tint: "blue", pet: "capy" },
  { key: "rateLimit", label: t('pets.state.rateLimit'), tint: "amber", pet: "capy" },
  { key: "error", label: t('pets.state.error'), tint: "coral", pet: "capy" },
  { key: "sleeping", label: t('pets.state.sleeping'), tint: "purple", pet: "capy" }];


  return (
    <section className="s pets" id="pets">
      <div className="container">
        <SectionHeading
          eyebrow={t('pets.eyebrow')}
          title={t('pets.title')}
          sub={t('pets.sub')} />
        

        <div className="pets-grid">
          {states.map((s) =>
          <div key={s.key} className="pet-state-card">
              <div className="pet-state-stage">
                <PetSprite pet={s.pet} state={s.key} size={88} hoverState={s.key === 'idle' ? 'running' : 'idle'} />
              </div>
              <div className="pet-state-name pixel">{s.label}</div>
              <div className="row items-center gap-2 pet-state-meta">
                <span className={`dot ${s.tint}`} />
                <span className="mono muted" style={{ fontSize: 11 }}>{s.key}</span>
              </div>
            </div>
          )}
        </div>

        <div className="pets-foot hatch-foot">
          <div className="hatch-form">
            <span className="hatch-prefix mono">{t('pets.hatch.prefix')}</span>
            <input
              type="text"
              className="hatch-input"
              defaultValue={t('pets.hatch.value')}
              spellCheck={false} />
            
            <button className="btn btn-primary hatch-cta">
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round">
                <path d="M3.5 7l3 3 4-6" />
              </svg>
              {t('pets.hatch.cta')}
            </button>
          </div>
          <div className="hatch-meta mono muted">
            <span className="dot mint" />
            {t('pets.hatch.meta1')} <a href="#docs" className="hatch-link">{t('pets.hatch.meta.link')}</a> {t('pets.hatch.meta2')}
          </div>
        </div>
      </div>
    </section>);

}

/* ---------- 7. SOUND AT A GLANCE ---------- */
function SoundSection() {
  const { t } = useT();
  const sounds = [
  { id: 'auth-blip', name: t('sounds.1.name'), duration: "0:01", category: t('sounds.1.cat'), description: t('sounds.1.desc'), src: null, tone: "blue" },
  { id: 'done-bell', name: t('sounds.2.name'), duration: "0:02", category: t('sounds.2.cat'), description: t('sounds.2.desc'), src: null, tone: "mint" },
  { id: 'rate-yawn', name: t('sounds.3.name'), duration: "0:03", category: t('sounds.3.cat'), description: t('sounds.3.desc'), src: null, tone: "amber" }];

  return (
    <section className="s sounds" id="sounds">
      <div className="container">
        <SectionHeading
          eyebrow={t('sounds.eyebrow')}
          title={t('sounds.title')}
          sub={t('sounds.sub')} />

        <div className="sounds-grid hero">
          {sounds.map((s) => <SoundButton key={s.id} {...s} variant="hero" />)}
        </div>

        <div className="sounds-foot row items-center gap-3 justify-center">
          <span className="sub" style={{ fontSize: 14, margin: 0, textAlign: 'center' }}>
            {t('sounds.foot')}
          </span>
        </div>
      </div>
    </section>);

}

/* ---------- 8. LOCAL-FIRST ---------- */
function LocalFirst() {
  const { t } = useT();
  return (
    <section className="s local" id="privacy">
      <div className="container">
        <SectionHeading
          eyebrow={t('local.eyebrow')}
          title={<>{t('local.title1')} <span className="muted">{t('local.title2')}</span></>}
          sub={t('local.sub')} />
        

        <div className="local-grid">
          <div className="local-card">
            <div className="local-card-num mono muted">01</div>
            <div className="local-card-title">{t('local.card.1.title')}</div>
            <div className="local-card-body">{t('local.card.1.body')}</div>
          </div>
          <div className="local-card">
            <div className="local-card-num mono muted">02</div>
            <div className="local-card-title">{t('local.card.2.title')}</div>
            <div className="local-card-body">{t('local.card.2.body')}</div>
          </div>
          <div className="local-card">
            <div className="local-card-num mono muted">03</div>
            <div className="local-card-title">{t('local.card.3.title')}</div>
            <div className="local-card-body">{t('local.card.3.body')}</div>
          </div>
        </div>

        <div className="local-log">
          <div className="local-log-head">
            <span className="mono muted" style={{ fontSize: 11 }}>~/Library/Application Support/VibePet/events.jsonl</span>
            <span className="mono muted" style={{ fontSize: 11 }}>tail -n 3</span>
          </div>
          <pre className="mono local-log-body">{`{"ts":"15:32:04","tool":"claude-code","state":"running","run_id":"3f7a","src":"hook:user-prompt"}
{"ts":"15:32:11","tool":"codex","state":"rateLimit","retry_at":"15:36:00","src":"hook:cli-error"}
{"ts":"15:32:18","tool":"cursor","state":"review","files":6,"src":"hook:completion"}`}</pre>
          <div className="local-log-foot row items-center gap-3">
            <span className="dot mint" />
            <span className="mono muted" style={{ fontSize: 12 }}>{t('local.log.note')}</span>
          </div>
        </div>
      </div>
    </section>);

}

/* ---------- 9. DOWNLOAD ---------- */
function DownloadSection() {
  const { t } = useT();
  return (
    <section className="s download" id="download">
      <div className="container">
        <SectionHeading
          align="center"
          maxWidth={620}
          eyebrow={t('dl.eyebrow')}
          title={t('dl.title')}
          sub={t('dl.sub')} />

        <div className="download-solo">
          <DownloadCommand variant="dmg" primary label={t('dl.cta')} />
          <div className="mono muted dl-card-meta">{t('dl.meta')}</div>
        </div>
      </div>
    </section>);

}

/* ---------- 10. FOOTER ---------- */
function Footer() {
  const { t } = useT();
  return (
    <footer className="foot">
      <div className="container">
        <div className="foot-grid">
          <div className="foot-brand">
            <div className="row items-center gap-3">
              <img src="assets/vibepet-logo.png" alt="VibePet" className="brand-logo-img" />
              <span className="brand-word">VibePet</span>
            </div>
            <p className="sub" style={{ fontSize: 14, margin: '12px 0 0', maxWidth: 320 }}>
              {t('foot.brand')}
            </p>
          </div>

          <div className="foot-col">
            <div className="foot-col-head mono muted">{t('foot.col.product')}</div>
            <a href="#pets">{t('foot.col.product.pets')}</a>
            <a href="#sounds">{t('foot.col.product.sounds')}</a>
            <a href="#tools">{t('foot.col.product.tools')}</a>
            <a href="#download">{t('foot.col.product.download')}</a>
          </div>

          <div className="foot-col">
            <div className="foot-col-head mono muted">{t('foot.col.community')}</div>
            <SocialLinks variant="labeled" showQR className="foot-social" />
          </div>

          <div className="foot-col">
            <div className="foot-col-head mono muted">{t('foot.col.legal')}</div>
            <a href="#privacy">{t('foot.col.legal.privacy')}</a>
            <a href="#terms">{t('foot.col.legal.terms')}</a>
          </div>
        </div>

        <div className="foot-rule" />

        <div className="foot-bottom mono muted">
          <span>© {new Date().getFullYear()} VibePet · {t('foot.copy')}</span>
          <span className="row items-center gap-2"><span className="dot mint" /> {t('foot.status')}</span>
        </div>
      </div>
    </footer>);

}

Object.assign(window, {
  Navbar, Hero, ChaosToCalm, HowItWorks, EightTools,
  PetPersonality, SoundSection, LocalFirst, DownloadSection, Footer
});