<script lang="ts">
  import Switch from "../../components/Switch.svelte"
  import Button from "../../components/Button.svelte"
  import Slider from "../../components/Slider.svelte"
  import Select from "@/interface/components/Select.svelte"
  import HotkeyInput from "@/interface/components/HotkeyInput.svelte"

  import browser from "webextension-polyfill"

  import type { SettingsList } from "@/interface/types/SettingsProps"
  import { settingsState } from "@/seqta/utils/listeners/SettingsState.ts"
  import PickerSwatch from "@/interface/components/PickerSwatch.svelte"
  import SidebarAppearance from "@/interface/components/SidebarAppearance.svelte"
  import ConnectMobileApp from "@/interface/components/ConnectMobileApp.svelte"
  import CloudSettingsSync from "@/interface/components/CloudSettingsSync.svelte"
  import CloudHeader from "@/interface/components/store/CloudHeader.svelte"
  import { cloudAuth } from "@/seqta/utils/CloudAuth"
  import { showPrivacyNotification } from "@/seqta/utils/Openers/OpenPrivacyNotification"
  import { showThemeOfTheMonthPopupNow } from "@/seqta/utils/Openers/OpenThemeOfTheMonthPopup"
  import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup"
  import { getSnapshotForUpload } from "@/seqta/utils/cloudSettingsSync"
  import { getStoredOverride, setApiBase } from "@/seqta/utils/DevApiBase"
  import { onMount } from "svelte"

  let devApiBaseInput = $state<string>(getStoredOverride() ?? "")
  let devApiBaseActive = $state<string | null>(getStoredOverride())

  function applyDevApiBase() {
    const trimmed = devApiBaseInput.trim()
    if (trimmed === "") {
      setApiBase(null)
      devApiBaseActive = null
      return
    }
    if (!/^https?:\/\//.test(trimmed)) {
      alert("Please enter a full URL starting with http:// or https://")
      return
    }
    setApiBase(trimmed)
    devApiBaseActive = trimmed.replace(/\/$/, "")
  }

  function clearDevApiBase() {
    devApiBaseInput = ""
    setApiBase(null)
    devApiBaseActive = null
  }

  import { getAllPluginSettings } from "@/plugins"
  import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage"

  const isEngage = isSeqtaEngageExperience();
  import type { BooleanSetting, StringSetting, NumberSetting, SelectSetting, ButtonSetting, HotkeySetting, ComponentSetting } from "@/plugins/core/types"

  // Union type representing all possible settings
  type SettingType =
    (Omit<BooleanSetting, 'type'> & { type: 'boolean', id: string }) |
    (Omit<StringSetting, 'type'> & { type: 'string', id: string }) |
    (Omit<NumberSetting, 'type'> & { type: 'number', id: string }) |
    (Omit<SelectSetting<string>, 'type'> & {
      type: 'select',
      id: string,
      options: string[]
    }) |
    (Omit<ButtonSetting, 'type'> & {
      type: 'button',
      id: string
    }) |
    (Omit<HotkeySetting, 'type'> & {
      type: 'hotkey',
      id: string
    }) |
    (Omit<ComponentSetting, 'type'> & {
      type: 'component',
      id: string,
      component: any
    });

  interface Plugin {
    pluginId: string;
    name: string;
    description: string;
    beta?: boolean;
    settings: Record<string, SettingType>;
  }

  const pluginSettings = getAllPluginSettings().filter(
    (plugin) => !(isSeqtaEngageExperience() && plugin.pluginId === "global-search"),
  ) as Plugin[];
  const pluginSettingsValues = $state<Record<string, Record<string, any>>>({});

  let cloudState = $state(cloudAuth.state);
  $effect(() => {
    const unsub = cloudAuth.subscribe((s) => { cloudState = s; });
    return unsub;
  });
  
  async function loadPluginSettings() {
    for (const plugin of pluginSettings) {
      if (Object.keys(plugin.settings).length === 0) continue;
      
      const storageKey = `plugin.${plugin.pluginId}.settings`;
      const stored = await browser.storage.local.get(storageKey);
      
      pluginSettingsValues[plugin.pluginId] = stored[storageKey] || {};
      
      for (const [key, setting] of Object.entries(plugin.settings)) {
        if (
          pluginSettingsValues[plugin.pluginId][key] === undefined &&
          setting.type !== 'button' &&
          setting.type !== 'component'
        ) {
          pluginSettingsValues[plugin.pluginId][key] = setting.default;
        }
      }
    }
  }
  
  async function updatePluginSetting(pluginId: string, key: string, value: any) {
    const storageKey = `plugin.${pluginId}.settings`;
    
    if (!pluginSettingsValues[pluginId]) {
      pluginSettingsValues[pluginId] = {};
    }
    pluginSettingsValues[pluginId][key] = value;
    
    const stored = await browser.storage.local.get(storageKey);
    const currentSettings = (stored[storageKey] || {}) as Record<string, any>;
    
    currentSettings[key] = value;
    
    await browser.storage.local.set({ [storageKey]: currentSettings });
  }

  onMount(() => {
    void loadPluginSettings();
  });

  const { showColourPicker, showFontPicker, showDisclaimer, showCloudPanel, activeSection = "general" } = $props<{
    showColourPicker: () => void;
    showFontPicker: () => void;
    showDisclaimer: (onConfirm: () => void, onCancel: () => void, title?: string, message?: string) => void;
    showCloudPanel: () => void;
    activeSection?: string;
  }>();

  /** Map each plugin into the settings sidebar category that fits its purpose. */
  const pluginSectionById: Record<string, string> = {
    "profile-picture": "account",
    "animated-background": "appearance",
    "background-music": "appearance",
    timetable: "timetable",
    timetableEdit: "timetable",
    "assessments-overview": "assessments",
    "assessments-average": "assessments",
    "grade-analytics": "assessments",
    "global-search": "features",
    "enhanced-navigation": "features",
    messageFolders: "features",
    notificationCollector: "features",
  };

  const showsSection = (section: string) =>
    activeSection === "all" || activeSection === section;

  const pluginBelongsInSection = (pluginId: string) =>
    activeSection === "all" ||
    (pluginSectionById[pluginId] ?? "features") === activeSection;


  async function exportCloudSettingsJsonToFile() {
    const payload = await getSnapshotForUpload();
    const blob = new Blob([JSON.stringify(payload, null, 2)], {
      type: "application/json",
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `betterseqta-plus-settings-export-${new Date().toISOString().replace(/[:.]/g, "-")}.json`;
    a.click();
    URL.revokeObjectURL(url);
  }
</script>

{#snippet Setting({ title, description, Component, props }: SettingsList) }
<div class="flex justify-between items-center px-5 py-5">
  <div class="pr-5">
    <h2 class="text-xl font-bold">{title}</h2>
    <p class="text-base text-zinc-600 dark:text-zinc-300">{description}</p>
  </div>
  <div class="shrink-0">
     <Component {...props} />
  </div>
</div>
{/snippet}

<div class="flex flex-col divide-y divide-zinc-100 dark:divide-zinc-700">
  {#if showsSection("account")}
    {@render Setting({
      title: "Connect Mobile App",
      description: "Link your SEQTA session to DesQTA — the modern desktop and mobile app for SEQTA Learn",
      id: 0,
      Component: ConnectMobileApp,
      props: {}
    })}

    <div class="border-none">
      <div class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40">
        <div class="flex justify-between items-center px-5 py-4">
          <div class="pr-4">
            <h2 class="text-xl font-bold">BetterSEQTA Cloud</h2>
            <p class="text-base text-zinc-600 dark:text-zinc-300">Account & sync</p>
          </div>
          <div>
            <CloudHeader alwaysShowUserName onClick={showCloudPanel} />
          </div>
        </div>
        {#if cloudState.isLoggedIn}
          <div class="px-3 pb-3">
            <CloudSettingsSync showDisclaimer={(onConfirm, onCancel) => showDisclaimer(onConfirm, onCancel, "Restore from cloud?", "This will replace your local settings with the cloud backup. Continue?")} />
          </div>
        {/if}
      </div>
    </div>
  {/if}

  {#if showsSection("general")}
    {#each [
      ...(!isEngage
        ? [
            {
              title: "Edit Sidebar Layout",
              description: "Reorder pages on the sidebar",
              id: 5,
              Component: Button,
              props: {
                onClick: () => browser.runtime.sendMessage({ type: 'currentTab', info: 'EditSidebar' }),
                text: "Edit"
              }
            },
            {
              title: "Icon Only Sidebar",
              description: "Show only icons in the sidebar for a compact layout",
              id: 14,
              Component: Switch,
              props: {
                state: $settingsState.iconOnlySidebar ?? false,
                onChange: (isOn: boolean) => settingsState.iconOnlySidebar = isOn
              }
            },
          ]
        : []),
      {
        title: "Animations",
        description: "Enable animations on certain pages",
        id: 6,
        Component: Switch,
        props: {
          state: $settingsState.animations,
          onChange: (isOn: boolean) => settingsState.animations = isOn
        }
      },
      {
        title: "12 Hour Time",
        description: "Prefer 12 hour time format for SEQTA",
        id: 9,
        Component: Switch,
        props: {
          state: $settingsState.timeFormat === "12",
          onChange: (isOn: boolean) => settingsState.timeFormat = isOn ? "12" : "24"
        }
      },
      {
        title: "Default Page",
        description: "Choose which page loads first when you open SEQTA",
        id: 10,
        Component: Select,
        props: {
          value: $settingsState.defaultPage ?? "home",
          onChange: (value: string) => (settingsState.defaultPage = value),
          options: isEngage
            ? [
                { value: "home", label: "Home" },
                { value: "dashboard", label: "Dashboard" },
                { value: "timetable", label: "Timetable" },
                { value: "messages", label: "Messages" },
                { value: "documents", label: "Documents" },
                { value: "reports", label: "Reports" },
              ]
            : [
                { value: "home", label: "Home" },
                { value: "dashboard", label: "Dashboard" },
                { value: "timetable", label: "Timetable" },
                { value: "welcome", label: "Welcome" },
                { value: "messages", label: "Messages" },
                { value: "documents", label: "Documents" },
                { value: "reports", label: "Reports" },
              ],
        },
      },
      ...(!isEngage
        ? [
            {
              title: "News Feed Source",
              description: "Choose the sources for your news feed",
              id: 11,
              Component: Select,
              props: {
                value: $settingsState.newsSource,
                onChange: (value: string) => settingsState.newsSource = value,
                options: [
                  { value: "australia", label: "Australia" },
                  { value: "usa", label: "USA" },
                  { value: "uk", label: "UK" },
                  { value: "taiwan", label: "Taiwan" },
                  { value: "hong_kong", label: "Hong Kong" },
                  { value: "panama", label: "Panama" },
                  { value: "canada", label: "Canada" },
                  { value: "singapore", label: "Singapore" },
                  { value: "japan", label: "Japan" },
                  { value: "netherlands", label: "Netherlands" },
                ],
              },
            },
          ]
        : []),
    ] as option (option.id)}
      {@render Setting(option)}
    {/each}
  {/if}

  {#if showsSection("appearance")}
    {#each [
      {
        title: "Custom Theme Colour",
        description: "Customise the overall theme colour of SEQTA Learn",
        id: 4,
        Component: PickerSwatch,
        props: {
          onClick: showColourPicker
        }
      },
      {
        title: "Interface Font",
        description: "Choose the typeface used across SEQTA Learn",
        id: 16,
        Component: Button,
        props: {
          onClick: showFontPicker,
          text: "Change"
        }
      },
    ] as option (option.id)}
      {@render Setting(option)}
    {/each}

    {#if !isEngage}
      <div class="border-none">
        <SidebarAppearance />
      </div>
    {/if}

    <div class="border-none">
      <div class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40">
        <div class="flex justify-between items-center px-5 py-4">
          <div class="pr-4">
            <h2 class="text-xl font-bold">Adaptive Theme Colour</h2>
            <p class="text-base text-zinc-600 dark:text-zinc-300">Change the theme colour based on the current class (e.g. when viewing a course or assessments page)</p>
          </div>
          <div>
            <Switch
              state={$settingsState.adaptiveThemeColour ?? false}
              onChange={(isOn: boolean) => settingsState.adaptiveThemeColour = isOn}
            />
          </div>
        </div>
        {#if $settingsState.adaptiveThemeColour}
          <div class="flex justify-between items-center px-5 py-4 pl-7 border-t border-zinc-100 dark:border-zinc-700/50">
            <div class="pr-4">
              <h2 class="text-xl font-bold">Soft Gradient</h2>
              <p class="text-base text-zinc-600 dark:text-zinc-300">Use a soft gradient instead of a solid colour when viewing a class</p>
            </div>
            <div>
              <Switch
                state={$settingsState.adaptiveThemeGradient ?? false}
                onChange={(isOn: boolean) => settingsState.adaptiveThemeGradient = isOn}
              />
            </div>
          </div>
          <div class="flex justify-between items-center px-5 py-4 pl-7 border-t border-zinc-100 dark:border-zinc-700/50">
            <div class="pr-4">
              <h2 class="text-xl font-bold">Smooth colour transition</h2>
              <p class="text-base text-zinc-600 dark:text-zinc-300">Ease between class/subject colours when navigating instead of switching instantly</p>
            </div>
            <div>
              <Switch
                state={$settingsState.adaptiveThemeColourTransition ?? true}
                onChange={(isOn: boolean) => settingsState.adaptiveThemeColourTransition = isOn}
              />
            </div>
          </div>
        {/if}
      </div>
    </div>
  {/if}

  {#if showsSection("general")}
  <div class="border-none">
    <div class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40">
      <div class="flex justify-between items-center px-5 py-4">
        <div class="pr-4">
          <h2 class="text-xl font-bold">Home Page Assessments</h2>
          <p class="text-base text-zinc-600 dark:text-zinc-300">Limit upcoming assessments shown on the home page by subject</p>
        </div>
      </div>
      <div class="flex justify-between items-center px-5 py-4 pl-7 border-t border-zinc-100 dark:border-zinc-700/50">
        <div class="pr-4">
          <h2 class="text-xl font-bold">Include Past Assessments</h2>
          <p class="text-base text-zinc-600 dark:text-zinc-300">Show past-due assessments from the upcoming list, matching the Assessments page</p>
        </div>
        <div>
          <Switch
            state={$settingsState.homeUpcomingIncludePast ?? true}
            onChange={(isOn: boolean) => (settingsState.homeUpcomingIncludePast = isOn)}
          />
        </div>
      </div>
      <div class="flex justify-between items-center px-5 py-4 pl-7 border-t border-zinc-100 dark:border-zinc-700/50">
        <div class="pr-4">
          <h2 class="text-xl font-bold">Maximum Subjects</h2>
          <p class="text-base text-zinc-600 dark:text-zinc-300">Number of subjects to include, ordered by soonest due date</p>
        </div>
        <Select
          value={String($settingsState.homeUpcomingSubjectsMax ?? 5)}
          onChange={(value: string) => (settingsState.homeUpcomingSubjectsMax = Number(value))}
          options={[
            { value: "0", label: "All" },
            { value: "3", label: "3" },
            { value: "5", label: "5" },
            { value: "7", label: "7" },
            { value: "10", label: "10" },
            { value: "15", label: "15" },
          ]}
        />
      </div>
      <div class="flex justify-between items-center px-5 py-4 pl-7 border-t border-zinc-100 dark:border-zinc-700/50">
        <div class="pr-4">
          <h2 class="text-xl font-bold">Maximum Assessments per Subject</h2>
          <p class="text-base text-zinc-600 dark:text-zinc-300">Assessments shown for each included subject</p>
        </div>
        <Select
          value={String($settingsState.homeUpcomingAssessmentsPerSubjectMax ?? 0)}
          onChange={(value: string) => (settingsState.homeUpcomingAssessmentsPerSubjectMax = Number(value))}
          options={[
            { value: "0", label: "All" },
            { value: "1", label: "1" },
            { value: "2", label: "2" },
            { value: "3", label: "3" },
            { value: "5", label: "5" },
            { value: "10", label: "10" },
          ]}
        />
      </div>
    </div>
  </div>
  {/if}

  {#each pluginSettings as plugin (plugin.pluginId)}
  {#if pluginBelongsInSection(plugin.pluginId)}
  <div class="border-none">
    <div class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40 {!(plugin as any).disableToggle && Object.keys(plugin.settings).length === 0 ? 'hidden' : ''}">
      <!-- Always show enable toggle if disableToggle is true -->
        {#if (plugin as any).disableToggle}
          <div class="flex justify-between items-center px-5 py-4">
            <div class="pr-4">
              <h2 class="flex gap-2 items-center text-xl font-bold">
                Enable {plugin.name}
                {#if plugin.beta}
                  <span class="px-2 py-0.5 text-xs font-medium text-orange-800 bg-orange-100 rounded-full border border-orange-300/30 dark:bg-orange-900/30 dark:text-orange-300 dark:border-orange-900/30">
                    Beta
                  </span>
                {/if}
              </h2>
              <p class="text-base text-zinc-600 dark:text-zinc-300">{plugin.description}</p>
            </div>
            <div>
              <Switch
                state={pluginSettingsValues[plugin.pluginId]?.enabled ?? true}
                onChange={async (value) => {
                  if (plugin.pluginId === 'assessments-average' && value === true) {
                    showDisclaimer(
                      async () => {
                        await updatePluginSetting(plugin.pluginId, 'enabled', true);
                      },
                      () => {},
                      "Assessment Averages Disclaimer",
                      "This feature calculates a simple average of your assessment grades. It does not take into account:\n• Assessment weightings\n• Different grading scales\n• Other factors used in official reports\n\nThe displayed average may be inaccurate compared to your actual marks found in reports.\n\nDo you want to enable this feature?"
                    );
                    return;
                  }
                  await updatePluginSetting(plugin.pluginId, 'enabled', value);
                }}
              />
            </div>
          </div>
        {/if}
  
        {#if !((plugin as any).disableToggle) || (pluginSettingsValues[plugin.pluginId]?.enabled ?? true)}
          {#each Object.entries(plugin.settings) as [key, setting] (key)}
            <!-- Skip the 'enabled' setting and hide cloud-only settings when not signed in -->
            {#if key !== 'enabled' && !(key === 'useCloudPfp' && !cloudState.isLoggedIn)}
              <div class="flex justify-between items-center px-5 py-4">
                <div class="pr-4">
                  <h2 class="text-xl font-bold">{setting.title || key}</h2>
                  <p class="text-base text-zinc-600 dark:text-zinc-300">{setting.description || ''}</p>
                </div>
                <div>
                  {#if setting.type === 'boolean'}
                    <Switch
                      state={pluginSettingsValues[plugin.pluginId]?.[key] ?? setting.default}
                      onChange={(value) => updatePluginSetting(plugin.pluginId, key, value)}
                    />
                  {:else if setting.type === 'number'}
                    <div class="w-28 shrink-0">
                      <Slider
                        state={pluginSettingsValues[plugin.pluginId]?.[key] ?? setting.default}
                        onChange={(value) => updatePluginSetting(plugin.pluginId, key, value)}
                        min={setting.min}
                        max={setting.max}
                        step={setting.step}
                      />
                    </div>
                  {:else if setting.type === 'string'}
                    <input
                      type="text"
                      class="px-2 py-1 text-sm rounded-md dark:bg-[#38373D]/50 bg-[#DDDDDD] dark:text-white border-none"
                      value={pluginSettingsValues[plugin.pluginId]?.[key] ?? setting.default}
                      oninput={(e) => updatePluginSetting(plugin.pluginId, key, e.currentTarget.value)}
                    />                
                  {:else if setting.type === 'select'}
                    <Select
                    value={pluginSettingsValues[plugin.pluginId]?.[key] ?? setting.default}
                    onChange={(value) => updatePluginSetting(plugin.pluginId, key, value)}
                    options={(setting.options as string[]).map(opt => ({
                      value: opt,
                      label: opt.charAt(0).toUpperCase() + opt.slice(1)
                      }))}
                    />
                  {:else if setting.type === 'button'}
                    <Button
                      onClick={() => setting.trigger?.()}
                      text={setting.title}
                    />
                  {:else if setting.type === 'hotkey'}
                    <HotkeyInput
                      value={pluginSettingsValues[plugin.pluginId]?.[key] ?? setting.default}
                      onChange={(value) => updatePluginSetting(plugin.pluginId, key, value)}
                    />
                  {:else if setting.type === 'component'}
                    {#if setting.component}
                      {@const Component = setting.component}
                      <Component />
                    {/if}
                  {/if}
                </div>
              </div>
            {/if}
          {/each}
        {/if}
      </div>
      {#if plugin.pluginId === 'global-search'}
        {@render Setting({
          title: "Theme of the Month",
          description: "Show the monthly featured theme popup when a new entry is available",
          id: 15,
          Component: Switch,
          props: {
            state: !($settingsState.themeOfTheMonthDisabled ?? false),
            onChange: (isOn: boolean) => settingsState.themeOfTheMonthDisabled = !isOn
          }
        })}
      {/if}
  </div>
  {/if}
  {/each}

  {#if showsSection("advanced")}
  {@render Setting({
    title: "BetterSEQTA+",
    description: "Enables BetterSEQTA+ features",
    id: 12,
    Component: Switch,
    props: {
      state: $settingsState.onoff,
      onChange: (isOn: boolean) => settingsState.onoff = isOn
    }
  })}

  {#if $settingsState.devMode}
    <div class="flex-col p-1 my-1 bg-gradient-to-br from-white rounded-xl border shadow-sm to-zinc-100 border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40">
      <div class="flex justify-between items-center px-5 py-4">
        <div class="pr-4">
          <h2 class="text-xl font-bold">Developer Mode</h2>
          <p class="text-base text-zinc-600 dark:text-zinc-300">Enables developer mode, allowing you to test new features and changes.</p>
        </div>
        <div>
          <Switch state={$settingsState.devMode} onChange={(isOn: boolean) => settingsState.devMode = isOn} />
        </div>
      </div>
      <div class="flex justify-between items-center px-5 py-4">
        <div class="pr-4">
          <h2 class="text-xl font-bold">Verbose logging</h2>
          <p class="text-base text-zinc-600 dark:text-zinc-300">Show diagnostic console output (indexer, theme manager, timetable colour patch, etc.)</p>
        </div>
        <div>
          <Switch
            state={$settingsState.verboseLogging ?? false}
            onChange={(isOn: boolean) => settingsState.verboseLogging = isOn}
          />
        </div>
      </div>
      <div class="flex justify-between items-center px-5 py-4">
        <div class="pr-4">
          <h2 class="text-xl font-bold">Delay loading screen</h2>
          <p class="text-base text-zinc-600 dark:text-zinc-300">Keep the loading overlay visible for 5 extra seconds so you can preview canvas variants.</p>
        </div>
        <div>
          <Switch
            state={$settingsState.devDelayLoadingScreen ?? false}
            onChange={(isOn: boolean) => settingsState.devDelayLoadingScreen = isOn}
          />
        </div>
      </div>
      <div class="flex justify-between items-center px-5 py-4">
        <div class="pr-4">
          <h2 class="text-xl font-bold">Sensitive Hider</h2>
          <p class="text-base text-zinc-600 dark:text-zinc-300">Replace sensitive content with mock data</p>
        </div>
        <div>
          <Switch
            state={$settingsState.hideSensitiveContent ?? false}
            onChange={(isOn: boolean) => settingsState.hideSensitiveContent = isOn}
          />
        </div>
      </div>
      <div class="flex justify-between items-center px-5 py-4">
        <div class="pr-4">
          <h2 class="text-xl font-bold">Mock Notices</h2>
          <p class="text-base text-zinc-600 dark:text-zinc-300">Use fake notice data on homepage instead of real data</p>
        </div>
        <div>
          <Switch 
            state={$settingsState.mockNotices ?? false} 
            onChange={(isOn: boolean) => settingsState.mockNotices = isOn} 
          />
        </div>
      </div>
      <div class="flex justify-between items-center px-5 py-4">
        <div class="pr-4">
          <h2 class="text-xl font-bold">Show Privacy Notification</h2>
          <p class="text-base text-zinc-600 dark:text-zinc-300">Show the privacy notification popup on next page load</p>
        </div>
        <div>
          <Button
            onClick={async () => {
              settingsState.privacyStatementShown = false;
              settingsState.privacyStatementLastUpdated = undefined;
              closeExtensionPopup();
              // Small delay to ensure popup is closed before showing notification
              await new Promise(resolve => setTimeout(resolve, 100));
              await showPrivacyNotification();
            }}
            text="Show Now"
          />
        </div>
      </div>
      <div class="flex justify-between items-center px-5 py-4">
        <div class="pr-4">
          <h2 class="text-xl font-bold">Show Theme of the Month</h2>
          <p class="text-base text-zinc-600 dark:text-zinc-300">Fetch and show the current month's popup now (ignores dismissed state)</p>
        </div>
        <div>
          <Button
            onClick={async () => {
              closeExtensionPopup();
              await new Promise((resolve) => setTimeout(resolve, 100));
              await showThemeOfTheMonthPopupNow();
            }}
            text="Show Now"
          />
        </div>
      </div>
      <div class="flex justify-between items-center px-5 py-4">
        <div class="pr-4">
          <h2 class="text-xl font-bold">Export cloud settings JSON</h2>
          <p class="text-base text-zinc-600 dark:text-zinc-300">Download the same payload as cloud sync (OAuth tokens stripped). For debugging and server testing.</p>
        </div>
        <div>
          <Button onClick={exportCloudSettingsJsonToFile} text="Export to file" />
        </div>
      </div>
      <div class="flex flex-col gap-2 px-4 py-3">
        <div class="flex justify-between items-start gap-3">
          <div class="pr-4">
            <h2 class="text-xl font-bold">API Base URL (session only)</h2>
            <p class="text-base text-zinc-600 dark:text-zinc-300">Override the content API host for this browser session. Cleared on restart. Affects themes, theme of the month, and other server-driven content.</p>
            {#if devApiBaseActive}
              <p class="text-xs mt-1 text-amber-600 dark:text-amber-400">
                Override active: <span class="font-mono">{devApiBaseActive}</span>
              </p>
            {/if}
          </div>
        </div>
        <div class="flex gap-2 items-center">
          <input
            type="text"
            placeholder="https://betterseqta.org"
            bind:value={devApiBaseInput}
            class="flex-1 px-2 py-1 text-xs rounded border bg-white dark:bg-zinc-800 border-zinc-300 dark:border-zinc-700 text-zinc-900 dark:text-zinc-100"
          />
          <Button onClick={applyDevApiBase} text="Apply" />
          {#if devApiBaseActive}
            <Button onClick={clearDevApiBase} text="Clear" />
          {/if}
        </div>
      </div>
      <div class="flex flex-col gap-2 px-4 py-3">
        <div>
          <h2 class="text-xl font-bold">GitHub latest version override</h2>
          <p class="text-base text-zinc-600 dark:text-zinc-300">Pretend a newer GitHub release exists to test the update badge. Only applies when dev mode is on.</p>
        </div>
        <input
          type="text"
          placeholder="e.g. 9.9.9"
          value={$settingsState.devGhReleaseVersionOverride ?? ""}
          oninput={(e) => {
            settingsState.devGhReleaseVersionOverride = e.currentTarget.value;
          }}
          class="px-2 py-1 text-xs rounded border bg-white dark:bg-zinc-800 border-zinc-300 dark:border-zinc-700 text-zinc-900 dark:text-zinc-100"
        />
      </div>
    </div>
  {/if}
  {/if}
</div>
