const { useState, useEffect, useRef, useCallback } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "font": "serif",
  "heroAlign": "left",
  "navStyle": "transparent",
  "palette": "gold",
  "indicator": "dots-right"
} /*EDITMODE-END*/;

// Palettes ---------------------------------------------------------
const PALETTES = {
  gold: { accent: "#c8a875", accentSoft: "#e9d9b8", bgWarm: "#b08a52", ink: "#1a1612", paper: "#f7f2ea" },
  copper: { accent: "#b87333", accentSoft: "#e0b48a", bgWarm: "#8b4f1d", ink: "#1a1208", paper: "#f6efe6" },
  green: { accent: "#5f8a72", accentSoft: "#b8cdbe", bgWarm: "#2d4a3e", ink: "#0f1a14", paper: "#eef2ee" },
  mono: { accent: "#202020", accentSoft: "#888888", bgWarm: "#0a0a0a", ink: "#0a0a0a", paper: "#ffffff" }
};

const FONT_STACKS = {
  serif: `"Cormorant Garamond", "Noto Serif SC", "Songti SC", "STSong", Georgia, serif`,
  sans: `"Inter", "Noto Sans SC", "PingFang SC", "Helvetica Neue", Arial, sans-serif`
};

// Panels list (footer is a mini panel - half height transition)
const PANEL_COUNT = 6; // hero, split, cities, cabin, partners, footer
const PANEL_LABELS = ["Home", "Heritage", "Routes", "Cabin", "Alliance", "Footer"];

// ===== Main =====
function App() {
  const [t, setTweak, panelReady] = useTweaks(TWEAK_DEFAULTS);
  const [idx, setIdx] = useState(0);
  const [navVisible, setNavVisible] = useState(true);
  const lastWheel = useRef(0);
  const lastY = useRef(0);
  const idxRef = useRef(0);
  idxRef.current = idx;

  const palette = PALETTES[t.palette] || PALETTES.gold;
  const font = FONT_STACKS[t.font] || FONT_STACKS.serif;

  const go = useCallback((next) => {
    next = Math.max(0, Math.min(PANEL_COUNT - 1, next));
    setIdx(next);
  }, []);

  // Wheel navigation with cooldown
  useEffect(() => {
    const onWheel = (e) => {
      e.preventDefault();
      const now = Date.now();
      if (now - lastWheel.current < 1100) return;
      if (Math.abs(e.deltaY) < 8) return;
      lastWheel.current = now;
      if (e.deltaY > 0) go(idxRef.current + 1);else
      go(idxRef.current - 1);
    };
    window.addEventListener('wheel', onWheel, { passive: false });
    return () => window.removeEventListener('wheel', onWheel);
  }, [go]);

  // Keyboard
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'ArrowDown' || e.key === 'PageDown' || e.key === ' ') {e.preventDefault();go(idxRef.current + 1);} else
      if (e.key === 'ArrowUp' || e.key === 'PageUp') {e.preventDefault();go(idxRef.current - 1);} else
      if (e.key === 'Home') go(0);else
      if (e.key === 'End') go(PANEL_COUNT - 1);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [go]);

  // Touch
  useEffect(() => {
    let startY = 0;
    const onStart = (e) => {startY = e.touches[0].clientY;};
    const onEnd = (e) => {
      const endY = e.changedTouches[0].clientY;
      const dy = startY - endY;
      if (Math.abs(dy) < 40) return;
      if (dy > 0) go(idxRef.current + 1);else
      go(idxRef.current - 1);
    };
    window.addEventListener('touchstart', onStart);
    window.addEventListener('touchend', onEnd);
    return () => {window.removeEventListener('touchstart', onStart);window.removeEventListener('touchend', onEnd);};
  }, [go]);

  // Mouse-move based nav reveal (auto-hide when moving down/idle)
  useEffect(() => {
    let timer;
    const onMove = (e) => {
      const dy = e.clientY - lastY.current;
      lastY.current = e.clientY;
      if (e.clientY < 120) {setNavVisible(true);} else
      if (dy < -4) {setNavVisible(true);} else
      if (dy > 6) {setNavVisible(false);}
      clearTimeout(timer);
      timer = setTimeout(() => setNavVisible(false), 2400);
    };
    window.addEventListener('mousemove', onMove);
    timer = setTimeout(() => setNavVisible(false), 3000);
    return () => {window.removeEventListener('mousemove', onMove);clearTimeout(timer);};
  }, []);

  // Notify host of slide changes (for speaker notes wire) — harmless if not used
  useEffect(() => {
    try {window.parent.postMessage({ slideIndexChanged: idx }, '*');} catch (e) {}
  }, [idx]);

  // Footer panel is shorter (50vh) — others are 100vh.
  // We translate the stack. Each non-footer panel = 100vh. Footer at end = 50vh.
  // Translate so the current panel sits at top of viewport, except last (footer) shows in bottom half.
  const translate = idx < PANEL_COUNT - 1 ? `translate3d(0, -${idx * 100}vh, 0)` : `translate3d(0, calc(-${(PANEL_COUNT - 2) * 100}vh - 50vh), 0)`;

  return (
    <div className="app" style={{ "--accent": palette.accent, "--accent-soft": palette.accentSoft, "--bg-warm": palette.bgWarm, "--ink": palette.ink, "--paper": palette.paper, "--font": font, fontFamily: font, color: palette.ink, background: palette.paper }}>
      <TopNav visible={navVisible} style={t.navStyle} idx={idx} onLogo={() => go(0)} />
      <Indicator pos={t.indicator} idx={idx} go={go} />
      <div className="stack" style={{ transform: translate, transition: 'transform 1000ms cubic-bezier(.7,0,.2,1)' }}>
        <Hero active={idx === 0} align={t.heroAlign} />
        <SplitPanel active={idx === 1} />
        <CitiesPanel active={idx === 2} />
        <CabinPanel active={idx === 3} />
        <PartnersPanel active={idx === 4} />
        <FooterPanel active={idx === 5} />
      </div>
      {panelReady ?
      <TweaksPanel title="Tweaks">
          <TweakSection title="排版">
            <TweakRadio label="字体" value={t.font} onChange={(v) => setTweak('font', v)} options={[{ value: 'serif', label: '衬线' }, { value: 'sans', label: '无衬线' }]} />
            <TweakSelect label="Hero 文案位置" value={t.heroAlign} onChange={(v) => setTweak('heroAlign', v)} options={[{ value: 'left', label: '左下' }, { value: 'center', label: '居中' }, { value: 'right', label: '右下' }]} />
          </TweakSection>
          <TweakSection title="导航 & 进度">
            <TweakSelect label="导航栏样式" value={t.navStyle} onChange={(v) => setTweak('navStyle', v)} options={[{ value: 'transparent', label: '透明叠加' }, { value: 'solid', label: '实色' }, { value: 'minimal', label: '极简' }]} />
            <TweakSelect label="翻页指示器" value={t.indicator} onChange={(v) => setTweak('indicator', v)} options={[{ value: 'dots-right', label: '右侧圆点' }, { value: 'lines-right', label: '右侧短线' }, { value: 'counter-bl', label: '左下计数' }, { value: 'none', label: '无' }]} />
          </TweakSection>
          <TweakSection title="主色调">
            <TweakColor label="" value={t.palette} onChange={(v) => setTweak('palette', v)}
          options={[
          ['#c8a875', '#b08a52', '#1a1612'],
          ['#b87333', '#8b4f1d', '#1a1208'],
          ['#5f8a72', '#2d4a3e', '#0f1a14'],
          ['#202020', '#ffffff', '#888888']]
          } />
            <div style={{ display: 'flex', gap: 6, marginTop: 6, fontSize: 11, opacity: .6, justifyContent: 'space-around' }}>
              <span>金</span><span>铜</span><span>墨绿</span><span>纯黑白</span>
            </div>
          </TweakSection>
        </TweaksPanel> :
      null}
    </div>);

}

// ===== Top Nav =====
function TopNav({ visible, style, idx, onLogo }) {
  const items = ["关于我们", "业务产品", "会员礼遇", "新闻动态", "加入我们"];
  const onHero = idx === 0;
  // navStyle: transparent | solid | minimal
  const isSolid = style === 'solid';
  const isMinimal = style === 'minimal';
  // On dark panels (hero, cabin, footer) use light text; on light panels (split, cities, partners) use dark text
  const darkPanel = idx === 0 || idx === 3 || idx === 5;
  const tone = isSolid ? 'on-solid' : darkPanel ? 'on-dark' : 'on-light';

  return (
    <header className={`nav ${visible ? 'nav--show' : 'nav--hide'} nav--${style} nav--${tone}`}>
      <div className="nav__inner">
        <button className="nav__logo" onClick={onLogo}>
          <span className="nav__logo-mark">◇</span>
          <span className="nav__logo-text">FLY DREAM</span>
          <span className="nav__logo-sub">梦想航空</span>
        </button>
        <nav className="nav__links">
          {items.map((it) => <a key={it} href="#" onClick={(e) => e.preventDefault()}>{it}</a>)}
        </nav>
        <div className="nav__right" style={{ height: "2px" }}>
          <button aria-label="search"><SearchIcon /></button>
          <button aria-label="account"><UserIcon /></button>
          <button aria-label="locale" className="nav__locale"><GlobeIcon /><span>中文</span></button>
        </div>
      </div>
    </header>);

}

function SearchIcon() {return <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.4" style={{ width: "28px", height: "28px" }}><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></svg>;}
function UserIcon() {return <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.4" style={{ width: "28px", height: "28px" }}><circle cx="12" cy="8" r="4" /><path d="M4 21a8 8 0 0 1 16 0" /></svg>;}
function GlobeIcon() {return <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.4" style={{ width: "28px", height: "28px" }}><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18" /></svg>;}

// ===== Indicator =====
function Indicator({ pos, idx, go }) {
  if (pos === 'none') return null;
  if (pos === 'counter-bl') {
    return (
      <div className="ind ind--counter">
        <span className="ind__current">{String(idx + 1).padStart(2, '0')}</span>
        <span className="ind__sep">/</span>
        <span className="ind__total">{String(PANEL_COUNT).padStart(2, '0')}</span>
      </div>);

  }
  return (
    <div className={`ind ind--right ind--${pos}`}>
      {Array.from({ length: PANEL_COUNT }).map((_, i) =>
      <button key={i} className={`ind__item ${i === idx ? 'is-active' : ''}`} onClick={() => go(i)}>
          <span className="ind__label">{PANEL_LABELS[i]}</span>
          {pos === 'lines-right' ? <span className="ind__line" /> : <span className="ind__dot" />}
        </button>
      )}
    </div>);

}

Object.assign(window, { App });