/* global React, Lenis */
const { useState, useEffect, useRef } = React;

/* ============================================================
   画像
   ── 実写差し替えはコード編集“不要”。assets/photos/ に下記の
      ファイル名で写真を置くだけで、自動で実写に切り替わります。
      （ファイルが無い間は暫定の Unsplash 写真を表示）
   ── 推奨ファイル名と被写体は TODO.md の「撮影リスト」を参照。
   ============================================================ */
const U = (id, w = 1600) =>
  `https://images.unsplash.com/photo-${id}?w=${w}&q=80&auto=format&fit=crop`;
const L = "assets/photos/";

// { local: 置きたいファイル名, web: 暫定プレースホルダ }
const PHOTOS = {
  heroMountain: { local: L + "hero-yama.jpg",   web: U("1505765050516-f72dcac9c60e") }, // 桜島・山（霧）
  heroSea:      { local: L + "hero-umi.jpg",    web: U("1501785888041-af3ef285b470") }, // 海・夕暮れ・港
  statement:    { local: L + "statement.jpg",   web: U("1469474968028-56623f02e42e", 2000) }, // 里山（光芒・全面）
  aboutSub:     { local: L + "about-sub.jpg",   web: U("1441974231531-c6227db76b6e", 800) },  // 自然・暮らし
  service01:    { local: L + "service-01.jpg",  web: U("1470071459604-3b5ec3a7fe05") }, // 地方創生
  service02:    { local: L + "service-02.jpg",  web: U("1490750967868-88aa4486c946") }, // 生産者支援・畑
};

// ローカル写真があれば優先。無ければ web プレースホルダにフォールバック。
function Img({ photo, src, alt = "", className, style, parallax }) {
  const local = photo ? photo.local : null;
  const web = photo ? photo.web : src;
  const [cur, setCur] = useState(local || web);
  const triedWeb = useRef(false);
  const extra = parallax != null ? { "data-parallax": parallax } : {};
  return (
    <img
      className={className}
      style={style}
      loading="lazy"
      alt={alt}
      src={cur}
      {...extra}
      onError={(e) => {
        if (!triedWeb.current && web && cur !== web) { triedWeb.current = true; setCur(web); }
        else { e.currentTarget.style.opacity = 0; }
      }}
    />
  );
}

/* ============================================================
   墨絵風アクセント
   ============================================================ */
function BirdBrush({ className, style }) {
  return (
    <span className={"brush " + className} style={style} aria-hidden="true">
      <svg viewBox="0 0 100 56">
        <path d="M3 38 C20 18 34 30 50 10 C66 30 80 18 97 38 C80 31 66 35 50 26 C34 35 20 31 3 38 Z" fill="currentColor" />
      </svg>
    </span>
  );
}
/* ============================================================
   Loader
   ============================================================ */
function Loader() {
  const [done, setDone] = useState(false);
  useEffect(() => {
    const t = setTimeout(() => setDone(true), 1250);
    return () => clearTimeout(t);
  }, []);
  return (
    <div className={"loader" + (done ? " done" : "")} aria-hidden="true">
      <div className="loader-mark"><span>ざ</span><span>ぼ</span><span>ん</span></div>
      <div className="loader-bar"></div>
    </div>
  );
}

/* ============================================================
   Header（縦書きナビ + ドロワー）
   ============================================================ */
const NAV = [
  { ja: "私たちについて", en: "About", href: "#about" },
  { ja: "事業内容",     en: "Service", href: "#service" },
  { ja: "会社概要",     en: "Company", href: "#company" },
  { ja: "お問い合わせ", en: "Contact", href: "#contact" },
];

function smoothTo(href) {
  const el = document.querySelector(href);
  if (!el) return;
  if (window.__lenis) window.__lenis.scrollTo(el, { duration: 1.6 });
  else el.scrollIntoView({ behavior: "smooth" });
}

function Header() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const go = (e, href) => { e.preventDefault(); setOpen(false); smoothTo(href); };

  return (
    <React.Fragment>
      <header className={"header" + (scrolled ? " scrolled" : "")}>
        <a href="#top" className="brand" onClick={(e) => go(e, "#top")} aria-label="３代目ざぼん株式会社">
          <img src="assets/logo.png" alt="" className="brand-logo" />
          <span className="brand-name">
            ３代目ざぼん
            <small>3rd Zabon Inc.</small>
          </span>
        </a>

        <nav className="nav-vert" aria-label="メインナビゲーション">
          {NAV.map((it) => (
            <a key={it.en} href={it.href} onClick={(e) => go(e, it.href)}>{it.ja}</a>
          ))}
        </nav>

        <button
          className={"hamburger" + (open ? " open" : "")}
          aria-label={open ? "メニューを閉じる" : "メニューを開く"}
          aria-expanded={open}
          onClick={() => setOpen((v) => !v)}
        >
          <span></span><span></span><span></span>
        </button>
      </header>

      <div className={"drawer" + (open ? " open" : "")} aria-hidden={!open}>
        <ul>
          {NAV.map((it) => (
            <li key={it.en}>
              <a href={it.href} onClick={(e) => go(e, it.href)}>
                <span>{it.ja}</span><small>{it.en}</small>
              </a>
            </li>
          ))}
        </ul>
        <div className="drawer-foot">
          〒890-0054　鹿児島県鹿児島市荒田1丁目50番16号
          <strong>TEL 090-2715-7480</strong>
        </div>
      </div>
    </React.Fragment>
  );
}

/* ============================================================
   Hero
   ============================================================ */
function Hero() {
  return (
    <section id="top" className="hero">
      <BirdBrush className="brush--bird-1" style={{ color: "var(--ink)" }} />
      <div className="hero-inner">
        <div className="hero-mark reveal">
          <span className="en">3rd Zabon Inc. — Kagoshima</span>
          <h1>３代目ざぼん</h1>
        </div>

        <figure className="hero-bands reveal d1" style={{ margin: "clamp(46px,6vw,78px) 0 0" }}>
          <div className="hero-band">
            <Img photo={PHOTOS.heroMountain} alt="鹿児島の山並み" parallax="0.06" />
            <figcaption>YAMA — 山</figcaption>
          </div>
          <div className="hero-band">
            <Img photo={PHOTOS.heroSea} alt="鹿児島の海と夕暮れ" parallax="0.06" />
            <figcaption>UMI — 海</figcaption>
          </div>
        </figure>

        <div className="hero-cap reveal d1">
          <span>Kagoshima · Kyushu</span>
          <span className="ja">農 ／ 海 ／ 山 ／ 茶 ／ 焼酎</span>
        </div>

        <div className="hero-lead reveal d2">
          <h2>
            鹿児島・九州を、もう少しおもしろく、<br />
            もう少し豊かに。
          </h2>
          <div className="hero-cta">
            <a href="#service" className="tlink" onClick={(e) => { e.preventDefault(); smoothTo("#service"); }}>
              事業について<span className="arrow"></span>
            </a>
            <a href="#contact" className="tlink" onClick={(e) => { e.preventDefault(); smoothTo("#contact"); }}>
              お問い合わせ<span className="arrow"></span>
            </a>
          </div>
        </div>
      </div>
      <div className="scroll-hint">Scroll</div>
    </section>
  );
}

/* ============================================================
   Statement（全面写真 + 縦書き）
   ============================================================ */
function Statement() {
  return (
    <section className="statement">
      <div className="statement-bg">
        <Img photo={PHOTOS.statement} alt="鹿児島の里山" parallax="0.10" />
      </div>
      <div className="statement-inner">
        <p className="statement-vert">
          地域でできることは、<br />
          地域でやる。
          <span className="small">　— ３代目ざぼんが大切にしていること。</span>
        </p>
      </div>
      <span className="statement-en">Doing what the region can do, within the region.</span>
    </section>
  );
}

/* ============================================================
   About
   ============================================================ */
function About() {
  return (
    <section id="about" className="section">
      <div className="container">
        <div className="about-grid">
          <figure className="about-figure reveal">
            <div className="main">
              <Img src="assets/profile.jpg" alt="代表取締役 下原裕隆" parallax="0.05" />
            </div>
            <div className="sub">
              <Img photo={PHOTOS.aboutSub} alt="" />
            </div>
          </figure>

          <div className="reveal d1">
            <span className="eyebrow">About<span className="ja">私たちについて</span></span>
            <h2 className="section-title">地域でできることは、地域でやる。</h2>
            <p className="about-body">
              ３代目ざぼんは、鹿児島で <strong>2022年</strong> に立ち上げた会社です。<br />
              地方創生に向けて、地域でできることは、なんでも取り組んでいきます。
              派手なことよりも、目の前の人と土地に向き合いながら、ひとつずつ。
              鹿児島・九州を、もう少しおもしろく、もう少し豊かに。
              そんな仕事を、これからも続けていきたいと思っています。
            </p>
            <div className="about-sign">
              <span className="line"></span>
              <span className="name">
                <small>Representative</small>
                代表取締役　下原 裕隆
              </span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Service（2本柱・左右非対称）
   ============================================================ */
function Service() {
  const items = [
    {
      num: "01", tag: "Regional Development", title: "地方創生",
      body: "鹿児島・九州の地域課題に向き合い、地域でできることを、地域とともに進めていきます。百年先も続く土地のために、いまできることを、ひとつずつ。",
      img: PHOTOS.service01, rev: false,
    },
    {
      num: "02", tag: "Producer Support", title: "地域の生産者支援",
      body: "地域の生産者のみなさんが、続けやすく、伝わりやすくなるよう。それぞれの現場に合わせて、つくる人の想いが届くかたちを一緒に考えます。",
      img: PHOTOS.service02, rev: true,
    },
  ];
  return (
    <section id="service" className="section section--paper2">
      <div className="container">
        <div className="service-head reveal">
          <span className="eyebrow">Service<span className="ja">事業内容</span></span>
          <h2 className="section-title">ふたつの柱で。</h2>
          <p className="lede" style={{ marginTop: 22, maxWidth: "44ch" }}>
            私たちの仕事は、いまのところ大きくふたつ。
            派手さはないかもしれませんが、地域に必要とされることを、ひとつずつ積み重ねています。
          </p>
        </div>

        <div className="service-list">
          {items.map((s) => (
            <article key={s.num} className={"service-row reveal" + (s.rev ? " rev" : "")}>
              <figure className="service-fig">
                <Img photo={s.img} alt={s.title} />
              </figure>
              <div className="service-text">
                <div className="service-num">{s.num}</div>
                <span className="service-tag">{s.tag}</span>
                <h3 className="service-title">{s.title}</h3>
                <p className="service-body">{s.body}</p>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Company
   ============================================================ */
function Company() {
  const rows = [
    { en: "Name", ja: "会社名", v: "３代目ざぼん株式会社" },
    { en: "Representative", ja: "代表者", v: "代表取締役　下原 裕隆" },
    { en: "Founded", ja: "設立", v: "2022年" },
    { en: "Address", ja: "所在地", v: <>〒890-0054<br />鹿児島県鹿児島市荒田1丁目50番16号</> },
    { en: "Tel", ja: "電話", v: "090-2715-7480" },
    { en: "Business", ja: "事業内容", v: "地方創生 ／ 地域の生産者支援" },
  ];
  const q = encodeURIComponent("鹿児島県鹿児島市荒田1丁目50番16号");
  return (
    <section id="company" className="section">
      <div className="container">
        <div className="company-grid">
          <div className="reveal">
            <span className="eyebrow">Company<span className="ja">会社概要</span></span>
            <h2 className="section-title" style={{ lineHeight: 1.4 }}>会社概要</h2>
          </div>
          <div className="reveal d1">
            <dl className="company-list">
              {rows.map((r) => (
                <div className="company-row" key={r.en}>
                  <dt>{r.en}<span className="ja">{r.ja}</span></dt>
                  <dd>{r.v}</dd>
                </div>
              ))}
            </dl>
            <div className="company-map">
              <iframe
                title="所在地マップ"
                src={`https://www.google.com/maps?q=${q}&output=embed`}
                loading="lazy"
                referrerPolicy="no-referrer-when-downgrade"
              />
              <a className="tlink company-map-link"
                 href={`https://www.google.com/maps/search/?api=1&query=${q}`}
                 target="_blank" rel="noopener noreferrer">
                Google Mapsで開く<span className="arrow"></span>
              </a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Contact
   ============================================================ */
function Contact() {
  return (
    <section id="contact" className="section contact">
      <div className="container">
        <div className="contact-grid">
          <div className="reveal">
            <span className="eyebrow">Contact<span className="ja">お問い合わせ</span></span>
            <h2 className="contact-title">お気軽に、<br />ご連絡ください。</h2>
            <p className="contact-sub">
              地域連携、生産者支援、その他のご相談など。
              まずはお電話・メールでご連絡いただければ、できることからお話しさせてください。
            </p>
            <div className="contact-tel">
              <a href="tel:09027157480">
                <small>お電話でのご相談</small>
                090-2715-7480
              </a>
            </div>
          </div>
          <div className="contact-info reveal d1">
            <div className="item">
              <small>Address</small>
              <strong>〒890-0054<br />鹿児島県鹿児島市荒田1丁目50番16号</strong>
            </div>
            <div className="item">
              <small>Tel</small>
              <strong>090-2715-7480</strong>
            </div>
            <div className="item">
              <small>Business Hours</small>
              <strong>平日 9:00 – 18:00</strong>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Footer（巨大タイポグラフィ）
   ============================================================ */
function Footer() {
  const giant = [
    { lbl: "Za", big: "ざ" },
    { lbl: "Bo", big: "ぼ" },
    { lbl: "N",  big: "ん" },
  ];
  return (
    <footer className="footer">
      <div className="footer-top">
        <div className="footer-brand">
          <div className="name">
            ３代目ざぼん株式会社
            <small>3rd Zabon Inc. · Kagoshima</small>
          </div>
          <p>
            〒890-0054　鹿児島県鹿児島市荒田1丁目50番16号<br />
            TEL 090-2715-7480
          </p>
        </div>
      </div>

      <div className="footer-giant" aria-hidden="true">
        {giant.map((g) => (
          <div className="cell" key={g.lbl}>
            <span className="lbl">{g.lbl}</span>
            <div className="big">{g.big}</div>
          </div>
        ))}
      </div>

      <div className="footer-base">
        <span>© 2026 3rd Zabon Inc.</span>
        <span>Made in Kagoshima</span>
      </div>
    </footer>
  );
}

/* ============================================================
   hooks
   ============================================================ */
function useRevealOnScroll() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); }
        });
      },
      { threshold: 0.14, rootMargin: "0px 0px -8% 0px" }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

function useSmoothScroll() {
  useEffect(() => {
    if (typeof Lenis === "undefined") return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const lenis = new Lenis({
      duration: 1.6,
      easing: (t) => 1 - Math.pow(1 - t, 8),
      smoothWheel: true,
      touchMultiplier: 1.6,
    });
    window.__lenis = lenis;
    let id;
    const raf = (time) => { lenis.raf(time); id = requestAnimationFrame(raf); };
    id = requestAnimationFrame(raf);
    return () => { cancelAnimationFrame(id); lenis.destroy(); window.__lenis = null; };
  }, []);
}

function useParallax() {
  useEffect(() => {
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const els = Array.from(document.querySelectorAll("[data-parallax]"));
    if (!els.length) return;
    let id;
    const update = () => {
      const vh = window.innerHeight;
      for (const el of els) {
        const speed = parseFloat(el.dataset.parallax) || 0.1;
        const r = el.getBoundingClientRect();
        if (r.bottom < -200 || r.top > vh + 200) continue;
        const center = r.top + r.height / 2;
        const off = (center - vh / 2) * -speed;
        el.style.transform = `translate3d(0, ${off.toFixed(1)}px, 0)`;
      }
      id = requestAnimationFrame(update);
    };
    id = requestAnimationFrame(update);
    return () => cancelAnimationFrame(id);
  }, []);
}

Object.assign(window, {
  Loader, Header, Hero, Statement, About, Service, Company, Contact, Footer,
  useRevealOnScroll, useSmoothScroll, useParallax,
});
