/* =================================================================
   Pages + history router
   Routes:  /                 home
            /videos           category (film)
            /videos/tides     work detail
            /apps  /webtools  category
            /about /contact
   ================================================================= */
const { useState: pUS, useEffect: pUE, useRef: pUR } = React;

/* ---------------- router ---------------- */
function useRoute() {
  const parse = () => {
    const raw = location.pathname.replace(/\/$/, '');
    const segs = raw.split('/').filter(Boolean);
    if (!segs.length) return { view: 'home', key: 'home' };
    if (segs[0] === 'about') return { view: 'about', key: 'about' };
    if (segs[0] === 'contact') return { view: 'contact', key: 'contact' };
    const cat = CAT_BY_ROUTE[segs[0]];
    if (!cat) return { view: 'home', key: 'home' };
    if (segs[1]) return { view: 'work', cat, slug: segs[1], key: `work:${segs[0]}/${segs[1]}` };
    return { view: 'category', cat, key: `cat:${segs[0]}` };
  };
  const [r, setR] = pUS(parse);
  pUE(() => {
    const f = () => setR(parse());
    window.addEventListener('popstate', f);
    return () => window.removeEventListener('popstate', f);
  }, []);
  return r;
}

/* label shown on the transition curtain */
function routeLabel(route, lang) {
  if (!route) return '';
  if (route.view === 'home') return 'INDEX';
  if (route.view === 'about') return L(window.PORTFOLIO.ui.about, lang).toUpperCase();
  if (route.view === 'contact') return L(window.PORTFOLIO.ui.contact, lang).toUpperCase();
  const cm = catMeta(route.cat);
  if (route.view === 'category') return `${cm.no} · ${L(cm.label, lang).toUpperCase()}`;
  if (route.view === 'work') {
    const w = workBySlug(route.cat, route.slug);
    return w ? w.title.toUpperCase() : '';
  }
  return '';
}

/* ---------------- footer (global) ---------------- */
function Footer({ data, lang }) {
  return (
    <footer className="ft">
      <a className="ft-cta" href="/contact" data-hot>
        <T as="span" className="ft-cta-lead mono-label" t={lang === 'jp' ? '一緒につくる' : "Let's work"} />
        <span className="ft-cta-mail">{data.contact.email}<i className="ft-arr">↗</i></span>
      </a>
      <div className="ft-row">
        <div className="ft-nav">
          {data.categories.map((c) => (
            <a key={c.id} href={`/${c.route}`} className="ft-link" data-hot><T t={c.label} lang={lang} /></a>
          ))}
          <a href="/about" className="ft-link" data-hot><T t={data.ui.about} lang={lang} /></a>
          <a href="/contact" className="ft-link" data-hot><T t={data.ui.contact} lang={lang} /></a>
        </div>
        <div className="ft-meta">
          <span className="mono-label faint">© {new Date().getFullYear()} {data.meta.nameEn}</span>
          <button className="ft-top mono-label" data-hot
            onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}>
            {L(data.ui.backTop, lang)} ↑
          </button>
        </div>
      </div>
    </footer>
  );
}

/* ================= HOME ================= */
function HomePage({ data, lang, topDirection }) {
  const scrollToIndex = () => {
    const el = document.querySelector('.home-index');
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 60, behavior: 'smooth' });
  };
  return (
    <div className="page page-home">
      <Hero direction={topDirection} data={data} lang={lang} onCue={scrollToIndex}
        key={topDirection + lang} />

      <section className="home-index">
        <div className="hi-head">
          <span className="mono-label">/ <T t={data.ui.selected} lang={lang} /> — <T t={data.ui.work} lang={lang} /></span>
          <span className="mono-label faint tnum">{String(
            data.works.film.length + data.works.app.length + data.works.web.length
          ).padStart(2, '0')} {L(data.ui.count, lang)}</span>
        </div>

        <div className="hi-list">
          {data.categories.map((c, i) => {
            const items = data.works[c.id];
            const sample = items.slice(0, 4).map((w) => w.title).join('  ·  ');
            return (
              <a className="hi-cat reveal" href={`/${c.route}`} data-hot key={c.id}
                style={{ transitionDelay: `${i * 90}ms` }}>
                <span className="hi-no mono-label tnum">{c.no}</span>
                <div className="hi-main">
                  <span className="hi-label"><T t={c.label} lang={lang} /></span>
                  <span className="hi-sample mono-label">{sample}</span>
                </div>
                <span className="hi-count mono-label tnum">{String(items.length).padStart(2, '0')}</span>
                <span className="hi-arr">→</span>
              </a>
            );
          })}
        </div>
      </section>

      <section className="home-about">
        <Reveal className="ha-inner">
          <span className="mono-label">/ <T t={data.ui.about} lang={lang} /></span>
          <T as="p" block className="ha-line" t={data.about} lang={lang} />
          <a className="ha-more" href="/about" data-hot><T t={lang === 'jp' ? 'もっと読む' : 'Read more'} /> →</a>
        </Reveal>
      </section>

      <Footer data={data} lang={lang} />
    </div>
  );
}

/* ================= CATEGORY ================= */
function CategoryPage({ data, lang, cat }) {
  const cm = catMeta(cat);
  const items = data.works[cat];
  return (
    <div className="page page-cat">
      <div className="cat-tabs-wrap">
        <TabBar data={data} activeCat={cat} lang={lang} />
      </div>

      <header className="cat-head">
        <div className="cat-head-l">
          <span className="cat-no mono-label tnum">{cm.no}</span>
          <h1 className="cat-title"><T t={cm.label} lang={lang} /></h1>
        </div>
        <T as="p" block className="cat-desc" t={cm.desc} lang={lang} />
        <span className="cat-count mono-label tnum">{String(items.length).padStart(2, '0')} {L(data.ui.count, lang)}</span>
      </header>

      <div className="rows cat-rows">
        {items.map((w, i) => (
          <WorkLink key={w.id} work={w} index={i} lang={lang} routeSlug={cm.route} />
        ))}
      </div>

      <Footer data={data} lang={lang} />
    </div>
  );
}

/* ================= WORK DETAIL ================= */
function WorkPage({ data, lang, cat, slug }) {
  const cm = catMeta(cat);
  const items = data.works[cat];
  const idx = items.findIndex((w) => w.slug === slug);
  const work = items[idx];

  pUE(() => { window.scrollTo(0, 0); }, [slug]);

  if (!work) {
    return (
      <div className="page page-work">
        <div className="wk-missing">
          <p className="mono-label">404 · NOT FOUND</p>
          <a href={`/${cm.route}`} className="wk-back" data-hot>← {L(cm.label, lang)}</a>
        </div>
        <Footer data={data} lang={lang} />
      </div>
    );
  }

  const prev = items[(idx - 1 + items.length) % items.length];
  const next = items[(idx + 1) % items.length];
  const num = String(idx + 1).padStart(2, '0');
  const total = String(items.length).padStart(2, '0');

  return (
    <div className="page page-work">
      <a href={`/${cm.route}`} className="wk-back" data-hot>
        <span className="wk-back-arr">←</span>
        <span>{cm.no} · <T t={cm.label} lang={lang} /></span>
      </a>

      <header className="wk-head">
        <div className="wk-index mono-label tnum">{num} <span className="faint">/ {total}</span></div>
        <h1 className="wk-title">{work.title}</h1>
        <div className="wk-metaline">
          <span className="tnum">{work.year}</span>
          <span className="wk-dot">·</span>
          <span><T t={work.role} lang={lang} /></span>
          <span className="wk-dot">·</span>
          <span><T t={work.client === 'Personal' ? L(data.ui.personal, lang) : work.client} lang={lang} /></span>
        </div>
      </header>

      <div className="wk-media">
        {cat === 'film'
          ? <VimeoFrame id={work.vimeoId} title={work.title} />
          : <Placeholder tag={work.platform || 'WEB'} label={`${work.title} — interface`} />}
      </div>

      <div className="wk-body">
        <div className="wk-overview-col">
          <span className="mono-label">/ <T t={data.ui.overview} lang={lang} /></span>
          <T as="p" block className="wk-overview" t={work.overview} lang={lang} />
          {work.links && work.links.length > 0 && (
            <div className="wk-links">
              {work.links.map((lk) => (
                <a key={lk.label} href={lk.url} target="_blank" rel="noreferrer" className="wk-link" data-hot>
                  <span>{lk.label}</span><span className="arr">↗</span>
                </a>
              ))}
            </div>
          )}
        </div>
        <dl className="wk-specs">
          <div><dt className="mono-label"><T t={data.ui.role} lang={lang} /></dt><dd><T t={work.role} lang={lang} /></dd></div>
          <div><dt className="mono-label"><T t={data.ui.year} lang={lang} /></dt><dd className="tnum">{work.year}</dd></div>
          <div><dt className="mono-label"><T t={data.ui.client} lang={lang} /></dt><dd><T t={work.client === 'Personal' ? L(data.ui.personal, lang) : work.client} lang={lang} /></dd></div>
          {work.platform && <div><dt className="mono-label">Platform</dt><dd>{work.platform}</dd></div>}
          <div><dt className="mono-label"><T t={data.ui.tools} lang={lang} /></dt><dd>{(work.tools || []).join(' · ')}</dd></div>
        </dl>
      </div>

      <nav className="wk-pager">
        <a className="wk-pg wk-pg-prev" href={`/${cm.route}/${prev.slug}`} data-hot>
          <span className="mono-label faint"><T t={data.ui.prev} lang={lang} /></span>
          <span className="wk-pg-t">{prev.title}</span>
        </a>
        <a className="wk-pg-all mono-label" href={`/${cm.route}`} data-hot><T t={data.ui.index} lang={lang} /></a>
        <a className="wk-pg wk-pg-next" href={`/${cm.route}/${next.slug}`} data-hot>
          <span className="mono-label faint"><T t={data.ui.next} lang={lang} /></span>
          <span className="wk-pg-t">{next.title}</span>
        </a>
      </nav>

      <Footer data={data} lang={lang} />
    </div>
  );
}

/* ================= ABOUT ================= */
function AboutPage({ data, lang }) {
  return (
    <div className="page page-about">
      <header className="ab-head">
        <span className="mono-label">/ <T t={data.ui.about} lang={lang} /></span>
        <h1 className="ab-name">
          <span className="ab-name-en">{data.meta.nameEn}</span>
          <span className="ab-name-jp">{data.meta.nameJp}</span>
        </h1>
      </header>

      <div className="ab-grid">
        <Reveal className="ab-body-wrap">
          <T as="p" block className="ab-body" t={data.about} lang={lang} />
        </Reveal>
        <Reveal className="ab-side" delay={120}>
          <dl className="facts">
            {data.facts.map((f, i) => (
              <div className="fact" key={i}>
                <dt className="mono-label"><T t={f.k} lang={lang} /></dt>
                <dd><T t={f.v} lang={lang} /></dd>
              </div>
            ))}
          </dl>
          <a className="ab-link" href="/videos" data-hot><T t={data.ui.viewWork} lang={lang} /> →</a>
        </Reveal>
      </div>

      <Footer data={data} lang={lang} />
    </div>
  );
}

/* ================= CONTACT ================= */
function ContactPage({ data, lang }) {
  return (
    <div className="page page-contact">
      <div className="ct-inner">
        <span className="mono-label">/ <T t={data.ui.contact} lang={lang} /></span>
        <a className="ct-mail" href={`mailto:${data.contact.email}`} data-hot>
          {data.contact.email}<span className="ct-arr">↗</span>
        </a>
        <div className="socials">
          {data.contact.socials.map((s) => (
            <a key={s.label} className="social" href={s.url} target="_blank" rel="noreferrer" data-hot>
              <span className="social-label">{s.label}</span>
              <span className="social-handle mono-label">{s.handle}</span>
            </a>
          ))}
        </div>
      </div>
      <Footer data={data} lang={lang} />
    </div>
  );
}

/* ================= dispatcher ================= */
function Page({ route, data, lang, topDirection }) {
  switch (route.view) {
    case 'category': return <CategoryPage data={data} lang={lang} cat={route.cat} />;
    case 'work': return <WorkPage data={data} lang={lang} cat={route.cat} slug={route.slug} />;
    case 'about': return <AboutPage data={data} lang={lang} />;
    case 'contact': return <ContactPage data={data} lang={lang} />;
    default: return <HomePage data={data} lang={lang} topDirection={topDirection} />;
  }
}

Object.assign(window, {
  useRoute, routeLabel, Page, Footer,
  HomePage, CategoryPage, WorkPage, AboutPage, ContactPage,
});
