/* global React */
/* PHASE 1 (Brand Kit V2) — nav + hero + footer + yakujihō dev banner.
   Taglines + body copy in this file are CLIENT-CONFIRMED and pending
   yakujihō (pharmacist/legal) review. Do not auto-soften. */

// Resolve asset path: products/*.html are one level deeper than root pages.
const MM_ASSET_PREFIX = (typeof window !== 'undefined' &&
  window.location.pathname.indexOf('/products/') !== -1)
  ? '../assets/'
  : 'assets/';
const { useState } = React;

// ============= Yakujihō dev banner — removed per client request =============
function YakujihouFlag() {
  return null;
}

// Resolve home page path: products/*.html are one level deeper than root pages.
const MM_HOME_HREF = (typeof window !== 'undefined' &&
  window.location.pathname.indexOf('/products/') !== -1)
  ? '../index.html'
  : 'index.html';

// True when we're currently on the home page (so anchor links can smooth-scroll
// in-place instead of triggering a navigation).
function mmIsHomePage() {
  if (typeof window === 'undefined') return false;
  var p = window.location.pathname;
  if (p.indexOf('/products/') !== -1) return false;
  if (/\/shop\.html$/.test(p)) return false;
  if (/\/intro(\.backup-[\w-]+)?\.html$/.test(p)) return false;
  return true;
}

function mmNavLinkClick(e, anchor) {
  if (!mmIsHomePage()) return; // let browser navigate to home + hash
  var el = document.getElementById(anchor);
  if (!el) return;
  e.preventDefault();
  el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  history.replaceState(null, '', '#' + anchor);
}

// ============= FloatingNav =============
function FloatingNav({ onShop }) {
  // Order: WORLD / MONSTERS / COLLAB / CONTACT
  const links = ['WORLD', 'MONSTERS', 'COLLAB', 'CONTACT'];
  return (
    <nav className="mm-nav" aria-label="Primary">
      <a className="mm-nav__brand" href={mmIsHomePage() ? '#top' : MM_HOME_HREF} aria-label="MY MONSTERS — home">
        <img className="mm-nav__logo" src={MM_ASSET_PREFIX + 'logo-mymonsters.png'} alt="" />
      </a>
      <ul className="mm-nav__links">
        {links.map(l => {
          const anchor = l.toLowerCase();
          return (
            <li key={l}>
              <a
                className="mm-nav__link"
                href={`${MM_HOME_HREF}#${anchor}`}
                onClick={(e) => mmNavLinkClick(e, anchor)}
              >{l}</a>
            </li>
          );
        })}
      </ul>
      <button className="mm-nav__cta" onClick={onShop}>SHOP NOW</button>
    </nav>
  );
}

// ============= Hero (Brand Kit V2) =============
// Confirmed tagline: EAT YOUR PAIN. (brand red) / 悩みを食い尽くせ。 (ink)
// REMOVED: FUEL THE FUTURE. / 未来に、燃料を。
//
// Opening overlay video: plays ONCE on page load, covers the hero,
// then fades out → the existing hero (title/actions/scrollhint) fades in.
// The video has the same headline burned into it; the existing hero
// is hidden (opacity:0) during playback so the two never co-exist.
//
// After the initial play, clicking the hero background replays the
// intro. Clicks on inner <a>/<button> elements (SHOP NOW, READ THE
// WORLD) take their native action — the closest() check on the
// section handler stops the replay trigger from hijacking them.
function Hero({ onShop }) {
  const [opening, setOpening] = useState(true);
  const [hideOverlay, setHideOverlay] = useState(false);
  const videoRef = React.useRef(null);
  React.useEffect(() => {
    if (!opening) return;
    // Some browsers stall autoplay until a manual .play() call even
    // when muted+playsInline are set. Try to kick it, and rewind so
    // replay clicks restart from frame 0.
    const v = videoRef.current;
    if (v) {
      try { v.currentTime = 0; } catch (_) {}
      try { v.play().catch(() => {}); } catch (_) {}
    }
    // Safety: if `ended` never fires (codec issue, decode error, etc.),
    // reveal the hero anyway after ~11s.
    const safety = setTimeout(() => endOpening(), 11000);
    return () => clearTimeout(safety);
  }, [opening]);
  const endOpening = () => {
    setOpening(false);
    // After the hero finishes its 500ms fade-in, drop the overlay from
    // the DOM entirely so it can't ever block clicks.
    setTimeout(() => setHideOverlay(true), 600);
  };
  const onSectionClick = (e) => {
    // Don't retrigger while the intro is currently playing.
    if (opening) return;
    if (e.defaultPrevented) return;
    if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    // Native links / buttons inside the hero (SHOP NOW, READ THE
    // WORLD ↘) keep their native behaviour — don't replay if the
    // click landed on one.
    if (e.target.closest('a, button')) return;
    // Replay: remount the video element + rerun the opening flow.
    setHideOverlay(false);
    setOpening(true);
  };
  return (
    <section
      className={`mm-hero ${opening ? 'is-opening' : 'is-opened'}`}
      data-screen-label="01 Hero"
      id="top"
      onClick={onSectionClick}
    >
      <div className="mm-hero__bg" aria-hidden="true">
        <div className="mm-hero__bg-fallback"></div>
      </div>
      <div className="mm-hero__inner">
        <h1 className="mm-hero__title">
          <span className="mm-hero__title-en">EAT YOUR PAIN.</span>
          <span className="mm-hero__title-jp">悩みを食い尽くせ。</span>
        </h1>
        <div className="mm-hero__actions">
          <button className="mm-btn mm-btn--filled" onClick={onShop}>SHOP NOW →</button>
          <a className="mm-btn mm-btn--ghost" href="#world">READ THE WORLD ↘</a>
        </div>
      </div>
      {hideOverlay ? null : (
        <video
          ref={videoRef}
          className={`mm-hero__opening ${opening ? '' : 'is-done'}`}
          autoPlay
          muted
          playsInline
          preload="auto"
          onEnded={endOpening}
          aria-hidden="true"
        >
          <source src="assets/hero-opening.webm" type="video/webm" />
        </video>
      )}
    </section>
  );
}

// ============= Footer (Brand Kit V2) =============
function Footer() {
  // Footer nav: WORLD/MONSTERS/COLLAB/HOME sections live only on the home page,
  // so on inner pages (shop / products) prefix them with the home-page path.
  // CONTACT (#contact) is the footer itself — present on every page — so it
  // stays a local anchor. SHOP points at shop.html with the right depth.
  const mmFootHomePrefix = mmIsHomePage() ? '' : MM_HOME_HREF;
  const mmFootShopHref = (typeof window !== 'undefined' &&
    window.location.pathname.indexOf('/products/') !== -1)
    ? '../shop.html'
    : 'shop.html';
  const cols = [
    { l: 'HOME',     h: mmFootHomePrefix + '#top' },
    { l: 'MONSTERS', h: mmFootHomePrefix + '#monsters' },
    { l: 'WORLD',    h: mmFootHomePrefix + '#world' },
    { l: 'COLLAB',   h: mmFootHomePrefix + '#collab' },
    { l: 'CONTACT',  h: '#contact' },
    { l: 'SHOP',     h: mmFootShopHref },
  ];
  return (
    <footer className="mm-footer" data-screen-label="99 Footer" id="contact">
      <div className="mm-footer__top">
        <div className="mm-footer__logo-wrap footer-logo-panel">
          <video
            className="footer-logo-video"
            autoPlay
            loop
            muted
            playsInline
            preload="metadata"
            aria-label="MY MONSTERS"
          >
            <source src={MM_ASSET_PREFIX + 'footer-logo-loop.webm'} type="video/webm" />
            {/* Fallback image renders inside the video tag if WebM is unsupported */}
            <img className="mm-footer__logo" src={MM_ASSET_PREFIX + 'logo-mymonsters.png'} alt="MY MONSTERS" />
          </video>
        </div>
      </div>
      <nav className="mm-footer__nav" aria-label="Footer">
        {cols.map(c => <a key={c.l} href={c.h}>{c.l}</a>)}
      </nav>
      <div className="mm-footer__hq">
        <div className="mm-footer__hq-title">THE MONSTERS&rsquo; HEADQUARTERS</div>
        <div className="mm-footer__hq-line">株式会社GROWX</div>
        <div className="mm-footer__hq-line">〒150&ndash;0001 東京都渋谷区神宮前3-2-19</div>
        <div className="mm-footer__hq-line">03-6161-2993</div>
        <div className="mm-footer__hq-line">info@growx.co.jp</div>
      </div>
      <div className="mm-footer__bottom">
        <span>© 2026 MY MONSTERS. All rights reserved.</span>
        <span className="mm-footer__manifesto">NO PLACEBO. JUST VIOLENCE.</span>
      </div>
    </footer>
  );
}

Object.assign(window, { YakujihouFlag, FloatingNav, Hero, Footer });
