/* global React, ReactDOM, MacPages, MacAtoms, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakToggle */
const { useState: useASm, useEffect: useAEm, useMemo: useAMm } = React;
const { ICONS, NAV_COLOR, NAV_ICON } = MacAtoms;

// Sidebar nav structure · macOS Settings groups items into sections.
const NAV_GROUPS = [
  {
    title: null,
    items: [
      { id: "home", label: "Home" },
    ],
  },
  {
    title: null,
    items: [
      { id: "voice", label: "Voice input" },
      { id: "output", label: "Output" },
      { id: "rules", label: "App rules" },
    ],
  },
  {
    title: null,
    items: [
      { id: "pill", label: "Pill overlay" },
      { id: "shortcut", label: "Shortcut" },
    ],
  },
  {
    title: null,
    items: [
      { id: "privacy", label: "Privacy & data" },
      { id: "about", label: "About" },
    ],
  },
];

const TITLE_MAP = {
  home:    "Home",
  voice:   "Voice input",
  output:  "Output",
  rules:   "App rules",
  pill:    "Pill overlay",
  shortcut:"Shortcut",
  privacy: "Privacy & data",
  about:   "About",
  advanced:"Advanced",
};

const SUB_MAP = {
  home:    "Get a quick read on Dimmy and jump to what you need.",
  voice:   "How Dimmy hears and transcribes your voice.",
  output:  "How Dimmy rewrites and delivers your dictation.",
  rules:   "Auto-switch the rewrite style based on the focused app.",
  pill:    "The floating pill · where it lives and how it looks.",
  shortcut:"The hotkey that starts and stops recording.",
  privacy: "What leaves your machine, and what doesn't.",
  about:   "Version, updates, and resources.",
  advanced:"Developer-leaning controls and diagnostics.",
};

function MacSettings({ theme, accent, advanced, sidebarStyle = "auto" }) {
  const [history, setHistory] = useASm(["home"]);
  const [cursor, setCursor] = useASm(0);
  const tab = history[cursor];
  const setTab = (id) => {
    if (id === history[cursor]) return;
    setHistory(h => [...h.slice(0, cursor + 1), id]);
    setCursor(c => c + 1);
  };
  const goBack = () => { if (cursor > 0) setCursor(c => c - 1); };
  const goForward = () => { if (cursor < history.length - 1) setCursor(c => c + 1); };
  const canBack = cursor > 0;
  const canForward = cursor < history.length - 1;

  const [search, setSearch] = useASm("");
  const [savedPulse, setSavedPulse] = useASm(false);

  const [data, setData] = useASm({
    sttMode: "cloud", sttProvider: "groq-whisper", lang: "en",
    micDevice: "macbook", micVolume: 70,
    vad: true, preprocessing: true, chunkStream: false,
    llmStyle: "comprehensible", llmDotColor: "#5ac8fa",
    llmMode: "cloud", llmProvider: "groq-llama", sameKey: true,
    autoPaste: true, clipboardHistory: false,
    previewState: "idle", position: "bottom-right",
    borderStyle: "rainbow", waveformStyle: "bars", alwaysOnTop: true,
    hotkeyMode: "toggle", cancelEsc: true, doubleTapLock: false,
    usageData: true, crashReports: true, feedbackKind: "general",
    autoUpdate: true, channel: "stable",
    llmLog: false, audioDebug: false, ggmlDebug: false,
    rulesEnabled: true, suggestRules: true, fallbackStyle: "comprehensible",
    rules: [
      { id: "r1", app: "Slack", exe: "Slack.app", icon: "apps", color: "#611F69", style: "genz", tone: "casual", enabled: true },
      { id: "r2", app: "Mail", exe: "Mail.app", icon: "send", color: "#0a84ff", style: "professional", tone: "formal", enabled: true },
      { id: "r3", app: "Visual Studio Code", exe: "Code.app", icon: "edit", color: "#0098FF", style: "prompt", tone: "technical", enabled: true },
      { id: "r4", app: "Notion", exe: "Notion.app", icon: "doc", color: "#222222", style: "summarize", tone: "neutral", enabled: true },
      { id: "r5", app: "WhatsApp", exe: "WhatsApp.app", icon: "speaker", color: "#25D366", style: "emoji", tone: "casual", enabled: true },
      { id: "r6", app: "Discord · gaming servers", exe: "Discord.app", icon: "speaker", color: "#5865F2", style: "genz", tone: "casual", enabled: false },
      { id: "r7", app: "Slack · #leadership", exe: "Slack.app", icon: "apps", color: "#611F69", style: "professional", tone: "formal", enabled: true },
      { id: "r8", app: "Terminal", exe: "Terminal.app", icon: "wrench", color: "#1c1c1e", style: "off", tone: "auto", enabled: true },
    ],
    advanced,
  });
  useAEm(() => setData(d => ({ ...d, advanced })), [advanced]);

  const set = (patch) => {
    setData(d => ({ ...d, ...patch }));
    setSavedPulse(true);
    setTimeout(() => setSavedPulse(false), 1500);
  };

  // Filter nav by search
  const filteredGroups = useAMm(() => {
    const q = search.trim().toLowerCase();
    const groups = NAV_GROUPS.map(g => ({
      ...g,
      items: g.items.filter(it => !q || it.label.toLowerCase().includes(q)),
    })).filter(g => g.items.length > 0);
    if (advanced) {
      groups.push({ title: null, items: [{ id: "advanced", label: "Advanced" }].filter(it => !q || it.label.toLowerCase().includes(q)) });
    }
    return groups.filter(g => g.items.length > 0);
  }, [search, advanced]);

  const { MacHome, MacVoice, MacOutput, MacPillPage, MacRulesPage, MacShortcut, MacPrivacy, MacAbout, MacAdvanced } = MacPages;
  const PAGE_MAP = {
    home: MacHome, voice: MacVoice, output: MacOutput, pill: MacPillPage,
    rules: MacRulesPage, shortcut: MacShortcut, privacy: MacPrivacy,
    about: MacAbout, advanced: MacAdvanced,
  };
  const Page = PAGE_MAP[tab];

  const styleOverride = useAMm(() => accent ? { "--accent": accent, "--accent-fill": accent } : {}, [accent]);

  return (
    <div className={`macwin ${theme}`} style={styleOverride}>
      {/* ── Sidebar ─────────────────────────────────────────── */}
      <div className="mac-sidebar">
        <div className="mac-titlebar">
          <span className="mac-traffic">
            <span className="light red"/>
            <span className="light yellow"/>
            <span className="light green"/>
          </span>
        </div>

        <div className="mac-sidebar-search">
          {ICONS.search}
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search"/>
        </div>

        <div className="mac-nav">
          {filteredGroups.map((g, i) => (
            <div key={i} style={{ paddingTop: i === 0 ? 4 : 12 }}>
              {g.items.map(it => (
                <div key={it.id} className={`mac-nav-item ${tab === it.id ? "active" : ""}`} onClick={() => setTab(it.id)}>
                  <span className="mac-nav-icon-wrap" style={{ background: NAV_COLOR[it.id] }}>
                    {ICONS[NAV_ICON[it.id]]}
                  </span>
                  {it.label}
                </div>
              ))}
            </div>
          ))}
        </div>

        <div className="mac-sidebar-footer">
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
            <span style={{ width: 10, height: 10, borderRadius: 99, background: "#30d158", boxShadow: "0 0 4px rgba(48,209,88,0.6)" }}/>
            v0.6.21
          </span>
          <label style={{ display: "inline-flex", alignItems: "center", gap: 6, cursor: "pointer" }}>
            <span style={{ fontSize: 11 }}>Advanced</span>
            <Switch on={data.advanced} onChange={(v) => set({ advanced: v })}/>
          </label>
        </div>
      </div>

      {/* ── Content right pane ─────────────────────────────── */}
      <div className="mac-content">
        <div className="mac-content-toolbar">
          <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
            <span className="mac-chev-group">
              <button className="mac-chev" onClick={goBack} aria-label="Back" disabled={!canBack}>
                <svg width="13" height="13" viewBox="0 0 13 13" fill="none"><path d="M8 2.5L4 6.5L8 10.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </button>
              <span className="mac-chev-divider"/>
              <button className="mac-chev" onClick={goForward} aria-label="Forward" disabled={!canForward}>
                <svg width="13" height="13" viewBox="0 0 13 13" fill="none"><path d="M5 2.5L9 6.5L5 10.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </button>
            </span>
            <span className="mac-content-title">{TITLE_MAP[tab]}</span>
          </span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
            {savedPulse && (
              <span className="mac-saved">
                <span className="check">✓</span>
                Saved
              </span>
            )}
            <span className="mac-status">
              <span className="dot"/>
              {data.sttProvider.replace(/-/g, " ")}
            </span>
          </span>
        </div>
        <div className="mac-content-scroll">
          <div className="mac-pagehead">
            <h1>{TITLE_MAP[tab]}</h1>
            <p>{SUB_MAP[tab]}</p>
          </div>
          <Page data={data} set={set} setTab={setTab}/>
        </div>
      </div>
    </div>
  );
}

function Switch({ on, onChange }) {
  return <button className={`mac-switch ${on ? "on" : ""}`} onClick={() => onChange(!on)} aria-pressed={on}/>;
}

function MacApp() {
  const [t, setTweak] = useTweaks({
    layout: "side-by-side",
    accent: "#0a84ff",
    advanced: true,
  });

  const renderInstance = (theme) => (
    <MacSettings theme={theme} accent={t.accent} advanced={t.advanced}/>
  );

  return (
    <div style={{
      width: "100vw", minHeight: "100vh", padding: "32px 16px 80px",
      display: "flex", flexDirection: "column", alignItems: "center", gap: 32,
      background: "radial-gradient(ellipse at top, #1a1a1f 0%, #0a0a0a 70%)",
    }}>
      <div style={{ textAlign: "center", color: "rgba(255,255,255,0.85)", maxWidth: 900 }}>
        <div style={{ fontFamily: '-apple-system, "SF Pro Display", system-ui, sans-serif', fontSize: 32, fontWeight: 600, letterSpacing: "-0.01em" }}>Dimmy Settings · macOS Tahoe redesign</div>
        <p style={{ fontSize: 14, color: "rgba(255,255,255,0.55)", marginTop: 8, lineHeight: 1.5 }}>
          Native macOS Settings.app aesthetic · Liquid Glass sidebar with squircle nav icons, grouped rounded tiles with internal dividers, NSSwitch / NSPopUpButton / NSSegmentedControl form controls. App Rules with drag-and-drop reorder and per-row delete.
        </p>
      </div>

      {t.layout === "side-by-side" ? (
        <div style={{ display: "flex", gap: 32, flexWrap: "wrap", justifyContent: "center" }}>
          <div>
            <Caption text="Dark"/>
            {renderInstance("dark")}
          </div>
          <div>
            <Caption text="Light"/>
            {renderInstance("light")}
          </div>
        </div>
      ) : (
        <div>
          <Caption text={t.layout === "dark" ? "Dark" : "Light"}/>
          {renderInstance(t.layout)}
        </div>
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection title="Layout">
          <TweakRadio label="View" value={t.layout} onChange={(v) => setTweak("layout", v)} options={[
            { value: "side-by-side", label: "Both" },
            { value: "dark", label: "Dark" },
            { value: "light", label: "Light" },
          ]}/>
        </TweakSection>
        <TweakSection title="Accent color">
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {[
              ["#0a84ff", "Blue"],
              ["#bf5af2", "Purple"],
              ["#ff375f", "Pink"],
              ["#30d158", "Green"],
              ["#ff9f0a", "Orange"],
              ["#ffd60a", "Yellow"],
            ].map(([c, l]) => (
              <button key={c} onClick={() => setTweak("accent", c)} style={{
                width: 28, height: 28, borderRadius: 99, padding: 0,
                background: c, border: t.accent === c ? "2px solid #fff" : "1px solid rgba(255,255,255,0.2)",
                cursor: "pointer", boxShadow: t.accent === c ? `0 0 12px ${c}66` : "none",
              }} title={l}/>
            ))}
          </div>
        </TweakSection>
        <TweakSection title="Mode">
          <TweakToggle label="Advanced" value={t.advanced} onChange={(v) => setTweak("advanced", v)}/>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

function Caption({ text }) {
  return (
    <div className="mac-caption">
      <span className="swatch"/>
      <span className="label">{text}</span>
    </div>
  );
}

// Embedded mode · single instance fills the iframe, theme driven by parent
function EmbedMacApp() {
  const params = new URLSearchParams(window.location.search);
  const initial = params.get("theme")
    || (window.matchMedia && window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark");
  const [theme, setTheme] = useASm(initial);
  useAEm(() => {
    document.body.classList.add("embed-mode");
    const onMsg = (e) => {
      if (!e.data || e.data.type !== "theme") return;
      if (e.data.theme === "dark" || e.data.theme === "light") setTheme(e.data.theme);
    };
    window.addEventListener("message", onMsg);
    if (window.parent !== window) {
      window.parent.postMessage({ type: "settings-ready", source: "mac" }, "*");
    }
    return () => {
      document.body.classList.remove("embed-mode");
      window.removeEventListener("message", onMsg);
    };
  }, []);
  useAEm(() => { document.documentElement.dataset.theme = theme; }, [theme]);
  return (
    <div style={{
      width: "100vw", height: "100vh", overflow: "hidden",
      background: theme === "light" ? "#F1EFEA" : "#0a0a0a",
      transition: "background 400ms",
    }}>
      <MacSettings theme={theme} accent="#0a84ff" advanced={true}/>
    </div>
  );
}

const macRoot = ReactDOM.createRoot(document.getElementById("root"));
const isEmbed = new URLSearchParams(window.location.search).get("embed") === "1";
macRoot.render(isEmbed ? <EmbedMacApp/> : <MacApp/>);
