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

// ====== Logo Mark (contour-inspired) ======
function LogoMark({ size = 32, color = "#1A1814" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none" aria-hidden="true">
      <circle cx="16" cy="16" r="4" stroke={color} strokeWidth="1.2" />
      <circle cx="16" cy="16" r="8" stroke={color} strokeWidth="1" opacity="0.7" />
      <path d="M4 16 Q10 10, 16 12 T28 16" stroke={color} strokeWidth="0.9" opacity="0.5" fill="none" />
      <path d="M2 20 Q10 14, 16 18 T30 20" stroke={color} strokeWidth="0.9" opacity="0.35" fill="none" />
      <circle cx="16" cy="16" r="1.2" fill="#D68A3C" />
    </svg>
  );
}

// ====== Contour divider (horizontal decorative line set) ======
function ContourDivider({ variant = "ink", density = 4 }) {
  const color = variant === "ink" ? "rgba(26,24,20,0.12)" : "rgba(63,93,74,0.18)";
  const lines = [];
  for (let i = 0; i < density; i++) {
    const y = 20 + i * 14;
    const amp = 8 + i * 2;
    const phase = i * 0.4;
    const path = makeWavePath(y, amp, phase, 1200);
    lines.push(
      <path key={i} d={path} stroke={color} strokeWidth="0.8" fill="none" opacity={1 - i * 0.15} />
    );
  }
  return (
    <div className="contour-divider" aria-hidden="true">
      <svg viewBox="0 0 1200 80" preserveAspectRatio="none">
        {lines}
      </svg>
    </div>
  );
}

function makeWavePath(y, amp, phase, width) {
  const pts = [];
  const steps = 40;
  for (let i = 0; i <= steps; i++) {
    const x = (i / steps) * width;
    const yy = y + Math.sin((i / steps) * Math.PI * 2 + phase) * amp
               + Math.sin((i / steps) * Math.PI * 5 + phase * 2) * (amp * 0.3);
    pts.push(`${i === 0 ? "M" : "L"} ${x.toFixed(1)} ${yy.toFixed(1)}`);
  }
  return pts.join(" ");
}

// ====== Topographic background SVG (decorative, used on hero etc.) ======
function TopoField({ seed = 1, opacity = 0.5, color = "#3F5D4A" }) {
  // deterministic pseudo-random
  const rand = (n) => {
    const x = Math.sin(n * 9301 + seed * 49297) * 233280;
    return x - Math.floor(x);
  };
  const peaks = [
    { x: 20, y: 30, r: 200 },
    { x: 70, y: 60, r: 240 },
    { x: 45, y: 80, r: 180 },
  ];
  const rings = [];
  const W = 1200, H = 700;
  // Build concentric irregular contours around each peak
  peaks.forEach((p, pi) => {
    for (let r = 0; r < 12; r++) {
      const baseR = 20 + r * 24;
      const pts = [];
      const N = 64;
      for (let i = 0; i <= N; i++) {
        const a = (i / N) * Math.PI * 2;
        const noise = (rand(pi * 100 + r * 7 + i) - 0.5) * (10 + r * 4);
        const rr = baseR + noise;
        const x = (p.x / 100) * W + Math.cos(a) * rr;
        const y = (p.y / 100) * H + Math.sin(a) * rr * 0.75;
        pts.push(`${i === 0 ? "M" : "L"} ${x.toFixed(1)} ${y.toFixed(1)}`);
      }
      rings.push(
        <path
          key={`${pi}-${r}`}
          d={pts.join(" ") + " Z"}
          fill="none"
          stroke={color}
          strokeWidth={r === 0 ? 1.2 : 0.7}
          opacity={(1 - r / 14) * opacity}
        />
      );
    }
  });
  return (
    <svg viewBox="0 0 1200 700" preserveAspectRatio="xMidYMid slice"
      style={{ position: "absolute", inset: 0, width: "100%", height: "100%", pointerEvents: "none" }}
      aria-hidden="true">
      {rings}
    </svg>
  );
}

// ====== Header / Nav ======
function Header({ current, onNav }) {
  const [menuOpen, setMenuOpen] = useState(false);

  const items = [
    { id: "home", jp: "ホーム", path: "/" },
    { id: "ando", jp: "Ando", path: "/products/ando" },
    { id: "fukushi-area-map", jp: "福祉エリアマップ", path: "/products/fukushi-area-map" },
    { id: "for-parents", jp: "ご家族の方へ", path: "/for-parents" },
    { id: "philosophy", jp: "思想", path: "/philosophy" },
    { id: "about", jp: "About", path: "/about" },
  ];

  const handleNav = (id) => {
    onNav(id);
    setMenuOpen(false);
  };

  useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen]);

  useEffect(() => {
    const onResize = () => { if (window.innerWidth > 640) setMenuOpen(false); };
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);

  return (
    <>
      <header className="site-header">
        <div className="container site-header-inner">
          <a className="logo" href="#/" onClick={(e) => { e.preventDefault(); handleNav("home"); }} aria-label="YORIAI ホーム">
            <span className="logo-mark"><LogoMark /></span>
            <span>YORIAI</span>
          </a>
          <nav className="nav nav-desktop" aria-label="メインナビゲーション">
            {items.map((it) => (
              <a key={it.id} href={`#${it.path}`}
                className={current === it.id ? "active nav-jp" : "nav-jp"}
                onClick={(e) => { e.preventDefault(); handleNav(it.id); }}>
                {it.jp}
              </a>
            ))}
            <a className="btn btn-ghost nav-cta" href="#/contact"
              onClick={(e) => { e.preventDefault(); handleNav("contact"); }}
              style={{ padding: "8px 18px", fontSize: 13 }}>
              お問い合わせ
            </a>
          </nav>
          <button
            className="hamburger"
            aria-label={menuOpen ? "メニューを閉じる" : "メニューを開く"}
            aria-expanded={menuOpen}
            aria-controls="mobile-menu"
            onClick={() => setMenuOpen((o) => !o)}
          >
            <span className={`hamburger-icon${menuOpen ? " is-open" : ""}`} aria-hidden="true">
              <span></span>
              <span></span>
              <span></span>
            </span>
          </button>
        </div>
      </header>
      <div
        id="mobile-menu"
        className={`mobile-menu${menuOpen ? " is-open" : ""}`}
        role="dialog"
        aria-modal="true"
        aria-label="ナビゲーション"
        aria-hidden={!menuOpen}
      >
        <nav aria-label="モバイルメインナビゲーション">
          {items.map((it) => (
            <a key={it.id} href={`#${it.path}`}
              className={`mobile-nav-link${current === it.id ? " active" : ""}`}
              onClick={(e) => { e.preventDefault(); handleNav(it.id); }}
              tabIndex={menuOpen ? 0 : -1}>
              {it.jp}
            </a>
          ))}
        </nav>
        <a
          className="btn btn-primary mobile-nav-cta"
          href="#/contact"
          onClick={(e) => { e.preventDefault(); handleNav("contact"); }}
          tabIndex={menuOpen ? 0 : -1}
        >
          お問い合わせ
        </a>
      </div>
    </>
  );
}

// ====== Footer ======
function Footer({ onNav }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid" style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr 1fr 1fr 1fr", gap: 40, marginBottom: 64 }}>
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 20 }}>
              <LogoMark color="#FBFAF7" />
              <span className="serif" style={{ fontSize: 20, color: "#FBFAF7", letterSpacing: "0.06em" }}>YORIAI</span>
            </div>
            <p className="body-sm" style={{ color: "rgba(251,250,247,0.6)", maxWidth: 360, lineHeight: 1.8 }}>
              認知の違いで失われた機会を、<br/>
              環境を変えることで取り戻す。
            </p>
          </div>
          <div>
            <h4>Product</h4>
            <div className="col gap-12 body-sm">
              <a href="#/products/fukushi-area-map" onClick={(e) => { e.preventDefault(); onNav("fukushi-area-map"); }}>福祉エリアマップ</a>
              <a href="#/products/ando" onClick={(e) => { e.preventDefault(); onNav("ando"); }}>Ando</a>
              <a href="https://map.yoriai.life/map" target="_blank" rel="noopener noreferrer">分析マップを開く ↗</a>
            </div>
          </div>
          <div>
            <h4>About</h4>
            <div className="col gap-12 body-sm">
              <a href="#/philosophy" onClick={(e) => { e.preventDefault(); onNav("philosophy"); }}>思想</a>
              <a href="#/about" onClick={(e) => { e.preventDefault(); onNav("about"); }}>このサイトについて</a>
              <a href="#/for-parents" onClick={(e) => { e.preventDefault(); onNav("for-parents"); }}>ご家族の方へ</a>
            </div>
          </div>
          <div>
            <h4>コラム</h4>
            <div className="col gap-12 body-sm">
              <a href="https://map.yoriai.life/articles?category=parents" target="_blank" rel="noopener noreferrer">保護者の方へ ↗</a>
              <a href="https://map.yoriai.life/articles?category=providers" target="_blank" rel="noopener noreferrer">事業者の方へ ↗</a>
              <a href="https://map.yoriai.life/articles" target="_blank" rel="noopener noreferrer">コラム一覧 ↗</a>
            </div>
          </div>
          <div>
            <h4>Legal</h4>
            <div className="col gap-12 body-sm">
              <a href="#/legal/tokushoho" onClick={(e) => { e.preventDefault(); onNav("tokushoho"); }}>特定商取引法</a>
              <a href="#/legal/privacy" onClick={(e) => { e.preventDefault(); onNav("privacy"); }}>プライバシー</a>
              <a href="#/contact" onClick={(e) => { e.preventDefault(); onNav("contact"); }}>お問い合わせ</a>
            </div>
          </div>
          <div>
            <h4>Contact</h4>
            <div className="col gap-12 body-sm">
              <a href="mailto:info@yoriai.life">info@yoriai.life</a>
              <span style={{ color: "rgba(251,250,247,0.5)" }}>東京都</span>
            </div>
          </div>
        </div>
        <div style={{ borderTop: "1px solid rgba(251,250,247,0.12)", paddingTop: 24, display: "flex", justifyContent: "space-between", fontSize: 12, color: "rgba(251,250,247,0.5)", letterSpacing: "0.04em" }}>
          <span>© 2026 YORIAI.</span>
          <span className="mono">yoriai.life</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { LogoMark, ContourDivider, TopoField, Header, Footer });
