/* ============================================================
   Nhà hàng Chay — Preloader + Navbar + Hero
   ============================================================ */

/* ---------- Preloader — Lotus Opening ----------
   Hoa sen nở + wordmark trên nền emerald.
   Tự fade-out, không kẹt scroll, tôn trọng reduced-motion. */
const PRELOADER_VISIBLE_MS = 2800;
const PRELOADER_FADE_MS = 700;
const PRELOADER_REDUCED_VISIBLE_MS = 1000;
const PRELOADER_REDUCED_FADE_MS = 250;

function Preloader() {
  const [done, setDone] = useState(false);  // bắt đầu fade-out
  const [gone, setGone] = useState(false);  // unmount khỏi DOM
  useLockBodyScroll(!gone);                  // khóa scroll trong lúc preload, trả lại khi gone

  useEffect(() => {
    const reduced = prefersReduced();
    const showMs = reduced ? PRELOADER_REDUCED_VISIBLE_MS : PRELOADER_VISIBLE_MS;
    const fadeMs = reduced ? PRELOADER_REDUCED_FADE_MS : PRELOADER_FADE_MS;
    const t1 = setTimeout(() => setDone(true), showMs);
    const t2 = setTimeout(() => setGone(true), showMs + fadeMs);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);

  if (gone) return null;
  return (
    <div className={`preloader ${done ? 'is-done' : ''}`} role="status" aria-live="polite" aria-hidden={done}>
      <div className="preloader-inner">
        <LotusMark size={132} className="preloader-lotus" />
        <div className="preloader-logo-card">
          <span className="brand-wordmark" style={{ fontSize: '20px' }}>NHÀ HÀNG CHAY</span>
        </div>
        <p className="preloader-name">Nhà hàng Chay</p>
        <p className="preloader-tag">Một bữa chay ấm lành đang được chuẩn bị…</p>
      </div>
    </div>
  );
}

const NAV_LINKS = [
  { label: 'Câu chuyện', href: '#story' },
  { label: 'Thực đơn', href: '#menu' },
  { label: 'Món nổi bật', href: '#experience' },
  { label: 'Không gian', href: '#space' },
  { label: 'Đánh giá', href: '#reviews' },
  { label: 'Liên hệ', href: '#contact' },
];

function Navbar() {
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const close = () => setOpen(false);

  return (
    <>
      <header
        className={`nav-root ${scrolled ? 'scrolled' : ''}`}
        style={{
          position: 'fixed', top: 0, left: 0, width: '100%', zIndex: 50,
          background: scrolled ? 'rgba(245,241,230,0.82)' : 'rgba(245,241,230,0.55)',
          backdropFilter: 'blur(18px)', WebkitBackdropFilter: 'blur(18px)',
          borderBottom: `1px solid ${scrolled ? 'rgba(90,75,68,0.12)' : 'rgba(90,75,68,0)'}`,
          transition: 'background .4s ease, border-color .4s ease',
        }}
      >
        <nav className="nav-inner">
          <a href="#top" aria-label="Nhà hàng Chay — về đầu trang" className="nav-logo">
            <span className="brand-wordmark" style={{ fontSize: '19px' }}>NHÀ HÀNG CHAY</span>
          </a>

          <div className="nav-links">
            {NAV_LINKS.map((l, i) => (
              <React.Fragment key={l.href}>
                <a href={l.href} className="nav-link">{l.label}</a>
                {i < NAV_LINKS.length - 1 && <span className="nav-dot" aria-hidden="true">·</span>}
              </React.Fragment>
            ))}
          </div>

          {/* CTA đặt bàn — chưa có link/kênh đặt bàn thật nên để href="#" (cập nhật sau) */}
          <a href="#" className="pill pill-primary nav-cta">Đặt bàn ngay</a>

          <button
            className="nav-burger"
            aria-label={open ? 'Đóng menu' : 'Mở menu'}
            aria-expanded={open}
            onClick={() => setOpen((v) => !v)}
          >
            <span className={`burger-bar ${open ? 'b1' : ''}`} />
            <span className={`burger-bar ${open ? 'b2' : ''}`} />
            <span className={`burger-bar ${open ? 'b3' : ''}`} />
          </button>
        </nav>
      </header>

      {/* Mobile overlay */}
      <div
        className="mobile-overlay"
        style={{
          opacity: open ? 1 : 0,
          pointerEvents: open ? 'auto' : 'none',
        }}
        aria-hidden={!open}
      >
        <span className="brand-wordmark overlay-logo" style={{ fontSize: '22px' }}>NHÀ HÀNG CHAY</span>
        <div className="overlay-links">
          {NAV_LINKS.map((l) => (
            <a key={l.href} href={l.href} onClick={close} className="overlay-link">{l.label}</a>
          ))}
        </div>
        <div className="overlay-cta">
          {/* Chưa có kênh đặt bàn thật -> href="#" (cập nhật sau) */}
          <a href="#" className="pill pill-primary" onClick={close}>Đặt bàn ngay</a>
          <a href="#contact" className="pill pill-outline-green" onClick={close}>Xem địa điểm</a>
        </div>
      </div>
    </>
  );
}

/* ---------- Hero ---------- */
/* Chỉ dùng ảnh không gian không chứa nhãn hiệu; slide đầu là ảnh nội thất chính.
   >1 slide -> autoplay + crossfade + dots. */
const HERO_SLIDES = [
  {
    id: 'interior-main',
    src: 'assets/gallery/interior.png',
    alt: 'Không gian ấm áp bên trong nhà hàng chay',
    label: 'Không gian ấm áp'
  },
  {
    id: 'table-moon',
    src: 'assets/images/vegetarian-samples/vegetarian_moon_table.png',
    alt: 'Góc bàn ăn nhà hàng chay tinh tế bên bức tường vầng trăng ấm',
    label: 'Góc bàn ăn'
  },
  {
    id: 'table-arch',
    src: 'assets/images/vegetarian-samples/vegetarian_arch_interior.png',
    alt: 'Không gian nhà hàng chay ấm áp — bàn ăn chay được bày biện tỉ mỉ dưới vòm tường',
    label: 'Bàn ăn tinh tế'
  }
];
const HERO_SLIDE_INTERVAL_MS = 3600;

function HeroTypewriter() {
  const tw = useTypewriter(
    'Thưởng thức món chay sáng tạo từ rau củ, nấm và nguyên liệu tự nhiên trong không gian ấm áp, tinh tế.',
    { speed: 26, startDelay: 650 }
  );
  return (
    <p className="hero-tw">
      {tw.displayed}
      {!tw.done && <span className="tw-cursor" aria-hidden="true" />}
    </p>
  );
}

function ImageTiles() {
  const [active, setActive] = useState(false);

  useEffect(() => {
    // Kích hoạt bung tỏa ảnh sau khi Preloader kết thúc
    const timer = setTimeout(() => {
      setActive(true);
    }, 1800);
    return () => clearTimeout(timer);
  }, []);

  const tiles = [
    {
      id: 'left',
      src: 'assets/images/vegetarian-samples/menu/banh-mi-pate-nam.png',
      alt: 'Bánh mì pate nấm chay thơm ngon',
      className: 'hero-image-tile hero-image-tile--left'
    },
    {
      id: 'middle',
      src: 'assets/images/vegetarian-samples/menu/lau-sa-te-chay.png',
      alt: 'Nồi lẩu sa tế chay rau nấm ấm áp',
      className: 'hero-image-tile hero-image-tile--middle'
    },
    {
      id: 'right',
      src: 'assets/images/vegetarian-samples/menu/tra-dau-den.png',
      alt: 'Trà đậu đen thanh mát tốt cho sức khỏe',
      className: 'hero-image-tile hero-image-tile--right'
    }
  ];

  return (
    <div className={`hero-image-tiles ${active ? 'is-active' : ''}`} aria-label="Hình ảnh món ăn chay đặc trưng">
      {tiles.map((tile) => (
        <div key={tile.id} className={tile.className}>
          <img src={tile.src} alt={tile.alt} loading="eager" decoding="async" />
          <div className="tile-sheen" aria-hidden="true" />
        </div>
      ))}
      <div className="hero-image-overlay" aria-hidden="true" />
    </div>
  );
}

function Hero() {
  const parallaxRef = useMouseParallax();

  return (
    <section id="top" className="hero plaster" ref={parallaxRef}>
      {/* decorative arch + glow layers */}
      <div className="hero-decor" aria-hidden="true">
        <div className="arch arch-1" />
        <div className="arch arch-2" />
        <div className="green-glow" />
      </div>

      <div className="hero-grid">
        {/* LEFT */}
        <div className="hero-content">
          <p className="hero-intro" aria-hidden="true">
            Ẩm thực chay thanh lành,<br />
            ấm nhẹ giữa nhịp phố.
          </p>

          <h1 className="hero-h1">
            <span className="hero-brand-line">
              <span className="hero-accent">Nhà hàng Chay</span>
              <span className="hero-dash"> — </span>
            </span>
            ẩm thực chay thanh lành cho <span className="no-break">mỗi ngày</span>
          </h1>

          <HeroTypewriter />

          <div className="hero-badges">
            <span className="badge"><span className="badge-dot" />Món chay sáng tạo</span>
            <span className="badge"><span className="badge-dot" />Nguyên liệu tự nhiên</span>
            <span className="badge"><span className="badge-dot" />10:00 – 22:00</span>
          </div>

          <div className="hero-actions">
            {/* Chưa có kênh đặt bàn thật -> href="#" (cập nhật sau) */}
            <a href="#" className="pill pill-primary">Đặt bàn ngay</a>
            <a href="#menu" className="pill pill-secondary">Xem thực đơn</a>
            <a href="#contact" className="pill pill-outline-green">Xem địa điểm</a>
          </div>
        </div>

        {/* RIGHT */}
        <div className="hero-visual">
          <ImageTiles />

          <div className="float-card float-card-a">
            <span className="fc-eyebrow"><Leaf size={13} color="var(--brand-leaf)" /> Không gian ấm áp</span>
            <p className="fc-text">Bàn gỗ, ghế mây và ánh đèn dịu.</p>
          </div>

          <div className="float-card float-card-b">
            <span className="fc-stat">Món chay</span>
            <span className="fc-stat-label">Sáng tạo từ rau củ &amp; nấm</span>
          </div>
        </div>
      </div>

      <div className="hero-scroll" aria-hidden="true">
        <span>Cuộn xuống</span>
        <span className="scroll-line" />
      </div>
    </section>
  );
}

Object.assign(window, { Preloader, Navbar, Hero, ImageTiles });
