/* global React, ReactDOM, MacPill, MacAtoms */
const { Switch, PopUp, Segmented, Slider, Radio, Tile, Row, GroupLabel, GroupFooter, ICONS } = MacAtoms;
const { useState: useMGS } = React;

const STYLE_MAP = {
  off: ["Off", "#8e8e93"], correct: ["Correct", "#30d158"],
  summarize: ["Summarize", "#ffd60a"], elaborate: ["Elaborate", "#34c759"],
  comprehensible: ["Comprehensible", "#5ac8fa"], professional: ["Professional", "#ff375f"],
  prompt: ["Prompt", "#bf5af2"], genz: ["Gen Z", "#ff2d92"],
  boomer: ["Boomer", "#ff9f0a"], emoji: ["Emoji", "#ffcc00"],
  acronyms: ["Acronyms", "#64d2ff"], imbruttito: ["Imbruttito", "#ff453a"],
  custom: ["Custom", "#ff9500"],
};
const STYLE_OPTS = Object.entries(STYLE_MAP).map(([v, [l]]) => ({ value: v, label: l }));

// ────────────────────────────────────────────────────────────
// Home
// ────────────────────────────────────────────────────────────
function MacHome({ data, setTab }) {
  return (
    <>
      <div className="mac-hero">
        <div className="text">
          <h2>Dimmy is ready to listen</h2>
          <p>Hold <span className="mac-key">⌃</span><span style={{ color: "var(--text-tertiary)", margin: "0 4px" }}>+</span><span className="mac-key">⌥</span> anywhere to dictate, then release. Your voice never leaves the cloud provider you chose.</p>
          <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
            <button className="mac-btn primary"><span style={{ display: "inline-flex" }}>{ICONS.mic}</span>Test microphone</button>
            <button className="mac-btn" onClick={() => setTab("shortcut")}>Change shortcut…</button>
          </div>
        </div>
        <div className="pill-stage">
          <MacPill state="idle" border="rainbow" waveform="bars" llmDot={data.llmDotColor}/>
        </div>
      </div>

      <div className="mac-stats">
        <div className="mac-stat"><span className="v">103</span><span className="l">Words dictated</span></div>
        <div className="mac-stat"><span className="v">0:56</span><span className="l">Speaking time</span></div>
        <div className="mac-stat"><span className="v">~1m</span><span className="l">Time saved</span></div>
      </div>

      <GroupLabel>Current setup</GroupLabel>
      <Tile>
        <Row icon="mic" iconBg="#ff375f" label="Speech-to-text" desc="Groq · whisper-large-v3-turbo (free) · Cloud">
          <button className="mac-btn" onClick={() => setTab("voice")}>Configure</button>
        </Row>
        <Row icon="bulb" iconBg="#ffcc00" label="Output style" desc="Comprehensible · Groq llama-3.3-70b">
          <span style={{ width: 8, height: 8, borderRadius: 99, background: "#5ac8fa", boxShadow: "0 0 6px #5ac8fa88", marginRight: 6 }}/>
          <button className="mac-btn" onClick={() => setTab("output")}>Configure</button>
        </Row>
        <Row icon="keyboard" iconBg="#0a84ff" label="Shortcut" desc="Toggle recording">
          <span className="mac-key">⌃</span>
          <span style={{ color: "var(--text-tertiary)" }}>+</span>
          <span className="mac-key">⌥</span>
        </Row>
      </Tile>

      <GroupLabel>Recent dictations</GroupLabel>
      <Tile>
        <div className="mac-recent">
          {[
            { t: "10:42", text: "Schedule a follow-up with the design team for Thursday afternoon.", style: "Professional", color: "#ff375f" },
            { t: "10:38", text: "Stavo per dire qualcosa di brillante, ma Dimmy ha capito questo.", style: "Imbruttito", color: "#ff453a" },
            { t: "09:14", text: "Refactor the audio buffer to clamp NaN values before they propagate.", style: "Correct", color: "#30d158" },
          ].map((r, i) => (
            <div key={i} className="row">
              <span className="time">{r.t}</span>
              <span className="text">{r.text}</span>
              <span className="style"><span className="swatch" style={{ background: r.color }}/>{r.style}</span>
            </div>
          ))}
        </div>
      </Tile>
    </>
  );
}

// ────────────────────────────────────────────────────────────
// Voice input
// ────────────────────────────────────────────────────────────
function MacVoice({ data, set }) {
  return (
    <>
      <GroupLabel>Speech recognition</GroupLabel>
      <Tile>
        <Row label="Mode" desc="Where transcription runs">
          <Segmented value={data.sttMode} onChange={(v) => set({ sttMode: v })}
            options={[{ value: "local", label: "On device" }, { value: "cloud", label: "Cloud" }]}/>
        </Row>
        <Row label="Provider" desc={data.sttMode === "cloud" ? "~250 ms typical latency" : "Whisper-tiny · 78 MB"}>
          <PopUp value={data.sttProvider} onChange={(v) => set({ sttProvider: v })} width={260}
            options={[
              { value: "groq-whisper", label: "Groq · whisper-large-v3-turbo (free)" },
              { value: "openai-whisper", label: "OpenAI · whisper-1" },
              { value: "deepgram-nova", label: "Deepgram · nova-3" },
              { value: "gemini", label: "Gemini · flash" },
            ]}/>
        </Row>
        <Row label="API key" desc="Stored in your Keychain · AES-256-GCM">
          <span style={{ color: "#30d158", fontSize: 12, fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 4 }}>
            {ICONS.check} Saved
          </span>
          <button className="mac-btn">Replace…</button>
        </Row>
        <Row label="Language">
          <PopUp value={data.lang} onChange={(v) => set({ lang: v })} width={160}
            options={[
              { value: "auto", label: "Auto detect" },
              { value: "en", label: "English" },
              { value: "it", label: "Italian" },
              { value: "es", label: "Spanish" },
              { value: "fr", label: "French" },
              { value: "de", label: "German" },
            ]}/>
        </Row>
      </Tile>
      <GroupFooter>Helps the model with rare words and names. Auto-detect identifies the language from your first sentence.</GroupFooter>

      <GroupLabel>Microphone</GroupLabel>
      <Tile>
        <Row label="Input device">
          <PopUp value={data.micDevice} onChange={(v) => set({ micDevice: v })} width={240}
            options={[
              { value: "macbook", label: "MacBook Pro Microphone" },
              { value: "airpods", label: "AirPods Pro 3" },
              { value: "yeti", label: "Yeti X (USB)" },
            ]}/>
        </Row>
        <Row label="Input level" desc="Speak now · bars should reach the middle">
          <div className="mac-meter"><div className="fill" style={{ width: "62%" }}/></div>
        </Row>
        <Row label="Microphone volume">
          <Slider value={data.micVolume} onChange={(v) => set({ micVolume: Math.round(v) })}/>
          <span style={{ marginLeft: 6, color: "var(--text-secondary)", fontSize: 12, minWidth: 28, fontVariantNumeric: "tabular-nums" }}>{Math.round(data.micVolume)}</span>
        </Row>
      </Tile>

      <GroupLabel>Audio processing</GroupLabel>
      <Tile>
        <Row label="Voice activity detection" desc="Stop recording after 3 seconds of silence">
          <Switch on={data.vad} onChange={(v) => set({ vad: v })}/>
        </Row>
        <Row label="Preprocessing" desc="Reduce noise and normalize volume before transcribing">
          <Switch on={data.preprocessing} onChange={(v) => set({ preprocessing: v })}/>
        </Row>
        {data.advanced && (
          <Row label="Chunk streaming" desc="Stream audio in 250 ms chunks for partial results">
            <Switch on={data.chunkStream} onChange={(v) => set({ chunkStream: v })}/>
          </Row>
        )}
      </Tile>

      <GroupLabel>Vocabulary</GroupLabel>
      <Tile>
        <Row label="Custom vocabulary" desc="Words and phrases the model should expect">
          <button className="mac-btn">{ICONS.edit}Edit list…</button>
        </Row>
      </Tile>
    </>
  );
}

// ────────────────────────────────────────────────────────────
// Output
// ────────────────────────────────────────────────────────────
function MacOutput({ data, set }) {
  return (
    <>
      <GroupLabel>Rewrite style</GroupLabel>
      <Tile>
        <div className="mac-row" style={{ flexDirection: "column", alignItems: "stretch", gap: 12 }}>
          <div className="meta">
            <p className="label">Style</p>
            <p className="desc">After transcribing, Dimmy rewrites your text before pasting.</p>
          </div>
          <div className="mac-chips">
            {Object.entries(STYLE_MAP).map(([v, [l, c]]) => (
              <button key={v} className={`mac-chip ${data.llmStyle === v ? "selected" : ""}`} onClick={() => set({ llmStyle: v, llmDotColor: c })}>
                <span className="swatch" style={{ background: c }}/>{l}
              </button>
            ))}
          </div>
        </div>
        <Row label="Mode">
          <Segmented value={data.llmMode} onChange={(v) => set({ llmMode: v })}
            options={[{ value: "local", label: "On device" }, { value: "cloud", label: "Cloud" }]}/>
        </Row>
        <Row label="Provider">
          <PopUp value={data.llmProvider} onChange={(v) => set({ llmProvider: v })} width={240}
            options={[
              { value: "groq-llama", label: "Groq · llama-3.3-70b (free)" },
              { value: "anthropic", label: "Anthropic · Claude Haiku 4.5" },
              { value: "openai", label: "OpenAI · gpt-4o-mini" },
              { value: "ollama", label: "Local (Ollama)" },
            ]}/>
        </Row>
        <Row label="Use same key as STT" desc="Reuse the speech-to-text key for the LLM provider">
          <Switch on={data.sameKey} onChange={(v) => set({ sameKey: v })}/>
        </Row>
      </Tile>

      <GroupLabel>Pasteboard</GroupLabel>
      <Tile>
        <Row label="Auto-paste into focused app" desc="Paste your transcription into whatever app has focus">
          <Switch on={data.autoPaste} onChange={(v) => set({ autoPaste: v })}/>
        </Row>
        <Row label="Keep in clipboard history" desc="Save your last 20 dictations locally">
          <Switch on={data.clipboardHistory} onChange={(v) => set({ clipboardHistory: v })}/>
        </Row>
      </Tile>
    </>
  );
}

// ────────────────────────────────────────────────────────────
// Pill overlay
// ────────────────────────────────────────────────────────────
function MacPillPage({ data, set }) {
  return (
    <>
      <GroupLabel>Live preview</GroupLabel>
      <div style={{ background: "var(--grouped-bg)", border: "0.5px solid var(--grouped-stroke)", borderRadius: 10, padding: "28px 16px", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 8, position: "relative", boxShadow: "var(--tile-shadow)" }}>
        <MacPill state={data.previewState} border={data.borderStyle} waveform={data.waveformStyle} llmDot={data.llmDotColor} timer={data.previewState === "recording" ? "0:04" : null} scale={1.4}/>
        <span style={{ position: "absolute", bottom: 8, right: 12, fontSize: 11, color: "var(--text-tertiary)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 500 }}>
          Preview · {data.previewState}
        </span>
      </div>
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 8 }}>
        {["idle", "recording", "transcribing", "processing", "done", "error"].map(s => (
          <button key={s} className={`mac-chip ${data.previewState === s ? "selected" : ""}`} onClick={() => set({ previewState: s })}>{s}</button>
        ))}
      </div>

      <GroupLabel>Position</GroupLabel>
      <Tile>
        <Row label="Default position" desc="You can always drag the pill to reposition it">
          <div className="mac-pospicker">
            {["top-left", "top-center", "top-right", "middle-left", "middle-center", "middle-right", "bottom-left", "bottom-center", "bottom-right"].map(id => (
              <button key={id} className={data.position === id ? "selected" : ""} onClick={() => set({ position: id })}/>
            ))}
          </div>
        </Row>
        <Row label="Reset position" desc="Snap the pill back to your default location">
          <button className="mac-btn">{ICONS.reset}Reset</button>
        </Row>
      </Tile>

      <GroupLabel>Appearance</GroupLabel>
      <Tile>
        <Row label="Border style" desc="Color and motion of the pill border while recording">
          <PopUp value={data.borderStyle} onChange={(v) => set({ borderStyle: v })} width={180} options={[
            { value: "rainbow", label: "Rainbow (rotating)" },
            { value: "blue", label: "Blue (pulsing)" },
            { value: "green", label: "Green (pulsing)" },
            { value: "purple", label: "Purple (pulsing)" },
            { value: "orange", label: "Orange (pulsing)" },
            { value: "none", label: "None" },
          ]}/>
        </Row>
        <Row label="Waveform style">
          <PopUp value={data.waveformStyle} onChange={(v) => set({ waveformStyle: v })} width={150} options={[
            { value: "bars", label: "Bars (centered)" },
            { value: "dots", label: "Dots" },
            { value: "line", label: "Line" },
          ]}/>
        </Row>
        <Row label="Always on top" desc="Float above other windows and full-screen apps">
          <Switch on={data.alwaysOnTop} onChange={(v) => set({ alwaysOnTop: v })}/>
        </Row>
      </Tile>
    </>
  );
}

// ────────────────────────────────────────────────────────────
// App rules · drag-and-drop reorder + delete
// ────────────────────────────────────────────────────────────
function MacRulesPage({ data, set }) {
  const toneOpts = [
    { value: "auto", label: "Auto (match app)" },
    { value: "casual", label: "Casual" },
    { value: "neutral", label: "Neutral" },
    { value: "formal", label: "Formal" },
    { value: "technical", label: "Technical" },
  ];
  const rules = data.rules || [];
  const update = (id, patch) => set({ rules: rules.map(r => r.id === id ? { ...r, ...patch } : r) });
  const remove = (id) => set({ rules: rules.filter(r => r.id !== id) });
  const add = () => {
    const id = `r${Date.now()}`;
    set({ rules: [...rules, { id, app: "New rule", exe: "", icon: "apps", color: "#8e8e93", style: "correct", tone: "auto", enabled: true }] });
  };

  const [dragId, setDragId] = useMGS(null);
  const [overId, setOverId] = useMGS(null);
  const [dropPos, setDropPos] = useMGS("before");
  const onDragStart = (e, id) => { setDragId(id); e.dataTransfer.effectAllowed = "move"; try { e.dataTransfer.setData("text/plain", id); } catch (_) {} };
  const onDragOver = (e, id) => {
    if (!dragId || dragId === id) return;
    e.preventDefault(); e.dataTransfer.dropEffect = "move";
    const r = e.currentTarget.getBoundingClientRect();
    setOverId(id); setDropPos((e.clientY - r.top) < r.height / 2 ? "before" : "after");
  };
  const onDragLeaveRow = (e, id) => { if (overId === id && !e.currentTarget.contains(e.relatedTarget)) setOverId(null); };
  const onDrop = (e, id) => {
    e.preventDefault();
    if (!dragId || dragId === id) { setDragId(null); setOverId(null); return; }
    const from = rules.findIndex(r => r.id === dragId);
    const next = [...rules];
    const [moved] = next.splice(from, 1);
    let target = next.findIndex(r => r.id === id);
    if (dropPos === "after") target += 1;
    next.splice(target, 0, moved);
    set({ rules: next });
    setDragId(null); setOverId(null);
  };
  const onDragEnd = () => { setDragId(null); setOverId(null); };

  return (
    <>
      <div className="mac-note" style={{ marginBottom: 8 }}>
        <span className="icon">{ICONS.info}</span>
        <div className="body">
          <strong>Match the rewrite to the app you're in</strong>
          Dimmy detects the focused app and applies its rule before pasting. Slack gets Gen Z, Mail gets Professional, your terminal gets nothing · your call. Rules are evaluated top-down; the first match wins.
        </div>
      </div>

      <GroupLabel>Auto-switching</GroupLabel>
      <Tile>
        <Row icon="apps" iconBg="#34c759" label="Enable app-aware rewriting" desc="When off, Dimmy always uses the default style.">
          <Switch on={data.rulesEnabled} onChange={(v) => set({ rulesEnabled: v })}/>
        </Row>
        <Row label="If no rule matches" desc="Fallback when the focused app isn't in the list">
          <PopUp value={data.fallbackStyle || "comprehensible"} onChange={(v) => set({ fallbackStyle: v })} width={180} options={STYLE_OPTS}/>
        </Row>
        <Row label="Suggest rules from usage" desc="Suggest rules based on apps you dictate into often. No data leaves your device.">
          <Switch on={data.suggestRules} onChange={(v) => set({ suggestRules: v })}/>
        </Row>
      </Tile>

      <GroupLabel>Rules · {rules.length}</GroupLabel>
      <Tile>
        <div className="mac-rules-head">
          <span></span><span></span><span>App</span><span>Style</span><span>Tone</span><span>On</span><span></span>
        </div>
        {rules.map(r => {
          const dragging = dragId === r.id;
          const over = overId === r.id && dragId && dragId !== r.id;
          const cls = `mac-rules-row ${dragging ? "dragging" : ""} ${over ? (dropPos === "before" ? "drop-before" : "drop-after") : ""}`;
          return (
            <div key={r.id} className={cls}
                 onDragOver={(e) => onDragOver(e, r.id)}
                 onDragLeave={(e) => onDragLeaveRow(e, r.id)}
                 onDrop={(e) => onDrop(e, r.id)}
                 style={{ opacity: r.enabled ? (dragging ? 0.4 : 1) : 0.5 }}>
              <span className="gripper" draggable
                    onDragStart={(e) => onDragStart(e, r.id)}
                    onDragEnd={onDragEnd}
                    title="Drag to reorder">{ICONS.gripper}</span>
              <span className="mac-row-icon" style={{ background: r.color, width: 22, height: 22 }}>{ICONS[r.icon] || ICONS.apps}</span>
              <div className="app">
                <span className="name">{r.app}</span>
                {r.exe && <span className="exe">{r.exe}</span>}
              </div>
              <div style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                <span style={{ width: 6, height: 6, borderRadius: 99, background: STYLE_MAP[r.style]?.[1] || "#8e8e93", flexShrink: 0 }}/>
                <PopUp value={r.style} onChange={(v) => update(r.id, { style: v })} width={130} options={STYLE_OPTS}/>
              </div>
              <PopUp value={r.tone} onChange={(v) => update(r.id, { tone: v })} width={120} options={toneOpts}/>
              <Switch on={r.enabled} onChange={(v) => update(r.id, { enabled: v })}/>
              <button className="mac-btn icon-only destructive" onClick={() => remove(r.id)} title="Delete rule" style={{ borderColor: "transparent", background: "transparent", boxShadow: "none" }}>
                {ICONS.trash}
              </button>
            </div>
          );
        })}
        {rules.length === 0 && (
          <div style={{ padding: 36, textAlign: "center", color: "var(--text-secondary)", fontSize: 13 }}>
            No rules yet. Add your first one · Dimmy will switch styles automatically when those apps are in focus.
          </div>
        )}
      </Tile>

      <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
        <button className="mac-btn primary" onClick={add}>{ICONS.plus}Add rule</button>
        <button className="mac-btn">{ICONS.search}Detect installed apps…</button>
      </div>

      <GroupLabel>Currently focused</GroupLabel>
      <Tile>
        <Row icon="apps" iconBg="#5865F2" label="Slack · #design-team" desc="Will use: Gen Z · Casual">
          <span className="mac-status"><span className="dot"/>Live detection</span>
        </Row>
      </Tile>
    </>
  );
}

// ────────────────────────────────────────────────────────────
// Shortcut
// ────────────────────────────────────────────────────────────
function MacShortcut({ data, set }) {
  return (
    <>
      <GroupLabel>Hotkey</GroupLabel>
      <Tile>
        <Row icon="keyboard" iconBg="#0a84ff" label="Activation hotkey" desc="Click to capture a new key combination">
          <span className="mac-key">⌃</span>
          <span style={{ color: "var(--text-tertiary)" }}>+</span>
          <span className="mac-key">⌥</span>
          <button className="mac-btn" style={{ marginLeft: 8 }}>Change…</button>
        </Row>
        <Row label="Behavior">
          <Segmented value={data.hotkeyMode} onChange={(v) => set({ hotkeyMode: v })}
            options={[{ value: "ptt", label: "Push-to-talk" }, { value: "toggle", label: "Toggle" }]}/>
        </Row>
      </Tile>

      <GroupLabel>Behavior</GroupLabel>
      <Tile>
        <Row label="Cancel with Escape" desc="Press Esc while recording to discard">
          <Switch on={data.cancelEsc} onChange={(v) => set({ cancelEsc: v })}/>
        </Row>
        {data.advanced && (
          <Row label="Double-tap to lock" desc="Double-tap the hotkey to record hands-free until tapped again">
            <Switch on={data.doubleTapLock} onChange={(v) => set({ doubleTapLock: v })}/>
          </Row>
        )}
      </Tile>
    </>
  );
}

// ────────────────────────────────────────────────────────────
// Privacy & data
// ────────────────────────────────────────────────────────────
function MacPrivacy({ data, set }) {
  return (
    <>
      <div className="mac-note" style={{ marginBottom: 8 }}>
        <span className="icon">{ICONS.shield}</span>
        <div className="body">
          <strong>Your transcriptions stay yours</strong>
          Dimmy never sends your transcriptions, audio, API keys, or microphone names. Anonymous usage data and crash reports help us spot bugs and decide what to build next.
        </div>
      </div>

      <GroupLabel>Telemetry</GroupLabel>
      <Tile>
        <Row label="Send anonymous usage data" desc='Things like "app started", "transcription completed in 2.3s". No content, no identifiers.'>
          <Switch on={data.usageData} onChange={(v) => set({ usageData: v })}/>
        </Row>
        <Row label="Send crash reports" desc="Stack trace only · no environment, no usernames in paths.">
          <Switch on={data.crashReports} onChange={(v) => set({ crashReports: v })}/>
        </Row>
      </Tile>

      <GroupLabel>Anonymous identifier</GroupLabel>
      <Tile>
        <Row label="Local ID" desc="48e033dd… · random, generated locally on first launch.">
          <button className="mac-btn">{ICONS.reset}Reset</button>
        </Row>
      </Tile>

      <GroupLabel>Feedback</GroupLabel>
      <Tile>
        <div className="mac-row" style={{ flexDirection: "column", alignItems: "stretch", gap: 10 }}>
          <PopUp value={data.feedbackKind} onChange={(v) => set({ feedbackKind: v })} width={180}
            options={[
              { value: "general", label: "General" },
              { value: "bug", label: "Bug report" },
              { value: "idea", label: "Idea or feature request" },
            ]}/>
          <textarea className="mac-textarea" placeholder="What's on your mind? Bugs, ideas, anything." defaultValue=""/>
          <input className="mac-text" placeholder="Your email (optional, only if you want a reply)"/>
          <div><button className="mac-btn primary">{ICONS.send}Send</button></div>
        </div>
      </Tile>

      <GroupLabel>More</GroupLabel>
      <Tile>
        <Row label="Privacy policy" desc="What we collect and why">
          <a href="#" className="mac-link">Open ›</a>
        </Row>
        <Row label="What we collect" desc="A specific, line-by-line breakdown">
          <a href="#" className="mac-link">Open ›</a>
        </Row>
      </Tile>
    </>
  );
}

// ────────────────────────────────────────────────────────────
// About
// ────────────────────────────────────────────────────────────
function MacAbout({ data, set }) {
  return (
    <>
      <div className="mac-hero">
        <div className="text">
          <h2>Dimmy 0.6.21</h2>
          <p>Voice dictation that stays out of your way. Made with irony · Released April 14, 2026.</p>
          <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
            <button className="mac-btn primary">Check for updates…</button>
            <button className="mac-btn">{ICONS.doc}View release notes</button>
          </div>
        </div>
        <div className="pill-stage" style={{ background: "transparent" }}>
          <img src="assets/icon_1024.png" alt="" style={{ width: 88, height: 88, filter: "drop-shadow(0 8px 24px rgba(10,132,255,0.35))" }}/>
        </div>
      </div>

      <GroupLabel>Updates</GroupLabel>
      <Tile>
        <Row label="Automatic updates" desc="Get new versions as they ship">
          <Switch on={data.autoUpdate} onChange={(v) => set({ autoUpdate: v })}/>
        </Row>
        <Row label="Update channel" desc="Stable releases or early previews">
          <PopUp value={data.channel} onChange={(v) => set({ channel: v })} width={140}
            options={[
              { value: "stable", label: "Stable" },
              { value: "beta", label: "Beta" },
              { value: "nightly", label: "Nightly" },
            ]}/>
        </Row>
      </Tile>

      <GroupLabel>Resources</GroupLabel>
      <Tile>
        <Row icon="globe" iconBg="#0a84ff" label="Documentation" desc="Guides, shortcuts, troubleshooting">
          <a href="#" className="mac-link">dimmy.app/docs ›</a>
        </Row>
        <Row icon="github" iconBg="#1c1c1e" label="GitHub repository" desc="Source, issues, releases">
          <a href="#" className="mac-link">github.com/KonradDallaOrg/dimmy ›</a>
        </Row>
        <Row icon="doc" iconBg="#8e8e93" label="License" desc="MIT · open source, free to fork">
          <a href="#" className="mac-link">View license ›</a>
        </Row>
      </Tile>
    </>
  );
}

// ────────────────────────────────────────────────────────────
// Advanced
// ────────────────────────────────────────────────────────────
function MacAdvanced({ data, set }) {
  return (
    <>
      <div className="mac-note" style={{ marginBottom: 8 }}>
        <span className="icon" style={{ background: "#ff9f0a" }}>{ICONS.warn}</span>
        <div className="body">
          <strong>Advanced settings</strong>
          These options can affect performance and stability. Change them only if you know what you're doing.
        </div>
      </div>

      <GroupLabel>Performance</GroupLabel>
      <Tile>
        <Row label="Metal acceleration" desc="No prior crashes detected.">
          <span style={{ color: "#30d158", fontSize: 12, fontWeight: 500 }}>● Active</span>
        </Row>
      </Tile>

      <GroupLabel>Diagnostics</GroupLabel>
      <Tile>
        <Row label="LLM log enabled" desc="Write all prompts and responses to disk for debugging">
          <Switch on={data.llmLog} onChange={(v) => set({ llmLog: v })}/>
        </Row>
        <Row label="Audio debug" desc="Save raw audio of each recording locally">
          <Switch on={data.audioDebug} onChange={(v) => set({ audioDebug: v })}/>
        </Row>
        <Row label="ggml debug logging" desc="Verbose model load · useful for diagnosing local model issues">
          <Switch on={data.ggmlDebug} onChange={(v) => set({ ggmlDebug: v })}/>
        </Row>
      </Tile>

      <GroupLabel>Reset</GroupLabel>
      <Tile>
        <Row label="Open log folder">
          <button className="mac-btn">{ICONS.folder}Reveal in Finder</button>
        </Row>
        <Row label="Reset all settings" desc="Restore Dimmy to factory defaults">
          <button className="mac-btn destructive">Reset…</button>
        </Row>
      </Tile>
    </>
  );
}

window.MacPages = { MacHome, MacVoice, MacOutput, MacPillPage, MacRulesPage, MacShortcut, MacPrivacy, MacAbout, MacAdvanced };
