// Top nav — brand + 「探索」 (Explore) menu + 「聯絡我們」 (Contact) — both modal style à la lingcarbon
function NavBar({ page, setPage, lang, setLang, t, scrolled }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [contactOpen, setContactOpen] = React.useState(false);

  // close on page change
  React.useEffect(() => { setMenuOpen(false); setContactOpen(false); }, [page]);

  // lock scroll while any overlay open
  React.useEffect(() => {
    const open = menuOpen || contactOpen;
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen, contactOpen]);

  // ESC closes overlays
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") { setMenuOpen(false); setContactOpen(false); } };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  // blur background while menu/contact open
  React.useEffect(() => {
    const main = document.querySelector("main");
    const footer = document.querySelector("footer");
    const open = menuOpen || contactOpen;
    [main, footer].forEach((el) => {
      if (!el) return;
      el.style.transition = "filter 0.5s var(--ease-out), transform 0.5s var(--ease-out)";
      el.style.filter = open ? "blur(8px) brightness(0.55)" : "none";
      el.style.transform = open ? "scale(0.985)" : "none";
      el.style.transformOrigin = "center top";
    });
  }, [menuOpen, contactOpen]);

  return (
    <React.Fragment>
      <header
        className="qs-nav"
        style={{
          position: "fixed", top: 0, left: 0, right: 0, zIndex: 60,
          transition: "all 0.4s var(--ease-out)",
          background: scrolled ? "color-mix(in srgb, var(--c-bg) 88%, transparent)" : "transparent",
          backdropFilter: scrolled ? "saturate(160%) blur(14px)" : "none",
          WebkitBackdropFilter: scrolled ? "saturate(160%) blur(14px)" : "none",
          borderBottom: scrolled ? "1px solid var(--c-line)" : "1px solid transparent",
        }}
      >
        <div
          className="shell"
          style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            padding: scrolled ? "12px 56px" : "20px 56px",
            transition: "padding 0.3s var(--ease-out)",
          }}
        >
          <div style={{ display: "flex", alignItems: "center", gap: 14, cursor: "pointer", flexShrink: 0, position: "relative", zIndex: 2 }}
               onClick={() => { setPage("home"); setMenuOpen(false); }}>
            <BrandMark />
            <div style={{ display: "flex", flexDirection: "column", lineHeight: 1 }}>
              <span style={{ fontFamily: "var(--f-serif)", fontSize: 22, letterSpacing: "0.02em",
                              color: menuOpen ? "var(--c-paper)" : "var(--c-ink)",
                              transition: "color 0.4s var(--ease-out)" }}>
                {t.brand}
              </span>
              <span style={{ fontFamily: "var(--f-mono)", fontSize: 9.5, letterSpacing: "0.22em",
                             color: "var(--c-aqua)", textTransform: "uppercase", marginTop: 3 }}>
                {t.brandSub}
              </span>
            </div>
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <button
              onClick={() => { setContactOpen(true); setMenuOpen(false); }}
              style={{
                background: "transparent", border: "1px solid var(--c-line)",
                padding: "10px 18px", borderRadius: 999, fontSize: 13,
                color: "var(--c-ink)", fontFamily: "inherit", cursor: "pointer",
                transition: "all 0.25s var(--ease-out)",
              }}
              onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--c-deep)"; e.currentTarget.style.background = "var(--c-mist)"; }}
              onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--c-line)"; e.currentTarget.style.background = "transparent"; }}
            >
              {t.bookCall}
            </button>
            <ExploreButton open={menuOpen} onClick={() => { setMenuOpen((v) => !v); setContactOpen(false); }} label={lang === "zh" ? "探索" : "Menu"} />
          </div>
        </div>
      </header>

      <ExploreMenu open={menuOpen} t={t} lang={lang} setLang={setLang} page={page} setPage={setPage}
                    onContactClick={() => { setMenuOpen(false); setContactOpen(true); }} />

      <ContactModal open={contactOpen} t={t} lang={lang} onClose={() => setContactOpen(false)} />
    </React.Fragment>
  );
}

function ExploreButton({ open, onClick, label }) {
  return (
    <button onClick={onClick} aria-label={label}
      style={{
        display: "inline-flex", alignItems: "center", gap: 10,
        background: open ? "var(--c-ink)" : "var(--c-deep)",
        color: "var(--c-paper)",
        padding: "10px 18px", borderRadius: 999,
        border: "none", fontSize: 13, fontFamily: "inherit",
        cursor: "pointer", transition: "background 0.25s var(--ease-out)",
        minWidth: 92, justifyContent: "center",
      }}>
      <span>{open ? (label === "Menu" ? "Close" : "關閉") : label}</span>
      <span style={{ position: "relative", width: 14, height: 12, display: "inline-block" }}>
        <span style={{
          position: "absolute", top: open ? 5 : 2, left: 0, right: 0, height: 1.5,
          background: "currentColor",
          transformOrigin: "center", transform: open ? "rotate(45deg)" : "none",
          transition: "all 0.3s var(--ease-out)",
        }} />
        <span style={{
          position: "absolute", top: open ? 5 : 9, left: 0, right: 0, height: 1.5,
          background: "currentColor",
          transform: open ? "rotate(-45deg)" : "none",
          transition: "all 0.3s var(--ease-out)",
        }} />
      </span>
    </button>
  );
}

function ExploreMenu({ open, t, lang, setLang, page, setPage, onContactClick }) {
  const pages = ["home", "consulting", "pm", "consumer", "collab", "about"];
  return (
    <div style={{
      position: "fixed", top: 0, left: 0, right: 0, zIndex: 55,
      background: "var(--c-ink)", color: "var(--c-paper)",
      transform: open ? "translateY(0)" : "translateY(-100%)",
      transition: "transform 0.6s cubic-bezier(0.65, 0, 0.35, 1)",
      paddingTop: 88, paddingBottom: 64,
      boxShadow: open ? "0 30px 60px -20px rgba(0,0,0,0.4)" : "none",
    }}>
      <div className="shell" style={{
        display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr", gap: 48, alignItems: "start",
      }}>
        {/* Pages */}
        <div>
          <div style={{ fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.2em",
                          color: "rgba(255,255,255,0.45)", marginBottom: 28, textTransform: "uppercase" }}>
            {lang === "zh" ? "服務" : "Pages"}
          </div>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid",
                        gridTemplateColumns: "1fr 1fr", gap: "14px 32px" }}>
            {pages.map((p, i) => (
              <MenuLink key={p} label={t.nav[p]} active={page === p} delay={open ? 100 + i * 50 : 0} open={open}
                          onClick={() => setPage(p)} />
            ))}
          </ul>
        </div>

        {/* Language */}
        <div>
          <div style={{ fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.2em",
                          color: "rgba(255,255,255,0.45)", marginBottom: 28, textTransform: "uppercase" }}>
            {lang === "zh" ? "語言" : "Language"}
          </div>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 14 }}>
            <MenuLink label="中文" active={lang === "zh"} delay={open ? 400 : 0} open={open}
                        onClick={() => setLang("zh")} />
            <MenuLink label="English" active={lang === "en"} delay={open ? 450 : 0} open={open}
                        onClick={() => setLang("en")} />
          </ul>
        </div>

        {/* Contact */}
        <div>
          <div style={{ fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.2em",
                          color: "rgba(255,255,255,0.45)", marginBottom: 28, textTransform: "uppercase" }}>
            {lang === "zh" ? "聯絡" : "Contact"}
          </div>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 14 }}>
            <MenuLink label={lang === "zh" ? "聯絡我們" : "Contact us"} delay={open ? 500 : 0} open={open}
                        onClick={onContactClick} />
            <MenuLink label="Email" delay={open ? 550 : 0} open={open}
                        href="mailto:qiao.shui.org@gmail.com" />
            <MenuLink label={lang === "zh" ? "撥打電話" : "Call"} delay={open ? 600 : 0} open={open}
                        href="tel:+886228087301" />
          </ul>
        </div>
      </div>

      {/* Bottom info strip */}
      <div className="shell" style={{
        marginTop: 56, paddingTop: 28, borderTop: "1px solid rgba(255,255,255,0.12)",
        display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 18,
        fontFamily: "var(--f-mono)", fontSize: 11.5, color: "rgba(255,255,255,0.55)",
        letterSpacing: "0.05em",
      }}>
        <span>(02) 2808-7301 · qiao.shui.org@gmail.com</span>
        <span>114025 台北市內湖區民權東路六段 120 巷 7 弄 6 號</span>
      </div>
    </div>
  );
}

function MenuLink({ label, active, delay, open, onClick, href }) {
  const [hover, setHover] = React.useState(false);
  const sharedStyle = {
    display: "flex", alignItems: "center", justifyContent: "space-between",
    background: "transparent", border: "none", padding: "8px 0",
    fontFamily: "var(--f-serif)", fontSize: 30, fontWeight: 400,
    letterSpacing: "-0.005em",
    color: active ? "var(--c-aqua)" : (hover ? "#fff" : "rgba(255,255,255,0.85)"),
    cursor: "pointer", textAlign: "left", textDecoration: "none",
    opacity: open ? 1 : 0,
    transform: open ? "translateY(0)" : "translateY(20px)",
    transition: `opacity 0.5s var(--ease-out) ${delay}ms, transform 0.5s var(--ease-out) ${delay}ms, color 0.2s var(--ease-out)`,
    width: "100%",
  };
  const inner = (
    <React.Fragment>
      <span>{label}</span>
      <span style={{
        fontFamily: "var(--f-mono)", fontSize: 14,
        opacity: hover || active ? 1 : 0.4,
        transform: hover ? "translateX(4px)" : "translateX(0)",
        transition: "all 0.25s var(--ease-out)",
      }}>{active ? "●" : "→"}</span>
    </React.Fragment>
  );
  return (
    <li onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
      {href ? (
        <a href={href} style={sharedStyle}>{inner}</a>
      ) : (
        <button onClick={onClick} style={sharedStyle}>{inner}</button>
      )}
    </li>
  );
}

function ContactModal({ open, t, lang, onClose }) {
  const [form, setForm] = React.useState({ name: "", email: "", type: "", message: "" });
  const [sent, setSent] = React.useState(false);
  const types = lang === "zh"
    ? ["氣流顧問", "專案管理", "消費級應用 QsHood", "企業合作", "其他"]
    : ["Airflow Consulting", "Project Management", "QsHood Consumer", "Partnership", "Other"];

  const submit = (e) => {
    e.preventDefault();
    const body = encodeURIComponent(
      `姓名 / Name：${form.name}\nEmail：${form.email}\n需求 / Type：${form.type}\n訊息 / Message：\n${form.message}`
    );
    const subject = encodeURIComponent(`[喬水官網詢問] ${form.type || "新訊息"} — ${form.name || ""}`);
    window.location.href = `mailto:qiao.shui.org@gmail.com?subject=${subject}&body=${body}`;
    setSent(true);
    setTimeout(() => setSent(false), 4000);
  };

  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 70,
        background: open ? "rgba(11,42,46,0.55)" : "rgba(11,42,46,0)",
        backdropFilter: open ? "blur(6px)" : "none",
        WebkitBackdropFilter: open ? "blur(6px)" : "none",
        opacity: open ? 1 : 0,
        pointerEvents: open ? "auto" : "none",
        transition: "all 0.4s var(--ease-out)",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 32,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          position: "relative", maxWidth: 920, width: "100%", maxHeight: "92vh",
          overflowY: "auto",
          background: "var(--c-ink)", color: "var(--c-paper)",
          borderRadius: 18,
          boxShadow: "0 40px 80px -20px rgba(0,0,0,0.5)",
          transform: open ? "scale(1) translateY(0)" : "scale(0.96) translateY(20px)",
          transition: "transform 0.45s var(--ease-out)",
          display: "grid", gridTemplateColumns: "1fr 1.4fr",
        }}
      >
        {/* Close */}
        <button onClick={onClose} aria-label="Close"
          style={{
            position: "absolute", top: 20, right: 20,
            width: 40, height: 40, borderRadius: 999,
            background: "rgba(255,255,255,0.08)", border: "1px solid rgba(255,255,255,0.12)",
            color: "var(--c-paper)", fontSize: 18, cursor: "pointer",
            display: "flex", alignItems: "center", justifyContent: "center",
            zIndex: 2,
          }}>×</button>

        {/* Left: contact info */}
        <div style={{ padding: "44px 36px", borderRight: "1px solid rgba(255,255,255,0.08)" }}>
          <h3 style={{ fontFamily: "var(--f-serif)", fontSize: 26, fontWeight: 400,
                        margin: "0 0 28px", letterSpacing: "-0.01em" }}>
            {lang === "zh" ? "諮詢氣流團隊" : "Contact the airflow team"}
          </h3>
          <ContactRow icon="◎" label={lang === "zh" ? "拜訪我們" : "Visit"}
                       value="114025 台北市內湖區民權東路六段 120 巷 7 弄 6 號" />
          <ContactRow icon="✉" label={lang === "zh" ? "與我們聯絡" : "Email"}
                       value="qiao.shui.org@gmail.com" href="mailto:qiao.shui.org@gmail.com" />
          <ContactRow icon="✆" label={lang === "zh" ? "聯絡我們" : "Phone"}
                       value="+886 2 2808-7301" href="tel:+886228087301" />
          <ContactRow icon="◎" label="LINE" value={lang === "zh" ? "喬水氣流官方帳號" : "Qiao Shui Official"} />
        </div>

        {/* Right: form */}
        <form onSubmit={submit} style={{ padding: "44px 36px" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 18 }}>
            <ModalField label={lang === "zh" ? "姓名" : "Name"} value={form.name}
                          onChange={(e) => setForm({ ...form, name: e.target.value })} required />
            <ModalField label={lang === "zh" ? "電子郵件" : "Email"} type="email" value={form.email}
                          onChange={(e) => setForm({ ...form, email: e.target.value })} required />
          </div>
          <div style={{ marginBottom: 18 }}>
            <ModalLabel>{lang === "zh" ? "服務需求" : "Service"}</ModalLabel>
            <select value={form.type} onChange={(e) => setForm({ ...form, type: e.target.value })}
              style={modalInputStyle}>
              <option value="" style={{ background: "var(--c-ink)" }}>
                {lang === "zh" ? "選擇一項服務" : "Select a service"}
              </option>
              {types.map((tp) => (
                <option key={tp} value={tp} style={{ background: "var(--c-ink)" }}>{tp}</option>
              ))}
            </select>
          </div>
          <div style={{ marginBottom: 24 }}>
            <ModalLabel>{lang === "zh" ? "訊息" : "Message"}</ModalLabel>
            <textarea rows={5} value={form.message}
              onChange={(e) => setForm({ ...form, message: e.target.value })}
              placeholder={lang === "zh" ? "簡述需求、場域、預算或時程..." : "Briefly describe your need, space, budget, or timeline..."}
              style={{ ...modalInputStyle, resize: "vertical", minHeight: 110 }} />
          </div>
          <button type="submit" className="btn btn-primary"
            style={{ background: "var(--c-aqua)", color: "var(--c-ink)", padding: "14px 24px", border: "none" }}>
            {sent ? (lang === "zh" ? "已送出 ✓" : "Sent ✓") : (lang === "zh" ? "傳送" : "Send")}
            <span style={{ fontFamily: "var(--f-mono)" }}>→</span>
          </button>
        </form>
      </div>
    </div>
  );
}

const modalInputStyle = {
  width: "100%", padding: "12px 14px",
  background: "rgba(255,255,255,0.05)",
  border: "1px solid rgba(255,255,255,0.15)",
  borderRadius: 10, color: "var(--c-paper)",
  fontFamily: "inherit", fontSize: 14, outline: "none",
  transition: "border-color 0.2s var(--ease-out), background 0.2s var(--ease-out)",
};

function ModalLabel({ children }) {
  return (
    <div style={{
      fontFamily: "var(--f-mono)", fontSize: 10.5, letterSpacing: "0.16em",
      textTransform: "uppercase", color: "rgba(255,255,255,0.6)", marginBottom: 8,
    }}>{children}</div>
  );
}

function ModalField({ label, value, onChange, type = "text", required }) {
  const [focused, setFocused] = React.useState(false);
  return (
    <div>
      <ModalLabel>{label}</ModalLabel>
      <input type={type} value={value} onChange={onChange} required={required}
             onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
             style={{
               ...modalInputStyle,
               borderColor: focused ? "var(--c-aqua)" : "rgba(255,255,255,0.15)",
             }} />
    </div>
  );
}

function ContactRow({ icon, label, value, href }) {
  const inner = (
    <React.Fragment>
      <div style={{
        fontFamily: "var(--f-mono)", fontSize: 10.5, letterSpacing: "0.16em",
        textTransform: "uppercase", color: "rgba(255,255,255,0.55)",
        display: "flex", alignItems: "center", gap: 8, marginBottom: 6,
      }}>
        <span style={{ color: "var(--c-aqua)", fontSize: 14 }}>{icon}</span>{label}
      </div>
      <div style={{ fontSize: 14, lineHeight: 1.55, color: "rgba(255,255,255,0.92)" }}>
        {value}
      </div>
    </React.Fragment>
  );
  return (
    <div style={{ marginBottom: 24 }}>
      {href ? (
        <a href={href} style={{ textDecoration: "none", color: "inherit" }}>{inner}</a>
      ) : inner}
    </div>
  );
}

// Logo mark
function BrandMark() {
  return (
    <svg width="36" height="36" viewBox="0 0 36 36" fill="none">
      <circle cx="18" cy="18" r="17" stroke="var(--c-aqua)" strokeWidth="1" opacity="0.45" />
      <path d="M6 13 C 12 11, 18 17, 24 13 C 28 10.5, 30 12, 31 13"
            stroke="var(--c-deep)" strokeWidth="1.5" strokeLinecap="round" fill="none" />
      <path d="M5 19 C 11 17, 17 23, 23 19 C 27 16.5, 29 18, 31 19"
            stroke="var(--c-aqua)" strokeWidth="1.5" strokeLinecap="round" fill="none" />
      <path d="M18 22 c -1.8 2.4 -2.6 4 -2.6 5.6 a 2.6 2.6 0 0 0 5.2 0 c 0 -1.6 -0.8 -3.2 -2.6 -5.6 z"
            fill="var(--c-deep)" />
    </svg>
  );
}

window.NavBar = NavBar;
window.BrandMark = BrandMark;
