/* tenroin-top/chrome.jsx — primitives, hooks, header, mobile nav, footer, mobile CTA */

const { useState, useEffect, useRef, useCallback } = React;

const NAV = [
  ['new2027','ニュース','NEWS'],
  ['stores','店舗','STORES'],
  ['learn','講座','SEMINARS'],
  ['series','読書クラブ','BOOK CLUB'],
  ['column','結婚相談所','BOOKLOVE'],
  ['note','note','MAGAZINE'],
];

const Star = ({size=14,color='var(--gold-500)',style}) =>
  <span style={{color,fontSize:size,lineHeight:1,display:'inline-block',...style}}>✦</span>;

function smooth(id){
  const el = document.getElementById(id);
  if(el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 54, behavior:'smooth' });
}

/* gentle scroll-reveal */
function useReveal(){
  useEffect(()=>{
    const reduce = matchMedia('(prefers-reduced-motion:reduce)').matches;
    if(!('IntersectionObserver' in window) || reduce){
      document.querySelectorAll('[data-reveal]:not(.is-in)').forEach(e=>e.classList.add('is-in'));
      // still watch for dynamically added nodes and reveal them immediately
      const mo0 = new MutationObserver(muts=>muts.forEach(m=>m.addedNodes.forEach(n=>{
        if(n.nodeType!==1) return;
        if(n.matches&&n.matches('[data-reveal]')) n.classList.add('is-in');
        n.querySelectorAll&&n.querySelectorAll('[data-reveal]:not(.is-in)').forEach(e=>e.classList.add('is-in'));
      })));
      mo0.observe(document.body,{ childList:true, subtree:true });
      return ()=>mo0.disconnect();
    }
    const io = new IntersectionObserver((ents,obs)=>{
      ents.forEach(e=>{ if(e.isIntersecting){ e.target.classList.add('is-in'); obs.unobserve(e.target); } });
    },{ threshold:.14, rootMargin:'0px 0px -8% 0px' });

    const observe = (el)=>{
      if(el.classList.contains('is-in')) return;
      // already in (or above) the viewport → reveal now, don't wait for a scroll
      if(el.getBoundingClientRect().top < innerHeight*1.05){ el.classList.add('is-in'); return; }
      io.observe(el);
    };
    document.querySelectorAll('[data-reveal]:not(.is-in)').forEach(observe);

    // catch nodes added later by React re-renders (filters, tabs, async lists)
    const mo = new MutationObserver(muts=>muts.forEach(m=>m.addedNodes.forEach(n=>{
      if(n.nodeType!==1) return;
      if(n.matches&&n.matches('[data-reveal]:not(.is-in)')) observe(n);
      n.querySelectorAll&&n.querySelectorAll('[data-reveal]:not(.is-in)').forEach(observe);
    })));
    mo.observe(document.body,{ childList:true, subtree:true });

    return ()=>{ io.disconnect(); mo.disconnect(); };
  });
}

/* parallax: elements with [data-parallax="speed"] translate on scroll */
function useParallax(){
  useEffect(()=>{
    const els = Array.from(document.querySelectorAll('[data-parallax]'));
    if(!els.length || matchMedia('(prefers-reduced-motion:reduce)').matches) return;
    let raf=0;
    const tick=()=>{
      raf=0;
      const vh=innerHeight;
      els.forEach(el=>{
        const sp=parseFloat(el.dataset.parallax)||.12;
        const r=el.getBoundingClientRect();
        const center=r.top+r.height/2-vh/2;
        el.style.transform=`translate3d(0,${(-center*sp).toFixed(1)}px,0) scale(${el.dataset.pscale||1})`;
      });
    };
    const onScroll=()=>{ if(!raf) raf=requestAnimationFrame(tick); };
    tick();
    addEventListener('scroll',onScroll,{passive:true});
    addEventListener('resize',onScroll);
    return ()=>{ removeEventListener('scroll',onScroll); removeEventListener('resize',onScroll); cancelAnimationFrame(raf); };
  });
}

function Header({ solid, onMenu }){
  return (
    <header className={'site-head'+(solid?' is-solid':'')}>
      <div className="head-strip">
        <span className="hs-en">READING LIFE — 本のその先の体験</span>
        <span className="hs-season">{window.MAG.ISSUE.ja} ／ {window.MAG.ISSUE.season}</span>
        <span className="hs-en">SINCE 2013</span>
      </div>
      <div className="head-inner">
        <nav className="head-nav">
          {NAV.slice(0,4).map(([id,jp])=>(
            <button key={id} className="head-link" onClick={()=>smooth(id)}>{jp}</button>
          ))}
        </nav>
        <button className="head-logo" onClick={()=>scrollTo({top:0,behavior:'smooth'})} aria-label="天狼院書店 TENRO-IN">
          <img src={solid?R('logoInk','assets/logo-wordmark-ink.png'):R('logoCream','assets/logo-wordmark-cream.png')} alt="天狼院書店 TENRO-IN"/>
        </button>
        <nav className="head-nav r">
          {NAV.slice(4).map(([id,jp])=>(
            <button key={id} className="head-link" onClick={()=>smooth(id)}>{jp}</button>
          ))}
          <a className="head-link is-sister" href="#bookshelf" onClick={e=>{e.preventDefault();smooth('bookshelf');}}>海の出版社<span className="ar">▸</span></a>
          <button className="head-mini desk">マイページ</button>
          <button className="head-burger" onClick={onMenu} aria-label="メニュー">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 6h18M3 12h18M3 18h18"/></svg>
          </button>
        </nav>
      </div>
    </header>
  );
}

function MobileNav({ open, onClose }){
  return (
    <div className={'mnav'+(open?' is-open':'')}>
      <div className="mnav-top">
        <img src={R('logoCream','assets/logo-wordmark-cream.png')} alt="天狼院書店"/>
        <button className="mnav-close" onClick={onClose} aria-label="閉じる">×</button>
      </div>
      <ul className="mnav-list">
        {NAV.map(([id,jp,en])=>(
          <li key={id}><button className="mnav-link" onClick={()=>{onClose();setTimeout(()=>smooth(id),260);}}>
            <span className="ml-en">{en}</span><span className="ml-jp">{jp}</span>
          </button></li>
        ))}
      </ul>
      <div className="mnav-foot">
        <button className="btn btn-ghost-l" onClick={()=>{onClose();setTimeout(()=>smooth('bookshelf'),260);}}>海の出版社 ▸</button>
        <button className="btn btn-gold" onClick={onClose}>マイページ / ログイン</button>
      </div>
    </div>
  );
}

function MobileCTA({ show }){
  return (
    <div className={'mcta'+(show?' is-show':'')}>
      <div className="mcta-in">
        <div className="mcta-l">
          <div className="mc-k">{window.MAG.ISSUE.ja}</div>
          <div className="mc-t">人生を変える、本と出合う。</div>
        </div>
        <button className="btn btn-gold" onClick={()=>smooth('stores')}>今号を読む →</button>
      </div>
    </div>
  );
}

function Colophon(){
  return (
    <section className="colophon">
      <div className="wrap colo-in" data-reveal>
        <p className="colo-quote">「本を読む」のではなく、<br/>「本のその先」を、生きる。<br/><span style={{color:'var(--gold-700)'}}>——次号も、あなたの人生に。</span></p>
        <div className="colo-sister">
          <div className="cso-en">SISTER MAGAZINE — 海の出版社</div>
          <h3 className="cso-h">AI時代の本を、天狼院から。</h3>
          <p className="cso-p">姉妹誌「海の出版社」では、SEA LEARNING や書籍診断など、読むことの新しい形を発信しています。</p>
          <a className="melt-cta" href="https://sea-publishing.com" onClick={e=>e.preventDefault()}>海の出版社をひらく<span className="ar">▸</span></a>
        </div>
      </div>
    </section>
  );
}

function Footer(){
  const stores = [
    ['SHIBUYA','天狼院カフェ SHIBUYA','東京都渋谷区神宮前6 宮下パーク','03-6450-6261'],
    ['NAGOYA','名古屋天狼院','名古屋市中区錦3 久屋大通','052-211-9791'],
    ['KYOTO','京都天狼院','京都市中京区三条通','075-708-3930'],
    ['FUKUOKA','福岡天狼院','福岡市中央区天神','092-518-7435'],
  ];
  const cols = [
    ['天狼院について',['READING LIFEとは','店主・三浦崇典','会社概要','採用情報','B2B・特約店']],
    ['まなぶ・あつまる',['ライティング・ゼミ','フォト部 / 演劇ゼミ','AI・ラボ','読書クラブ','結婚相談所BOOKLove']],
    ['よむ・かう',['WEB READING LIFE','note マガジン','メディアグランプリ','オンライン書店']],
    ['つながる',['海の出版社 ▸','天狼院クリエイターズ','メールマガジン','お問い合わせ']],
  ];
  return (
    <footer className="site-foot" id="footer">
      <div className="foot-stores" data-reveal>
        {stores.map(([en,nm,ad,tel])=>(
          <div className="foot-store" key={en}>
            <div className="fst-en">{en}</div>
            <div className="fst-name">{nm}</div>
            <span className="fst-l">{ad}</span>
            <span className="fst-l">TEL {tel}</span>
          </div>
        ))}
      </div>
      <div className="foot-top">
        <div className="foot-brand">
          <img src={R('footLogo','assets/logo-cream-sm.png')} alt="天狼院書店 TENRO-IN"/>
          <p className="foot-tag">READING LIFE — 本のその先の体験。</p>
          <div className="foot-stars"><Star color="var(--gold-400)"/><Star size={10} color="rgba(214,188,126,.7)"/><Star size={8} color="rgba(214,188,126,.5)"/></div>
        </div>
        <div className="foot-cols">
          {cols.map(([h,items])=>(
            <div key={h}>
              <div className="foot-h">{h}</div>
              {items.map(it=><button key={it} className="foot-l">{it}</button>)}
            </div>
          ))}
        </div>
      </div>
      <div className="foot-bottom">
        <span>© {new Date().getFullYear()} 天狼院書店 ／ 株式会社海の出版社</span>
        <span className="foot-sns">
          <button>X</button><button>INSTAGRAM</button><button>YOUTUBE</button><button>NOTE</button>
        </span>
        <span>プライバシーポリシー　・　特定商取引法に基づく表記</span>
      </div>
    </footer>
  );
}

Object.assign(window, { Star, smooth, useReveal, useParallax, Header, MobileNav, MobileCTA, Colophon, Footer });
