// shared.jsx — Logo, Nav, Footer, helpers used across pages

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

/* ---------------------------------------------------------- *
 * Logo — recreated as inline SVG so we can theme the wordmark *
 * ---------------------------------------------------------- */
function LogoMark({ small }) {
  // Three overlapping shapes (red square / green triangle / blue circle)
  // matching the original logo geometry, plus a wordmark we can theme.
  const w = small ? 42 : 48;
  return (
    <span className="nav__logo">
      <svg
        className="logo-mark"
        width={w}
        height={w}
        viewBox="0 0 36 36"
        aria-hidden="true"
      >
        {/* red rotated square */}
        <rect
          x="9" y="17" width="13" height="13"
          transform="rotate(6 15.5 23.5)"
          fill="#c8362c" fillOpacity=".82"
        />
        {/* green triangle */}
        <polygon
          points="14,9 28,7 25,22"
          fill="#2f8a4e" fillOpacity=".82"
        />
        {/* blue circle */}
        <circle cx="13" cy="14" r="7" fill="#3b8fc4" fillOpacity=".82" />
      </svg>
      <span className="nav__logo-text word"
        style={{
          fontFamily: 'Inter, sans-serif',
          fontWeight: 700,
          fontSize: small ? 18 : 19.5,
          letterSpacing: '0.10em'
        }}
      >
        VARIETIES
      </span>
    </span>
  );
}

/* ---------------------------------------------------------- *
 * Hash router hook                                            *
 * ---------------------------------------------------------- */
let __pendingAnchor = null;

function __scrollToAnchor(id, behavior) {
  let tries = 0;
  const max = 30;
  const attempt = () => {
    const el = document.getElementById(id);
    if (el) {
      el.scrollIntoView({ behavior: behavior || 'instant', block: 'start' });
    } else if (++tries < max) {
      requestAnimationFrame(attempt);
    } else {
      window.scrollTo({ top: 0, behavior: 'instant' });
    }
  };
  requestAnimationFrame(attempt);
}

function useHashRoute() {
  const [route, setRoute] = useState(() => window.location.hash.replace('#/', '') || 'home');
  useEffect(() => {
    const onHash = () => {
      const r = window.location.hash.replace('#/', '') || 'home';
      setRoute(r);
      if (__pendingAnchor) {
        const id = __pendingAnchor;
        __pendingAnchor = null;
        __scrollToAnchor(id, 'instant');
      } else {
        window.scrollTo({ top: 0, behavior: 'instant' });
      }
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return route;
}

function navigate(to, anchor) {
  if (window.location.hash === '#/' + to) {
    if (anchor) {
      __scrollToAnchor(anchor, 'smooth');
    } else {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  } else {
    if (anchor) __pendingAnchor = anchor;
    window.location.hash = '#/' + to;
  }
}

/* ---------------------------------------------------------- *
 * Reveal-on-scroll wrapper                                    *
 * ---------------------------------------------------------- */
function Reveal({ children, delay = 0, as: As = 'div', className = '', ...rest }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setTimeout(() => setShown(true), delay);
        io.disconnect();
      }
    }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return (
    <As
      ref={ref}
      className={`reveal ${shown ? 'is-in' : ''} ${className}`}
      {...rest}
    >
      {children}
    </As>
  );
}

/* ---------------------------------------------------------- *
 * Nav                                                         *
 * ---------------------------------------------------------- */
function Nav({ route }) {
  const [scrolled, setScrolled] = useState(false);
  const [mobOpen, setMobOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => { setMobOpen(false); }, [route]);

  const links = [
    { to: 'home',     label: 'ホーム' },
    { to: 'services', label: 'サービス' },
    { to: 'company',  label: '会社概要' }
  ];

  return (
    <React.Fragment>
      <header className={`nav ${scrolled ? 'is-scrolled' : ''}`}>
        <a
          href="#/home"
          onClick={(e) => { e.preventDefault(); navigate('home'); }}
        >
          <LogoMark />
        </a>
        <nav className="nav__menu">
          {links.map((l) => (
            <a
              key={l.to}
              href={'#/' + l.to}
              className={route === l.to ? 'is-active' : ''}
              onClick={(e) => { e.preventDefault(); navigate(l.to); }}
            >
              {l.label}
            </a>
          ))}
        </nav>
        <div className="nav__cta">
          <a
            href="#/contact"
            className="btn btn--primary"
            onClick={(e) => { e.preventDefault(); navigate('contact'); }}
          >
            お問い合わせ
            <span className="arr">
              <svg width="12" height="10" viewBox="0 0 12 10" fill="none">
                <path d="M1 5h10M7 1l4 4-4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </span>
          </a>
          <button className="nav__burger" aria-label="メニュー" onClick={() => setMobOpen((v) => !v)}>
            <span />
          </button>
        </div>
      </header>

      <div className={`mob ${mobOpen ? 'is-open' : ''}`}>
        <button className="mob__close" aria-label="閉じる" onClick={() => setMobOpen(false)}>
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
            <path d="M2 2l16 16M18 2L2 18" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
        </button>
        {links.map((l) => (
          <a
            key={l.to}
            href={'#/' + l.to}
            onClick={(e) => { e.preventDefault(); navigate(l.to); setMobOpen(false); }}
          >
            {l.label}
          </a>
        ))}
        <div style={{ marginTop: 32 }}>
          <a className="btn btn--primary btn--lg mob__cta"
            href="#/contact"
            onClick={(e) => { e.preventDefault(); navigate('contact'); setMobOpen(false); }}
          >
            お問い合わせ
            <span className="arr">
              <svg width="12" height="10" viewBox="0 0 12 10" fill="none">
                <path d="M1 5h10M7 1l4 4-4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </span>
          </a>
        </div>
      </div>
    </React.Fragment>
  );
}

/* ---------------------------------------------------------- *
 * Footer                                                      *
 * ---------------------------------------------------------- */
function Footer() {
  const year = new Date().getFullYear();
  return (
    <footer className="foot">
      <div className="foot__grid">
        <div className="foot__brand">
          <div className="brand-row">
            <LogoMark />
            <span className="ja">株式会社バラエティーズ</span>
          </div>
          <p>
            中小企業のための、堅実で先進的なウェブパートナー。<br/>
            戦略立案から制作、運用、AI活用までを一貫して担います。
          </p>
        </div>
        <div className="foot__col">
          <h5>Site</h5>
          <ul>
            <li><a href="#/home"     onClick={(e)=>{e.preventDefault();navigate('home');}}>ホーム</a></li>
            <li><a href="#/services" onClick={(e)=>{e.preventDefault();navigate('services');}}>サービス</a></li>
            <li><a href="#/company"  onClick={(e)=>{e.preventDefault();navigate('company');}}>会社概要</a></li>

            <li><a href="#/privacy"  onClick={(e)=>{e.preventDefault();navigate('privacy');}}>プライバシーポリシー</a></li>
          </ul>
        </div>
        <div className="foot__col">
          <h5>Services</h5>
          <ul>
            <li><a href="#/services" onClick={(e)=>{e.preventDefault();navigate('services');}}>コーポレートサイト制作</a></li>
            <li><a href="#/services" onClick={(e)=>{e.preventDefault();navigate('services');}}>LP制作</a></li>
            <li><a href="#/services" onClick={(e)=>{e.preventDefault();navigate('services');}}>ECサイト制作</a></li>
            <li><a href="#/services" onClick={(e)=>{e.preventDefault();navigate('services');}}>SEO対策</a></li>
            <li><a href="#/services" onClick={(e)=>{e.preventDefault();navigate('services');}}>保守運用</a></li>
          </ul>
        </div>
        <div className="foot__col">
          <h5>Contact</h5>
          <ul>
            <li>東京都西東京市富士町４−２−７</li>
            <li>050-1793-8686</li>
            <li>info@varieties.co.jp</li>
            <li>平日 10:00–18:00</li>
          </ul>
        </div>
      </div>
      <div className="foot__bot">
        <span>© {year} VARIETIES, INC.</span>
        <a href="#/privacy" onClick={(e)=>{e.preventDefault();navigate('privacy');}}>Privacy Policy</a>
      </div>
    </footer>
  );
}

/* ---------------------------------------------------------- *
 * Page hero (sub pages)                                       *
 * ---------------------------------------------------------- */
function PageHero({ crumb, ja, en, sub }) {
  return (
    <section className="phero">
      <div className="phero__inner">
        <div className="phero__crumb">{crumb}</div>
        <h1 className="phero__title">
          {ja}
          {en && <small>{en}</small>}
        </h1>
        {sub && <p className="phero__sub">{sub}</p>}
      </div>
    </section>
  );
}

Object.assign(window, {
  LogoMark, Nav, Footer, Reveal, PageHero, useHashRoute, navigate
});
