// Subpage shell: simplified TopNav + Footer + helpers for non-home pages.
// Loaded with Babel; depends on React being on window.

const { useState: _useS, useEffect: _useE, useRef: _useR } = React;

// ─── Language preference (localStorage-backed, shared across pages) ─────────
const PAGE_LANG_KEY = 'marip-lang';
const getPageLang = () => {
  try {
    const v = localStorage.getItem(PAGE_LANG_KEY);
    return v === 'en' ? 'en' : 'ja';
  } catch (e) { return 'ja'; }
};
const setPageLang = (v) => {
  try { localStorage.setItem(PAGE_LANG_KEY, v === 'en' ? 'en' : 'ja'); } catch (e) {}
};
function usePageLang() {
  const [lang, setLangState] = _useS(getPageLang());
  const setLang = (v) => {
    if (v === lang) return;
    setPageLang(v);
    setLangState(v);
    // Reload so per-page i18n dictionaries pick up the new lang on initial render
    window.location.reload();
  };
  return [lang, setLang];
}

// ─── PageNav strings ────────────────────────────────────────────────────────
const NAV_I18N = {
  ja: { contact: 'お問い合わせ' },
  en: { contact: 'Contact' },
};

// ─── PageFooter strings (used by every subpage) ─────────────────────────────
const FOOTER_I18N = {
  ja: {
    brand: '株式会社MARIP',
    tagline: 'Make Ripples — System Engineering, Web & Software',
    addrLines: ['〒150-0002', '東京都渋谷区渋谷2-19-15', '宮益坂ビルディング609'],
    companyInfoLabel: '— Company Information —',
    companyInfoMore: '会社概要を見る',
    companyInfo: [
      { k: '会社名',   v: '株式会社MARIP' },
      { k: '代表者',   v: '代表取締役 松瀬 仁志' },
      { k: '設立',     v: '2023年9月12日' },
      { k: '資本金',   v: '100万円' },
      { k: '事業内容', v: 'SES / 受託開発 / Web制作 / エージェント事業' },
      { k: '所在地',   v: '東京都渋谷区渋谷2-19-15 宮益坂ビルディング609' },
    ],
    links: [
      { label: 'サービス',           href: 'services/' },
      { label: '会社案内',           href: 'company/' },
      { label: '採用',               href: 'careers/' },
      { label: 'お知らせ',           href: 'news/' },
      { label: 'お問い合わせ',       href: 'contact/' },
      { label: 'プライバシーポリシー', href: 'privacy/' },
    ],
    copy: 'All rights reserved.',
  },
  en: {
    brand: 'MARIP Inc.',
    tagline: 'Make Ripples — System Engineering, Web & Software',
    addrLines: ['Miyamasuzaka Bldg 609', '2-19-15 Shibuya, Shibuya-ku', 'Tokyo 150-0002, Japan'],
    companyInfoLabel: '— Company Information —',
    companyInfoMore: 'View company profile',
    companyInfo: [
      { k: 'Company',        v: 'MARIP Inc.' },
      { k: 'Representative', v: 'Hitoshi Matsuse, CEO' },
      { k: 'Founded',        v: 'September 12, 2023' },
      { k: 'Capital',        v: 'JPY 1,000,000' },
      { k: 'Business',       v: 'SES / Contract Dev / Web / Engineer Agency' },
      { k: 'Address',        v: 'Miyamasuzaka Bldg 609, 2-19-15 Shibuya, Shibuya-ku, Tokyo 150-0002, Japan' },
    ],
    links: [
      { label: 'Services', href: 'services/' },
      { label: 'Company',  href: 'company/' },
      { label: 'Careers',  href: 'careers/' },
      { label: 'News',     href: 'news/' },
      { label: 'Contact',  href: 'contact/' },
      { label: 'Privacy',  href: 'privacy/' },
    ],
    copy: 'All rights reserved.',
  },
};

// ─── Custom cursor (matches TOP page) ───────────────────────────────────────
const PageCursor = ({ accent = '#F4F8F6' }) => {
  const dotRef = _useR(null);
  const ringRef = _useR(null);
  _useE(() => {
    let mx = -100, my = -100, rx = -100, ry = -100;
    const onMove = (e) => { mx = e.clientX; my = e.clientY; };
    window.addEventListener('mousemove', onMove);
    let raf;
    const tick = () => {
      rx += (mx - rx) * 0.18;
      ry += (my - ry) * 0.18;
      if (dotRef.current) dotRef.current.style.transform = `translate(${mx}px, ${my}px) translate(-50%, -50%)`;
      if (ringRef.current) ringRef.current.style.transform = `translate(${rx}px, ${ry}px) translate(-50%, -50%)`;
      raf = requestAnimationFrame(tick);
    };
    tick();
    return () => {
      window.removeEventListener('mousemove', onMove);
      cancelAnimationFrame(raf);
    };
  }, []);
  return (
    <>
      <div ref={dotRef} className="cursor-dot" style={{ background: accent }}></div>
      <div ref={ringRef} className="cursor-ring" style={{ borderColor: 'rgba(255,255,255,0.35)' }}></div>
    </>
  );
};

// ─── Subpage navigation data (single source of truth) ───────────────────────
// hrefs are relative to project root. Trailing slash directories (no index.html)
// keep canonical URL parity with sitemap.xml / canonical tags.
const SITE_NAV = [
  { label: 'Services', jp: 'サービス', href: 'services/', num: '01' },
  { label: 'Mission', jp: 'ミッション', href: 'mission/', num: '02' },
  { label: 'Company', jp: '会社案内', href: 'company/', num: '03' },
  { label: 'Careers', jp: '採用', href: 'careers/', num: '04' },
  { label: 'News', jp: 'お知らせ', href: 'news/', num: '05' },
  { label: 'Contact', jp: 'お問い合わせ', href: 'contact/', num: '06' },
];

// All paths are absolute so links work from any depth.
// home prop is the relative path to root (e.g. "../" or "../../") for the brand link.

const PageNav = ({ home = '../', current = '' }) => {
  const [scrolled, setScrolled] = _useS(false);
  const [menuOpen, setMenuOpen] = _useS(false);
  const [lang, setLang] = usePageLang();
  // Auto-apply scroll-reveal to page sections for all subpages
  useAutoReveal();
  _useE(() => {
    const onS = () => setScrolled(window.scrollY > 20);
    onS();
    window.addEventListener('scroll', onS);
    return () => window.removeEventListener('scroll', onS);
  }, []);
  _useE(() => {
    document.body.classList.toggle('no-scroll', menuOpen);
    return () => document.body.classList.remove('no-scroll');
  }, [menuOpen]);
  _useE(() => {
    const onKey = (e) => { if (e.key === 'Escape') setMenuOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);
  const tNav = NAV_I18N[lang];
  const menuLabel = lang === 'en' ? 'Menu' : 'メニュー';
  const closeLabel = lang === 'en' ? 'Close' : '閉じる';
  const currentKey = (current || '').replace(/^\//, '').replace(/\/$/, '');
  return (
    <header className={`topnav ${scrolled || menuOpen ? 'topnav--scrolled' : 'topnav--scrolled'}`}>
      <div className="topnav-inner">
        <a href={home} className="brand">
          <img src={`${home}assets/marip-logo.svg`} alt="MARIP" className="brand-logo" />
          <span className="brand-sub">Inc.</span>
        </a>
        <nav className="topnav-links">
          {SITE_NAV.map((n, i) => {
            const isCurrent = currentKey && n.href.startsWith(currentKey + '/');
            return (
              <a
                key={i}
                href={`${home}${n.href}`}
                className="topnav-link"
                style={isCurrent ? { color: 'var(--fg)' } : undefined}
              >
                <span className="topnav-link-num">{n.num}</span>
                <span>{lang === 'en' ? n.label : n.jp}</span>
              </a>
            );
          })}
        </nav>
        <div className="topnav-right">
          <div className="lang-switch">
            <button className={lang === 'ja' ? 'active' : ''} onClick={() => setLang('ja')}>JA</button>
            <span>/</span>
            <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
          </div>
          <a href={`${home}contact/`} className="mag-btn"
            style={{ background: '#F4F8F6', color: '#0C1814', border: '1px solid #F4F8F6' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
              {tNav.contact}
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </span>
          </a>
          <button
            type="button"
            className={`nav-toggle ${menuOpen ? 'nav-toggle--open' : ''}`}
            aria-label={menuOpen ? closeLabel : menuLabel}
            aria-expanded={menuOpen}
            onClick={() => setMenuOpen(o => !o)}
          >
            <span className="nav-toggle-bar"></span>
          </button>
        </div>
      </div>
      <div
        className={`mobile-menu ${menuOpen ? 'mobile-menu--open' : ''}`}
        role="dialog"
        aria-hidden={!menuOpen}
      >
        <button
          type="button"
          className="mobile-menu-close"
          aria-label={closeLabel}
          onClick={() => setMenuOpen(false)}
        >
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none" aria-hidden="true">
            <path d="M3 3l12 12M15 3L3 15" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
        </button>
        <nav className="mobile-menu-nav">
          {SITE_NAV.map((n, i) => {
            const isCurrent = currentKey && n.href.startsWith(currentKey + '/');
            return (
              <a
                key={i}
                href={`${home}${n.href}`}
                className={`mobile-menu-link ${isCurrent ? 'mobile-menu-link--current' : ''}`}
                onClick={() => setMenuOpen(false)}
              >
                <span className="mobile-menu-link-num">{n.num}</span>
                <span>{lang === 'en' ? n.label : n.jp}</span>
              </a>
            );
          })}
        </nav>
        <div className="mobile-menu-foot">
          <div className="lang-switch lang-switch--mobile">
            <button className={lang === 'ja' ? 'active' : ''} onClick={() => setLang('ja')}>JA</button>
            <span>/</span>
            <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
          </div>
          <a
            href={`${home}contact/`}
            className="mobile-menu-cta"
            onClick={() => setMenuOpen(false)}
          >
            <span>{tNav.contact}</span>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </a>
        </div>
      </div>
    </header>
  );
};

// ─── Sub hero / page header ─────────────────────────────────────────────────
const SubHero = ({ eyebrow, en, title, lede, crumbs, theme = 'noir', intensity = 0.7 }) => {
  const innerRef = _useR(null);
  _useE(() => {
    const root = innerRef.current;
    if (!root) return;
    const items = root.querySelectorAll('.subhero-crumbs, .subhero-eyebrow, .subhero-title, .subhero-en, .subhero-lede');
    items.forEach((el, i) => {
      el.style.opacity = '0';
      el.style.transform = 'translateY(24px)';
      el.style.transition = `transform .9s cubic-bezier(.22,1,.36,1) ${i * 0.12}s, opacity .9s ease ${i * 0.12}s`;
    });
    requestAnimationFrame(() => {
      items.forEach(el => {
        el.style.opacity = '1';
        el.style.transform = 'translateY(0)';
      });
    });
  }, []);
  return (
    <section className="subhero">
      {typeof window !== 'undefined' && window.RippleCanvas && (
        <div className="subhero-ripple">
          <window.RippleCanvas theme={theme} intensity={intensity} />
        </div>
      )}
      <div className="subhero-inner" ref={innerRef}>
        {crumbs && (
          <div className="subhero-crumbs">
            {crumbs.map((c, i) => (
              <React.Fragment key={i}>
                {i > 0 && <span className="sep">/</span>}
                {c.href ? <a href={c.href}>{c.label}</a> : <span>{c.label}</span>}
              </React.Fragment>
            ))}
          </div>
        )}
        {eyebrow && (
          <div className="subhero-eyebrow">
            <span className="subhero-eyebrow-line"></span>
            <span>{eyebrow}</span>
          </div>
        )}
        <h1 className="subhero-title">{title}</h1>
        {en && <p className="subhero-en">{en}</p>}
        {lede && <p className="subhero-lede">{lede}</p>}
      </div>
    </section>
  );
};

// ─── Footer (lighter version, links to all real pages) ──────────────────────
const PageFooter = ({ home = '../' }) => {
  const lang = getPageLang();
  const t = FOOTER_I18N[lang];
  return (
    <footer className="footer">
      <div className="footer-top">
        <div className="footer-brand">
          <img src={`${home}assets/marip-logo.svg`} alt="MARIP" className="footer-logo" />
          <div>
            <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '0.02em' }}>{t.brand}</div>
            <div className="footer-tag">{t.tagline}</div>
          </div>
        </div>
        <div className="footer-addr">
          {t.addrLines.map((line, i) => (
            <React.Fragment key={i}>{line}{i < t.addrLines.length - 1 && <br />}</React.Fragment>
          ))}
        </div>
      </div>

      <div className="footer-company">
        <div className="footer-company-head">
          <span className="eyebrow">{t.companyInfoLabel}</span>
          <a href={`${home}company/`} className="footer-company-more">
            {t.companyInfoMore}
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
              <path d="M5 12h14M12 5l7 7-7 7" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </a>
        </div>
        <dl className="footer-company-list">
          {t.companyInfo.map((row, i) => (
            <div className="footer-company-row" key={i}>
              <dt>{row.k}</dt>
              <dd>{row.v}</dd>
            </div>
          ))}
        </dl>
      </div>

      <div className="footer-huge" style={{ color: 'var(--accent)' }}>
        MARIP
        <span className="footer-huge-sub">—Make Ripples—</span>
      </div>

      <div className="footer-bot">
        <div className="footer-links">
          {t.links.map((l, i) => (
            <a key={i} href={`${home}${l.href}`}>{l.label}</a>
          ))}
        </div>
        <div className="footer-copy">
          © {new Date().getFullYear()} MARIP Inc. {t.copy}
        </div>
      </div>
    </footer>
  );
};

// ─── Generic CTA band ───────────────────────────────────────────────────────
const PageCta = ({ title, sub, button, href = '../contact/' }) => {
  const lang = getPageLang();
  const label = button || (lang === 'en' ? 'Contact' : 'お問い合わせ');
  return (
    <section className="page-cta">
      <div>
        <h2>{title}</h2>
        {sub && <p>{sub}</p>}
      </div>
      <a href={href} className="mag-btn"
        style={{ background: '#F4F8F6', color: '#0C1814', border: '1px solid #F4F8F6' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
          {label}
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </span>
      </a>
    </section>
  );
};

// イントロオーバーレイ（marip-intro--lock）が外れるまで実行を待つヘルパ。
// オーバーレイ表示中に IntersectionObserver が幾何的に「見えている」と判定し、
// アニメがオーバーレイの裏で消化されてしまうのを防ぐ。
const _afterIntro = (fn) => {
  if (!document.documentElement.classList.contains('marip-intro--lock')) {
    fn();
    return () => {};
  }
  const mo = new MutationObserver(() => {
    if (!document.documentElement.classList.contains('marip-intro--lock')) {
      mo.disconnect();
      fn();
    }
  });
  mo.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
  return () => mo.disconnect();
};

// ─── Reveal-on-scroll wrapper (mirror of TOP page's Reveal) ─────────────────
const Reveal = ({ children, delay = 0, y = 40, className = '' }) => {
  const ref = _useR(null);
  const [visible, setVisible] = _useS(false);
  _useE(() => {
    const el = ref.current;
    if (!el) return;
    let obs;
    const stopWait = _afterIntro(() => {
      obs = new IntersectionObserver(
        ([e]) => { if (e.isIntersecting) { setVisible(true); obs.disconnect(); } },
        { threshold: 0.15 }
      );
      obs.observe(el);
    });
    return () => { stopWait(); if (obs) obs.disconnect(); };
  }, []);
  return (
    <div
      ref={ref}
      className={className}
      style={{
        transform: visible ? 'translateY(0)' : `translateY(${y}px)`,
        opacity: visible ? 1 : 0,
        transition: `transform 1.1s cubic-bezier(.22,1,.36,1) ${delay}s, opacity 1.1s ease ${delay}s`,
      }}
    >
      {children}
    </div>
  );
};

// ─── Auto-reveal: any element with [data-reveal] gets fade-up on scroll ─────
// Also auto-targets common page section elements so existing pages get the
// TOP-page style fade-up without per-page edits.
const useAutoReveal = () => {
  _useE(() => {
    let obs;
    const apply = () => {
      const selectors = [
        '[data-reveal]',
        '.page-section .page-section-head',
        '.page-section .prose > *',
        '.page-section > .def-table',
        '.page-section > .map-frame',
        '.page-section > .feature-grid > *',
        '.page-section > .timeline > *',
        '.page-section > .step-list > *',
        '.page-section > .article-meta',
        '.value-cell',
        '.mvv-row',
        '.ripple-diagram',
        '.article > *',
      ];
      const els = Array.from(new Set(document.querySelectorAll(selectors.join(','))));
      if (!els.length) return;
      els.forEach((el) => {
        if (el.dataset.revealApplied === '1') return;
        el.dataset.revealApplied = '1';
        el.style.opacity = '0';
        el.style.transform = 'translateY(40px)';
        el.style.transition = 'transform 1.0s cubic-bezier(.22,1,.36,1), opacity 1.0s ease';
        const d = parseFloat(el.dataset.revealDelay || '0');
        el.style.transitionDelay = `${d}s`;
      });
      obs = new IntersectionObserver(entries => {
        entries.forEach(en => {
          if (en.isIntersecting) {
            en.target.style.opacity = '1';
            en.target.style.transform = 'translateY(0)';
            obs.unobserve(en.target);
          }
        });
      }, { threshold: 0.12, rootMargin: '0px 0px -8% 0px' });
      els.forEach(el => obs.observe(el));
    };
    // Wait two frames so React has flushed the full subtree to the DOM.
    // さらに、初回訪問時はイントロオーバーレイが消えるまで観測開始を待つ。
    let stopWait = () => {};
    const r1 = requestAnimationFrame(() => requestAnimationFrame(() => {
      stopWait = _afterIntro(apply);
    }));
    return () => {
      cancelAnimationFrame(r1);
      stopWait();
      if (obs) obs.disconnect();
    };
  }, []);
};

Object.assign(window, {
  SITE_NAV, PageNav, PageCursor, SubHero, PageFooter, PageCta, Reveal, useAutoReveal,
  getPageLang, setPageLang, usePageLang, NAV_I18N, FOOTER_I18N,
});
