import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { AdvancedTab } from "./tabs/Advanced";
import { ChipsTab } from "./tabs/Chips";
import { GeneralTab } from "./tabs/General";
import { GettingStartedTab } from "./tabs/GettingStarted";
import { TooltipsTab } from "./tabs/Tooltips";
import { TypographyTab } from "./tabs/Typography";
import { useSearchIndex } from "./hooks/useSearchIndex";
import { coerceInt } from "./constants";
import { baseTabs } from "./baseTabs";
import { BASE_LAYOUT_LABELS, BASE_STYLE_LABELS } from "./previewUtils";
import { Preview, SearchContext, SearchResultsView } from "./components";
import type { SearchableFieldData } from "./components";
import type { RequiresToggle } from "./settingsSchema";
import type { Settings, TabId, ToastState } from "./types";

export type { Settings } from "./types";

const BASE_TAB_IDS = new Set<string>([
  "general",
  "chips",
  "typography",
  "tooltips",
  "advanced",
]);

type AdminSectionId = "getting-started" | TabId;
type NavIconProps = { className?: string };

export interface AppProps {
  data?: Record<string, unknown>;
}

function BookIcon({ className = "b3-wvs-w-4 b3-wvs-h-4" }: NavIconProps) {
  return (
    <svg
      className={className}
      fill="none"
      viewBox="0 0 24 24"
      strokeWidth={1.5}
      stroke="currentColor"
    >
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M12 6.042A8.967 8.967 0 0 0 6 3.75c-1.052 0-2.062.18-3 .512v14.25A8.987 8.987 0 0 1 6 18c2.305 0 4.408.867 6 2.292m0-14.25a8.966 8.966 0 0 1 6-2.292c1.052 0 2.062.18 3 .512v14.25A8.987 8.987 0 0 0 18 18a8.967 8.967 0 0 0-6 2.292m0-14.25v14.25"
      />
    </svg>
  );
}

function GearIcon({ className = "b3-wvs-w-4 b3-wvs-h-4" }: NavIconProps) {
  return (
    <svg
      className={className}
      fill="none"
      viewBox="0 0 24 24"
      strokeWidth={1.5}
      stroke="currentColor"
    >
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.431.992a7.723 7.723 0 0 1 0 .255c-.007.378.138.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z"
      />
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"
      />
    </svg>
  );
}

function SwatchIcon({ className = "b3-wvs-w-4 b3-wvs-h-4" }: NavIconProps) {
  return (
    <svg
      className={className}
      fill="none"
      viewBox="0 0 24 24"
      aria-hidden="true"
    >
      <rect
        x="3"
        y="3"
        width="7.5"
        height="7.5"
        rx="1.75"
        fill="currentColor"
      />
      <rect
        x="13.5"
        y="3"
        width="7.5"
        height="7.5"
        rx="1.75"
        fill="currentColor"
        opacity="0.9"
      />
      <rect
        x="3"
        y="13.5"
        width="7.5"
        height="7.5"
        rx="1.75"
        fill="currentColor"
        opacity="0.8"
      />
      <rect
        x="13.5"
        y="13.5"
        width="7.5"
        height="7.5"
        rx="1.75"
        fill="currentColor"
      />
    </svg>
  );
}

function TypeIcon({ className = "b3-wvs-w-4 b3-wvs-h-4" }: NavIconProps) {
  return (
    <svg
      className={className}
      fill="none"
      viewBox="0 0 24 24"
      strokeWidth={1.5}
      stroke="currentColor"
    >
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M4.5 6h15m-7.5 0v12m-4.5 0h9"
      />
    </svg>
  );
}

function TooltipIcon({ className = "b3-wvs-w-4 b3-wvs-h-4" }: NavIconProps) {
  return (
    <svg
      className={className}
      fill="none"
      viewBox="0 0 24 24"
      strokeWidth={1.5}
      stroke="currentColor"
    >
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M8.25 7.5h7.5m-11.25 4.5h15M7.5 16.5h9"
      />
    </svg>
  );
}

function WrenchIcon({ className = "b3-wvs-w-4 b3-wvs-h-4" }: NavIconProps) {
  return (
    <svg
      className={className}
      fill="none"
      viewBox="0 0 24 24"
      strokeWidth={1.5}
      stroke="currentColor"
    >
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M11.42 15.17 17.25 21A2.652 2.652 0 0 0 21 17.25l-5.877-5.877m-1.144-1.143v-.001l-.001-.001m-1.143 1.144-.002.001-.001.002m1.146-1.146 2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 1 1-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 0 0 4.486-6.336l-3.276 3.277a3.004 3.004 0 0 1-2.25-2.25l3.276-3.276a4.5 4.5 0 0 0-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085m-1.745 1.437L5.909 7.5H4.5L2.25 3.75l1.5-1.5L7.5 4.5v1.409l4.26 4.26m-1.745 1.437 1.745-1.437m6.615 8.206L15.75 15.75M4.867 19.125h.008v.008h-.008v-.008Z"
      />
    </svg>
  );
}

const NAV_ICONS: Record<AdminSectionId, React.ComponentType<NavIconProps>> = {
  "getting-started": BookIcon,
  general: GearIcon,
  chips: SwatchIcon,
  typography: TypeIcon,
  tooltips: TooltipIcon,
  advanced: WrenchIcon,
};

function evaluateToggleState(
  settings: Settings,
  requiresToggle?: RequiresToggle,
): boolean {
  if (!requiresToggle) {
    return true;
  }

  const settingValue = settings[requiresToggle.settingKey as keyof Settings];
  const expectedValue =
    requiresToggle.enabledValue === undefined
      ? true
      : requiresToggle.enabledValue;

  switch (requiresToggle.operator ?? "equals") {
    case "greaterThan":
      return Number(settingValue) > Number(expectedValue);
    case "notEquals":
      return settingValue !== expectedValue;
    case "equals":
    default:
      return settingValue === expectedValue;
  }
}

function App({ data: providedData }: AppProps) {
  const data = providedData ?? (window as any).b3WvsData ?? {};
  const restUrl = data.rest_url || "";
  const nonce = data.nonce || "";
  const adminColor = data.admin_color || "#4f46e5";
  const adminUrls = data.admin_urls ?? {};
  const usageStats = data.usage_stats ?? {
    terms_total: 0,
    attribute_taxonomies_configured: 0,
    products_with_overrides: 0,
    by_type: { color: 0, button: 0 },
  };

  const [settings, setSettings] = useState<Settings>(
    () => (data.settings ?? {}) as Settings,
  );
  const [activeSection, setActiveSection] = useState<AdminSectionId>(() => {
    if (typeof window === "undefined") {
      return "getting-started";
    }

    const hash = window.location.hash.replace(/^#/, "");
    if (hash === "getting-started") {
      return "getting-started";
    }

    return BASE_TAB_IDS.has(hash) ? (hash as TabId) : "getting-started";
  });
  const [activeGeneralSubTab, setActiveGeneralSubTab] = useState<
    "layout" | "size" | "options"
  >("layout");
  const [toast, setToast] = useState<ToastState>({
    show: false,
    type: "success",
    message: "",
  });
  const [saving, setSaving] = useState(false);
  const [resetting, setResetting] = useState(false);
  const [previewSelectedIndex, setPreviewSelectedIndex] = useState(0);
  const [searchQuery, setSearchQuery] = useState("");
  const [highlightedFieldId, setHighlightedFieldId] = useState<string | null>(
    null,
  );
  const toastTimeoutRef = useRef<number | null>(null);
  const highlightTimeoutRef = useRef<number | null>(null);

  // ── Nav slider animation state ──
  const navRef = useRef<HTMLElement>(null);
  const navBtnRefs = useRef<Record<string, HTMLButtonElement | null>>({});
  const [navSliderStyle, setNavSliderStyle] = useState<React.CSSProperties>({
    height: 0,
    width: 0,
    transform: "translate(0,0)",
    opacity: 0,
  });

  const updateNavSlider = useCallback(() => {
    const activeEl = navBtnRefs.current[activeSection];
    const container = navRef.current;
    if (!activeEl || !container) return;
    try {
      const aRect = activeEl.getBoundingClientRect();
      const cRect = container.getBoundingClientRect();
      if (aRect.height === 0 || cRect.height === 0) return;
      setNavSliderStyle({
        height: aRect.height,
        width: aRect.width,
        transform: `translate(${aRect.left - cRect.left}px,${aRect.top - cRect.top}px)`,
        opacity: 1,
      });
    } catch {
      /* ignore measurement errors during resize/zoom */
    }
  }, [activeSection]);

  useEffect(() => {
    requestAnimationFrame(updateNavSlider);
  }, [updateNavSlider]);

  useEffect(() => {
    let timer: number;
    const onResize = () => {
      clearTimeout(timer);
      timer = window.setTimeout(
        () => requestAnimationFrame(updateNavSlider),
        50,
      );
    };
    window.addEventListener("resize", onResize, { passive: true });
    const fallback = setTimeout(updateNavSlider, 150);
    return () => {
      window.removeEventListener("resize", onResize);
      clearTimeout(fallback);
      clearTimeout(timer);
    };
  }, [updateNavSlider]);

  const { fields, registerField, unregisterField, search } = useSearchIndex({
    useSchema: true,
  });

  useEffect(() => {
    let cancelled = false;

    async function loadSettings() {
      if (!restUrl) {
        return;
      }

      try {
        const response = await fetch(`${restUrl}/settings`, {
          method: "GET",
          headers: { "X-WP-Nonce": nonce },
          credentials: "same-origin",
        });
        if (!response.ok) {
          throw new Error("GET settings failed");
        }

        const json = (await response.json()) as
          | Settings
          | { settings?: Settings };
        const resolved =
          json && typeof json === "object" && "settings" in json
            ? json.settings
            : (json as Settings);

        if (!cancelled && resolved && typeof resolved === "object") {
          setSettings(resolved);
        }
      } catch {
        // Ignore; localized settings are already present.
      }
    }

    void loadSettings();

    return () => {
      cancelled = true;
    };
  }, [nonce, restUrl]);

  useEffect(() => {
    return () => {
      if (toastTimeoutRef.current) {
        window.clearTimeout(toastTimeoutRef.current);
      }
      if (highlightTimeoutRef.current) {
        window.clearTimeout(highlightTimeoutRef.current);
      }
    };
  }, []);

  const searchResults = useMemo(() => {
    if (!searchQuery.trim()) {
      return [];
    }

    return search(searchQuery);
  }, [search, searchQuery]);

  const navItems = useMemo(
    () => [
      {
        id: "getting-started" as AdminSectionId,
        label: "Getting Started",
        Icon: BookIcon,
      },
      ...baseTabs.map((tab) => ({
        id: tab.id as AdminSectionId,
        label: tab.label,
        Icon: NAV_ICONS[tab.id as AdminSectionId] ?? GearIcon,
      })),
    ],
    [],
  );

  const previewShowLabels = settings.show_labels !== false;
  const previewShowLabelsColors = settings.show_labels_colors !== false;
  const previewEnableTooltips = settings.enable_tooltips !== false;
  const previewLayout = "wrap";
  const previewSelectorStyle = "underline";
  const previewLayoutPaddingTop = coerceInt(settings.layout_padding_top, 5);
  const previewLayoutPaddingRight = coerceInt(settings.layout_padding_right, 5);
  const previewLayoutPaddingBottom = coerceInt(
    settings.layout_padding_bottom,
    5,
  );
  const previewLayoutPaddingLeft = coerceInt(settings.layout_padding_left, 5);
  const previewLabelFontSize = coerceInt(settings.label_font_size, 14);
  const previewLabelTextColor =
    typeof settings.label_text_color === "string"
      ? settings.label_text_color
      : "";
  const previewSwatchWidth = coerceInt(settings.swatch_width, 32);
  const previewSwatchHeight = coerceInt(settings.swatch_height, 32);
  const previewSwatchGap = coerceInt(settings.swatch_gap, 12);
  const attributesAdminUrl =
    typeof adminUrls.attributes === "string" ? adminUrls.attributes : "#";
  const productsAdminUrl =
    typeof adminUrls.products === "string" ? adminUrls.products : "#";

  function setActiveSectionWithHash(section: AdminSectionId) {
    setActiveSection(section);

    if (typeof window !== "undefined") {
      const url = new URL(window.location.href);
      url.hash = section;
      window.history.replaceState(
        null,
        "",
        `${url.pathname}${url.search}${url.hash}`,
      );
    }
  }

  function showToast(payload: {
    type: ToastState["type"];
    message: string;
    durationMs?: number;
  }) {
    setToast({ show: true, type: payload.type, message: payload.message });

    const durationMs =
      typeof payload.durationMs === "number" && payload.durationMs > 300
        ? payload.durationMs
        : 2800;

    if (toastTimeoutRef.current) {
      window.clearTimeout(toastTimeoutRef.current);
    }

    toastTimeoutRef.current = window.setTimeout(() => {
      setToast((current) => ({ ...current, show: false }));
      toastTimeoutRef.current = null;
    }, durationMs);
  }

  function highlightField(fieldId: string) {
    setHighlightedFieldId(fieldId);

    if (highlightTimeoutRef.current) {
      window.clearTimeout(highlightTimeoutRef.current);
    }

    highlightTimeoutRef.current = window.setTimeout(() => {
      setHighlightedFieldId(null);
      highlightTimeoutRef.current = null;
    }, 3000);

    window.setTimeout(() => {
      const element = document.getElementById(fieldId);
      element?.scrollIntoView({ behavior: "smooth", block: "center" });
    }, 100);
  }

  function navigateToField(target: {
    id: string;
    tabId: string;
    subTab?: string;
  }) {
    if (target.tabId === "general" && target.subTab) {
      setActiveGeneralSubTab(target.subTab as "layout" | "size" | "options");
    }

    setSearchQuery("");
    setActiveSectionWithHash(target.tabId as AdminSectionId);
    highlightField(target.id);
  }

  function handleSelectSearchResult(result: SearchableFieldData) {
    if (
      result.requiresToggle &&
      !evaluateToggleState(settings, result.requiresToggle)
    ) {
      const toggleTarget = fields.find(
        (field) => field.id === result.requiresToggle?.toggleFieldId,
      );

      if (toggleTarget) {
        showToast({
          type: "info",
          message:
            result.requiresToggle.message ?? "Enable the parent setting first.",
          durationMs: 3200,
        });
        navigateToField({
          id: toggleTarget.id,
          tabId: toggleTarget.tabId,
          subTab: toggleTarget.subTab,
        });
        return;
      }
    }

    navigateToField({
      id: result.id,
      tabId: result.tabId,
      subTab: result.subTab,
    });
  }

  async function handleSave() {
    if (!restUrl) {
      return;
    }

    setSaving(true);
    try {
      const response = await fetch(`${restUrl}/settings`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-WP-Nonce": nonce,
        },
        credentials: "same-origin",
        body: JSON.stringify(settings),
      });

      if (!response.ok) {
        throw new Error("Save failed");
      }

      const json = (await response.json()) as { settings?: Settings };
      if (json.settings) {
        setSettings(json.settings);
      }

      showToast({ type: "success", message: "Settings saved" });
    } catch {
      showToast({ type: "error", message: "Failed to save settings" });
    } finally {
      setSaving(false);
    }
  }

  async function handleResetToDefaults() {
    if (!restUrl) {
      return;
    }

    const confirmed = window.confirm(
      "Reset all settings to their default values?",
    );
    if (!confirmed) {
      return;
    }

    setResetting(true);
    try {
      const response = await fetch(`${restUrl}/settings/reset`, {
        method: "POST",
        headers: { "X-WP-Nonce": nonce },
        credentials: "same-origin",
      });

      if (!response.ok) {
        throw new Error("Reset failed");
      }

      const json = (await response.json()) as { settings?: Settings };
      if (json.settings) {
        setSettings(json.settings);
      }

      showToast({ type: "success", message: "Settings reset to defaults" });
    } catch {
      showToast({ type: "error", message: "Failed to reset settings" });
    } finally {
      setResetting(false);
    }
  }

  const searchContextValue = useMemo(
    () => ({
      registerField,
      unregisterField,
      highlightedFieldId,
    }),
    [highlightedFieldId, registerField, unregisterField],
  );

  const isSearching = searchQuery.trim().length > 0;
  const showSaveReset = activeSection !== "getting-started" || isSearching;

  return (
    <SearchContext.Provider value={searchContextValue}>
      <div
        className="b3-wvs-relative b3-wvs-min-h-screen b3-wvs-bg-slate-50 b3-wvs-text-slate-900 is-density-compact"
        style={{ "--b3-wvs-admin-color": adminColor } as React.CSSProperties}
        data-density="compact"
      >
        <div className="b3-wvs-sticky b3-wvs-top-0 b3-wvs-z-20 b3-wvs-border-b b3-wvs-border-slate-200 b3-wvs-bg-white/95 b3-wvs-backdrop-blur">
          <div className="b3-wvs-settings-header-bar b3-wvs-mx-auto b3-wvs-w-full b3-wvs-max-w-7xl b3-wvs-px-4 sm:b3-wvs-px-6 b3-wvs-py-3 sm:b3-wvs-py-4">
            <div className="b3-wvs-settings-header-main b3-wvs-flex b3-wvs-items-center b3-wvs-gap-2 sm:b3-wvs-gap-3">
              <h1 className="b3-wvs-text-lg sm:b3-wvs-text-2xl b3-wvs-font-bold b3-wvs-text-slate-900">
                B3 Swatches Settings
              </h1>
            </div>
            <div className="b3-wvs-settings-header-actions b3-wvs-flex b3-wvs-items-center b3-wvs-gap-3">
              {showSaveReset ? (
                <>
                  <button
                    type="button"
                    onClick={handleResetToDefaults}
                    disabled={saving || resetting}
                    className="b3-wvs-shell-btn is-secondary"
                  >
                    {resetting ? "Resetting..." : "Reset to Defaults"}
                  </button>
                  <button
                    type="button"
                    onClick={handleSave}
                    disabled={saving || resetting}
                    className="b3-wvs-shell-btn is-primary"
                  >
                    {saving ? "Saving..." : "Save Settings"}
                  </button>
                </>
              ) : null}
            </div>
          </div>
        </div>

        <div className="b3-wvs-mx-auto b3-wvs-flex b3-wvs-w-full b3-wvs-max-w-7xl b3-wvs-flex-col b3-wvs-gap-4 sm:b3-wvs-gap-6 b3-wvs-px-4 sm:b3-wvs-px-6 b3-wvs-py-5 sm:b3-wvs-py-8 lg:b3-wvs-flex-row">
          <aside className="b3-wvs-w-full b3-wvs-shrink-0 lg:b3-wvs-w-56 lg:b3-wvs-sticky lg:b3-wvs-top-20 lg:b3-wvs-self-start">
            <nav
              ref={navRef}
              className="b3-wvs-grid b3-wvs-gap-1"
              style={{ position: "relative" }}
            >
              {/* Animated sliding pill */}
              <div
                className="b3-wvs-nav-slider b3-wvs-bg-admin"
                style={{
                  ...navSliderStyle,
                  transition:
                    "transform 0.35s cubic-bezier(0.34,1.56,0.64,1), height 0.25s ease, width 0.25s ease, opacity 0.2s ease",
                }}
                aria-hidden="true"
              />

              <div className="b3-wvs-mb-3">
                <label
                  htmlFor="b3-wvs-settings-search"
                  className="b3-wvs-sr-only"
                >
                  Search settings
                </label>

                <div className="b3-wvs-relative">
                  <div className="b3-wvs-pointer-events-none b3-wvs-absolute b3-wvs-inset-y-0 b3-wvs-left-4 b3-wvs-flex b3-wvs-items-center">
                    <svg
                      className="b3-wvs-h-4 b3-wvs-w-4 b3-wvs-text-gray-400"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                      />
                    </svg>
                  </div>

                  <input
                    id="b3-wvs-settings-search"
                    type="text"
                    value={searchQuery}
                    onChange={(event) => setSearchQuery(event.target.value)}
                    placeholder="Search settings..."
                    className="b3-wvs-ios-search b3-wvs-pl-11 b3-wvs-pr-14"
                  />

                  <button
                    type="button"
                    onClick={() => setSearchQuery("")}
                    className={`b3-wvs-absolute b3-wvs-inset-y-0 b3-wvs-right-3 b3-wvs-flex b3-wvs-items-center b3-wvs-text-[13px] b3-wvs-font-medium b3-wvs-text-gray-400 hover:b3-wvs-text-gray-700 b3-wvs-transition-all b3-wvs-duration-300 b3-wvs-ease-out ${
                      searchQuery
                        ? "b3-wvs-opacity-100 b3-wvs-translate-x-0"
                        : "b3-wvs-opacity-0 b3-wvs-translate-x-1 b3-wvs-pointer-events-none"
                    }`}
                    aria-label="Clear search"
                  >
                    Clear
                  </button>
                </div>

                <p className="b3-wvs-mt-2 b3-wvs-text-[11px] b3-wvs-leading-4 b3-wvs-text-gray-500">
                  Search all settings, then click a result.
                </p>
              </div>

              {navItems.map((item) => {
                const isActive = item.id === activeSection;
                return (
                  <button
                    key={item.id}
                    ref={(el) => {
                      navBtnRefs.current[item.id] = el;
                    }}
                    type="button"
                    onClick={(event) => {
                      event.preventDefault();
                      event.stopPropagation();
                      setActiveSectionWithHash(item.id);
                      setSearchQuery("");
                    }}
                    className={`b3-wvs-nav-item ${isActive ? "is-active" : ""}`}
                    style={{ position: "relative", zIndex: 2 }}
                  >
                    <item.Icon
                      className={`b3-wvs-w-4 b3-wvs-h-4 b3-wvs-shrink-0 ${
                        isActive ? "b3-wvs-text-white" : "b3-wvs-text-slate-400"
                      }`}
                    />
                    <span>{item.label}</span>
                  </button>
                );
              })}
            </nav>

            <div className="b3-wvs-mt-6 sm:b3-wvs-mt-8 lg:b3-wvs-sticky lg:b3-wvs-top-24">
              <div className="b3-wvs-rounded-2xl b3-wvs-border b3-wvs-border-slate-200 b3-wvs-bg-white b3-wvs-p-4 b3-wvs-shadow-sm">
                <div className="b3-wvs-flex b3-wvs-flex-col b3-wvs-items-center b3-wvs-gap-1 b3-wvs-mb-3">
                  <h3 className="b3-wvs-text-sm b3-wvs-font-semibold b3-wvs-text-gray-900 b3-wvs-text-center">
                    Live Preview
                  </h3>
                  <div className="b3-wvs-flex b3-wvs-flex-wrap b3-wvs-items-center b3-wvs-justify-center b3-wvs-gap-x-3 b3-wvs-gap-y-1 b3-wvs-text-[11px] b3-wvs-text-gray-500 b3-wvs-text-center">
                    <span>Layout: {BASE_LAYOUT_LABELS[previewLayout]}</span>
                    <span>
                      Selector: {BASE_STYLE_LABELS[previewSelectorStyle]}
                    </span>
                    <span>Click an option</span>
                  </div>
                </div>

                <div className="b3-wvs-admin-preview b3-wvs-bg-gray-50 b3-wvs-rounded-lg b3-wvs-p-4 b3-wvs-border b3-wvs-border-gray-200 b3-wvs-max-h-[70vh] b3-wvs-overflow-auto">
                  <div className="b3-wvs-space-y-6">
                    <div className="b3-wvs-space-y-2">
                      <div className="b3-wvs-text-xs b3-wvs-font-semibold b3-wvs-text-gray-700">
                        Color
                      </div>
                      <Preview
                        key="color-preview"
                        rawSettings={settings}
                        showLabels={previewShowLabels}
                        showLabelsColors={previewShowLabelsColors}
                        enableTooltips={previewEnableTooltips}
                        layoutPaddingTop={previewLayoutPaddingTop}
                        layoutPaddingRight={previewLayoutPaddingRight}
                        layoutPaddingBottom={previewLayoutPaddingBottom}
                        layoutPaddingLeft={previewLayoutPaddingLeft}
                        labelFontSize={previewLabelFontSize}
                        labelTextColor={previewLabelTextColor}
                        mode="colors"
                        selectedColor={settings.selected_color || adminColor}
                        swatchWidth={previewSwatchWidth}
                        swatchHeight={previewSwatchHeight}
                        swatchGap={previewSwatchGap}
                        selectedIndex={previewSelectedIndex}
                        onSelectIndex={setPreviewSelectedIndex}
                      />
                    </div>

                    <div className="b3-wvs-space-y-2">
                      <div className="b3-wvs-text-xs b3-wvs-font-semibold b3-wvs-text-gray-700">
                        Button/Label
                      </div>
                      <Preview
                        key="button-preview"
                        rawSettings={settings}
                        showLabels={previewShowLabels}
                        showLabelsColors={previewShowLabelsColors}
                        enableTooltips={previewEnableTooltips}
                        layoutPaddingTop={previewLayoutPaddingTop}
                        layoutPaddingRight={previewLayoutPaddingRight}
                        layoutPaddingBottom={previewLayoutPaddingBottom}
                        layoutPaddingLeft={previewLayoutPaddingLeft}
                        labelFontSize={previewLabelFontSize}
                        labelTextColor={previewLabelTextColor}
                        mode="buttons"
                        selectedColor={settings.selected_color || adminColor}
                        swatchWidth={previewSwatchWidth}
                        swatchHeight={previewSwatchHeight}
                        swatchGap={previewSwatchGap}
                        selectedIndex={previewSelectedIndex}
                        onSelectIndex={setPreviewSelectedIndex}
                      />
                    </div>
                  </div>
                </div>

                <p className="b3-wvs-text-xs b3-wvs-text-gray-500 b3-wvs-mt-3">
                  Updates in real-time.
                </p>
              </div>
            </div>
          </aside>

          <main className="b3-wvs-flex-1 b3-wvs-min-w-0">
            {isSearching ? (
              <h2 className="b3-wvs-mb-4 b3-wvs-text-4xl b3-wvs-font-bold b3-wvs-text-slate-900">
                Search Results
              </h2>
            ) : null}
            <div className="b3-wvs-rounded-2xl b3-wvs-border b3-wvs-border-slate-200 b3-wvs-bg-white b3-wvs-p-4 sm:b3-wvs-p-6 b3-wvs-shadow-sm">
              {isSearching ? (
                <SearchResultsView
                  query={searchQuery}
                  results={searchResults}
                  onSelectResult={handleSelectSearchResult}
                  onClearSearch={() => setSearchQuery("")}
                  isToggleEnabled={(result) =>
                    evaluateToggleState(settings, result.requiresToggle)
                  }
                />
              ) : activeSection === "getting-started" ? (
                <GettingStartedTab
                  attributesAdminUrl={attributesAdminUrl}
                  productsAdminUrl={productsAdminUrl}
                  usageStats={usageStats}
                />
              ) : (
                <>
                  {activeSection === "general" ? (
                    <GeneralTab
                      settings={settings}
                      setSettings={setSettings}
                      adminColor={adminColor}
                      activeGeneralSubTab={activeGeneralSubTab}
                      setActiveGeneralSubTab={setActiveGeneralSubTab}
                    />
                  ) : null}

                  {activeSection === "chips" ? (
                    <ChipsTab
                      settings={settings}
                      setSettings={setSettings}
                      adminColor={adminColor}
                    />
                  ) : null}

                  {activeSection === "typography" ? (
                    <TypographyTab
                      settings={settings}
                      setSettings={setSettings}
                      adminColor={adminColor}
                    />
                  ) : null}

                  {activeSection === "tooltips" ? (
                    <TooltipsTab
                      settings={settings}
                      setSettings={setSettings}
                      adminColor={adminColor}
                    />
                  ) : null}

                  {activeSection === "advanced" ? (
                    <AdvancedTab
                      settings={settings}
                      setSettings={setSettings}
                      adminColor={adminColor}
                    />
                  ) : null}

                  <div className="b3-wvs-flex b3-wvs-justify-end b3-wvs-mt-6">
                    <button
                      type="button"
                      onClick={handleSave}
                      disabled={saving}
                      className="b3-wvs-shell-btn is-primary"
                    >
                      {saving ? "Saving..." : "Save Settings"}
                    </button>
                  </div>
                </>
              )}
            </div>
          </main>
        </div>

        <div
          className={`b3-wvs-fixed b3-wvs-bottom-4 b3-wvs-right-4 sm:b3-wvs-bottom-8 sm:b3-wvs-right-8 b3-wvs-z-50 b3-wvs-transition-all b3-wvs-duration-500 b3-wvs-ease-[cubic-bezier(0.16,1,0.3,1)] ${
            toast.show
              ? "b3-wvs-translate-x-0 b3-wvs-opacity-100"
              : "b3-wvs-translate-x-[120%] b3-wvs-opacity-0 b3-wvs-pointer-events-none"
          }`}
        >
          <div
            className={`b3-wvs-flex b3-wvs-items-center b3-wvs-gap-3 b3-wvs-px-6 b3-wvs-py-4 b3-wvs-rounded-lg b3-wvs-shadow-lg b3-wvs-bg-admin b3-wvs-border b3-wvs-border-admin-light b3-wvs-border-l-4 b3-wvs-text-white b3-wvs-font-medium ${
              toast.type === "success"
                ? "b3-wvs-border-l-emerald-400"
                : toast.type === "info"
                  ? "b3-wvs-border-l-sky-400"
                  : "b3-wvs-border-l-rose-400"
            }`}
          >
            <span
              className={`b3-wvs-inline-flex b3-wvs-h-2.5 b3-wvs-w-2.5 b3-wvs-rounded-full b3-wvs-bg-white/80 ${
                toast.type === "success"
                  ? "b3-wvs-ring-2 b3-wvs-ring-emerald-300"
                  : toast.type === "info"
                    ? "b3-wvs-ring-2 b3-wvs-ring-sky-300"
                    : "b3-wvs-ring-2 b3-wvs-ring-rose-300"
              }`}
              aria-hidden="true"
            />
            <span>{toast.message}</span>
          </div>
        </div>
      </div>
    </SearchContext.Provider>
  );
}

export default App;
