// Shared primitive components — adapted for multi-page navigation
const { useState, useEffect } = React;

// レスポンシブ用：メディアクエリの一致状態を返すフック
function useMediaQuery(query) {
  const [matches, setMatches] = useState(
    typeof window !== "undefined" && window.matchMedia ? window.matchMedia(query).matches : false
  );
  useEffect(() => {
    if (typeof window === "undefined" || !window.matchMedia) return;
    const m = window.matchMedia(query);
    const handler = () => setMatches(m.matches);
    handler();
    m.addEventListener("change", handler);
    return () => m.removeEventListener("change", handler);
  }, [query]);
  return matches;
}

// Compute base prefix so links & assets resolve correctly from both the site root
// (index.html, strengths.html, ...) and the /recruit/ subdirectory.
const BASE = (typeof window !== "undefined" && /\/recruit(\/|$)/.test(window.location.pathname)) ? "../" : "";
const p = (rel) => BASE + rel;

function Button({ variant = "primary", children, href, onClick, style, arrow = true }) {
  const [hover, setHover] = useState(false);
  const base = {
    fontFamily: 'var(--font-sans)',
    fontSize: 15,
    fontWeight: 500,
    padding: "16px 28px",
    borderRadius: "var(--radius-pill)",
    border: "none",
    cursor: "pointer",
    display: "inline-flex",
    alignItems: "center",
    gap: 10,
    transition: "all 160ms cubic-bezier(0.22,1,0.36,1)",
    textDecoration: "none",
    whiteSpace: "nowrap",
  };
  const primary = {
    background: hover ? "var(--purple-dark)" : "var(--purple)",
    color: "#fff",
    transform: hover ? "translateY(-2px)" : "translateY(0)",
    boxShadow: hover ? "0 8px 22px rgba(124,92,255,0.32)" : "0 0 0 rgba(0,0,0,0)",
  };
  const secondary = {
    background: hover ? "#1A1A1A" : "transparent",
    color: hover ? "#fff" : "#1A1A1A",
    border: "1px solid #1A1A1A",
    transform: hover ? "translateY(-2px)" : "translateY(0)",
  };
  const ghost = {
    background: "transparent",
    color: hover ? "var(--purple)" : "#1A1A1A",
    border: "1px solid " + (hover ? "var(--purple)" : "#E5E5E5"),
  };
  const onDark = {
    background: hover ? "#fff" : "transparent",
    color: hover ? "#1A1530" : "#fff",
    border: "1px solid rgba(255,255,255,0.5)",
    transform: hover ? "translateY(-2px)" : "translateY(0)",
  };
  const styleMap = { primary, secondary, ghost, onDark };
  const Tag = href ? "a" : "button";
  return (
    <Tag
      href={href}
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{ ...base, ...styleMap[variant], ...style }}
    >
      {children}
      {arrow && <span style={{ fontFamily: 'var(--font-mono-label)', fontSize: 16, transform: hover ? "translateX(3px)" : "translateX(0)", transition: "transform 160ms cubic-bezier(0.22,1,0.36,1)" }}>→</span>}
    </Tag>
  );
}

function SectionLabel({ children, accent = true, dark = false, style }) {
  return (
    <div
      style={{
        fontFamily: 'var(--font-mono-label)',
        fontSize: 12,
        letterSpacing: "0.15em",
        textTransform: "uppercase",
        fontWeight: 500,
        color: accent ? "var(--purple)" : (dark ? "#B0A8CC" : "#6B6B6B"),
        display: "inline-flex",
        alignItems: "center",
        gap: "0.7em",
        whiteSpace: "nowrap",
        ...style,
      }}
    >
      <span style={{ opacity: 0.6 }}>—</span>
      {children}
      <span style={{ opacity: 0.6 }}>—</span>
    </div>
  );
}

function TopBar() {
  return (
    <div
      style={{
        borderBottom: "1px solid #E5E5E5",
        padding: "12px 48px",
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        fontFamily: 'var(--font-mono-label)',
        fontSize: 11.5,
        letterSpacing: "0.18em",
        textTransform: "uppercase",
        color: "#6B6B6B",
        fontWeight: 500,
        background: "#FAF8F5",
      }}
    >
      <span>EST. 2024</span>
      <span>AI-NATIVE SYSTEM ENGINEERING</span>
      <span>BACKED BY EAST VENTURES</span>
    </div>
  );
}

function Logo({ height = 32 }) {
  const aspect = 827 / 344;
  return (
    <img src={p("assets/logo-horizontal.png")} alt="日本AIセンター" style={{ height, width: height * aspect, display: "block" }} />
  );
}

function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const isMobile = useMediaQuery("(max-width: 860px)");
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 10);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => { if (!isMobile) setOpen(false); }, [isMobile]);
  const isRecruit = BASE === "../";
  const corporateItems = [
    { href: p("strengths.html"), label: "私たちの強み" },
    { href: p("business.html"), label: "事業内容" },
    { href: p("about.html"), label: "会社概要" },
    // 発信コンテンツ準備中のため非表示（記事整備後に戻す）
    // { href: p("insights.html"), label: "発信" },
    { href: p("contact.html"), label: "お問い合わせ" },
  ];
  const recruitItems = [
    { href: p("recruit/index.html"), label: "採用TOP" },
    { href: p("recruit/about.html"), label: "私たちについて" },
    { href: p("recruit/jobs.html"), label: "求人一覧" },
    { href: p("recruit/interview.html"), label: "インタビュー" },
    { href: p("recruit/environment.html"), label: "働く環境" },
  ];
  const items = isRecruit ? recruitItems : corporateItems;
  const logoHref = isRecruit ? p("recruit/index.html") : p("index.html");
  const ctaPrimary = isRecruit
    ? { href: p("recruit/entry.html"), label: "エントリー" }
    : { href: p("recruit/index.html"), label: "採用情報" };
  const ctaSecondary = isRecruit
    ? { href: p("index.html"), label: "コーポレートサイト" }
    : { href: p("recruit/entry.html"), label: "カジュアル面談" };
  return (
    <nav
      style={{
        position: "sticky",
        top: 0,
        zIndex: 20,
        padding: isMobile ? "12px 16px" : "16px 24px",
        background: "transparent",
        pointerEvents: "none",
      }}
    >
      <div
        style={{
          pointerEvents: "auto",
          maxWidth: 1320,
          margin: "0 auto",
          height: isMobile ? 58 : 64,
          padding: isMobile ? "0 10px 0 18px" : "0 12px 0 26px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          borderRadius: 999,
          background: scrolled ? "rgba(255,255,255,0.62)" : "rgba(255,255,255,0.40)",
          backdropFilter: "blur(22px) saturate(180%)",
          WebkitBackdropFilter: "blur(22px) saturate(180%)",
          border: "1px solid rgba(255,255,255,0.7)",
          boxShadow: scrolled
            ? "0 12px 36px rgba(31,38,135,0.16), inset 0 1px 0 rgba(255,255,255,0.85), inset 0 -1px 0 rgba(124,92,255,0.05)"
            : "0 8px 26px rgba(31,38,135,0.10), inset 0 1px 0 rgba(255,255,255,0.75)",
          transition: "background 320ms cubic-bezier(0.22,1,0.36,1), box-shadow 320ms cubic-bezier(0.22,1,0.36,1)",
        }}
      >
        <a href={logoHref} style={{ display: "block" }}>
          <Logo height={isMobile ? 30 : 38} />
        </a>

        {!isMobile && (
          <div style={{ display: "flex", gap: 28 }}>
            {items.map((it) => (
              <a key={it.href} href={it.href}
                style={{
                  fontFamily: 'var(--font-sans)',
                  fontSize: 13.5,
                  color: "#1A1A1A",
                  textDecoration: "none",
                  fontWeight: 400,
                  transition: "color 160ms",
                }}
                onMouseEnter={(e) => e.currentTarget.style.color = "var(--purple)"}
                onMouseLeave={(e) => e.currentTarget.style.color = "#1A1A1A"}
              >
                {it.label}
              </a>
            ))}
          </div>
        )}

        {!isMobile && (
          <div style={{ display: "flex", gap: 8 }}>
            <Button variant="secondary" href={ctaSecondary.href} arrow={false} style={{ padding: "10px 18px", fontSize: 13, borderRadius: 999 }}>{ctaSecondary.label}</Button>
            <Button variant="primary" href={ctaPrimary.href} arrow={false} style={{ padding: "10px 18px", fontSize: 13, borderRadius: 999 }}>{ctaPrimary.label}</Button>
          </div>
        )}

        {isMobile && (
          <button
            onClick={() => setOpen((o) => !o)}
            aria-label="メニュー"
            aria-expanded={open}
            style={{
              width: 42, height: 42, borderRadius: 999, border: "none",
              background: "transparent", cursor: "pointer",
              display: "flex", flexDirection: "column", alignItems: "center",
              justifyContent: "center", gap: 5,
            }}
          >
            <span style={{ display: "block", width: 20, height: 2, borderRadius: 2, background: "#1A1A1A", transition: "transform 240ms, opacity 240ms", transform: open ? "translateY(7px) rotate(45deg)" : "none" }} />
            <span style={{ display: "block", width: 20, height: 2, borderRadius: 2, background: "#1A1A1A", transition: "opacity 200ms", opacity: open ? 0 : 1 }} />
            <span style={{ display: "block", width: 20, height: 2, borderRadius: 2, background: "#1A1A1A", transition: "transform 240ms, opacity 240ms", transform: open ? "translateY(-7px) rotate(-45deg)" : "none" }} />
          </button>
        )}
      </div>

      {isMobile && (
        <div
          style={{
            pointerEvents: open ? "auto" : "none",
            maxWidth: 1320,
            margin: "10px auto 0",
            borderRadius: 22,
            background: "rgba(255,255,255,0.80)",
            backdropFilter: "blur(22px) saturate(180%)",
            WebkitBackdropFilter: "blur(22px) saturate(180%)",
            border: "1px solid rgba(255,255,255,0.7)",
            boxShadow: "0 12px 36px rgba(31,38,135,0.16)",
            maxHeight: open ? 520 : 0,
            opacity: open ? 1 : 0,
            overflow: "hidden",
            transition: "max-height 340ms cubic-bezier(0.22,1,0.36,1), opacity 240ms ease",
          }}
        >
          <div style={{ display: "flex", flexDirection: "column", padding: "10px 14px 18px" }}>
            {items.map((it) => (
              <a key={it.href} href={it.href}
                style={{
                  fontFamily: 'var(--font-sans)', fontSize: 16, color: "#1A1A1A",
                  textDecoration: "none", fontWeight: 500, padding: "14px 8px",
                  borderBottom: "1px solid rgba(0,0,0,0.06)",
                }}
              >
                {it.label}
              </a>
            ))}
            <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 16 }}>
              <Button variant="primary" href={ctaPrimary.href} arrow={false} style={{ width: "100%", justifyContent: "center", padding: "14px 18px", borderRadius: 999 }}>{ctaPrimary.label}</Button>
              <Button variant="secondary" href={ctaSecondary.href} arrow={false} style={{ width: "100%", justifyContent: "center", padding: "14px 18px", borderRadius: 999 }}>{ctaSecondary.label}</Button>
            </div>
          </div>
        </div>
      )}
    </nav>
  );
}

function SideRail() {
  const isMobile = useMediaQuery("(max-width: 860px)");
  if (isMobile) return null;
  return (
    <div style={{ position: "fixed", right: 16, top: "50%", transform: "translateY(-50%)", display: "flex", flexDirection: "column", gap: 10, zIndex: 15 }}>
      {[
        { k: "MEET", jp: "カジュアル面談", href: p("recruit/entry.html") },
        { k: "RECRUIT", jp: "採用情報", href: p("recruit/index.html") },
      ].map((it) => (
        <a key={it.k} href={it.href}
          style={{
            background: "#fff",
            border: "1px solid #E5E5E5",
            borderRadius: 8,
            padding: "18px 10px",
            width: 48,
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            gap: 12,
            textDecoration: "none",
            boxShadow: "0 4px 16px rgba(0,0,0,0.04)",
            transition: "all 160ms cubic-bezier(0.22,1,0.36,1)",
          }}
          onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.borderColor = "var(--purple)"; }}
          onMouseLeave={(e) => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.borderColor = "#E5E5E5"; }}
        >
          <div style={{ writingMode: "vertical-rl", fontFamily: 'var(--font-mono-label)', fontSize: 10, letterSpacing: "0.2em", color: "var(--purple)", fontWeight: 500 }}>{it.k}</div>
          <div style={{ writingMode: "vertical-rl", fontFamily: 'var(--font-serif)', fontSize: 13, color: "#1A1A1A" }}>{it.jp}</div>
        </a>
      ))}
    </div>
  );
}

function Footer() {
  const corp = [
    { href: p("index.html"), label: "TOP" },
    { href: p("strengths.html"), label: "選ばれる理由" },
    { href: p("business.html"), label: "事業内容" },
    { href: p("about.html"), label: "会社概要" },
    // 発信コンテンツ準備中のため非表示（記事整備後に戻す）
    // { href: p("insights.html"), label: "発信" },
    { href: p("contact.html"), label: "お問い合わせ" },
  ];
  const rec = [
    { href: p("recruit/index.html"), label: "採用TOP" },
    { href: p("recruit/about.html"), label: "私たちについて" },
    { href: p("recruit/jobs.html"), label: "求人一覧" },
    { href: p("recruit/interview.html"), label: "エンジニアインタビュー" },
    { href: p("recruit/environment.html"), label: "働く環境・制度" },
    { href: p("recruit/entry.html"), label: "エントリー" },
  ];
  const linkStyle = { fontFamily: 'var(--font-sans)', fontSize: 14, color: "#1A1A1A", textDecoration: "none", transition: "color 160ms" };
  const isMobile = useMediaQuery("(max-width: 768px)");
  return (
    <footer style={{ background: "#FAF8F5", padding: isMobile ? "64px 22px 32px" : "96px 48px 40px", borderTop: "1px solid #E5E5E5" }}>
      <div style={{ maxWidth: 1280, margin: "0 auto" }}>
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1.4fr 1fr 1fr", gap: isMobile ? 40 : 64 }}>
          <div>
            <Logo height={56} />
            <p style={{ fontFamily: 'var(--font-sans)', fontSize: 14, color: "#6B6B6B", marginTop: 24, lineHeight: 1.8, maxWidth: 380 }}>
              SIer から、AIer へ。<br />
              AIエージェントと人が協働して、会社は動く。<br />
              その実践から生まれた、新しい人材のかたち。
            </p>
          </div>
          <div>
            <div style={{ fontFamily: 'var(--font-mono-label)', fontSize: 11, letterSpacing: "0.2em", color: "var(--purple)", fontWeight: 500, marginBottom: 22 }}>— CORPORATE —</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {corp.map((l) => <a key={l.href} href={l.href} style={linkStyle}
                onMouseEnter={(e) => e.currentTarget.style.color = "var(--purple)"}
                onMouseLeave={(e) => e.currentTarget.style.color = "#1A1A1A"}
              >{l.label}</a>)}
            </div>
          </div>
          <div>
            <div style={{ fontFamily: 'var(--font-mono-label)', fontSize: 11, letterSpacing: "0.2em", color: "var(--purple)", fontWeight: 500, marginBottom: 22 }}>— RECRUIT —</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {rec.map((l) => <a key={l.href} href={l.href} style={linkStyle}
                onMouseEnter={(e) => e.currentTarget.style.color = "var(--purple)"}
                onMouseLeave={(e) => e.currentTarget.style.color = "#1A1A1A"}
              >{l.label}</a>)}
            </div>
          </div>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderTop: "1px solid #E5E5E5", marginTop: 72, paddingTop: 24, flexWrap: "wrap", gap: 16 }}>
          <div style={{ fontFamily: 'var(--font-mono-label)', fontSize: 11, letterSpacing: "0.14em", color: "#6B6B6B" }}>© 2026 日本AIセンター株式会社 · ALL RIGHTS RESERVED</div>
          <div style={{ display: "flex", gap: 24, fontFamily: 'var(--font-sans)', fontSize: 12, color: "#6B6B6B" }}>
            <a href="https://x.com/Ishida_aicenter" target="_blank" rel="noopener noreferrer" style={{ color: "#6B6B6B", textDecoration: "none" }}>X / Twitter</a>
            <a href="https://note.com/ai_center" target="_blank" rel="noopener noreferrer" style={{ color: "#6B6B6B", textDecoration: "none" }}>note</a>
            <a href="https://line.me/ti/p/vax5rNxqMQ" target="_blank" rel="noopener noreferrer" style={{ color: "#6B6B6B", textDecoration: "none" }}>LINE</a>
            <a href={p("privacy.html")} style={{ color: "#6B6B6B", textDecoration: "none" }}>プライバシーポリシー</a>
            <a href={p("tokusho.html")} style={{ color: "#6B6B6B", textDecoration: "none" }}>特定商取引法表記</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// Scroll-reveal wrapper
function Reveal({ children, delay = 0, style }) {
  const ref = React.useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const obs = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) { setVisible(true); obs.disconnect(); } },
      { threshold: 0.12, rootMargin: "0px 0px -40px 0px" }
    );
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return (
    <div
      ref={ref}
      style={{
        opacity: visible ? 1 : 0,
        transform: visible ? "translateY(0)" : "translateY(20px)",
        transition: `opacity 600ms cubic-bezier(0.22,1,0.36,1) ${delay}ms, transform 600ms cubic-bezier(0.22,1,0.36,1) ${delay}ms`,
        ...style,
      }}
    >
      {children}
    </div>
  );
}

Object.assign(window, { Button, SectionLabel, TopBar, Logo, Nav, SideRail, Footer, Reveal, BASE, p, useMediaQuery });
