/* global React, Common, Motion */
const { Eyebrow, SectionTitle, SectionLead } = Common;
const { useTheme } = Motion;
const { useState: useSeS, useRef: useSeR, useEffect: useSeE } = React;

// Real navigable Settings. Iframe-embedded mac/win settings prototypes.
// Theme syncs to parent site via postMessage.
function SettingsSection() {
  const { theme } = useTheme();
  const [os, setOS] = useSeS(() => {
    if (typeof navigator === "undefined") return "mac";
    const ua = navigator.userAgent || "";
    if (/Win/.test(ua)) return "win";
    return "mac";
  });
  const iframeRef = useSeR(null);

  // Push theme to iframe whenever it changes (and on initial mount).
  useSeE(() => {
    const send = () => {
      const w = iframeRef.current && iframeRef.current.contentWindow;
      if (w) w.postMessage({ type: "theme", theme }, "*");
    };
    send();
    const f = iframeRef.current;
    if (f) f.addEventListener("load", send);
    // Handshake: child posts "settings-ready" on mount.
    const onReady = (e) => {
      if (e.data && e.data.type === "settings-ready") send();
    };
    window.addEventListener("message", onReady);
    return () => {
      if (f) f.removeEventListener("load", send);
      window.removeEventListener("message", onReady);
    };
  }, [theme, os]);

  const src = `assets/settings/${os}/index.html?embed=1&theme=${theme}`;

  return (
    <section id="features" style={{ padding: "120px 32px", position: "relative" }}>
      <div className="container">
        <div className="reveal" style={{ textAlign: "center", marginBottom: 36 }}>
          <Eyebrow num={7} color="#A78BFA">it's a real app</Eyebrow>
          <div style={{ height: 16 }}/>
          <SectionTitle align="center" maxWidth={760}>
            Settings that<br/>
            <span className="grad-text">respect your attention.</span>
          </SectionTitle>
          <SectionLead align="center" maxWidth={580}>
            No 7-step onboarding. No account. Search, click, change. Done. Click around. It's the real thing.
          </SectionLead>
        </div>

        {/* OS toggle */}
        <div className="reveal" style={{ display: "flex", justifyContent: "center", marginBottom: 24 }}>
          <div style={{
            display: "inline-flex", padding: 4,
            background: "var(--bg-elev)",
            border: "1px solid var(--line)",
            borderRadius: 10, gap: 4,
          }}>
            {[
              ["mac", "macOS"],
              ["win", "Windows"],
            ].map(([id, label]) => (
              <button key={id} onClick={() => setOS(id)} style={{
                padding: "8px 16px", borderRadius: 7,
                background: os === id ? "var(--line)" : "transparent",
                border: 0, color: os === id ? "var(--fg)" : "var(--fg-muted)",
                fontSize: 13, fontFamily: "var(--font-sans)",
                fontWeight: os === id ? 600 : 500,
                cursor: "pointer", transition: "all 200ms",
              }}>
                {label}
              </button>
            ))}
          </div>
        </div>

        {/* Iframe with real navigable settings, sits flush with the page,
            no double frame. The mockup inside fills 100% (body.embed-mode CSS). */}
        <div className="reveal" style={{
          position: "relative",
          maxWidth: 1280, marginInline: "auto",
          borderRadius: 14, overflow: "hidden",
          border: "1px solid var(--line)",
          background: theme === "light" ? "#F1EFEA" : "#0a0a0a",
        }}>
          <iframe
            ref={iframeRef}
            key={os}
            src={src}
            title={`Dimmy Settings, ${os === "mac" ? "macOS" : "Windows"}`}
            style={{
              display: "block", width: "100%",
              // dvh (dynamic viewport) instead of vh: on iOS the URL bar shows/
              // hides during scroll, vh would shrink/grow the iframe and shove
              // every section below up and down. dvh stays stable. Mobile gets
              // a fixed pixel height via the @media rule below.
              height: "min(820px, 78dvh)",
              border: 0, background: "transparent",
            }}
            loading="lazy"
          />
        </div>

        <div className="reveal" style={{
          marginTop: 14, textAlign: "center",
          fontFamily: "var(--font-mono)", fontSize: 11,
          color: "var(--fg-faint)", letterSpacing: "0.08em",
        }}>
          live prototype · click anywhere · theme follows the page
        </div>

        <div className="reveal" style={{
          marginTop: 48,
          display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 1,
          background: "var(--line)",
          border: "1px solid var(--line)",
          borderRadius: 14, overflow: "hidden",
          maxWidth: 1080, marginInline: "auto",
        }}>
          {[
            { t: "Live preview", s: "See pill states before applying", c: "#38BDF8" },
            { t: "9-grid position", s: "Snap anywhere, drag to fine-tune", c: "#34D399" },
            { t: "Border styles", s: "Rainbow, solid, breathing, off", c: "#A78BFA" },
            { t: "Per-app rules", s: "Different shortcut, different style", c: "#FB923C" },
          ].map((f, i) => (
            <div key={i} style={{ padding: "22px 20px", background: "var(--bg)" }}>
              <div style={{
                width: 8, height: 8, borderRadius: 99, background: f.c,
                boxShadow: `0 0 12px ${f.c}88`,
                marginBottom: 14,
              }}/>
              <div style={{ fontWeight: 600, fontSize: 14, color: "var(--fg)" }}>{f.t}</div>
              <div style={{ marginTop: 4, fontSize: 12, color: "var(--fg-faint)", lineHeight: 1.45 }}>{f.s}</div>
            </div>
          ))}
        </div>
      </div>

      <style>{`
        @media (max-width: 720px) {
          section[id="features"] [style*="grid-template-columns: repeat(4"] { grid-template-columns: repeat(2, 1fr) !important; }
          section[id="features"] iframe { height: 540px !important; }
        }
      `}</style>
    </section>
  );
}

window.SettingsSection = SettingsSection;
