/* global React */
const { useState, useEffect, useRef } = React;

// ============================================================
// NAV
// ============================================================
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);
  const close = () => setOpen(false);
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''} ${open ? 'menu-open' : ''}`}>
      <div className="wrap nav-inner">
        <a href="#top" className="nav-logo" aria-label="MALAHẦM" onClick={close}>
          <img src="images/logo-horizontal.png" alt="MALAHẦM" />
        </a>
        <ul className="nav-links">
          <li><a href="#story" onClick={close}>Câu chuyện</a></li>
          <li><a href="#broths" onClick={close}>Vị Lẩu</a></li>
          <li><a href="#how" onClick={close}>Cách dùng</a></li>
          <li><a href="#topping" onClick={close}>Topping</a></li>
          <li><a href="#locations" onClick={close}>Cửa hàng</a></li>
        </ul>
        <button
          className="burger"
          aria-label={open ? 'Đóng menu' : 'Mở menu'}
          aria-expanded={open}
          onClick={() => setOpen(o => !o)}
        >
          <span></span><span></span><span></span>
        </button>
      </div>
    </nav>
  );
}

// ============================================================
// HERO
// ============================================================
function Hero() {
  return (
    <header id="top" className="hero">
      <div className="hero-bg">
        <img src="images/hero-banner.jpg" alt="" />
        <div className="hero-bg-fade"></div>
      </div>
      <div className="wrap hero-grid">
        <div className="hero-text">
          <div className="hero-eyebrow">
            <span className="dot"></span>
            Lẩu Mala Tứ Xuyên · Hầm Việt
          </div>
          <h1 className="hero-title">
            <span className="line1">Vị lửa</span>
            <span className="line1">Từ <span className="swash">Tứ Xuyên</span></span>
            <span className="line2">Hầm chuẩn Việt.</span>
          </h1>
          <p className="hero-sub">
            Sáu nồi nước dùng nấu chậm, bốn mươi loại topping tươi mỗi ngày.
            Bạn chọn, chúng tôi hầm, chỉ trong 90 giây.
          </p>
          <div className="hero-actions">
            <a href="#broths" className="btn-primary">Xem thực đơn <span>→</span></a>
            <a href="#locations" className="btn-ghost">Tìm cửa hàng gần bạn</a>
          </div>
          <div className="hero-meta">
            <span className="label">Đánh giá thực khách</span>
            <span className="stars">★★★★★</span>
            <span className="num">4.9</span>
            <span className="div"></span>
            <span className="txt">Hơn <b>12.000</b> lượt thưởng thức / tháng</span>
            <span className="div"></span>
            <span className="txt">Mở cửa <b>10:00 – 22:30</b> hằng ngày</span>
          </div>
        </div>
      </div>
      <div className="stamp-badge">
        <div>
          <div className="num">90<span style={{fontSize: '18px'}}>s</span></div>
          <div className="lbl">Hầm là Xong</div>
        </div>
      </div>
    </header>
  );
}

// ============================================================
// TICKER
// ============================================================
function Ticker() {
  const items = [
    'Mala Cay Tê',
    'Hầm Chuẩn Việt',
    '90 Giây Là Xong',
    '6 Vị Nước Dùng',
    'Topping Tươi Mỗi Ngày',
    'Hầm Chậm, Ngọt Sâu',
  ];
  const doubled = [...items, ...items, ...items];
  return (
    <div className="ticker">
      <div className="ticker-track">
        {doubled.map((it, i) => (
          <span key={i} className="ticker-item">
            <span className="star">✦</span> {it}
          </span>
        ))}
      </div>
    </div>
  );
}

// ============================================================
// STORY
// ============================================================
function Story() {
  const cards = [
    {
      num: '01',
      title: 'Lửa từ Tứ Xuyên',
      body: 'Hoa tiêu xanh, ớt khô Erjingtiao, đậu bản và 14 vị thảo mộc. Bí phương cay tê chính gốc, không pha tạp.',
    },
    {
      num: '02',
      title: 'Tay người Việt hầm',
      body: 'Mỗi nồi nước dùng được hầm liên tục từ 6–10 giờ với xương, sá sùng và rau củ Đà Lạt cho vị ngọt thanh tự nhiên.',
    },
    {
      num: '03',
      title: 'Bạn là người chọn',
      body: 'Hơn 40 loại topping: thịt bò tươi, hải sản, viên thả, nấm, rau, mì khoai. Một bát của riêng bạn, đúng vị bạn thích.',
    },
  ];
  return (
    <section id="story" className="story">
      <div className="wrap">
        <div className="section-head">
          <div>
            <span className="eyebrow">Câu chuyện</span>
            <h2>Cay tê là cảm xúc,<br/>hầm chậm là tình cảm.</h2>
          </div>
          <p className="lead">
            MALA HẦM là cuộc gặp gỡ giữa lửa Tứ Xuyên và niêu hầm Việt Nam.
            Cay tê làm bừng tỉnh vị giác, hầm chậm giữ trọn cái ngọt của xương,
            rau và thuốc bắc.
          </p>
        </div>
        <div className="story-grid">
          {cards.map(c => (
            <div className="story-card" key={c.num}>
              <div className="num">{c.num}</div>
              <h3>{c.title}</h3>
              <p>{c.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============================================================
// BROTHS
// ============================================================
const BROTHS = [
  {
    id: 'mala-beef',
    name: 'Hầm Bò Cay Tê',
    cn: '川味麻辣牛肉',
    img: 'images/bowl-mala-beef.webp',
    heat: 4,
    stamp: '',
    desc: 'Vị cay tê đặc trưng đầy \nkích thích, khiến người ăn \nkhó lòng từ chối.',
  },
  {
    id: 'pork-bone',
    name: 'Hầm Xương Heo Ngô Ngọt',
    cn: '浓汤玉米骨汤',
    img: 'images/bowl-pork-corn.webp',
    heat: 0,
    stamp: '',
    desc: 'Nước dùng được hầm kỹ \ntừ xương, vị ngọt thanh \ntự nhiên từ ngô.',
  },
  {
    id: 'silkie',
    name: 'Hầm Gà Ác Thuốc Bắc',
    cn: '滋补乌鸡汤',
    img: 'images/bowl-silkie.webp',
    heat: 0,
    stamp: '',
    desc: 'Món hầm bổ dưỡng \nvới vị thảo mộc nhẹ nhàng \ntốt cho sức khỏe.',
  },
  {
    id: 'tomato',
    name: 'Hầm Cà Chua Chua Ngọt',
    cn: '番茄浓汤牛肉',
    img: 'images/bowl-tomato.webp',
    heat: 1,
    stamp: '',
    desc: 'Vị chua thanh dịu nhẹ \ntừ cà chua tươi, mang lại cảm \ngiác ngon miệng.',
  },
  {
    id: 'mala-mix',
    name: 'Trộn Cay Tê Mala',
    cn: '川香麻辣拌',
    img: 'images/bowl-mala-mix.webp',
    heat: 5,
    stamp: '',
    desc: 'Sự kết hợp đậm đà giữa \ncác loại gia vị cay tê, tạo \nnên món trộn lạ miệng.',
  },
];

function Broths() {
  const [active, setActive] = React.useState(0);
  const activeRef = React.useRef(0);
  const sectionRef = React.useRef(null);
  const lastInputRef = React.useRef(0);
  const touchStartYRef = React.useRef(0);

  React.useEffect(() => { activeRef.current = active; }, [active]);

  const completedRef = React.useRef(false);

  React.useEffect(() => {
    const section = sectionRef.current;
    if (!section) return;

    // The section is engaged when its midpoint is near the viewport midpoint —
    // a wide window so scroll velocity can't skip past the engagement moment.
    const inEngagementZone = () => {
      const rect = section.getBoundingClientRect();
      const vh = window.innerHeight;
      return rect.top < vh * 0.5 && rect.bottom > vh * 0.5;
    };

    // Snap the page so the section sits flush at the viewport top.
    const snap = () => {
      const rect = section.getBoundingClientRect();
      if (Math.abs(rect.top) > 1) {
        window.scrollTo({ top: section.offsetTop, behavior: 'instant' });
      }
    };

    const advance = (dir) => {
      const idx = activeRef.current;
      if (dir > 0 && idx === BROTHS.length - 1) {
        completedRef.current = true; // release downward — let page scroll past
        return false;
      }
      if (dir < 0 && idx === 0) return false; // release upward
      const now = performance.now();
      if (now - lastInputRef.current < 650) return true;
      lastInputRef.current = now;
      const next = Math.max(0, Math.min(BROTHS.length - 1, idx + dir));
      if (next !== idx) setActive(next);
      return true;
    };

    const onWheel = (e) => {
      if (completedRef.current) return;
      if (!inEngagementZone()) return;
      const dir = Math.sign(e.deltaY);
      if (dir === 0) return;
      if (advance(dir)) {
        e.preventDefault();
        snap();
      }
    };

    const onTouchStart = (e) => {
      touchStartYRef.current = e.touches[0].clientY;
    };
    const onTouchMove = (e) => {
      if (completedRef.current) return;
      if (!inEngagementZone()) return;
      const dy = touchStartYRef.current - e.touches[0].clientY;
      if (Math.abs(dy) < 28) return;
      const dir = dy > 0 ? 1 : -1;
      if (advance(dir)) {
        e.preventDefault();
        snap();
        touchStartYRef.current = e.touches[0].clientY;
      }
    };

    const onKey = (e) => {
      if (completedRef.current) return;
      if (!inEngagementZone()) return;
      let dir = 0;
      if (e.key === 'ArrowDown' || e.key === 'PageDown' || e.key === ' ') dir = 1;
      else if (e.key === 'ArrowUp' || e.key === 'PageUp') dir = -1;
      else return;
      if (advance(dir)) {
        e.preventDefault();
        snap();
      }
    };

    // Reset the "completed" flag when the user has scrolled far away
    // from the section (in either direction) so the lock can re-engage.
    const onScroll = () => {
      if (!completedRef.current) return;
      const rect = section.getBoundingClientRect();
      const vh = window.innerHeight;
      if (rect.top > vh * 0.8 || rect.bottom < vh * 0.2) {
        completedRef.current = false;
      }
    };

    window.addEventListener('wheel', onWheel, { passive: false });
    window.addEventListener('touchstart', onTouchStart, { passive: true });
    window.addEventListener('touchmove', onTouchMove, { passive: false });
    window.addEventListener('keydown', onKey);
    window.addEventListener('scroll', onScroll, { passive: true });

    return () => {
      window.removeEventListener('wheel', onWheel);
      window.removeEventListener('touchstart', onTouchStart);
      window.removeEventListener('touchmove', onTouchMove);
      window.removeEventListener('keydown', onKey);
      window.removeEventListener('scroll', onScroll);
    };
  }, []);

  const current = BROTHS[active];

  return (
    <section id="broths" ref={sectionRef} className="broths">
      <div className="broths-pin">
        <div className="wrap">
          <div className="section-head">
            <div>
              <span className="eyebrow">Vị Lẩu</span>
              <h2>Chọn vị Lẩu<br/>mà bạn yêu thích.</h2>
            </div>
            <p className="lead">
              Năm vị nước dùng được nấu chậm, từ cay tê bốc lửa đến hầm thuốc bắc dịu nhẹ.
              Cuộn xuống để khám phá từng vị một.
            </p>
          </div>

          <div className="spotlight">
            <div className="spotlight-bowl" key={'bowl-' + active}>
              <img src={current.img} alt={current.name} />
            </div>
            <div className="spotlight-text" key={'text-' + active}>
              <div className="sp-num">
                {String(active + 1).padStart(2, '0')}
                <span className="sp-num-sep">/</span>
                05
              </div>
              <h3 className="sp-name">{current.name}</h3>
              <p className="sp-desc">{current.desc.replace(/\n/g, ' ')}</p>
            </div>
          </div>

          <div className="bowl-switcher">
            <div className="switcher-track" role="tablist">
              {BROTHS.map((b, i) => (
                <button
                  key={b.id}
                  role="tab"
                  aria-selected={active === i}
                  className={`switcher-item ${active === i ? 'active' : ''}`}
                  onClick={() => setActive(i)}
                >
                  <span className="switcher-num">{String(i + 1).padStart(2, '0')}</span>
                  <div className="switcher-thumb">
                    <img src={b.img} alt="" />
                  </div>
                  <span className="switcher-name">{b.name}</span>
                </button>
              ))}
            </div>
            <div className="switcher-progress">
              <div className="switcher-progress-bar" style={{ width: `${((active + 1) / BROTHS.length) * 100}%` }}></div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============================================================
// HOW
// ============================================================
function How() {
  const steps = [
    { num: 'BƯỚC 01', title: 'Chọn topping', body: 'Hơn 40 nguyên liệu tươi: thịt, hải sản, viên thả, nấm, rau, mì khoai.', timing: '60s' },
    { num: 'BƯỚC 02', title: 'Chọn nước dùng', body: 'Sáu nồi đang sôi: từ cay tê mala, hầm xương ngô ngọt đến gà ác thuốc bắc.', timing: '10s' },
    { num: 'BƯỚC 03', title: 'Bếp hầm cho bạn', body: 'Topping được nhúng vào nồi nước dùng đã sôi, hầm chuẩn đúng từng nguyên liệu.', timing: '90s' },
    { num: 'BƯỚC 04', title: 'Thưởng thức', body: 'Một bát đầy đặn, đúng vị bạn chọn, kèm cơm trắng hoặc bánh mì giòn.', timing: '∞' },
  ];
  return (
    <section id="how" className="how">
      <div className="wrap">
        <div className="section-head">
          <div>
            <span className="eyebrow">Cách dùng</span>
            <h2>Bốn bước.<br/>Một bát đúng vị.</h2>
          </div>
          <p className="lead">
            Bạn không cần biết nấu, chỉ cần biết bạn thích gì.
            Mọi việc còn lại nằm trên thanh ray bếp hầm của chúng tôi.
          </p>
        </div>
        <div className="how-grid">
          {steps.map(s => (
            <div className="how-step" key={s.num}>
              <div className="num">{s.num}</div>
              <h3>{s.title}</h3>
              <p>{s.body}</p>
              <div className="timing">~ {s.timing}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============================================================
// TOPPING / PRICING
// ============================================================
function Toppings() {
  const tags = [
    'Bò Mỹ tươi',
    'Tôm sú',
    'Mực ống',
    'Viên cá hồi',
    'Đậu phụ non',
    'Nấm kim châm',
    'Nấm đùi gà',
    'Cải thảo',
    'Cải bó xôi',
    'Mì khoai lang',
    'Phù trúc',
    'Ngô ngọt',
    'Khoai môn',
  ];
  return (
    <section id="topping" className="toppings">
      <div className="wrap toppings-inner">
        <div>
          <div className="eyebrow">Topping</div>
          <h2>Tự chọn,<br/>tự cân,<br/>tự bát.</h2>
          <div className="pricing">
            <div className="price-big">32K</div>
            <div className="price-meta">
              <span className="vnd">VND</span>
              <span className="per">/ 100G ĐỒNG GIÁ</span>
            </div>
          </div>
          <p className="lede">
            Hơn 40 nguyên liệu tươi mỗi ngày, đồng giá theo trọng lượng.
            Bạn cầm khay, chọn đúng những gì bạn muốn ăn, không hơn, không kém.
          </p>
          <div className="topping-tags">
            {tags.map(t => (
              <span className="topping-tag" key={t}>{t}</span>
            ))}
            <span className="topping-tag" style={{borderColor:'var(--mh-cream)', background:'rgba(251,246,233,0.08)'}}>
              + 100 nguyên liệu khác
            </span>
          </div>
        </div>
        <div className="topping-vis">
          <div className="plate"></div>
          <div className="topping-orbit">
            <div className="topping-chip s1"><img src="images/bowl-pork-corn.webp" alt="" /></div>
            <div className="topping-chip s2"><img src="images/bowl-mala-mix.webp" alt="" /></div>
            <div className="topping-chip s3"><img src="images/bowl-tomato.webp" alt="" /></div>
            <div className="topping-chip s4"><img src="images/bowl-silkie.webp" alt="" /></div>
          </div>
          <div className="topping-orbit r">
            <div className="topping-chip s5"><img src="images/bowl-mala-beef.webp" alt="" /></div>
            <div className="topping-chip s6"><img src="images/bowl-mala-mix.webp" alt="" /></div>
          </div>
          <div className="topping-center">
            <div className="char">麻</div>
            <div className="lbl">CHỌN · CÂN · ĂN</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============================================================
// LOCATIONS
// ============================================================
function Locations() {
  const loc = {
    name: 'Hà Nội, Đống Đa',
    status: 'Đang phục vụ',
    addr: '115-K1 P. Giảng Võ, Ô Chợ Dừa, Hà Nội',
    hours: '10:00 – 22:30',
  };
  return (
    <section id="locations" className="locations">
      <div className="wrap">
        <div className="section-head">
          <div>
            <span className="eyebrow">Cửa hàng</span>
            <h2>Ghé chúng tôi.</h2>
          </div>
          <p className="lead">
            Chúng tôi vừa mở cửa hàng đầu tiên.
            Ghé qua, ngồi cạnh thanh ray bếp, nghe tiếng dầu rơi vào niêu cay tê.
          </p>
        </div>
        <div className="loc-single">
          <div className="loc-card loc-card-hero">
            <div className="map">
              <svg viewBox="0 0 800 480" preserveAspectRatio="xMidYMid slice">
                <g stroke="rgba(26,20,16,0.12)" strokeWidth="1" fill="none">
                  <path d="M0 100 L800 130" />
                  <path d="M0 200 L800 230" />
                  <path d="M0 300 L800 290" />
                  <path d="M0 400 L800 380" />
                  <path d="M120 0 L140 480" />
                  <path d="M300 0 L320 480" />
                  <path d="M500 0 L520 480" />
                  <path d="M680 0 L700 480" />
                </g>
                <circle cx="400" cy="240" r="160" fill="rgba(200,36,42,0.06)" />
                <circle cx="400" cy="240" r="100" fill="rgba(200,36,42,0.10)" />
                <circle cx="400" cy="240" r="54" fill="rgba(200,36,42,0.16)" />
              </svg>
              <div className="pin"><span>麻</span></div>
              <div className="map-tag">CỬA HÀNG ĐẦU TIÊN</div>
            </div>
            <div className="body">
              <div className="status">
                <span className="pip"></span>{loc.status}
              </div>
              <h3>{loc.name}</h3>
              <p className="addr">{loc.addr}</p>
              <div className="hours">
                <div><span>Giờ mở</span><br/><b>{loc.hours}</b></div>
                <div><span>Khai trương</span><br/><b>Vừa mở cửa</b></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============================================================
// CTA BAND
// ============================================================
function CtaBand() {
  return (
    <section id="book" className="cta-band">
      <div className="wrap">
        <h2>Vị lửa từ Tứ Xuyên.<br/><span className="red">Hầm chuẩn Việt.</span></h2>
      </div>
    </section>
  );
}

// ============================================================
// FOOTER
// ============================================================
function Footer() {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-top">
          <div className="footer-brand">
            <img className="logo" src="images/logo-stacked.png" alt="MALAHẦM" />
            <p>Lẩu Mala Tứ Xuyên hầm theo cách của người Việt: nấu chậm, cay tê, ngọt sâu.</p>
          </div>
          <div className="footer-col">
            <h4>Khám phá</h4>
            <ul>
              <li><a href="#story">Câu chuyện thương hiệu</a></li>
              <li><a href="#broths">Vị Lẩu</a></li>
              <li><a href="#topping">Topping</a></li>
              <li><a href="#how">Cách dùng</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Hỗ trợ</h4>
            <ul>
              <li><a href="#">Giờ mở cửa</a></li>
              <li><a href="#">Giao hàng tận nơi</a></li>
              <li><a href="#">Đặt tiệc & sự kiện</a></li>
              <li><a href="#">Câu hỏi thường gặp</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Liên hệ</h4>
            <div className="footer-address">
              115-K1 P. Giảng Võ,<br/>Ô Chợ Dừa, Hà Nội
            </div>
            <div className="footer-hotline-label">Hotline 24/7</div>
            <div className="footer-hotline">1900 1900</div>
            <ul style={{marginTop: 12}}>
              <li><a href="mailto:hello@malaham.vn">hello@malaham.vn</a></li>
              <li><a href="#">Hợp tác nhượng quyền</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 MALA HẦM · Mọi quyền được bảo lưu</span>
          <div className="socials">
            <a href="#" aria-label="Facebook">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M22 12a10 10 0 10-11.5 9.9V15h-2.5v-3h2.5V9.8c0-2.5 1.5-3.8 3.7-3.8 1.1 0 2.2.2 2.2.2v2.4h-1.2c-1.2 0-1.6.8-1.6 1.6V12h2.7l-.4 3h-2.3v6.9A10 10 0 0022 12z"/></svg>
            </a>
            <a href="#" aria-label="Instagram">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="0.5" fill="currentColor"/></svg>
            </a>
            <a href="#" aria-label="TikTok">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M21 8.5a7.5 7.5 0 01-5-1.8V16a6 6 0 11-6-6v3a3 3 0 103 3V2h3a4.5 4.5 0 005 4.5v2z"/></svg>
            </a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ============================================================
// APP
// ============================================================
function App() {
  return (
    <>
      <Nav />
      <Hero />
      <Ticker />
      <Story />
      <Broths />
      <How />
      <Toppings />
      <Locations />
      <CtaBand />
      <Footer />
    </>
  );
}

Object.assign(window, { App, Nav, Hero, Ticker, Story, Broths, How, Toppings, Locations, CtaBand, Footer });
