/* global React, ReactDOM, Pill, SettingsPages, SettingsAtoms, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakToggle, TweakSelect */
const { useState: useAS, useEffect: useAE, useMemo: useAM } = React;

const NAV = [
  { id: "home",     label: "Home",          icon: "\uE80F" }, // Home
  { id: "voice",    label: "Voice input",   icon: "\uE720" }, // Microphone
  { id: "output",   label: "Output",        icon: "\uE945" }, // Lightbulb
  { id: "pill",     label: "Pill overlay",  icon: "\uE7B5" }, // Pinned
  { id: "rules",    label: "App rules",     icon: "\uECAA" }, // AllApps
  { id: "shortcut", label: "Shortcut",      icon: "\uE765" }, // KeyboardClassic
  { id: "privacy",  label: "Privacy & data",icon: "\uE72E" }, // Lock
  { id: "about",    label: "About",         icon: "\uE946" }, // Info
  { id: "advanced", label: "Advanced",      icon: "\uE957" }, // Developer / wrench
];

function SettingsApp({ theme, navStyle, accent, advanced }) {
  const [tab, setTab] = useAS("home");
  const [search, setSearch] = useAS("");
  const [savedPulse, setSavedPulse] = useAS(false);

  const [data, setData] = useAS({
    sttMode: "cloud",
    sttProvider: "groq-whisper",
    lang: "en",
    micDevice: "realtek",
    micVolume: 70,
    vad: true,
    preprocessing: true,
    chunkStream: false,
    llmStyle: "comprehensible",
    llmDotColor: "#38BDF8",
    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.exe", icon: "\uE8BD", color: "#5865F2", style: "genz", tone: "casual", enabled: true },
      { id: "r2", app: "Microsoft Outlook", exe: "OUTLOOK.EXE", icon: "\uE715", color: "#0078D4", style: "professional", tone: "formal", enabled: true },
      { id: "r3", app: "Visual Studio Code", exe: "Code.exe", icon: "\uE943", color: "#0098FF", style: "prompt", tone: "technical", enabled: true },
      { id: "r4", app: "Notion", exe: "Notion.exe", icon: "\uE70B", color: "#222222", style: "summarize", tone: "neutral", enabled: true },
      { id: "r5", app: "WhatsApp", exe: "WhatsApp.exe", icon: "\uE8F2", color: "#25D366", style: "emoji", tone: "casual", enabled: true },
      { id: "r6", app: "Discord · gaming servers", exe: "Discord.exe", icon: "\uE99A", color: "#5865F2", style: "genz", tone: "casual", enabled: false },
      { id: "r7", app: "Slack · #leadership", exe: "slack.exe", icon: "\uE8BD", color: "#611F69", style: "professional", tone: "formal", enabled: true },
      { id: "r8", app: "Windows Terminal", exe: "WindowsTerminal.exe", icon: "\uE756", color: "#4CC2FF", style: "off", tone: "auto", enabled: true },
    ],
    advanced,
  });
  useAE(() => setData(d => ({ ...d, advanced })), [advanced]);

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

  const filteredNav = useAM(() => {
    const items = advanced ? NAV : NAV.filter(n => n.id !== "advanced");
    if (!search.trim()) return items;
    const q = search.toLowerCase();
    return items.filter(n => n.label.toLowerCase().includes(q));
  }, [search, advanced]);

  const { HomePage, VoicePage, OutputPage, PillPage, ShortcutPage, PrivacyPage, AboutPage, AdvancedPage, RulesPage } = SettingsPages;
  const Page = ({ home: HomePage, voice: VoicePage, output: OutputPage, pill: PillPage, rules: RulesPage,
                  shortcut: ShortcutPage, privacy: PrivacyPage, about: AboutPage, advanced: AdvancedPage })[tab];
  const titleMap = {
    home: ["Home", "Get a quick read on Dimmy and jump to what you need."],
    voice: ["Voice input", "How Dimmy hears and transcribes your voice."],
    output: ["Output", "How Dimmy rewrites and delivers your dictation."],
    pill: ["Pill overlay", "The floating pill · where it lives and how it looks."],
    rules: ["App rules", "Auto-switch the rewrite style based on the focused app."],
    shortcut: ["Shortcut", "The hotkey that starts and stops recording."],
    privacy: ["Privacy & data", "What leaves your machine, and what doesn't."],
    about: ["About", "Version, updates, and resources."],
    advanced: ["Advanced", "Developer-leaning controls and diagnostics."],
  };
  const [pageTitle, pageSub] = titleMap[tab];

  const styleVarOverride = useAM(() => accent ? { "--accent": accent, "--accent-secondary": accent } : {}, [accent]);

  return (
    <div className={`winwin ${theme}`} style={{
      width: 1080, height: 720, ...styleVarOverride,
    }}>
      {/* Title bar */}
      <div className="titlebar">
        <div className="title">
          <img src="assets/icon_1024.png" alt=""/>
          <span>Settings</span>
        </div>
        <div className="caption-buttons">
          <button className="caption-btn" aria-label="Minimize">&#xE921;</button>
          <button className="caption-btn" aria-label="Maximize">&#xE922;</button>
          <button className="caption-btn close" aria-label="Close">&#xE8BB;</button>
        </div>
      </div>

      <div className="body">
        {/* Sidebar */}
        <div className="sidebar" style={navStyle === "compact" ? { width: 56 } : {}}>
          <button className="hamburger" aria-label="Menu">&#xE700;</button>
          {navStyle !== "compact" && (
            <div className="search-wrap">
              <div className="search">
                <span className="icon">&#xE721;</span>
                <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search settings"/>
              </div>
            </div>
          )}
          <div className="nav">
            {filteredNav.map(n => (
              <button key={n.id} className={`nav-item ${tab === n.id ? "active" : ""}`} onClick={() => setTab(n.id)}
                      title={navStyle === "compact" ? n.label : undefined}
                      style={navStyle === "compact" ? { padding: "0 14px", justifyContent: "center" } : {}}>
                <span className="nav-icon">{n.icon}</span>
                {navStyle !== "compact" && n.label}
              </button>
            ))}
          </div>
          {navStyle !== "compact" && (
            <div className="sidebar-footer">
              <div className="toggle-row" style={{ fontSize: 12, color: "var(--text-secondary)", justifyContent: "space-between" }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                  <span style={{ fontFamily: "Segoe Fluent Icons", fontSize: 14 }}>&#xE957;</span>
                  Advanced mode
                </span>
                <button className={`toggle ${data.advanced ? "on" : ""}`} onClick={() => set({ advanced: !data.advanced })}/>
              </div>
            </div>
          )}
        </div>

        {/* Content */}
        <div className="content">
          <div className="page">
            <div className="page-header">
              <div>
                <h1 className="page-title">{pageTitle}</h1>
                <p className="page-subtitle">{pageSub}</p>
              </div>
              <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                {savedPulse && (
                  <span style={{
                    display: "inline-flex", alignItems: "center", gap: 6, padding: "4px 10px",
                    background: "rgba(108,203,95,0.16)", border: "1px solid rgba(108,203,95,0.35)",
                    borderRadius: 99, fontSize: 12, color: "#6ccb5f", animation: "dimmy-fade-in 200ms",
                  }}>
                    <span style={{ fontFamily: "Segoe Fluent Icons", fontSize: 12 }}>&#xE73E;</span>
                    Saved
                  </span>
                )}
                <span className="status-chip">
                  <span className="ldot"/>
                  Listening · {data.sttProvider.replace(/-/g, " ")}
                </span>
              </div>
            </div>
            <Page data={data} set={set} setTab={setTab}/>
          </div>
        </div>
      </div>
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks({
    theme: "dark",      // dark | light
    navStyle: "full",   // full | compact
    accent: "#4cc2ff",
    advanced: true,
    layout: "side-by-side", // side-by-side | dark | light
  });

  const renderInstance = (theme) => (
    <SettingsApp theme={theme} navStyle={t.navStyle} 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: "Segoe UI Variable Display, Segoe UI, system-ui", fontSize: 32, fontWeight: 600, letterSpacing: "-0.01em" }}>Dimmy Settings · Windows 11 redesign</div>
        <p style={{ fontSize: 14, color: "rgba(255,255,255,0.55)", marginTop: 8, lineHeight: 1.5 }}>
          Native WinUI 3 / Fluent. Eight-section information architecture, search, live pill preview, auto-save with InfoBar feedback, and an explicit Advanced mode toggle in the sidebar footer. Dark and light themes side-by-side below.
        </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="Navigation">
          <TweakRadio label="Sidebar" value={t.navStyle} onChange={(v) => setTweak("navStyle", v)} options={[
            { value: "full", label: "Full" },
            { value: "compact", label: "Compact" },
          ]}/>
        </TweakSection>
        <TweakSection title="Accent color">
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {[
              ["#4cc2ff", "Default"],
              ["#34D399", "Mint"],
              ["#38BDF8", "Cyan"],
              ["#6366F1", "Indigo"],
              ["#A78BFA", "Violet"],
              ["#F472B6", "Pink"],
            ].map(([c, l]) => (
              <button key={c} onClick={() => setTweak("accent", c)} style={{
                width: 32, height: 32, borderRadius: 6, 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 mode" value={t.advanced} onChange={(v) => setTweak("advanced", v)}/>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

function Caption({ text }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12, color: "rgba(255,255,255,0.55)" }}>
      <span style={{ width: 6, height: 6, borderRadius: 99, background: "rgba(255,255,255,0.5)" }}/>
      <span style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 600 }}>{text}</span>
    </div>
  );
}

// Embedded mode · single instance fills the iframe, theme driven by parent
function EmbedWinApp() {
  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] = useAS(initial);
  useAE(() => {
    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: "win" }, "*");
    }
    return () => {
      document.body.classList.remove("embed-mode");
      window.removeEventListener("message", onMsg);
    };
  }, []);
  useAE(() => { document.documentElement.dataset.theme = theme; }, [theme]);
  return (
    <div style={{
      width: "100vw", height: "100vh", overflow: "hidden",
      background: theme === "light" ? "#F1EFEA" : "#0a0a0a",
      transition: "background 400ms",
    }}>
      <SettingsApp theme={theme} navStyle="full" accent="#4cc2ff" advanced={true}/>
    </div>
  );
}

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