All files / packages/sds-subsystems/.storybook/addons/theme-builder/src/components ThemeBuilderPanel.jsx

0% Statements 0/90
0% Branches 0/20
0% Functions 0/27
0% Lines 0/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useGlobals } from 'storybook/manager-api';
import '../../../../../../sds-styling-hooks/dist/themes/cosmos/cosmos.hooks.custom-props.css';
import '../../../../../../sds-styling-hooks/dist/themes/cosmos/cosmos.shared.hooks.custom-props.css';
import '../../../../../../sds-styling-hooks/dist/themes/cosmos/cosmos.component.hooks.custom-props.css';
import '../../../../../dist/css/slds2.css';
import ColorSwatch from './ColorSwatch';
import Slider from './Slider';
import Button from './Button';
import ColorPicker from './ColorPicker';
import Accordion from './Accordion';
import AccordionPanel from './AccordionPanel';
import Combobox from './Combobox';
import SavedThemesTable from './SavedThemesTable';
import Modal from './Modal';
import processThemeState from '../utilities/theme-processor';
import SvgIcon from './SvgIcon';
import Tabs, { TabItem } from './Tabs';
import CheckboxToggle from './CheckboxToggle';
import FONT_OPTIONS, { getFontLabel } from '../utilities/font-options';
 
// Inline constants (matching index.js)
const ADDON_ID = 'sds-theme-builder';
const SAVED_THEMES_STORAGE_KEY = 'sds-theme-builder-saved-themes';
 
// Styles are now handled by CSS file
 
export const ThemeBuilderPanel = ({ active }) => {
  // If the panel is not active, don't render anything
  if (!active) {
    return null;
  }
 
  // const colorChangeTimeout = useRef(null);
 
  // ✅ Use useGlobals for theme state management
  const [globals, updateGlobals] = useGlobals();
  const [curExpanded, setCurExpanded] = useState(2);
  const [isExportModalOpen, setIsExportModalOpen] = useState(false);
  const [isSaveModalOpen, setIsSaveModalOpen] = useState(false);
  const [hasThemeChanges, setHasThemeChanges] = useState(false);
  const [themeName, setThemeName] = useState('');
 
  // Load saved themes from local storage
  const loadSavedThemes = useCallback(() => {
    try {
      const stored = localStorage.getItem(SAVED_THEMES_STORAGE_KEY);
      if (stored) {
        return JSON.parse(stored);
      } else I{
        return [];
      }
    } catch (error) {
      console.error('Error loading saved themes from localStorage:', error);
    }
  }, []);
 
  // COSMOS theme - the default baseline theme
  const cosmosTheme = {
    colors: {
      brand: '#066AFE',
      success: '#056764',
      error: '#b60554',
      warning: '#8c4b02',
      info: '#0b5cab',
    },
    typography: {
      fontSize: '13px',
      fontFamily: 'default',
      lineHeight: 1.375,
      fontScale: 1,
    },
    spacing: {
      scale: 1,
    },
    borderRadius: {
      scale: 1,
    },
    shadows: {
      show: true,
    },
  };
 
  // Saved themes data - loaded from local storage
  const [savedThemes, setSavedThemes] = useState(loadSavedThemes);
  const [activeThemeName, setActiveThemeName] = useState(globals.brand || 'default');
  const [activeTab, setActiveTab] = useState(0);
  const [baselineTheme, setBaselineTheme] = useState(cosmosTheme); // Track the baseline theme for reset operations
 
  useEffect(() => {
    setActiveThemeName(globals.brand);
  }, [globals.brand]);
 
  // Current theme state - backfilled with COSMOS values for missing properties
  const themeState = {
    ...cosmosTheme,
    ...globals.themeState,
    colors: {
      ...cosmosTheme.colors,
      ...globals.themeState?.colors,
    },
    typography: {
      ...cosmosTheme.typography,
      ...globals.themeState?.typography,
    },
    spacing: {
      ...cosmosTheme.spacing,
      ...globals.themeState?.spacing,
    },
    borderRadius: {
      ...cosmosTheme.borderRadius,
      ...globals.themeState?.borderRadius,
    },
    shadows: {
      ...cosmosTheme.shadows,
      ...globals.themeState?.shadows,
    },
  };
 
  const [currentThemeData, setCurrentThemeData] = useState(themeState);
 
  // Get the current baseline theme for reset operations
  // Returns: applied saved theme (if any) OR COSMOS theme (default baseline)
  const getCurrentBaselineTheme = () => {
    return baselineTheme; // baselineTheme now defaults to cosmosTheme
  };
 
  const updateTheme = useCallback(
    (category, key, value) => {
      const newTheme = {
        ...themeState,
        [category]: {
          ...themeState[category], // ← Preserve existing properties of same category
          [key]: value,
        },
      };
 
      // Check if theme has changed from baseline (COSMOS or applied saved theme)
      const hasChanges = JSON.stringify(newTheme) !== JSON.stringify(getCurrentBaselineTheme());
      setHasThemeChanges(hasChanges);
      // ✅ Update globals instead of local state
      updateGlobals({
        brand: 'temp',
        themeState: newTheme,
      });
 
      setCurrentThemeData(newTheme);
    },
    [themeState, updateGlobals, getCurrentBaselineTheme],
  );
 
  const resetTheme = useCallback(() => {
    const resetThemeState = getCurrentBaselineTheme();
 
    // Reset change tracking since we're back to baseline
    setHasThemeChanges(false);
 
    // ✅ Reset globals instead of local state
    updateGlobals({
      themeState: resetThemeState,
    });
  }, [updateGlobals, getCurrentBaselineTheme]);
 
  // const getBorderRadiusLabel = (scale) => {
  //   return borderRadius.find((item) => item.scale === scale).label || 'Medium (default)';
  // };
 
  const getSpacingLabel = (scale) => {
    return spacing.find((item) => item.scale === scale).label || 'Standard (default)';
  };
 
  // const getColorPaletteSwatch = () => {
  //   return Object.keys(themeState?.colors).map((color) => (
  //     <ColorSwatch key={color} color={themeState?.colors[color]} label={themeState?.colors[color]} />
  //   ));
  // };
 
  // Generate CSS for export
  const generateExportCSS = () => {
    const allHookMappings = processThemeState(themeState, getCurrentBaselineTheme());
    if (allHookMappings.length === 0) {
      return ':root {\n  /* No theme customizations */\n}';
    }
    const cssVariables = allHookMappings.map((mapping) => `  ${mapping.name}: ${mapping.value};`).join('\n');
    return `:root {\n${cssVariables}\n}`;
  };
 
  // Copy CSS to clipboard
  const copyToClipboard = async () => {
    try {
      const css = generateExportCSS();
      await navigator.clipboard.writeText(css);
      // You could add a toast notification here
    } catch (err) {
      console.error('Failed to copy CSS:', err);
    }
  };
 
  // Handle export modal
  const handleExportTheme = () => {
    setIsExportModalOpen(true);
  };
 
  const handleCloseExportModal = () => {
    setIsExportModalOpen(false);
  };
 
  // Handle save theme modal
  const handleSaveTheme = () => {
    setIsSaveModalOpen(true);
  };
 
  const handleCloseSaveModal = () => {
    setIsSaveModalOpen(false);
    setThemeName('');
  };
 
  // Helper function to create a theme from current state
  const createThemeFromCurrentState = useCallback(
    (themeName) => {
      return {
        id: `theme-${Date.now()}`, // Generate unique ID
        name: themeName,
        themeData: { ...themeState }, // Direct copy of current theme state
      };
    },
    [themeState],
  );
 
  const handleConfirmSaveTheme = useCallback(() => {
    if (!themeName.trim()) {
      alert('Please enter a theme name');
      return;
    }
 
    // Check if theme name already exists
    const existingTheme = savedThemes.find(
      (theme) => theme.name.toLowerCase() === themeName.trim().toLowerCase(),
    );
 
    if (existingTheme) {
      alert('A theme with this name already exists. Please choose a different name.');
      return;
    }
 
    // Check if theme with same state values already exists
    const currentThemeData = JSON.stringify(themeState);
    const duplicateTheme = savedThemes.find((theme) => JSON.stringify(theme.themeData) === currentThemeData);
 
    if (duplicateTheme) {
      alert(
        `A theme with the same configuration already exists: "${duplicateTheme.name}". Please modify your theme settings before saving.`,
      );
      return;
    }
 
    // Create new theme from current state
    const newTheme = createThemeFromCurrentState(themeName.trim());
 
    // Add to saved themes
    const updatedThemes = [...savedThemes, newTheme];
    setSavedThemes(updatedThemes);
 
    // Save to local storage
    try {
      localStorage.setItem(SAVED_THEMES_STORAGE_KEY, JSON.stringify(updatedThemes));
      setActiveThemeName(newTheme.name);
      updateGlobals({
        brand: 'default',
        // themeState: newTheme.themeData,
      });
      resetTheme();
    } catch (error) {
      console.error('Error saving theme to localStorage:', error);
      alert('Error saving theme. Please try again.');
      return;
    }
 
    // Close modal and reset form
    handleCloseSaveModal();
 
    // Reset change tracking since we've saved the current state
    setHasThemeChanges(false);
    // Clear active theme since we've saved a new one
    setActiveThemeName(null);
    // Reset baseline theme to COSMOS since we've saved a new one
    setBaselineTheme(cosmosTheme);
 
    // Switch to "Manage Themes" tab (index 1) after saving a new theme
    setTimeout(() => {
      setActiveTab(1);
    }, 100);
  }, [themeName, savedThemes, createThemeFromCurrentState, themeState]);
 
  // Handle saved theme actions
  const handleApplyTheme = useCallback(
    (savedTheme) => {
      // Directly apply the theme data to globals - no transformation needed
      // localStorage.setItem(ACTIVE_THEME_STORAGE_KEY, savedTheme.name);
      updateGlobals({
        brand: savedTheme.name,
        themeState: savedTheme.themeData,
      });
      // Reset change tracking since we're applying a saved theme
      setHasThemeChanges(false);
      // Set this theme as active
      setActiveThemeName(savedTheme.name);
      // Set this theme as the baseline for reset operations
      setBaselineTheme(savedTheme.themeData);
 
      // Switch to "Configure New Theme" tab (index 0) after applying a saved theme
      setTimeout(() => {
        setActiveTab(0);
      }, 100);
    },
    [updateGlobals],
  );
 
  const handleDeleteTheme = useCallback(
    (theme) => {
      if (window.confirm(`Are you sure you want to delete "${theme.name}"?`)) {
        // Remove theme from saved themes
        const updatedThemes = savedThemes.filter((t) => t.id !== theme.id);
        setSavedThemes(updatedThemes);
 
        // Reset theme state to COSMOS (baseline)
        updateGlobals({
          themeState: cosmosTheme,
        });
 
        // Clear active theme name (no theme is active anymore)
        setActiveThemeName(null);
 
        // Reset baseline theme to COSMOS
        setBaselineTheme(cosmosTheme);
 
        // Clear change tracking (no RESET buttons should appear)
        setHasThemeChanges(false);
 
        // Update local storage
        try {
          // const activeTheme = localStorage.getItem(ACTIVE_THEME_STORAGE_KEY);
          if (theme.name === activeThemeName) {
            // localStorage.setItem(ACTIVE_THEME_STORAGE_KEY, updatedThemes[0].name);
            updateGlobals({
              brand: 'default',
            });
          } else {
            updateGlobals({
              brand: theme.name,
              themeState: theme.themeData,
            });
          }
          localStorage.setItem(SAVED_THEMES_STORAGE_KEY, JSON.stringify(updatedThemes));
        } catch (error) {
          console.error('Error updating localStorage after deletion:', error);
          alert('Error deleting theme. Please try again.');
          // Revert the state change
          setSavedThemes(savedThemes);
        }
      }
    },
    [savedThemes, cosmosTheme],
  );
 
  return (
    <div
      className="theme-builder-panel slds-color-scheme_light"
      style={{ height: '100%', overflowY: 'auto' }}
    >
      <div className="slds-p-left_large slds-p-top_large slds-p-right_small slds-p-bottom_large">
        <div className="slds-grid slds-grid_align-spread slds-m-bottom_medium slds-wrap slds-m-right_small">
          <h3 className="slds-text-heading_medium">Theme Builder</h3>
          <div className="slds-grid slds-gutters slds-wrap slds-m-left_xx-small">
            <Button
              label="SAVE THEME"
              onClick={handleSaveTheme}
              disabled={!hasThemeChanges}
              variant="neutral"
              size="small"
              className="slds-m-vertical_xx-small"
            />
            <Button
              label="EXPORT THEME"
              onClick={handleExportTheme}
              variant="brand"
              size="small"
              className="slds-m-vertical_xx-small"
            />
          </div>
        </div>
        <Tabs
          selectedIndex={activeTab || 0}
          onTabChange={(tabIndex) => {
            setActiveTab(tabIndex);
          }}
        >
          <TabItem title="Configure Theme">
            <Accordion id="base-example-accordion">
              <AccordionPanel
                expanded={curExpanded === 2}
                id={2}
                key={2}
                onTogglePanel={(event) => setCurExpanded(curExpanded === 2 ? null : 2)}
                summary={`Color`}
              >
                <div className="slds-m-bottom_medium">
                  <p>
                    Define the primary brand color and manage the theme's semantic colors for UI states and
                    neutrals.
                  </p>
                  <p>
                    <strong>Note:</strong> Your chosen colors will be automatically adjusted to ensure
                    accessibility compliance and visual harmony across your theme.
                  </p>
                </div>
                <div className="slds-grid slds-m-bottom_medium">
                  <div>
                    <div className="slds-grid slds-is-relative">
                      <ColorPicker
                        value={themeState?.colors?.brand}
                        label="Color"
                        id="brand-color-picker"
                        onChange={(hex) => updateTheme('colors', 'brand', hex)}
                      />
                      {getCurrentBaselineTheme().colors.brand !== themeState.colors.brand ? (
                        <div className="slds-grid slds-p-top_x-large slds-p-left_x-small">
                          <Button
                            onClick={(e) =>
                              updateTheme('colors', 'brand', getCurrentBaselineTheme().colors.brand)
                            }
                            variant="icon"
                            iconName="skip_back"
                            iconPosition="left"
                            size="small"
                          />
                        </div>
                      ) : (
                        <div style={{ padding: '13px' }}></div>
                      )}
                    </div>
                  </div>
                  {/* <div className="slds-grid slds-size_3-of-12 slds-m-horizontal_large">
                <div>
                      <p className="slds-m-bottom_small slds-color-picker__summary-label slds-p-top_xx-small">
                        Brand Palette
                      </p>
                  {getColorPaletteSwatch()}
                    </div>
                  </div> */}
                </div>
                <div className=" slds-m-bottom_medium">Advance Settings</div>
                <div>
                  <div>
                    <div className="slds-grid slds-m-bottom_medium slds-is-relative">
                      <ColorPicker
                        value={themeState?.colors?.success}
                        label="Success Color"
                        id="success-color-picker"
                        onChange={(hex) => updateTheme('colors', 'success', hex)}
                      />
                      {getCurrentBaselineTheme().colors.success !== themeState.colors.success ? (
                        <div className="slds-grid slds-p-top_x-large slds-p-left_x-small">
                          <Button
                            onClick={(e) =>
                              updateTheme('colors', 'success', getCurrentBaselineTheme().colors.success)
                            }
                            variant="icon"
                            iconName="skip_back"
                            iconPosition="left"
                            size="small"
                          />
                        </div>
                      ) : (
                        <div style={{ padding: '13px' }}></div>
                      )}
                    </div>
                    <div className="slds-grid slds-m-bottom_medium slds-is-relative">
                      <ColorPicker
                        value={themeState?.colors?.error}
                        label="Error Color"
                        id="error-color-picker"
                        onChange={(hex) => updateTheme('colors', 'error', hex)}
                      />
                      {getCurrentBaselineTheme().colors.error !== themeState.colors.error ? (
                        <div className="slds-grid slds-p-top_x-large slds-p-left_x-small">
                          <Button
                            onClick={(e) =>
                              updateTheme('colors', 'error', getCurrentBaselineTheme().colors.error)
                            }
                            variant="icon"
                            iconName="skip_back"
                            iconPosition="left"
                            size="small"
                          />
                        </div>
                      ) : (
                        <div style={{ padding: '13px' }}></div>
                      )}
                    </div>
                  </div>
                  <div>
                    <div className="slds-grid slds-m-bottom_medium slds-is-relative">
                      <ColorPicker
                        value={themeState?.colors?.warning}
                        label="Warning Color"
                        id="warning-color-picker"
                        onChange={(hex) => updateTheme('colors', 'warning', hex)}
                      />
                      {getCurrentBaselineTheme().colors.warning !== themeState.colors.warning ? (
                        <div className="slds-grid slds-p-top_x-large slds-p-left_x-small">
                          <Button
                            onClick={(e) =>
                              updateTheme('colors', 'warning', getCurrentBaselineTheme().colors.warning)
                            }
                            variant="icon"
                            iconName="skip_back"
                            iconPosition="left"
                            size="small"
                          />
                        </div>
                      ) : (
                        <div style={{ padding: '13px' }}></div>
                      )}
                    </div>
                    <div className="slds-grid slds-m-bottom_medium slds-is-relative">
                      <ColorPicker
                        value={themeState?.colors?.info}
                        label="Info Color"
                        id="info-color-picker"
                        onChange={(hex) => updateTheme('colors', 'info', hex)}
                      />
                      {getCurrentBaselineTheme().colors.info !== themeState.colors.info ? (
                        <div className="slds-grid slds-p-top_x-large slds-p-left_x-small">
                          <Button
                            onClick={(e) =>
                              updateTheme('colors', 'info', getCurrentBaselineTheme().colors.info)
                            }
                            variant="icon"
                            iconName="skip_back"
                            iconPosition="left"
                            size="small"
                          />
                        </div>
                      ) : (
                        <div style={{ padding: '13px' }}></div>
                      )}
                    </div>
                  </div>
                </div>
              </AccordionPanel>
              <AccordionPanel
                expanded={curExpanded === 5}
                id={5}
                key={5}
                onTogglePanel={() => setCurExpanded(curExpanded === 5 ? null : 5)}
                summary={`Typography`}
              >
                <div className=" slds-m-bottom_medium">
                  <p>
                    Customize global fonts, base sizes, and line heights to define the visual hierarchy and
                    readability of your theme.
                  </p>
                </div>
                <div>
                  <div className="slds-grid slds_vertical-align-center slds-m-bottom_medium">
                    <div
                      className="slds-size_10-of-12 slds-p-right_small"
                      style={{ width: '100%', maxWidth: '275px' }}
                    >
                      <p className=" slds-form-element__label">Global font</p>
                      <Combobox
                        id="combobox-typography-font-family"
                        onChange={(opt) => updateTheme('typography', 'fontFamily', opt.value)}
                        options={FONT_OPTIONS}
                        value={getFontLabel(themeState?.typography?.fontFamily)}
                        rightInputIcon={
                          <SvgIcon
                            symbol={'down'}
                            className="slds-input__icon-group slds-input__icon-group_right slds-icon slds-icon-text-default slds-icon_xx-small slds-m-horizontal_small"
                          />
                        }
                      />
                    </div>
                    {getCurrentBaselineTheme().typography.fontFamily !== themeState.typography.fontFamily ? (
                      <div className="slds-grid_align-end slds-m-top_x-large slds-p-top_xx-small">
                        <Button
                          onClick={(e) =>
                            updateTheme(
                              'typography',
                              'fontFamily',
                              getCurrentBaselineTheme().typography.fontFamily,
                            )
                          }
                          variant="icon"
                          iconName="skip_back"
                          iconPosition="left"
                          size="small"
                        />
                      </div>
                    ) : (
                      <div style={{ padding: '13px' }}></div>
                    )}
                  </div>
                  <div className="slds-grid slds_vertical-align-center">
                    <div
                      className="slds-size_10-of-12 slds-m-bottom_medium"
                      style={{ width: '100%', maxWidth: '275px' }}
                    >
                      <p className=" slds-form-element__label">Font size</p>
                      <Slider
                        id="font-scale-slider"
                        value={currentThemeData?.typography?.fontScale}
                        step={0.05}
                        min={1}
                        max={1.35}
                        rangeLabel={'1x - 1.35x'}
                        onInput={(event, { value }) => {
                          updateTheme('typography', 'fontScale', value);
                        }}
                      />
                    </div>
                    {getCurrentBaselineTheme().typography.fontScale !== themeState.typography.fontScale ? (
                      <div className="slds-grid slds-grid_align-end slds-m-top_x-large slds-p-top_x-small">
                        <Button
                          onClick={(e) =>
                            updateTheme(
                              'typography',
                              'fontScale',
                              getCurrentBaselineTheme().typography.fontScale,
                            )
                          }
                          variant="icon"
                          iconName="skip_back"
                          iconPosition="left"
                          size="small"
                        />
                      </div>
                    ) : (
                      <div style={{ padding: '13px' }}></div>
                    )}
                  </div>
                  <div className="slds-grid slds_vertical-align-center">
                    <div
                      className="slds-size_10-of-12 slds-m-bottom_medium"
                      style={{ width: '100%', maxWidth: '275px' }}
                    >
                      <p className=" slds-form-element__label">Line height</p>
                      <Slider
                        id="line-height-slider"
                        value={currentThemeData?.typography?.lineHeight}
                        step={0.05}
                        min={1}
                        max={1.8}
                        rangeLabel={'1x - 1.8x'}
                        onInput={(event, { value }) => {
                          updateTheme('typography', 'lineHeight', value);
                        }}
                      />
                    </div>
                    {getCurrentBaselineTheme().typography.lineHeight !== themeState.typography.lineHeight ? (
                      <div className="slds-grid slds-grid_align-end slds-m-top_x-large slds-p-top_x-small">
                        <Button
                          onClick={(e) =>
                            updateTheme(
                              'typography',
                              'lineHeight',
                              getCurrentBaselineTheme().typography.lineHeight,
                            )
                          }
                          variant="icon"
                          iconName="skip_back"
                          iconPosition="left"
                          size="small"
                        />
                      </div>
                    ) : (
                      <div style={{ padding: '13px' }}></div>
                    )}
                  </div>
                </div>
              </AccordionPanel>
 
              <AccordionPanel
                expanded={curExpanded === 3}
                id={3}
                key={3}
                onTogglePanel={() => setCurExpanded(curExpanded === 3 ? null : 3)}
                summary={`Spacing`}
              >
                <div className=" slds-m-bottom_medium">
                  <p>
                    Choose how spacious or compact your layout feels—rest assured, we’ll adjust the spacing
                    behind the scenes to best fit compact mode.
                  </p>
                </div>
                <div className="slds-grid slds_vertical-align-center">
                  <div
                    className="slds-size_10-of-12 slds-m-bottom_medium"
                    style={{ width: '100%', maxWidth: '275px' }}
                  >
                    <p className="slds-form-element__label">Default spacing</p>
                    <Slider
                      id="line-height-slider"
                      value={currentThemeData?.spacing?.scale}
                      step={0.05}
                      min={0.5}
                      max={1.5}
                      rangeLabel={'0.5x - 1.5x'}
                      onInput={(event, { value }) => {
                        updateTheme('spacing', 'scale', value);
                      }}
                    />
                  </div>
                  {getCurrentBaselineTheme().spacing.scale !== themeState.spacing.scale ? (
                    <div className="slds-grid slds-grid_align-end slds-m-top_x-large slds-p-top_x-small">
                      <Button
                        onClick={(e) =>
                          updateTheme('spacing', 'scale', getCurrentBaselineTheme().spacing.scale)
                        }
                        variant="icon"
                        iconName="skip_back"
                        iconPosition="left"
                        size="small"
                      />
                    </div>
                  ) : (
                    <div style={{ padding: '13px' }}></div>
                  )}
                </div>
              </AccordionPanel>
 
              <AccordionPanel
                expanded={curExpanded === 1}
                id={1}
                key={1}
                onTogglePanel={() => setCurExpanded(curExpanded === 1 ? null : 1)}
                summary={`Border Radius`}
              >
                <div className="slds-m-bottom_medium">
                  <p>
                    Control how rounded or sharp your elements appear. Adjust the border radius to match your
                    brand’s personality.
                  </p>
                </div>
                <div className="slds-grid slds_vertical-align-center slds-m-bottom_medium">
                  <div
                    className="slds-size_10-of-12 slds-m-bottom_medium"
                    style={{ width: '100%', maxWidth: '275px' }}
                  >
                    <p className=" slds-form-element__label ">Global border radius</p>
                    <Slider
                      id="border-radius-slider"
                      value={themeState?.borderRadius?.scale}
                      step={0.05}
                      min={0}
                      max={2}
                      rangeLabel={'0 - 2x'}
                      onInput={(event, { value }) => {
                        updateTheme('borderRadius', 'scale', value);
                      }}
                    />
                  </div>
                  {getCurrentBaselineTheme().borderRadius.scale !== themeState.borderRadius.scale ? (
                    <div className="slds-grid slds-grid_align-end slds-m-top_x-large slds-p-top_x-small">
                      <Button
                        onClick={(e) =>
                          updateTheme('borderRadius', 'scale', getCurrentBaselineTheme().borderRadius.scale)
                        }
                        variant="icon"
                        iconName="skip_back"
                        iconPosition="left"
                        size="small"
                      />
                    </div>
                  ) : (
                    <div style={{ padding: '13px' }}></div>
                  )}
                </div>
              </AccordionPanel>
 
              <AccordionPanel
                expanded={curExpanded === 4}
                id={4}
                key={4}
                onTogglePanel={() => setCurExpanded(curExpanded === 4 ? null : 4)}
                summary={`Shadows`}
              >
                <div className=" slds-m-bottom_medium">
                  <p>
                    Toggle the use of shadows throughout the interface. Shadows create a sense of elevation,
                    making elements appear as if they are floating above the background.
                  </p>
                </div>
                <div
                  className="slds-grid slds_vertical-align-center slds-m-bottom_medium slds-grid_align-spread"
                  style={{ maxWidth: '500px' }}
                >
                  <div className=" slds-form-element__label">Use shadows</div>
                  <div className="slds-size_3-of-12 ">
                    <CheckboxToggle
                      checked={currentThemeData.shadows.show}
                      onChange={(e) => updateTheme('shadows', 'show', e.target.checked)}
                    />
                  </div>
                </div>
              </AccordionPanel>
            </Accordion>
          </TabItem>
          <TabItem title="Manage Themes">
            <div className="slds-p-around_large">
              {/* <h3 className="slds-text-heading_medium slds-m-bottom_medium">Saved Themes</h3> */}
              <SavedThemesTable
                themes={savedThemes}
                onApplyTheme={handleApplyTheme}
                onDeleteTheme={handleDeleteTheme}
                activeThemeName={activeThemeName}
              />
            </div>
          </TabItem>
        </Tabs>
      </div>
 
      {/* Export Theme Modal */}
      <Modal
        id="export-theme-modal"
        isOpen={isExportModalOpen}
        heading="Export Theme"
        tagline="Copy the generated CSS variables for your theme"
        onRequestClose={handleCloseExportModal}
        size="large"
        primaryLabel="Copy to Clipboard"
        secondaryLabel="Close"
        onSecondary={handleCloseExportModal}
        onPrimary={copyToClipboard}
      >
        <div className="slds-form slds-form_stacked">
          <div className="slds-form-element slds-m-bottom_small">
            <label className="slds-form-element__label" htmlFor="export-css-textarea">
              CSS Variables
            </label>
            <div className="slds-form-element__control">
              <textarea
                id="export-css-textarea"
                className="slds-textarea"
                readOnly
                rows={12}
                value={generateExportCSS()}
              />
            </div>
          </div>
          <p className="slds-text-color_weak slds-text-body_small">
            Tip: Click "Copy to Clipboard" and paste into your app's global :root or theme scope.
          </p>
        </div>
      </Modal>
 
      {/* Save Theme Modal */}
      <Modal
        id="save-theme-modal"
        isOpen={isSaveModalOpen}
        heading="Save Theme"
        tagline="Name and save your current configuration"
        onRequestClose={handleCloseSaveModal}
        size="medium"
        onSecondary={handleCloseSaveModal}
        onPrimary={handleConfirmSaveTheme}
        primaryLabel="Save Theme"
        secondaryLabel="Cancel"
      >
        <div className="slds-form slds-form_stacked">
          <div className="slds-form-element">
            <label className="slds-form-element__label" htmlFor="theme-name-input">
              Theme Name
            </label>
            <div className="slds-form-element__control">
              <input
                id="theme-name-input"
                type="text"
                className="slds-input"
                placeholder="e.g., Brand Sunrise"
                value={themeName}
                onChange={(e) => setThemeName(e.target.value)}
              />
            </div>
          </div>
          <p className="slds-text-color_weak slds-text-body_small slds-m-top_small">
            The theme will be saved in your browser and listed under "Manage Themes".
          </p>
        </div>
      </Modal>
    </div>
  );
};