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

// ── Icon helper (mask-based, inherits currentColor) ────────────
function Ic({ name, size = 16, color = "currentColor", className = "ic", style }) {
  return (
    <span
      className={className}
      aria-hidden="true"
      style={{
        display: "inline-block",
        width: size, height: size,
        backgroundColor: color,
        WebkitMask: `url(assets/icons/${name}.svg) center / contain no-repeat`,
        mask: `url(assets/icons/${name}.svg) center / contain no-repeat`,
        flex: "none",
        ...(style || {}),
      }}
    />
  );
}

// ── fade-up: simple IntersectionObserver hook ─────────────────
function useReveal() {
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
    }, { threshold: 0.12 });
    document.querySelectorAll(".fade-up").forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

// ── Count-up number ───────────────────────────────────────────
function CountUp({ to, duration = 1600, suffix = "", prefix = "", format = (n) => n.toLocaleString() }) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  useEffect(() => {
    let raf;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            const v = Number.isInteger(to) ? Math.round(to * eased) : to * eased;
            setVal(v);
            if (t < 1) raf = requestAnimationFrame(tick);
          };
          raf = requestAnimationFrame(tick);
          io.disconnect();
        }
      });
    }, { threshold: 0.5 });
    if (ref.current) io.observe(ref.current);
    return () => { io.disconnect(); if (raf) cancelAnimationFrame(raf); };
  }, [to, duration]);
  return <span ref={ref}>{prefix}{format(val)}{suffix}</span>;
}

// ── Top navigation (shared across pages) ──────────────────────
function TopNav({ active = "home", showLang = true, onHero = false }) {
  const { lang, setLang } = useLang();
  const t = useT();
  // Seed onHeroState from current scroll so deep-link / scroll-restore don't flash transparent nav over dark content.
  const [onHeroState, setOnHeroState] = React.useState(
    () => onHero && (typeof window === "undefined" || window.scrollY < window.innerHeight - 100)
  );
  const [menuOpen, setMenuOpen] = React.useState(false);
  // If onHero, switch to solid background after scroll past hero
  React.useEffect(() => {
    if (!onHero) return;
    const onScroll = () => setOnHeroState(window.scrollY < window.innerHeight - 100);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, [onHero]);
  // ESC closes mobile menu
  React.useEffect(() => {
    if (!menuOpen) return;
    const onKey = (e) => { if (e.key === "Escape") setMenuOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [menuOpen]);
  const items = [
    { id: "about", label: t("nav.about"), href: "about.html" },
    { id: "business", label: t("nav.business"), href: "business.html" },
    { id: "equipment", label: t("nav.equipment"), href: "equipment.html" },
    { id: "contact", label: t("nav.contact"), href: "index.html#contact" },
  ];
  const closeMenu = () => setMenuOpen(false);
  return (
    <header className={`topnav ${onHero && onHeroState ? "topnav--on-hero" : ""} ${menuOpen ? "topnav--menu-open" : ""}`}>
      <div className="topnav__inner">
        <a href="index.html" className="topnav__brand" aria-label="The Myong" onClick={closeMenu}>
          <span className="symbol" aria-hidden="true"></span>
          <span className="word">{t("nav.brand")}</span>
        </a>
        <nav className="topnav__menu">
          {items.map((it) => (
            <a key={it.id} href={it.href} className={active === it.id ? "active" : ""} onClick={closeMenu}>{it.label}</a>
          ))}
        </nav>
        {showLang && (
          <div className="topnav__lang" role="tablist" aria-label="Language">
            {["KR", "EN", "CN"].map((l) => (
              <button key={l} className={lang === l ? "active" : ""} onClick={() => setLang(l)}>{l}</button>
            ))}
          </div>
        )}
        <a href="mailto:tm@themyong.co.kr" className="btn btn--primary btn--sm" onClick={closeMenu}><Ic name="mail" size={14} /> tm@themyong.co.kr</a>
        <button
          type="button"
          className="topnav__burger"
          aria-label={menuOpen ? "Close menu" : "Open menu"}
          aria-expanded={menuOpen}
          onClick={() => setMenuOpen((v) => !v)}
        >
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
        </button>
      </div>
    </header>
  );
}

// ── Footer ─────────────────────────────────────────────────
function Footer() {
  const t = useT();
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer__top">
          <div className="footer__brand">
            <span className="word">{t("nav.brand")}</span>
            <span className="tag">{t("footer.brand_tag")}</span>
          </div>
          <div className="footer__links">
            <div className="footer__col">
              <span className="hd">{t("footer.col_company")}</span>
              <a href="about.html">{t("footer.link_greeting")}</a>
              <a href="about.html#history">{t("footer.link_history")}</a>
              <a href="about.html#org">{t("footer.link_org")}</a>
              <a href="about.html#certs">{t("footer.link_certs")}</a>
            </div>
            <div className="footer__col">
              <span className="hd">{t("footer.col_business")}</span>
              <a href="business.html">{t("footer.link_capabilities")}</a>
              <a href="business.html#products">{t("footer.link_products")}</a>
              <a href="equipment.html">{t("footer.link_equipment")}</a>
            </div>
            <div className="footer__col">
              <span className="hd">{t("footer.col_contact")}</span>
              <a href="index.html#contact">{t("footer.link_inquiry")}</a>
              <a href="about.html#location">{t("footer.link_location")}</a>
              <a href="assets/회사소개서.pdf" download>{t("footer.link_brochure")}</a>
            </div>
          </div>
        </div>
        <div className="footer__bottom">
          <div className="info">
            <span>{t("footer.address")}</span>
            <span>{t("footer.biz_no")}</span>
            <span>{t("footer.fax")}</span>
            <span>{t("footer.email")}</span>
          </div>
          <div>{t("footer.copyright")}</div>
        </div>
      </div>
    </footer>
  );
}

// ── Page Hero (subpages) ─────────────────────────────────────
function PageHero({ title, intro }) {
  return (
    <section className="page-hero" data-screen-label="00 Page Hero">
      <div className="page-hero__bg" />
      <div className="page-hero__inner">
        <div>
          <h1>{title}</h1>
        </div>
        {intro && <p className="page-hero__intro">{intro}</p>}
      </div>
    </section>
  );
}

// ── Shower head SVG (hero visual) ────────────────────────────
function ShowerHeadSVG() {
  const t = useT();
  const rings = [];
  for (let r = 1; r <= 7; r++) {
    const n = r * 6;
    for (let i = 0; i < n; i++) {
      const a = (i / n) * Math.PI * 2;
      rings.push({ x: 200 + Math.cos(a) * r * 18, y: 200 + Math.sin(a) * r * 18, r: 3.2 });
    }
  }
  rings.unshift({ x: 200, y: 200, r: 3.6 });
  return (
    <svg viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg" aria-label="Shower head precision drawing">
      <defs>
        <radialGradient id="plate" cx="50%" cy="40%" r="60%">
          <stop offset="0%" stopColor="#3A4A66" stopOpacity="0.4" />
          <stop offset="60%" stopColor="#1B1F2A" stopOpacity="0.22" />
          <stop offset="100%" stopColor="#0a0a0b" stopOpacity="0" />
        </radialGradient>
        <linearGradient id="ring" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#9EC5FF" stopOpacity="0.6" />
          <stop offset="100%" stopColor="#9EC5FF" stopOpacity="0.15" />
        </linearGradient>
      </defs>
      <g stroke="rgba(255,255,255,0.07)" strokeWidth="0.5">
        <line x1="20" y1="200" x2="380" y2="200" />
        <line x1="200" y1="20" x2="200" y2="380" />
        <line x1="60" y1="60" x2="340" y2="340" />
        <line x1="60" y1="340" x2="340" y2="60" />
      </g>
      <circle cx="200" cy="200" r="170" fill="url(#plate)" />
      <circle cx="200" cy="200" r="170" fill="none" stroke="url(#ring)" strokeWidth="1" />
      <circle cx="200" cy="200" r="155" fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="0.5" strokeDasharray="2 4" />
      <circle cx="200" cy="200" r="140" fill="none" stroke="rgba(255,255,255,0.08)" strokeWidth="0.5" />
      <g fill="rgba(255,255,255,0.55)">
        {rings.map((p, i) => <circle key={i} cx={p.x} cy={p.y} r={p.r} />)}
      </g>
      <g fill="rgba(0,0,0,0.4)">
        {rings.map((p, i) => <circle key={i} cx={p.x} cy={p.y} r={p.r * 0.5} />)}
      </g>
      <g stroke="rgba(158,197,255,0.7)" strokeWidth="0.8" fill="none">
        <line x1="200" y1="200" x2="290" y2="100" />
        <circle cx="290" cy="100" r="3" fill="rgba(158,197,255,0.9)" />
        <line x1="290" y1="100" x2="340" y2="100" />
      </g>
      <text x="346" y="98" fill="rgba(158,197,255,0.95)" style={{ font: "600 10px var(--font-sans)", letterSpacing: "0.15em" }}>Ø0.4mm</text>
      <text x="346" y="111" fill="rgba(255,255,255,0.45)" style={{ font: "500 8px var(--font-sans)", letterSpacing: "0.15em" }}>{t("hero.svg_min_hole")}</text>
      <g stroke="rgba(255,255,255,0.3)" strokeWidth="0.6">
        <line x1="30" y1="195" x2="30" y2="205" />
        <line x1="370" y1="195" x2="370" y2="205" />
        <line x1="32" y1="200" x2="368" y2="200" strokeDasharray="3 3" />
      </g>
      <text x="200" y="193" textAnchor="middle" fill="rgba(255,255,255,0.6)" style={{ font: "600 10px var(--font-sans)", letterSpacing: "0.18em" }}>Ø300mm</text>
    </svg>
  );
}

Object.assign(window, { Ic, useReveal, CountUp, TopNav, Footer, PageHero, ShowerHeadSVG });
