// Shared atoms

const { useState: useStateA, useEffect: useEffectA } = React;

const Dot = ({ c = "var(--ink-3)", size = 6 }) => (
  <span style={{ display: "inline-block", width: size, height: size, borderRadius: 999, background: c, verticalAlign: "middle" }} />
);

const Pill = ({ children, tone = "ink" }) => {
  const tones = {
    ink: { bg: "var(--bg-2)", fg: "var(--ink-2)", bd: "var(--line)" },
    accent: { bg: "var(--accent-soft)", fg: "var(--accent)", bd: "transparent" },
    warn: { bg: "var(--warn-soft)", fg: "var(--warn)", bd: "transparent" },
  }[tone];
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: "4px 10px", borderRadius: 999,
      background: tones.bg, color: tones.fg,
      border: `1px solid ${tones.bd}`,
      fontFamily: "var(--mono)", fontSize: 11, letterSpacing: 0.02,
    }}>{children}</span>
  );
};

const Btn = ({ children, variant = "primary", href = "#", onClick, small }) => {
  const base = {
    display: "inline-flex", alignItems: "center", gap: 8,
    padding: small ? "8px 14px" : "12px 18px",
    borderRadius: 8, fontSize: small ? 13 : 14, fontWeight: 500,
    cursor: "pointer", border: "1px solid transparent", transition: "all 120ms ease",
  };
  const variants = {
    primary: { ...base, background: "var(--ink)", color: "var(--bg)" },
    ghost: { ...base, background: "transparent", color: "var(--ink)", borderColor: "var(--line)" },
  };
  return (
    <a href={href} onClick={onClick} style={variants[variant]}
       onMouseEnter={e => { if (variant === "primary") e.currentTarget.style.background = "var(--ink-2)"; if (variant === "ghost") e.currentTarget.style.background = "var(--bg-2)"; }}
       onMouseLeave={e => { if (variant === "primary") e.currentTarget.style.background = "var(--ink)"; if (variant === "ghost") e.currentTarget.style.background = "transparent"; }}>
      {children}
    </a>
  );
};

// WideWired logo. Two variants:
//   - product: the header/nav mark. Chinese version shows "WideWired / 网迅达" when lang=zh.
//   - company: the footer mark, always English (company brand, not product brand).
const LogoMark = ({ size = 22, lang, variant = "company" }) => {
  const src = useThemeLogoA(variant === "product" && lang === "zh");
  return (
    <img src={src} alt="WideWired"
         style={{ height: size, width: Math.round(size * 386.65 / 162), display: "block", flexShrink: 0 }}/>
  );
};

function useThemeLogoA(useCN = false) {
  const pick = (t) => {
    if (useCN) return t === "dark" ? "assets/widewired-logo-cn-white.svg" : "assets/widewired-logo-cn.svg";
    return t === "dark" ? "assets/widewired-logo-white.svg" : "assets/widewired-logo-ink.svg";
  };
  const [src, setSrc] = useStateA(() => {
    const t = typeof document !== "undefined" ? document.documentElement.dataset.theme : "light";
    return pick(t);
  });
  useEffectA(() => {
    const update = () => setSrc(pick(document.documentElement.dataset.theme));
    update();
    const obs = new MutationObserver(update);
    obs.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
    return () => obs.disconnect();
  }, [useCN]);
  return src;
}

function SectionHeader({ kicker, title, subtitle, body, subtitleNoWrap }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 64, marginBottom: 48, alignItems: "end" }}>
      <div>
        <div className="kicker">{kicker}</div>
        <h2 style={{ fontSize: 44, margin: "12px 0 0 0", letterSpacing: -0.025, fontWeight: 500, lineHeight: 1.1, whiteSpace: subtitleNoWrap ? "nowrap" : undefined }}>
          {title}{subtitle && <><br/><span style={{ color: "var(--ink-3)", whiteSpace: subtitleNoWrap ? "nowrap" : undefined }}>{subtitle}</span></>}
        </h2>
      </div>
      {body && <p style={{ fontSize: 17, color: "var(--ink-2)", margin: 0, lineHeight: 1.55, textWrap: "pretty" }}>{body}</p>}
    </div>
  );
}

function Nav({ ctx, theme, toggleTheme, lang, setLang }) {
  const [scrolled, setScrolled] = useStateA(false);
  useEffectA(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const { t } = ctx;
  return (
    <div style={{
      position: "sticky", top: 0, zIndex: 40,
      background: scrolled ? "color-mix(in oklab, var(--bg) 85%, transparent)" : "transparent",
      backdropFilter: scrolled ? "blur(12px) saturate(140%)" : "none",
      borderBottom: scrolled ? "1px solid var(--line)" : "1px solid transparent",
      transition: "all 180ms ease",
    }}>
      <div className="wrap" style={{ display: "flex", alignItems: "center", height: 80, gap: 32 }}>
        <a href="#top" style={{ display: "flex", alignItems: "center", gap: 10, fontWeight: 600, letterSpacing: -0.01 }}>
          <LogoMark size={56} lang={lang} variant="product" />
        </a>
        <nav style={{ display: "flex", gap: 24, marginLeft: 20 }}>
          {[[t.nav.howitworks, "#flow"], [t.nav.pricing, "#pricing"], [t.nav.diff, "#advantage"], [t.nav.china, "#china"]].map(([l, h]) => (
            <a key={h} href={h} style={{ fontSize: 14, color: "var(--ink-2)" }}
               onMouseEnter={e => e.currentTarget.style.color = "var(--ink)"}
               onMouseLeave={e => e.currentTarget.style.color = "var(--ink-2)"}>{l}</a>
          ))}
        </nav>
        <div style={{ flex: 1 }} />
        <div style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
          <div style={{ display: "inline-flex", border: "1px solid var(--line)", borderRadius: 6, padding: 2, background: "var(--bg-2)" }}>
            {["en", "zh"].map(l => (
              <button key={l} onClick={() => setLang(l)} style={{
                padding: "4px 10px", border: 0, borderRadius: 4,
                background: lang === l ? "var(--bg)" : "transparent",
                fontFamily: "var(--mono)", fontSize: 11, cursor: "pointer",
                color: lang === l ? "var(--ink)" : "var(--ink-3)",
                textTransform: "uppercase", letterSpacing: 0.05,
              }}>{l === "en" ? "EN" : "中"}</button>
            ))}
          </div>
          <button onClick={toggleTheme} aria-label="theme" style={{
            width: 30, height: 30, borderRadius: 6, border: "1px solid var(--line)",
            background: "var(--bg-2)", color: "var(--ink-2)", cursor: "pointer",
            display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 13,
          }}>{theme === "dark" ? "☾" : "☀"}</button>
        </div>
        <div style={{ width: 1, height: 20, background: "var(--line)", margin: "0 4px" }} />
        <Btn variant="ghost" small href="app.html">{t.nav.signin}</Btn>
      </div>
    </div>
  );
}

function TweaksPanel({ state, setState, onReset }) {
  return (
    <div style={{
      position: "fixed", bottom: 20, right: 20, zIndex: 50, width: 260,
      background: "var(--bg)", border: "1px solid var(--line)", borderRadius: 12,
      boxShadow: "0 20px 50px -20px color-mix(in oklab, var(--ink) 35%, transparent)", overflow: "hidden",
    }}>
      <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--line)", background: "var(--bg-2)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span style={{ fontSize: 13, fontWeight: 500 }}>Tweaks</span>
        <button onClick={onReset} style={{ border: 0, background: "transparent", fontSize: 11, color: "var(--ink-3)", cursor: "pointer", fontFamily: "var(--mono)" }}>reset</button>
      </div>
      <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 14 }}>
        <TweakRow label="Language">
          <Segmented value={state.lang} options={[["en", "EN"], ["zh", "中文"]]} onChange={v => setState({ ...state, lang: v })}/>
        </TweakRow>
        <TweakRow label="Theme">
          <Segmented value={state.theme} options={[["light", "Light"], ["dark", "Dark"]]} onChange={v => setState({ ...state, theme: v })}/>
        </TweakRow>
        <TweakRow label="Accent hue">
          <input type="range" min="0" max="360" step="1" value={state.accent}
            onChange={e => setState({ ...state, accent: +e.target.value })} style={{ width: "100%" }}/>
          <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>oklch(.62 .13 {state.accent})</div>
        </TweakRow>
      </div>
    </div>
  );
}

const TweakRow = ({ label, children }) => (
  <div>
    <div className="kicker" style={{ marginBottom: 6, fontSize: 10 }}>{label}</div>
    {children}
  </div>
);

const Segmented = ({ value, options, onChange }) => (
  <div style={{ display: "inline-flex", border: "1px solid var(--line)", borderRadius: 6, padding: 2, background: "var(--bg-2)" }}>
    {options.map(([k, l]) => (
      <button key={k} onClick={() => onChange(k)} style={{
        padding: "6px 10px", border: 0, borderRadius: 4,
        background: value === k ? "var(--bg)" : "transparent",
        fontSize: 12, cursor: "pointer", color: value === k ? "var(--ink)" : "var(--ink-3)",
      }}>{l}</button>
    ))}
  </div>
);

Object.assign(window, { Dot, Pill, Btn, LogoMark, SectionHeader, Nav, TweaksPanel });
