const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

function ArrowRight({ size = 14 }) {return <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M4 12h16M14 6l6 6-6 6" /></svg>;}
function SwapIcon() {return <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M3 8h14l-3-3M21 16H7l3 3" /></svg>;}
function Caret({ open }) {return <svg viewBox="0 0 12 8" width="10" height="6" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .25s' }}><path d="M1 1l5 5 5-5" fill="none" stroke="currentColor" strokeWidth="1.4" /></svg>;}

// ===== Hero =====
function Hero({ active, align }) {
  const ref = useRefP(null);
  useEffectP(() => {
    if (!active) return;
    const el = ref.current;
    if (!el) return;
    let raf;
    const onMove = (e) => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const x = (e.clientX / window.innerWidth - 0.5) * 18;
        const y = (e.clientY / window.innerHeight - 0.5) * 10;
        el.style.transform = `translate3d(${x}px, ${y}px, 0)`;
      });
    };
    window.addEventListener('mousemove', onMove);
    return () => {window.removeEventListener('mousemove', onMove);cancelAnimationFrame(raf);};
  }, [active]);

  return (
    <section className={`panel panel--hero ${active ? 'is-in' : ''}`} data-screen-label="01 Hero">
      <div className="hero__bg" ref={ref}>
        <img src="assets/pc/hero-plane.jpg" alt="" draggable="false" />
      </div>
      <div className="hero__vignette" />
      <div className="hero__content">
        <div className="reveal r2">
          <h1 className="hero__title">
            <em>梦想航空 DREAM启程</em>
          </h1>
        </div>
        <div className="reveal r3">
          <HeroBooking />
        </div>
      </div>
    </section>);
}

// ===== Hero Booking Bar =====
const CITIES_DOMESTIC = ['北京', '上海', '广州', '深圳', '杭州', '成都'];
const CITIES_OVERSEAS = ['西雅图', '巴黎', '悉尼', '纽约'];
const ALL_CITIES = [...CITIES_DOMESTIC, ...CITIES_OVERSEAS];
const WEEKDAYS_FULL = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
const WEEKDAYS_SHORT = ['日', '一', '二', '三', '四', '五', '六'];

function startOfDay(d) {const x = new Date(d);x.setHours(0, 0, 0, 0);return x;}
function sameDay(a, b) {return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();}
function fmtDateLabel(d) {return `${d.getMonth() + 1}月${d.getDate()}日 ${WEEKDAYS_FULL[d.getDay()]}`;}
function addDays(d, n) {const x = new Date(d);x.setDate(x.getDate() + n);return x;}

function HeroBooking() {
  const [from, setFrom] = useStateP('北京');
  const [to, setTo] = useStateP('西雅图');
  const [trip, setTrip] = useStateP('one-way'); // 'one-way' | 'round-trip'
  const [departDate, setDepartDate] = useStateP(() => startOfDay(new Date()));
  const [returnDate, setReturnDate] = useStateP(() => addDays(new Date(), 7));
  const [open, setOpen] = useStateP(null); // 'from' | 'to' | 'date' | null
  const wrapRef = useRefP(null);

  useEffectP(() => {
    const onDoc = (e) => {if (!wrapRef.current) return;if (!wrapRef.current.contains(e.target)) setOpen(null);};
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);

  const pickFrom = (c) => {
    setFrom(c);
    if (c === to) {
      // pick another city for "to"
      const alt = ALL_CITIES.find((x) => x !== c);
      setTo(alt);
    }
    setOpen(null);
  };
  const pickTo = (c) => {
    setTo(c);
    if (c === from) {
      const alt = ALL_CITIES.find((x) => x !== c);
      setFrom(alt);
    }
    setOpen(null);
  };

  const toggleTrip = () => {
    setTrip((t) => {
      const next = t === 'one-way' ? 'round-trip' : 'one-way';
      // When switching back to one-way, clear the return date
      if (next === 'one-way') setReturnDate(null);
      return next;
    });
  };

  // Date range pick logic for round-trip
  const pickDate = (d) => {
    if (trip === 'one-way') {
      setDepartDate(d);
      setOpen(null);
    } else {
      // Round-trip: if no depart yet OR clicked before depart OR both already set, reset to depart
      if (!departDate || d < departDate || returnDate) {
        setDepartDate(d);
        setReturnDate(null);
      } else {
        setReturnDate(d);
        setOpen(null);
      }
    }
  };

  const dateLabel = trip === 'one-way' ?
  fmtDateLabel(departDate) :
  returnDate ?
  `${fmtDateLabel(departDate)} - ${fmtDateLabel(returnDate)}` :
  `${fmtDateLabel(departDate)} - 选择返程`;

  return (
    <div className="hero__booking" ref={wrapRef}>
      {/* 始发 */}
      <div className="hero__field hero__field--city">
        <button className="hero__field-btn" onClick={() => setOpen((o) => o === 'from' ? null : 'from')}>
          <span className="hero__field-label">始发</span>
          <span className="hero__field-value">{from}</span>
          <Caret open={open === 'from'} />
        </button>
        {open === 'from' && <CityPop selected={from} exclude={to} onPick={pickFrom} />}
      </div>

      {/* 到达 */}
      <div className="hero__field hero__field--city">
        <button className="hero__field-btn" onClick={() => setOpen((o) => o === 'to' ? null : 'to')}>
          <span className="hero__field-label">到达</span>
          <span className="hero__field-value">{to}</span>
          <Caret open={open === 'to'} />
        </button>
        {open === 'to' && <CityPop selected={to} exclude={from} onPick={pickTo} />}
      </div>

      {/* Trip toggle */}
      <button className={`hero__trip hero__trip--${trip}`} onClick={toggleTrip} title={trip === 'one-way' ? '单程 · 点击切换往返' : '往返 · 点击切换单程'}>
        <span className="hero__trip-icon">{trip === 'one-way' ? '→' : '⇄'}</span>
      </button>

      {/* 日期 */}
      <div className="hero__field hero__field--date">
        <button className="hero__field-btn" onClick={() => setOpen((o) => o === 'date' ? null : 'date')}>
          <span className="hero__field-label">日期</span>
          <span className="hero__field-value">{dateLabel}</span>
          <Caret open={open === 'date'} />
        </button>
        {open === 'date' &&
        <DatePop trip={trip} departDate={departDate} returnDate={returnDate} onPick={pickDate} />
        }
      </div>

      <button className="hero__book-btn" onClick={() => alert(`已为您预订：${from} → ${to}\n${dateLabel}`)}>
        <span>尊享预订</span>
        <ArrowRight size={14} />
      </button>
    </div>);

}

function CityPop({ selected, exclude, onPick }) {
  const groups = [
  { label: '国内', items: CITIES_DOMESTIC },
  { label: '海外', items: CITIES_OVERSEAS }];

  return (
    <div className="hero__pop hero__pop--city">
      {groups.map((g) =>
      <div key={g.label} className="hero__pop-group">
          <div className="hero__pop-group-label">— {g.label} —</div>
          <div className="hero__pop-group-grid">
            {g.items.map((c) => {
            const disabled = c === exclude;
            return (
              <button key={c} disabled={disabled} className={`hero__pop-city ${c === selected ? 'is-active' : ''} ${disabled ? 'is-disabled' : ''}`} onClick={() => !disabled && onPick(c)}>
                  {c}
                </button>);

          })}
          </div>
        </div>
      )}
    </div>);

}

function DatePop({ trip, departDate, returnDate, onPick }) {
  const today = startOfDay(new Date());
  const months = [];
  for (let m = 0; m < 3; m++) months.push(new Date(today.getFullYear(), today.getMonth() + m, 1));
  return (
    <div className="hero__pop hero__pop--date">
      <div className="hero__pop-hint">
        {trip === 'one-way' ? '请选择出行日期' : returnDate ? '点击日期可重新选择' : departDate ? '请继续选择返程日期' : '请选择出发日期'}
      </div>
      <div className="hero__pop-cals">
        {months.map((m, i) =>
        <CalendarMonth key={i} month={m} today={today} trip={trip} departDate={departDate} returnDate={returnDate} onPick={onPick} />
        )}
      </div>
    </div>);

}

function CalendarMonth({ month, today, trip, departDate, returnDate, onPick }) {
  const y = month.getFullYear(),mo = month.getMonth();
  const firstDay = new Date(y, mo, 1).getDay();
  const daysIn = new Date(y, mo + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < firstDay; i++) cells.push(null);
  for (let d = 1; d <= daysIn; d++) cells.push(d);
  return (
    <div className="cal">
      <div className="cal__head">{y}年 {mo + 1}月</div>
      <div className="cal__weeks">{WEEKDAYS_SHORT.map((w) => <span key={w}>{w}</span>)}</div>
      <div className="cal__grid">
        {cells.map((d, i) => {
          if (d == null) return <span key={i} className="cal__cell cal__cell--empty" />;
          const cell = new Date(y, mo, d);
          const past = cell < today;
          const ok = !past;
          const isDepart = departDate && sameDay(cell, departDate);
          const isReturn = returnDate && sameDay(cell, returnDate);
          const inRange = trip === 'round-trip' && departDate && returnDate && cell > departDate && cell < returnDate;
          const cls = ['cal__cell'];
          if (ok) cls.push('is-valid');
          if (past) cls.push('is-past');
          if (isDepart) cls.push('is-sel', 'is-depart');
          if (isReturn) cls.push('is-sel', 'is-return');
          if (inRange) cls.push('is-range');
          return (
            <button key={i} disabled={!ok} className={cls.join(' ')} onClick={() => ok && onPick(cell)}>{d}</button>);

        })}
      </div>
    </div>);

}

// ===== Split (Brand intro - Bulgari-style contract animation) =====
function SplitPanel({ active }) {
  const fullText = "梦想相伴 ｜ 天地无界";
  const [typed, setTyped] = useStateP("");

  useEffectP(() => {
    if (!active) { setTyped(""); return; }
    let i = 0;
    setTyped("");
    // Wait for the panel reveal animation (~1s) before starting to type
    const start = setTimeout(() => {
      const id = setInterval(() => {
        i++;
        setTyped(fullText.slice(0, i));
        if (i >= fullText.length) clearInterval(id);
      }, 280);
      // Save id on closure so cleanup can clear it
      timer.current = id;
    }, 1400);
    return () => {
      clearTimeout(start);
      if (timer.current) clearInterval(timer.current);
    };
  }, [active]);
  const timer = useRefP({ current: null });

  return (
    <section className={`panel panel--split ${active ? 'is-in' : ''}`} data-screen-label="02 Heritage">
      <div className="split__inner">
        <div className="split__media-wrap">
          <div className="split__media">
            <img src="assets/pc/brand-plane.jpg" alt="梦想航空" />
          </div>
          <p className="split__caption">
            <span className="split__caption-text">{typed}</span>
            <span className={`split__caption-caret ${typed.length < fullText.length ? 'is-typing' : ''}`} aria-hidden="true">|</span>
          </p>
        </div>
        <div className="split__copy">
          <div className="split__copy-inner">
            <h2 className="split__title reveal r2">品牌介绍</h2>
            <p className="split__lead reveal r3" style={{ fontSize: "20px" }}>梦想航空是一家以"科技+服务"双轮驱动的高端航空品牌。</p>
            <p className="split__body reveal r4">
              我们以 AI Agent 为中枢，深度融合 Skytrax 五星与福布斯七星级标准，通过 AI 智能服务与顶尖乘务团队协同，打通地面接送、空中体验、目的地服务三大场景，构建天地空立体服务体系。
            </p>
            <p className="split__body reveal r5">
              依托战略伙伴在高速数字马达与智能算法领域的深厚积淀，我们正探索从地面到天空的技术迁移路径，涵盖 AI 副驾、智能客舱环境管理、新型混合推进等前沿科研方向，致力于打造具备自我进化能力的空中科技生态，让科技在运营中持续学习、迭代进化，让每一次飞行都比上一次更懂您。
            </p>
          </div>
        </div>
      </div>
    </section>);

}

// ===== Cities =====
const CITIES = [
{ city: "SEATTLE", cn: "西雅图", from: "北京", code: "PEK ⇄ SEA", note: "周二 MU6800/周六 MU8600班次", cta: "尊享预订", img: "assets/pc/city-seattle.jpg", status: "active" },
{ city: "PARIS", cn: "巴黎", from: "上海", code: "PVG ⇄ CDG", note: "航线规划中 · 2026 Q3", cta: "敬请期待", img: "assets/pc/city-paris.jpg", status: "soon" },
{ city: "SYDNEY", cn: "悉尼", from: "广州", code: "CAN ⇄ SYD", note: "航线规划中 · 2026 Q4", cta: "敬请期待", img: "assets/pc/city-sydney.jpg", status: "soon" }];


function CitiesPanel({ active }) {
  return (
    <section className={`panel panel--cities ${active ? 'is-in' : ''}`} data-screen-label="04 Routes">
      <header className="cities__head">
        <h2 className="reveal r2" style={{ fontSize: "44px", fontFamily: "\"Noto Serif SC\"" }}>甄选航线 · 极致体验</h2>
        <p className="reveal r3"><span>梦想相伴 ｜ 天地无界</span></p>
      </header>
      <div className="cities__grid">
        {CITIES.map((c, i) =>
        <article key={c.city} className={`city reveal r${i + 4}`}>
            <div className="city__img"><img src={c.img} alt={c.city} /></div>
            <div className="city__meta">
              <div className="city__route"><b style={{ fontFamily: "serif" }}>{c.from}</b> <SwapIcon /> <b>{c.cn}</b></div>
              <div className="city__note" style={{ fontSize: "14px" }}>{c.note}</div>
            </div>
            <button className={`city__cta city__cta--${c.status}`}>
              <span>{c.cta}</span>
              <span className="city__cta-arrow"><ArrowRight size={12} /></span>
            </button>
          </article>
        )}
      </div>
    </section>);

}

// ===== Cabin (3-stage tabs with sub-items) =====
const CABIN_STATES = [
{ key: "depart", iconSvg: "car", label: "启程臻礼", storyLabel: "权益礼遇", en: "DEPARTURE",
  headline: "启程臻礼·礼遇每一步", headlineEn: "PREMIUM DEPARTURE",
  img: "assets/pc/cabin-departure.jpg",
  items: [
  { t: "尊享地面接送", d: "豪华车队全程接驳，从府邸门廊到舷梯，以专属司机与白手套礼仪完成衔接。" },
  { t: "地面丝滑", d: "Physical AI 重构值机与登机流程——全智能柜台、智能行李分拣、APP 预填，指尖操作，无感通关。" },
  { t: "智慧侯机", d: "充满时代感与科技含量，让候机变成享受，而非等待。" }]
},
{ key: "cabin", iconSvg: "bar", label: "云端臻享", storyLabel: "权益礼遇", en: "IN-FLIGHT",
  headline: "云端臻享·奢享每一刻", headlineEn: "ABOARD THE DREAM",
  img: "assets/pc/cabin-bar.jpg",
  items: [
  { t: "机载智能化", d: "AI 服务与具身智能技术进入客舱，全面刷新飞机的科技属性。" },
  { t: "空中美馔定制", d: "米其林星厨与侍酒师同行，主菜、配酒、茶点皆可依您的偏好提前订制。" },
  { t: "极致睡眠", d: "高品质的座椅选型，让每一位乘客都能拥有真正的平躺睡眠体验。" }]
},
{ key: "arrive", iconSvg: "key", label: "落地臻程", storyLabel: "权益礼遇", en: "ARRIVAL",
  headline: "落地臻程·续享每一程", headlineEn: "DESTINATION CARE",
  img: "assets/pc/cabin-arrival.jpg",
  items: [
  { t: "快捷入境通关", d: "与目的地海关绿色通道协同，专人陪同入境，行李直送车辆，无需任何等待。" },
  { t: "到达地接礼宾", d: "甄选车队与多语种礼宾在廊桥外恭候，将您送往酒店或目的地的每一处目的。" },
  { t: "酒店无缝衔接", d: "全球甄选酒店伙伴预先备好您的偏好房型，抵达即入住，让旅途自然延续。" }]
}];


function CabinPanel({ active }) {
  const [tab, setTab] = useStateP(0);
  const lastInteract = useRefP(0);

  useEffectP(() => { if (active) { setTab(0); lastInteract.current = Date.now(); } }, [active]);

  // Auto-rotate every 5s, but reset on manual tab click
  useEffectP(() => {
    if (!active) return;
    const id = setInterval(() => {
      if (Date.now() - lastInteract.current >= 6000) {
        setTab(t => (t + 1) % CABIN_STATES.length);
        lastInteract.current = Date.now();
      }
    }, 1000);
    return () => clearInterval(id);
  }, [active]);

  const onPickTab = (i) => { setTab(i); lastInteract.current = Date.now(); };
  const s = CABIN_STATES[tab];
  return (
    <section className={`panel panel--cabin ${active ? 'is-in' : ''}`} data-screen-label="03 Cabin">
      <div className="cabin__bgs">
        {CABIN_STATES.map((c, i) =>
        <div key={c.key} className={`cabin__bg ${i === tab ? 'is-active' : ''}`}>
            <img src={c.img} alt="" />
          </div>
        )}
      </div>
      <div className="cabin__shade" />
      <div className="cabin__inner">
        <header className="cabin__head reveal r1" key={'h-' + s.key}>
          <span className="kicker kicker--light">{s.headlineEn}</span>
          <h2 style={{ fontFamily: "\"Noto Serif SC\"" }}>{s.headline}</h2>
          <a className="cabin__story-link" href="#" onClick={(e) => e.preventDefault()}>
            <span>{s.storyLabel || s.label}</span>
            <span className="cabin__story-arrow">&gt;&gt;</span>
          </a>
        </header>
        <div className="cabin__story reveal r2" key={s.key}>
          <ul className="cabin__items">
            {/* 三块子内容已按要求隐藏（保留代码，需要时取消注释即可恢复）
            {s.items.map((it, i) =>
            <li key={it.t} style={{ animationDelay: `${0.12 + i * 0.08}s` }}>
                <span className="cabin__items-num">0{i + 1}</span>
                <div className="cabin__items-body">
                  <span className="cabin__items-text">{it.t}</span>
                  <span className="cabin__items-desc">{it.d}</span>
                </div>
              </li>
            )}
            */}
          </ul>
        </div>
        <div className="cabin__tabs">
          {CABIN_STATES.map((c, i) =>
          <button key={c.key} className={`cabin__tab ${i === tab ? 'is-active' : ''}`} onClick={() => onPickTab(i)}>
              <CabinTabIcon kind={c.iconSvg} />
              <span>{c.label}</span>
              <span className="cabin__tab-num">{String(i + 1).padStart(2, '0')}</span>
            </button>
          )}
        </div>
      </div>
    </section>);
}

function CabinTabIcon({ kind }) {
  const c = { width: 20, height: 20, fill: "none", stroke: "currentColor", strokeWidth: 1.4 };
  if (kind === 'car') return <svg viewBox="0 0 24 24" {...c}><path d="M3 16h18M5 16l1.5-5h11L19 16M7 16v2M17 16v2" /><circle cx="8" cy="16" r="1.3" /><circle cx="16" cy="16" r="1.3" /></svg>;
  if (kind === 'bar') return <svg viewBox="0 0 24 24" {...c}><path d="M5 4h14l-6 7v8M9 19h8" /><path d="M7 4l5 7" /></svg>;
  if (kind === 'key') return <svg viewBox="0 0 24 24" {...c}><circle cx="8" cy="12" r="4" /><path d="M12 12h9M18 12v3M21 12v2" /></svg>;
  return null;
}

// ===== Partners =====
const PARTNERS = [
{ title: "服务联盟", en: "SERVICE PARTNERS", body: "携手全球高净值品牌，共同构建一张围绕您出行半径的高端立体服务网。", img: "assets/pc/partner-service.jpg?v=2" },
{ title: "技术合作", en: "TECH PARTNERS", body: "与全球顶尖的工程智慧站在一起，连接一切关于飞行的想象，让科技回归服务于人的本质。", img: "assets/pc/partner-tech.jpg" },
{ title: "联合航线", en: "CODE-SHARE", body: "与全球甄选承运人开放联合航线，让航线联合，不止于连通天地，更在于重塑体验。", img: "assets/pc/partner-route.jpg" }];


function PartnersPanel({ active }) {
  return (
    <section className={`panel panel--partners ${active ? 'is-in' : ''}`} data-screen-label="05 Alliance">
      <header className="partners__head">
        <h2 className="reveal r2" style={{ fontSize: "44px", fontFamily: "\"Noto Serif SC\"" }}>全球联盟 · 寰宇同频</h2>
        <p className="partners__head-en reveal r3">Global Alliance · United in Harmony</p>
      </header>
      <div className="partners__grid">
        {PARTNERS.map((p, i) =>
        <article key={p.title} className={`partner reveal r${i + 3}`}>
            <div className="partner__img"><img src={p.img} alt="" /></div>
            <h3>{p.title}</h3>
            <span className="partner__en">{p.en}</span>
            <p style={{ fontFamily: "\"Noto Serif SC\"" }}>{p.body}</p>
            <a className="partner__cta" href="#" onClick={(e) => e.preventDefault()}><span>业务合作</span></a>
          </article>
        )}
      </div>
    </section>);

}

// ===== Footer =====
function FooterPanel({ active }) {
  const cols = [
  { title: "梦想航空", items: ["品牌历程", "甄选航线", "奢享礼遇", "目的地体验"] },
  { title: "系列产品", items: ["天际系列", "尊途系列", "重构系列"] },
  { title: "全球合作伙伴", items: ["联营航线", "技术合作", "服务联盟"] },
  { title: "联系我们", items: ["商务合作", "品牌合作", "投资者关系"] }];

  const socials = [
  { src: "assets/pc/social-douyin.png?v=2", label: "抖音" },
  { src: "assets/pc/social-wechat.png?v=2", label: "微信" },
  { src: "assets/pc/social-weibo.png?v=2", label: "微博" },
  { src: "assets/pc/social-xhs.png?v=2", label: "小红书" },
  { src: "assets/pc/social-x.png?v=2", label: "X" },
  { src: "assets/pc/social-linkedin.png?v=2", label: "LinkedIn" },
  { src: "assets/pc/social-instagram.png?v=2", label: "Instagram" }];

  return (
    <section className={`panel panel--footer ${active ? 'is-in' : ''}`} data-screen-label="06 Footer">
      <div className="footer__inner">
        <div className="footer__row footer__row--contact">
          <div className="footer__contact">
            <div className="footer__row-label">邮件联系</div>
            <a className="footer__email" href="mailto:info@dreamfly.group">
              <span>Info@dreamfly.group</span>
              <img className="footer__mail-icon" src="assets/pc/icon-mail.png?v=2" alt="" />
            </a>
          </div>
          <div className="footer__follow">
            <div className="footer__row-label">关注我们</div>
            <div className="footer__social">
              {socials.map((s) =>
              <a key={s.label} href="#" onClick={(e) => e.preventDefault()} aria-label={s.label}>
                  <img src={s.src} alt={s.label} />
                </a>
              )}
            </div>
          </div>
        </div>

        <div className="footer__cols">
          {cols.map((c) =>
          <div key={c.title} className="footer__col">
              <div className="footer__col-title">{c.title}</div>
              {c.items.map((it) => <a key={it} href="#" onClick={(e) => e.preventDefault()}>{it}</a>)}
            </div>
          )}
        </div>

        <div className="footer__end">
          <div className="footer__wordmark">追觅·梦想航空</div>
          <div className="footer__bottom">
            <span>© 2026 梦想航空科技有限公司</span>
            <span>沪公网安备 31010602008949号</span>
            <span>沪ICP备20008735号-2</span>
          </div>
        </div>
      </div>
    </section>);

}

Object.assign(window, { Hero, SplitPanel, CitiesPanel, CabinPanel, PartnersPanel, FooterPanel, ArrowRight, SwapIcon });