'use client';

import { useState } from 'react';
import {
  Palette,
  Check,
  Star,
  Eye,
  Monitor,
  Smartphone,
  LayoutDashboard,
  Sun,
  X,
} from 'lucide-react';
import { useTheme } from '@/components/theme-provider';
import { type DesignTheme } from '@/lib/themes';
import { cn } from '@/lib/cn';
import { authFetch } from '@/lib/auth';

/* ─── Live Preview Modal ─── */

function ThemePreviewModal({
  theme,
  onClose,
  onApply,
}: {
  theme: DesignTheme;
  onClose: () => void;
  onApply: () => void;
}) {
  const [tab, setTab] = useState<'dashboard' | 'sidebar' | 'cards'>('dashboard');

  const c = theme.colors;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative bg-white rounded-2xl shadow-2xl w-full max-w-[900px] max-h-[85vh] overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between px-4 sm:px-6 py-4 border-b">
          <div className="flex items-center gap-3 min-w-0">
            <div
              className="w-8 h-8 rounded-lg shrink-0"
              style={{ backgroundColor: c['--primary'] }}
            />
            <div className="min-w-0">
              <h3 className="font-semibold text-gray-900 truncate">{theme.name}</h3>
              <p className="text-xs text-gray-500 truncate">{theme.style}</p>
            </div>
          </div>
          <div className="flex items-center gap-2 shrink-0 ml-2">
            <button
              onClick={onApply}
              className="hidden sm:flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium text-white"
              style={{ backgroundColor: c['--primary'] }}
            >
              <Check className="h-4 w-4" />
              Применить
            </button>
            <button
              onClick={onClose}
              className="p-2 rounded-lg hover:bg-gray-100 text-gray-500"
            >
              <X className="h-5 w-5" />
            </button>
          </div>
        </div>

        {/* Tabs */}
        <div className="flex gap-1 px-4 sm:px-6 pt-4 overflow-x-auto">
          {[
            { id: 'dashboard' as const, label: 'Дашборд', icon: LayoutDashboard },
            { id: 'sidebar' as const, label: 'Сайдбар', icon: Monitor },
            { id: 'cards' as const, label: 'Карточки', icon: Smartphone },
          ].map((t) => (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              className={cn(
                'flex items-center gap-2 px-3 sm:px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap',
                tab === t.id
                  ? 'text-white'
                  : 'text-gray-600 hover:bg-gray-100',
              )}
              style={tab === t.id ? { backgroundColor: c['--primary'] } : {}}
            >
              <t.icon className="h-4 w-4" />
              {t.label}
            </button>
          ))}
        </div>

        {/* Preview area */}
        <div className="p-4 sm:p-6 overflow-y-auto" style={{ maxHeight: 'calc(85vh - 180px)' }}>
          <div
            className="rounded-xl overflow-hidden border"
            style={{
              backgroundColor: c['--background'],
              borderColor: c['--border'],
            }}
          >
            {tab === 'dashboard' && (
              <div className="flex flex-col sm:flex-row min-h-[300px] sm:min-h-[400px]">
                {/* Mini sidebar */}
                <div
                  className="w-full sm:w-48 p-4 flex sm:flex-col gap-2 overflow-x-auto sm:overflow-x-visible"
                  style={{ backgroundColor: c['--sidebar-bg'] }}
                >
                  <div className="hidden sm:flex items-center gap-2 mb-4">
                    <div
                      className="w-6 h-6 rounded"
                      style={{ backgroundColor: c['--sidebar-active'] }}
                    />
                    <span
                      className="text-sm font-bold"
                      style={{ color: c['--sidebar-active'] }}
                    >
                      MyFitCRM
                    </span>
                  </div>
                  {['Дашборд', 'Клиенты', 'Расписание', 'Продажи', 'Отчёты'].map((item, i) => (
                    <div
                      key={item}
                      className="px-3 py-2 rounded-lg text-xs font-medium whitespace-nowrap"
                      style={
                        i === 0
                          ? { backgroundColor: c['--sidebar-active'], color: '#fff' }
                          : { color: c['--sidebar-text'] }
                      }
                    >
                      {item}
                    </div>
                  ))}
                </div>
                {/* Content */}
                <div className="flex-1 p-4 sm:p-6">
                  <h2
                    className="text-lg font-bold mb-4"
                    style={{
                      color: c['--text'],
                      fontFamily: theme.fonts.heading,
                    }}
                  >
                    Дашборд
                  </h2>
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
                    {[
                      { label: 'Продажи', value: '24' },
                      { label: 'Клиенты', value: '156' },
                      { label: 'Конверсия', value: '89%' },
                      { label: 'Рейтинг', value: '4.8' },
                    ].map((m) => (
                      <div
                        key={m.label}
                        className="rounded-xl p-3 sm:p-4"
                        style={{
                          backgroundColor: c['--card'],
                          borderWidth: 1,
                          borderStyle: 'solid',
                          borderColor: c['--border'],
                        }}
                      >
                        <p
                          className="text-xl sm:text-2xl font-bold"
                          style={{ color: c['--primary'] }}
                        >
                          {m.value}
                        </p>
                        <p
                          className="text-xs mt-1"
                          style={{ color: c['--muted'] }}
                        >
                          {m.label}
                        </p>
                      </div>
                    ))}
                  </div>
                  {/* Chart area */}
                  <div
                    className="rounded-xl p-4 h-24 sm:h-32 flex items-end gap-1"
                    style={{
                      backgroundColor: c['--card'],
                      borderWidth: 1,
                      borderStyle: 'solid',
                      borderColor: c['--border'],
                    }}
                  >
                    {[40, 65, 50, 80, 60, 90, 75, 85, 70, 95, 80, 88].map((h, i) => (
                      <div
                        key={i}
                        className="flex-1 rounded-t"
                        style={{
                          height: `${h}%`,
                          backgroundColor: c['--primary'],
                          opacity: 0.7 + (i / 40),
                        }}
                      />
                    ))}
                  </div>
                </div>
              </div>
            )}

            {tab === 'sidebar' && (
              <div className="flex flex-col sm:flex-row min-h-[300px] sm:min-h-[400px]">
                <div
                  className="w-full sm:w-64 p-4 flex flex-col"
                  style={{ backgroundColor: c['--sidebar-bg'] }}
                >
                  <div className="flex items-center gap-3 mb-6 px-2">
                    <div
                      className="w-10 h-10 rounded-xl flex items-center justify-center text-lg font-bold shrink-0"
                      style={{
                        backgroundColor: c['--sidebar-active'],
                        color: c['--primary-foreground'],
                      }}
                    >
                      F
                    </div>
                    <div>
                      <span
                        className="text-sm font-bold"
                        style={{ color: '#fff' }}
                      >
                        MyFitCRM
                      </span>
                      <p
                        className="text-[10px]"
                        style={{ color: c['--sidebar-text'] }}
                      >
                        Панель управления
                      </p>
                    </div>
                  </div>
                  <div className="space-y-1">
                    {[
                      { label: 'Дашборд', active: true },
                      { label: 'Клубы', active: false },
                      { label: 'Лицензии', active: false },
                      { label: 'Мониторинг', active: false },
                      { label: 'Аудит', active: false },
                      { label: 'Разработка', active: false },
                      { label: 'Документы', active: false },
                      { label: 'Темы', active: false },
                    ].map((item) => (
                      <div
                        key={item.label}
                        className="px-3 py-2.5 rounded-lg text-sm font-medium cursor-default"
                        style={
                          item.active
                            ? {
                                backgroundColor: c['--sidebar-active'],
                                color: '#fff',
                              }
                            : { color: c['--sidebar-text'] }
                        }
                      >
                        {item.label}
                      </div>
                    ))}
                  </div>
                  <div className="mt-auto pt-4 border-t" style={{ borderColor: c['--border'] }}>
                    <div className="flex items-center gap-2 px-2">
                      <div
                        className="w-3 h-3 rounded-full"
                        style={{ backgroundColor: c['--success'] }}
                      />
                      <span className="text-xs" style={{ color: c['--sidebar-text'] }}>
                        Система онлайн
                      </span>
                    </div>
                  </div>
                </div>
                <div
                  className="flex-1 p-8 flex items-center justify-center min-h-[100px]"
                  style={{ backgroundColor: c['--background'] }}
                >
                  <p className="text-sm" style={{ color: c['--muted'] }}>
                    Содержимое страницы
                  </p>
                </div>
              </div>
            )}

            {tab === 'cards' && (
              <div
                className="p-4 sm:p-6 min-h-[300px] sm:min-h-[400px]"
                style={{ backgroundColor: c['--background'] }}
              >
                <h3
                  className="text-lg font-bold mb-4"
                  style={{ color: c['--text'], fontFamily: theme.fonts.heading }}
                >
                  Элементы интерфейса
                </h3>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  {/* Stat card */}
                  <div
                    className="rounded-xl p-5"
                    style={{
                      backgroundColor: c['--card'],
                      border: `1px solid ${c['--border']}`,
                    }}
                  >
                    <p className="text-xs font-medium mb-1" style={{ color: c['--muted'] }}>
                      Продажи за месяц
                    </p>
                    <p className="text-3xl font-bold" style={{ color: c['--primary'] }}>
                      847,500
                    </p>
                    <p className="text-xs mt-2" style={{ color: c['--success'] }}>
                      +12.5% к прошлому месяцу
                    </p>
                  </div>
                  {/* Client card */}
                  <div
                    className="rounded-xl p-5"
                    style={{
                      backgroundColor: c['--card'],
                      border: `1px solid ${c['--border']}`,
                    }}
                  >
                    <p className="text-xs font-medium mb-1" style={{ color: c['--muted'] }}>
                      Активных клиентов
                    </p>
                    <p className="text-3xl font-bold" style={{ color: c['--text'] }}>
                      1,247
                    </p>
                    <div className="flex flex-wrap gap-2 mt-2">
                      <span
                        className="text-[10px] px-2 py-0.5 rounded-full font-medium"
                        style={{ backgroundColor: c['--primary'] + '20', color: c['--primary'] }}
                      >
                        Новых: 34
                      </span>
                      <span
                        className="text-[10px] px-2 py-0.5 rounded-full font-medium"
                        style={{ backgroundColor: c['--success'] + '20', color: c['--success'] }}
                      >
                        Активных: 892
                      </span>
                    </div>
                  </div>
                  {/* Buttons */}
                  <div
                    className="rounded-xl p-5"
                    style={{
                      backgroundColor: c['--card'],
                      border: `1px solid ${c['--border']}`,
                    }}
                  >
                    <p className="text-xs font-medium mb-3" style={{ color: c['--muted'] }}>
                      Кнопки
                    </p>
                    <div className="flex flex-wrap gap-2">
                      <button
                        className="px-4 py-2 rounded-lg text-xs font-medium"
                        style={{ backgroundColor: c['--primary'], color: c['--primary-foreground'] }}
                      >
                        Основная
                      </button>
                      <button
                        className="px-4 py-2 rounded-lg text-xs font-medium"
                        style={{ border: `1px solid ${c['--primary']}`, color: c['--primary'] }}
                      >
                        Обводка
                      </button>
                      <button
                        className="px-4 py-2 rounded-lg text-xs font-medium"
                        style={{ backgroundColor: c['--error'], color: '#fff' }}
                      >
                        Опасность
                      </button>
                      <button
                        className="px-4 py-2 rounded-lg text-xs font-medium"
                        style={{ backgroundColor: c['--success'], color: '#fff' }}
                      >
                        Успех
                      </button>
                    </div>
                  </div>
                  {/* Table preview */}
                  <div
                    className="rounded-xl p-5"
                    style={{
                      backgroundColor: c['--card'],
                      border: `1px solid ${c['--border']}`,
                    }}
                  >
                    <p className="text-xs font-medium mb-3" style={{ color: c['--muted'] }}>
                      Таблица
                    </p>
                    <table className="w-full text-xs">
                      <thead>
                        <tr style={{ borderBottom: `1px solid ${c['--border']}` }}>
                          <th className="text-left py-1.5 font-medium" style={{ color: c['--muted'] }}>
                            Клиент
                          </th>
                          <th className="text-left py-1.5 font-medium" style={{ color: c['--muted'] }}>
                            Статус
                          </th>
                        </tr>
                      </thead>
                      <tbody>
                        {[
                          { name: 'Иванов А.', status: 'Активен', color: c['--success'] },
                          { name: 'Петрова М.', status: 'Ожидает', color: c['--warning'] },
                          { name: 'Сидоров К.', status: 'Новый', color: c['--primary'] },
                        ].map((row) => (
                          <tr
                            key={row.name}
                            style={{ borderBottom: `1px solid ${c['--border']}` }}
                          >
                            <td className="py-1.5" style={{ color: c['--text'] }}>
                              {row.name}
                            </td>
                            <td className="py-1.5">
                              <span
                                className="px-2 py-0.5 rounded-full text-[10px] font-medium"
                                style={{
                                  backgroundColor: row.color + '20',
                                  color: row.color,
                                }}
                              >
                                {row.status}
                              </span>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Mobile apply button + palette strip */}
        <div className="px-4 sm:px-6 pb-4 space-y-3">
          {/* Mobile apply button */}
          <button
            onClick={onApply}
            className="sm:hidden w-full flex items-center justify-center gap-2 px-4 py-3 rounded-xl text-sm font-medium text-white"
            style={{ backgroundColor: c['--primary'] }}
          >
            <Check className="h-4 w-4" />
            Применить тему
          </button>
          {/* Palette */}
          <div className="flex items-center gap-3 overflow-x-auto pb-1">
            <span className="text-xs text-gray-500 shrink-0">Палитра:</span>
            {theme.palette.map((p) => (
              <div key={p.name} className="flex items-center gap-1.5 shrink-0">
                <div
                  className="w-5 h-5 rounded-full border border-gray-200"
                  style={{ backgroundColor: p.hex }}
                />
                <span className="text-[10px] text-gray-500 font-mono">{p.hex}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ─── Main Page ─── */

export default function ThemesSettingsPage() {
  const { themeId, setTheme, allThemes } = useTheme();
  const [previewTheme, setPreviewTheme] = useState<DesignTheme | null>(null);

  const [saving, setSaving] = useState(false);

  const [error, setError] = useState<string | null>(null);

  const handleApply = (id: string) => {
    setTheme(id);
    setPreviewTheme(null);
    setSaving(true);
    setError(null);
    const apiBase = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/v1';
    authFetch(`${apiBase}/admin/themes/active`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ themeId: id }),
    })
      .then((res) => {
        if (!res.ok) {
          setError(`Не удалось сохранить тему: ${res.status}`);
        }
      })
      .catch(() => {
        setError('Не удалось сохранить тему — проверьте подключение к серверу');
      })
      .finally(() => setSaving(false));
  };

  const currentTheme = allThemes.find((t) => t.id === themeId);

  return (
    <div>
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6">
        <div className="flex items-center gap-3">
          <div className="bg-primary/10 p-2.5 rounded-lg shrink-0">
            <Palette className="h-6 w-6 text-primary" />
          </div>
          <div>
            <h1 className="text-xl font-bold text-text">Темы оформления</h1>
            <p className="text-sm text-muted mt-0.5">
              10 светлых дизайн-комплектов для кастомизации интерфейса
            </p>
          </div>
        </div>
      </div>

      {/* Current theme badge */}
      <div className="bg-card rounded-xl border border-border p-4 mb-6 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div className="flex items-center gap-3">
          <div
            className="w-10 h-10 rounded-xl shrink-0"
            style={{ backgroundColor: currentTheme?.colors['--primary'] }}
          />
          <div>
            <p className="text-sm font-medium text-text">
              Текущая тема: <span className="font-bold">{currentTheme?.name}</span>
            </p>
            <p className="text-xs text-muted">{currentTheme?.style}</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Sun className="h-4 w-4 text-muted" />
          <span className="text-xs text-muted">Светлая тема</span>
        </div>
      </div>

      {/* Error message */}
      {error && (
        <div className="bg-error/10 border border-error/30 rounded-xl p-4 mb-6 flex items-center justify-between">
          <p className="text-sm text-error">{error}</p>
          <button onClick={() => setError(null)} className="text-error hover:text-error/80">
            <X className="h-4 w-4" />
          </button>
        </div>
      )}

      {/* Theme grid — responsive: 1 col mobile, 2 cols tablet+ */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4" data-testid="themes-grid">
        {allThemes.map((theme) => {
          const isActive = theme.id === themeId;
          const c = theme.colors;

          return (
            <div
              key={theme.id}
              data-testid={`theme-card-${theme.id}`}
              className={cn(
                'bg-card rounded-xl border overflow-hidden transition-all',
                isActive ? 'border-primary ring-2 ring-primary/20' : 'border-border hover:border-primary/40',
              )}
            >
              {/* Theme preview strip */}
              <div
                className="h-24 relative flex"
                style={{ backgroundColor: c['--background'] }}
              >
                {/* Mini sidebar */}
                <div
                  className="w-16 h-full flex flex-col items-center pt-3 gap-1.5"
                  style={{ backgroundColor: c['--sidebar-bg'] }}
                >
                  <div
                    className="w-6 h-6 rounded"
                    style={{ backgroundColor: c['--sidebar-active'] }}
                  />
                  {[1, 2, 3].map((i) => (
                    <div
                      key={i}
                      className="w-8 h-1.5 rounded-full opacity-40"
                      style={{ backgroundColor: c['--sidebar-text'] }}
                    />
                  ))}
                </div>
                {/* Mini content */}
                <div className="flex-1 p-3">
                  <div className="flex gap-2 mb-2">
                    {[1, 2, 3].map((i) => (
                      <div
                        key={i}
                        className="flex-1 h-8 rounded"
                        style={{
                          backgroundColor: c['--card'],
                          border: `1px solid ${c['--border']}`,
                        }}
                      >
                        <div
                          className="w-6 h-1.5 rounded-full mt-2 ml-2"
                          style={{ backgroundColor: c['--primary'], opacity: 0.7 }}
                        />
                      </div>
                    ))}
                  </div>
                  <div
                    className="h-8 rounded"
                    style={{
                      backgroundColor: c['--card'],
                      border: `1px solid ${c['--border']}`,
                    }}
                  />
                </div>

                {/* Active badge */}
                {isActive && (
                  <div
                    className="absolute top-2 right-2 flex items-center gap-1 px-2 py-1 rounded-full text-[10px] font-bold"
                    style={{ backgroundColor: c['--primary'], color: c['--primary-foreground'] }}
                  >
                    <Check className="h-3 w-3" />
                    Активна
                  </div>
                )}
              </div>

              {/* Theme info */}
              <div className="p-4">
                <div className="flex items-center justify-between mb-2">
                  <h3 className="font-semibold text-text text-sm truncate mr-2">{theme.name}</h3>
                  <div className="flex items-center gap-1 shrink-0">
                    <Star className="h-3.5 w-3.5 text-yellow-500 fill-yellow-500" />
                    <span className="text-xs font-bold text-text">{theme.rating}</span>
                  </div>
                </div>
                <p className="text-xs text-muted mb-3 line-clamp-2">{theme.description}</p>

                {/* Color dots */}
                <div className="flex gap-1.5 mb-3">
                  {theme.palette.map((color) => (
                    <div
                      key={color.name}
                      className="w-5 h-5 rounded-full border border-border"
                      style={{ backgroundColor: color.hex }}
                      title={`${color.name}: ${color.hex}`}
                    />
                  ))}
                </div>

                {/* Tags */}
                <div className="flex flex-wrap gap-1 mb-3">
                  {theme.tags.map((tag) => (
                    <span
                      key={tag}
                      className="text-[10px] font-medium px-2 py-0.5 rounded-full"
                      style={{
                        backgroundColor: c['--primary'] + '15',
                        color: c['--primary'],
                      }}
                    >
                      {tag}
                    </span>
                  ))}
                </div>

                {/* Fonts */}
                <p className="text-[10px] text-muted mb-3">
                  Шрифт: {theme.fonts.heading}
                  {theme.fonts.heading !== theme.fonts.body && ` / ${theme.fonts.body}`}
                </p>

                {/* Actions — stack on very small, row on wider */}
                <div className="flex gap-2" data-testid={`theme-actions-${theme.id}`}>
                  <button
                    onClick={() => setPreviewTheme(theme)}
                    className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2.5 rounded-lg text-xs font-medium border border-border text-text hover:bg-background transition-colors"
                  >
                    <Eye className="h-3.5 w-3.5" />
                    Предпросмотр
                  </button>
                  {isActive ? (
                    <div className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2.5 rounded-lg text-xs font-medium bg-primary/10 text-primary">
                      <Check className="h-3.5 w-3.5" />
                      Активна
                    </div>
                  ) : (
                    <button
                      onClick={() => handleApply(theme.id)}
                      disabled={saving}
                      className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2.5 rounded-lg text-xs font-medium text-white transition-colors disabled:opacity-50"
                      style={{ backgroundColor: c['--primary'] }}
                    >
                      {saving ? 'Сохранение...' : 'Применить'}
                    </button>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Recommendations */}
      <div className="mt-8 bg-card rounded-xl border border-border p-4 sm:p-6">
        <h2 className="text-lg font-semibold text-text mb-4">Рекомендации по выбору</h2>
        <div className="overflow-x-auto -mx-4 sm:mx-0">
          <table className="w-full text-sm min-w-[500px]">
            <thead>
              <tr className="border-b border-border">
                <th className="text-left py-3 px-4 font-medium text-muted">Тип клуба</th>
                <th className="text-left py-3 px-4 font-medium text-muted">Рекомендуемая тема</th>
                <th className="text-left py-3 px-4 font-medium text-muted">Причина</th>
              </tr>
            </thead>
            <tbody>
              {[
                { type: 'Универсальный фитнес-клуб', theme: 'FitPulse Orange', reason: 'Универсальный, энергичный стиль' },
                { type: 'CrossFit / единоборства', theme: 'Crimson Power', reason: 'Красный = энергия и мощь' },
                { type: 'Сетевой клуб (5+ точек)', theme: 'Royal Blue', reason: 'Корпоративный, надёжный' },
                { type: 'Йога / wellness', theme: 'Emerald Wellness', reason: 'Мягкие тона, спокойствие' },
                { type: 'Бутик-студия', theme: 'Nordic Frost', reason: 'Минимализм = премиум' },
                { type: 'Бассейн / SPA', theme: 'Pacific Teal', reason: 'Водная тематика' },
                { type: 'EMS / инновации', theme: 'Amethyst Light', reason: 'Hi-tech, современно' },
                { type: 'Женский клуб / пилатес', theme: 'Rose Garden', reason: 'Элегантный, женственный' },
                { type: 'Молодёжный клуб', theme: 'Sunset Coral', reason: 'Тёплые, динамичные тона' },
                { type: 'Любой тип (нейтральный)', theme: 'Cloud Professional', reason: 'Универсальная деловая палитра' },
              ].map((row, i) => (
                <tr key={i} className="border-b border-border last:border-0">
                  <td className="py-2.5 px-4 text-text font-medium">{row.type}</td>
                  <td className="py-2.5 px-4 text-primary font-medium">{row.theme}</td>
                  <td className="py-2.5 px-4 text-muted">{row.reason}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Preview modal */}
      {previewTheme && (
        <ThemePreviewModal
          theme={previewTheme}
          onClose={() => setPreviewTheme(null)}
          onApply={() => handleApply(previewTheme.id)}
        />
      )}
    </div>
  );
}
