/* Aifit — top parts: FontSizeToggle, Header, SideRail, Hero */
(function () {
  const { useState, useEffect } = React;
  const Icon = window.Icon;

  /* ---------- font-size accessibility ---------- */
  function FontSizeToggle() {
    const [val, setVal] = useState("normal");
    useEffect(() => {
      const s = localStorage.getItem("aifit-fz") || "normal";
      apply(s); setVal(s);
    }, []);
    function apply(k) {
      const el = document.documentElement;
      if (k === "normal") el.removeAttribute("data-fz"); else el.setAttribute("data-fz", k);
      localStorage.setItem("aifit-fz", k);
    }
    const opts = [["normal", "標準"], ["large", "大"], ["xlarge", "特大"]];
    return (
      <div className="fz" role="group" aria-label="文字サイズの変更">
        <span className="fz-cap">文字サイズ</span>
        <div className="fz-btns">
          {opts.map(([k, lbl], i) => (
            <button key={k} className={"fz-btn" + (val === k ? " is-on" : "")}
              onClick={() => { apply(k); setVal(k); }} aria-pressed={val === k}>
              <span className="fz-a" style={{ fontSize: 0.7 + i * 0.16 + "rem" }}>あ</span>
              <span className="fz-l">{lbl}</span>
            </button>
          ))}
        </div>
      </div>
    );
  }

  /* ---------- header ---------- */
  function Brand({ light }) {
    return (
      <a className={"brand" + (light ? " brand--light" : "")} href="#top" aria-label="aifit ホーム">
        <img className="brand-logo" src={light ? "logo/aifit-logo-white.png" : "logo/aifit-logo.png"} alt="aifit" />
        <span className="brand-tag">諸事情対応専門・創業{new Date().getFullYear() - 1947}年</span>
      </a>
    );
  }

  function Header({ contact, nav }) {
    const [scrolled, setScrolled] = useState(false);
    const [hidden, setHidden] = useState(false);
    const [open, setOpen] = useState(false);
    useEffect(() => {
      const on = () => setScrolled(window.scrollY > 20);
      on(); window.addEventListener("scroll", on, { passive: true });
      return () => window.removeEventListener("scroll", on);
    }, []);
    // mobile: peek out on the way up, tuck away while scrolling down / at rest
    useEffect(() => {
      let lastY = window.scrollY, idle;
      const onScroll = () => {
        const y = window.scrollY;
        clearTimeout(idle);
        if (y < 60) setHidden(false);
        else if (y > lastY + 3) setHidden(true);
        else if (y < lastY - 3) setHidden(false);
        lastY = y;
        idle = setTimeout(() => { if (window.scrollY > 60) setHidden(true); }, 500);
      };
      window.addEventListener("scroll", onScroll, { passive: true });
      return () => { window.removeEventListener("scroll", onScroll); clearTimeout(idle); };
    }, []);
    useEffect(() => { document.body.style.overflow = open ? "hidden" : ""; }, [open]);
    return (
      <header className={"hdr" + (scrolled ? " is-scrolled" : "") + (hidden && !open ? " hdr--hidden" : "")}>
        <div className="hdr-inner wrap">
          <Brand />
          <nav className="hdr-nav" aria-label="メインメニュー">
            {nav.map((n, i) => n.drop ? (
              <div key={i} className="hdr-drop">
                <button className="hdr-drop-toggle">{n.label}<span className="hdr-caret" aria-hidden="true">▾</span></button>
                <div className="hdr-drop-menu">
                  {n.drop.map((d, j) => <a key={j} href={d.href} className="hdr-drop-item" target={/^https?:/.test(d.href) ? "_blank" : undefined} rel={/^https?:/.test(d.href) ? "noopener" : undefined}>{d.label}</a>)}
                </div>
              </div>
            ) : (
              <a key={i} href={n.href} className="hdr-link" target={/^https?:/.test(n.href) ? "_blank" : undefined} rel={/^https?:/.test(n.href) ? "noopener" : undefined}>{n.label}</a>
            ))}
          </nav>
          <div className="hdr-right">
            <a className="hdr-tel" href={contact.telLink}>
              <Icon name="phoneCall" strokeWidth={1.7} />
              <span className="hdr-tel-tx">
                <span className="hdr-tel-num">{contact.tel}</span>
                <span className="hdr-tel-hours">{contact.hours}</span>
              </span>
            </a>
            <FontSizeToggle />
            <button className="hdr-burger" onClick={() => setOpen(true)} aria-label="メニューを開く">
              <Icon name="menu" strokeWidth={1.8} />
            </button>
          </div>
        </div>

        {/* drawer */}
        <div className={"drawer" + (open ? " is-open" : "")} role="dialog" aria-modal="true" aria-hidden={!open}>
          <div className="drawer-scrim" onClick={() => setOpen(false)}></div>
          <div className="drawer-panel">
            <div className="drawer-top">
              <Brand />
              <button className="drawer-close" onClick={() => setOpen(false)} aria-label="閉じる"><Icon name="close" strokeWidth={1.8} /></button>
            </div>
            <nav className="drawer-nav" aria-label="メニュー">
              {nav.map((n, i) => n.drop ? (
                <div key={i} className="drawer-group">
                  <span className="drawer-grouplabel">{n.label}</span>
                  {n.drop.map((d, j) => <a key={j} href={d.href} className="drawer-link drawer-sub" target={/^https?:/.test(d.href) ? "_blank" : undefined} rel={/^https?:/.test(d.href) ? "noopener" : undefined} onClick={() => setOpen(false)}>{d.label}<Icon name="arrow" strokeWidth={1.6} /></a>)}
                </div>
              ) : (
                <a key={i} href={n.href} className="drawer-link" target={/^https?:/.test(n.href) ? "_blank" : undefined} rel={/^https?:/.test(n.href) ? "noopener" : undefined} onClick={() => setOpen(false)}>{n.label}<Icon name="arrow" strokeWidth={1.6} /></a>
              ))}
            </nav>
            <a className="ai-badge ai-badge--lg drawer-ai" href={contact.chat} target="_blank" rel="noopener">
              <Icon name="spark" className="spark" strokeWidth={1.6} />Aifitチャットに相談する
            </a>
            <a className="drawer-tel" href={contact.telLink}>
              <Icon name="phoneCall" strokeWidth={1.7} />
              <span><b>{contact.tel}</b><small>{contact.hours}</small></span>
            </a>
          </div>
        </div>
      </header>
    );
  }

  /* ---------- right action rail ---------- */
  function SideRail({ contact }) {
    const items = [
      { icon: "doc", label: "資料請求", href: "https://saiki-sousai.com/document/" },
    ];
    return (
      <aside className="rail" aria-label="クイックメニュー">
        <a className="rail-ai" href={contact.chat} target="_blank" rel="noopener">
          <Icon name="spark" strokeWidth={1.6} />
          <span>Aifitチャット<br />に相談</span>
        </a>
        <a className="rail-urgent" href={contact.telLink}>
          <Icon name="phoneCall" strokeWidth={1.7} />
          <span>お急ぎの方はこちら<br /><b>24時間対応</b></span>
        </a>
        <a className="rail-line" href={contact.line} target="_blank" rel="noopener">
          <Icon name="line" strokeWidth={1.6} />
          <span>LINEで<br />相談</span>
        </a>
        {items.map((it, i) => (
          <a key={i} className="rail-item" href={it.href}
             target={/^https?:/.test(it.href) ? "_blank" : undefined}
             rel={/^https?:/.test(it.href) ? "noopener" : undefined}>
            <Icon name={it.icon} strokeWidth={1.6} />
            <span>{it.label}</span>
          </a>
        ))}
        <button className="rail-top" onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })} aria-label="ページ上部へ">
          <Icon name="top" strokeWidth={1.8} />
          <span>PAGE<br />TOP</span>
        </button>
      </aside>
    );
  }

  /* ---------- hero ---------- */
  function Hero({ platform, selected, onSelect, contact }) {
    const Platform = window.Platform;
    return (
      <section className="hero" id="top">
        <image-slot id="ph-hero" className="hero-photo" shape="rect" src="img/hero-poster.webp"
          placeholder="メインビジュアル（ご家族の写真など）"
          style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}></image-slot>
        <video className="hero-video" data-src={window.matchMedia && window.matchMedia("(max-width: 768px)").matches ? "video/top-sp.mp4" : "video/top.mp4"} ref={(el) => window.aifitVidMount && window.aifitVidMount(el)} autoPlay muted loop playsInline aria-hidden="true"></video>
        <div className="hero-scrim" aria-hidden="true"></div>
        <div className="wrap hero-wrap">
          <div className="hero-copy hero-copy--statement">
            <span className="hero-since">創業{new Date().getFullYear() - 1947}年</span>
            <h1 className="hero-statement">創業者が<em className="hs-gold">東広島市社会福祉協議会会長</em>を務めた、<br />
              <em className="hs-pop">諸事情対応</em>専門の<em className="hs-pop">葬儀社</em>。</h1>
          </div>
          <div className="hero-plat">
            <Platform nodes={platform} selected={selected} onSelect={onSelect} />
          </div>
        </div>
      </section>
    );
  }

  Object.assign(window, { FontSizeToggle, Header, SideRail, Hero });
})();
