// dashboard-experimental-features-card-cli.js — extracted verbatim from dashboard.js (pure move).

// ── Experimental features card (client-side beta flags) ──
// Uses chrome.storage.local for flags that don't need server persistence.
// Currently powers the V2 IA sidebar toggle.
function renderExperimentalFeaturesCard() {
  // Toggle element — matches the .toggle / .toggle.on pattern used by settingToggle().
  const toggle = el("div", {
    class: "toggle",
    id: "exp-nav-v2-toggle",
    onclick: async function () {
      const newValue = !this.classList.contains("on");
      this.classList.toggle("on", newValue);
      await chrome.storage.local.set({ _navIaV2: newValue });
      // The opt-in/out event is the highest-signal telemetry for the IA rollout.
      logTelemetry("ia_v2", newValue ? "opt_in" : "opt_out");
      // Rebuild the sidebar in-place so the change is visible without a full reload.
      try {
        await buildSidebar();
      } catch {}
      const hintEl = document.getElementById("exp-nav-v2-hint");
      if (hintEl) {
        hintEl.textContent = newValue
          ? "Switched to the new navigation. Reload (Ctrl+R) if anything looks off."
          : "Reverted to classic navigation.";
      }
      toast(`New navigation: ${newValue ? "ON" : "OFF"}`, "ok");
    },
  });

  const row = el("div", { class: "toggle-row" }, [
    el("div", { class: "toggle-label" }, [
      el("div", {}, "New navigation (beta)"),
      el(
        "div",
        { class: "muted small", style: "font-weight: 400; margin-top: 2px;" },
        "Reorganizes the sidebar around jobs (Discover / Campaigns / Autopilot / CRM). Telegram features move to a collapsed Power Tools section.",
      ),
    ]),
    toggle,
  ]);

  // V3 toggle — compact navigation. When ON, supersedes V2.
  const toggleV3 = el("div", {
    class: "toggle",
    id: "exp-nav-v3-toggle",
    onclick: async function () {
      const newValue = !this.classList.contains("on");
      this.classList.toggle("on", newValue);
      await chrome.storage.local.set({ _navIaV3: newValue });
      logTelemetry("ia_v3", newValue ? "opt_in" : "opt_out");
      try {
        await buildSidebar();
      } catch {}
      const hintEl = document.getElementById("exp-nav-v3-hint");
      if (hintEl) {
        hintEl.textContent = newValue
          ? "Switched to compact navigation. 5 primary sections + a context pane that follows what you're doing. ⌘K is your friend for everything else."
          : "Reverted to previous navigation.";
      }
      toast(`Compact nav: ${newValue ? "ON" : "OFF"}`, "ok");
    },
  });
  const rowV3 = el("div", { class: "toggle-row" }, [
    el("div", { class: "toggle-label" }, [
      el("div", {}, "Compact navigation (v3, recommended)"),
      el(
        "div",
        { class: "muted small", style: "font-weight: 400; margin-top: 2px;" },
        "5 primary sections + a context pane that follows the active section. Per-platform tools collapse off the sidebar — reach them via ⌘K. Supersedes the v2 beta when ON.",
      ),
    ]),
    toggleV3,
  ]);

  const card = el("div", { class: "card" }, [
    el("div", { class: "card-title" }, "Experimental"),
    el(
      "div",
      { class: "muted small", style: "margin-bottom: 8px;" },
      "Try in-progress features. Toggle off any time.",
    ),
    rowV3,
    el(
      "div",
      {
        class: "muted small",
        id: "exp-nav-v3-hint",
        style: "margin-top: 8px; margin-bottom: 16px;",
      },
      "",
    ),
    row,
    el("div", { class: "muted small", id: "exp-nav-v2-hint", style: "margin-top: 8px;" }, ""),
  ]);

  // Hydrate initial toggle state on the next tick (after element is in DOM).
  // V3 is now default-on (flipped 2026-05). Toggle reflects ON unless the
  // user has explicitly stored `false`.
  setTimeout(async () => {
    const stored = await chrome.storage.local.get(["_navIaV2", "_navIaV3"]);
    const t2 = document.getElementById("exp-nav-v2-toggle");
    const t3 = document.getElementById("exp-nav-v3-toggle");
    if (t2 && stored._navIaV2 === true) t2.classList.add("on");
    if (t3 && stored._navIaV3 !== false) t3.classList.add("on");
  }, 0);

  return card;
}

function renderSettingsNotifications(data) {
  // Existing server-side notification toggles. Phase 2 will fold the
  // user_preferences (notify_matches, notify_opportunities) into here.
  return el("div", {}, [
    el("div", { class: "card" }, [
      el("div", { class: "card-title" }, "Notifications"),
      settingToggle(
        "Outreach alerts",
        "notif_outreach",
        data.notificationPrefs?.outreachAlerts !== false,
      ),
      settingToggle(
        "Signal alerts",
        "notif_signals",
        data.notificationPrefs?.signalAlerts !== false,
      ),
      settingToggle(
        "Session expiry alerts",
        "notif_sessions",
        data.notificationPrefs?.sessionAlerts !== false,
      ),
      settingToggle(
        "Daily briefing",
        "bd_briefing_enabled",
        data.notificationPrefs?.dailyBriefing !== false,
      ),
      settingToggle(
        "Reply alerts",
        "reply_alert_enabled",
        data.notificationPrefs?.replyAlerts !== false,
      ),
      settingToggle(
        "Auto-pause on first reply",
        "pause_on_first_reply",
        data.notificationPrefs?.pauseOnReply === true,
      ),
    ]),
  ]);
}

async function renderSettingsAiKeys() {
  const wrap = el("div", { id: "settings-ai-keys" }, [
    el("div", { class: "card" }, [
      el("div", { class: "card-title" }, "AI Provider Keys"),
      el(
        "div",
        { class: "muted", style: "font-size: 12px; margin-bottom: 12px;" },
        "Plug in your own API key to unlock AI features (auto-reply, active member, smart campaigns) without paying for Premium. Keys are stored encrypted, never shared.",
      ),
      el("div", { id: "ai-keys-list" }, [el("div", { class: "loading" }, "Loading\u2026")]),
    ]),
  ]);

  // Async load
  api("settings-api-keys-list")
    .then((data) => {
      const list = wrap.querySelector("#ai-keys-list");
      if (!list) return;
      if (data?.error) {
        list.replaceChildren(el("div", { class: "muted" }, `Error: ${data.error}`));
        return;
      }
      const keys = data.keys || [];
      list.replaceChildren(...keys.map(renderAiKeyRow), renderAiKeyAddForm());
    })
    .catch((err) => {
      const list = wrap.querySelector("#ai-keys-list");
      if (list) list.replaceChildren(el("div", { class: "muted" }, `Error: ${err.message}`));
    });

  return wrap;
}

function renderAiKeyRow(k) {
  const row = el(
    "div",
    {
      class: "channel-row",
      style:
        "padding: 10px 12px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 12px;",
    },
    [
      el("div", { class: "channel-icon" }, k.configured ? "\ud83d\udd11" : "\u2014"),
      el("div", { style: "flex: 1;" }, [
        el("div", { class: "primary-cell" }, k.provider),
        el(
          "div",
          { class: "muted", style: "font-size: 11px; font-family: var(--font-mono);" },
          k.configured ? k.masked : "Not configured",
        ),
      ]),
      k.configured
        ? el(
            "button",
            {
              class: "btn btn-tiny btn-secondary",
              type: "button",
              onclick: async () => {
                const r = await api("settings-api-keys-delete", { provider: k.provider });
                if (r?.error) toast(r.error, "err");
                else {
                  toast("Removed", "ok");
                  renderSettings();
                }
              },
            },
            "Remove",
          )
        : null,
    ],
  );
  return row;
}

function renderAiKeyAddForm() {
  let pickedProvider = "deepseek";
  let entry = "";

  return el(
    "div",
    { style: "padding: 16px 12px 4px; border-top: 1px solid var(--border); margin-top: 8px;" },
    [
      el("div", { class: "wizard-label" }, "Add or update key"),
      el("div", { style: "display: flex; gap: 8px; margin-top: 6px;" }, [
        el(
          "select",
          {
            class: "filter-select",
            style: "max-width: 140px;",
            onchange: (e) => {
              pickedProvider = e.target.value;
            },
          },
          [
            el("option", { value: "deepseek" }, "DeepSeek"),
            el("option", { value: "openai" }, "OpenAI"),
            el("option", { value: "anthropic" }, "Anthropic"),
          ],
        ),
        el("input", {
          class: "wizard-input",
          type: "password",
          placeholder: "sk-\u2026",
          oninput: (e) => {
            entry = e.target.value.trim();
          },
          style: "flex: 1;",
        }),
        el(
          "button",
          {
            class: "btn btn-primary btn-tiny",
            type: "button",
            onclick: async (ev) => {
              if (!entry || entry.length < 10) {
                toast("Please paste the full key", "err");
                return;
              }
              await withProgress(ev.currentTarget, async () => {
                const r = await api("settings-api-keys-save", {
                  body: { provider: pickedProvider, key: entry },
                });
                if (r?.error) toast(r.error, "err");
                else {
                  toast("Saved", "ok");
                  renderSettings();
                }
              });
            },
          },
          "Save",
        ),
      ]),
    ],
  );
}

async function renderSettingsPreferences() {
  const wrap = el("div", { id: "settings-preferences" }, [
    el("div", { class: "card" }, [
      el("div", { class: "card-title" }, "Network preferences"),
      el(
        "div",
        { class: "muted", style: "font-size: 12px; margin-bottom: 12px;" },
        "Tune how the bot picks matches and opportunities for you. These sync to your Telegram /preferences.",
      ),
      el("div", { id: "prefs-form" }, [el("div", { class: "loading" }, "Loading\u2026")]),
    ]),
  ]);

  api("settings-preferences-get")
    .then((p) => {
      const form = wrap.querySelector("#prefs-form");
      if (!form) return;
      if (p?.error) {
        form.replaceChildren(el("div", { class: "muted" }, `Error: ${p.error}`));
        return;
      }
      if (!p.hasProfile) {
        form.replaceChildren(
          el("div", { class: "empty-state-hint", style: "padding: 16px;" }, [
            "You don't have a profile yet. Open Telegram and run ",
            el("code", {}, "/intro"),
            " to register, then come back here.",
          ]),
        );
        return;
      }

      const state = {
        notify_matches: !!p.notify_matches,
        notify_opportunities: !!p.notify_opportunities,
        digest_frequency: p.digest_frequency || "weekly",
        primary_goal: p.primary_goal || "",
      };

      function save(patch) {
        Object.assign(state, patch);
        api("settings-preferences-save", { body: patch }).then((r) => {
          if (r?.error) toast(r.error, "err");
        });
      }

      form.replaceChildren(
        // Toggle: notify matches
        el("div", { class: "toggle-row" }, [
          el("span", { class: "toggle-label" }, "Match notifications"),
          el("div", {
            class: `toggle ${state.notify_matches ? "on" : ""}`,
            onclick: (ev) => {
              const next = !state.notify_matches;
              ev.currentTarget.classList.toggle("on", next);
              save({ notify_matches: next });
            },
          }),
        ]),
        // Toggle: notify opportunities
        el("div", { class: "toggle-row" }, [
          el("span", { class: "toggle-label" }, "Opportunity notifications"),
          el("div", {
            class: `toggle ${state.notify_opportunities ? "on" : ""}`,
            onclick: (ev) => {
              const next = !state.notify_opportunities;
              ev.currentTarget.classList.toggle("on", next);
              save({ notify_opportunities: next });
            },
          }),
        ]),
        // Digest frequency
        el("div", { style: "padding: 8px 0;" }, [
          el("div", { class: "wizard-label" }, "Digest frequency"),
          el(
            "select",
            {
              class: "filter-select",
              style: "margin-top: 4px;",
              onchange: (e) => save({ digest_frequency: e.target.value }),
              value: state.digest_frequency,
            },
            [
              el(
                "option",
                {
                  value: "daily",
                  selected: state.digest_frequency === "daily" ? "selected" : null,
                },
                "Daily",
              ),
              el(
                "option",
                {
                  value: "weekly",
                  selected: state.digest_frequency === "weekly" ? "selected" : null,
                },
                "Weekly",
              ),
              el(
                "option",
                {
                  value: "never",
                  selected: state.digest_frequency === "never" ? "selected" : null,
                },
                "Never",
              ),
            ],
          ),
        ]),
        // Primary goal
        el("div", { style: "padding: 8px 0;" }, [
          el("div", { class: "wizard-label" }, "Primary goal"),
          el(
            "select",
            {
              class: "filter-select",
              style: "margin-top: 4px;",
              onchange: (e) => save({ primary_goal: e.target.value }),
            },
            [
              el(
                "option",
                { value: "", selected: !state.primary_goal ? "selected" : null },
                "Not set",
              ),
              el(
                "option",
                {
                  value: "find_clients",
                  selected: state.primary_goal === "find_clients" ? "selected" : null,
                },
                "Find clients",
              ),
              el(
                "option",
                {
                  value: "raise_capital",
                  selected: state.primary_goal === "raise_capital" ? "selected" : null,
                },
                "Raise capital",
              ),
              el(
                "option",
                {
                  value: "hire_talent",
                  selected: state.primary_goal === "hire_talent" ? "selected" : null,
                },
                "Hire talent",
              ),
              el(
                "option",
                {
                  value: "find_partner",
                  selected: state.primary_goal === "find_partner" ? "selected" : null,
                },
                "Find a partner",
              ),
            ],
          ),
        ]),
      );
    })
    .catch((err) => {
      const form = wrap.querySelector("#prefs-form");
      if (form) form.replaceChildren(el("div", { class: "muted" }, `Error: ${err.message}`));
    });

  return wrap;
}
