<?php
// admin/template_page.php
// Theme Studio: central UI design-system controls.

$page_title = 'استوديو التصميم';

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
if (function_exists('ensure_db')) ensure_db(true);
require_once __DIR__ . '/ui_settings.php';
require_once __DIR__ . '/ui_design_system.php';
require_once __DIR__ . '/theme_assets_lib.php';

$conn = $GLOBALS['conn'] ?? null;
if ($conn instanceof mysqli) {
  ua_ensure_settings_table($conn);
}
mysqli_report(MYSQLI_REPORT_OFF);

$themes = function_exists('ua_theme_legacy_options') ? ua_theme_legacy_options() : [];

$designModes = [
  'v2' => 'Design System V2 - موحّد عام',
];
$fontFamilies = [
  'system' => 'خط النظام',
  'cairo' => 'Cairo - Arabic UI',
  'tajawal' => 'Tajawal - Arabic clean',
  'noto_kufi' => 'Noto Kufi Arabic',
  'ibm_plex_arabic' => 'IBM Plex Sans Arabic',
  'almarai' => 'Almarai - Arabic compact',
  'tahoma' => 'Tahoma',
  'segoe'  => 'Segoe UI',
  'arial'  => 'Arial',
];
$fontWeights = ['500' => 'عادي', '600' => 'متوسط', '700' => 'عريض', '800' => 'عريض جداً'];
$borderStyles = ['solid' => 'مصمت', 'dashed' => 'متقطع', 'double' => 'مزدوج'];
$cardStyles = ['soft' => 'ظل ناعم', 'flat' => 'مسطح', 'strong' => 'بارز'];
$spacingScales = ['tight' => 'مضغوط', 'normal' => 'متوازن', 'roomy' => 'واسع'];
$pageWidths = ['none' => 'بدون حد', '1280' => '1280px', '1440' => '1440px', '1600' => '1600px'];

$msg = '';
$err = '';

$normalizeColor = static function(string $value): string {
  $value = trim($value);
  if ($value === '') return '';
  if ($value[0] !== '#') $value = '#' . $value;
  return preg_match('/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', $value) ? $value : '';
};

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $conn instanceof mysqli) {
  $designMode = ua_design_choice($_POST['ui_design_mode'] ?? 'v2', array_keys($designModes), 'v2');
  $theme = ua_design_choice($_POST['ui_theme'] ?? 'armoury_dark', array_keys($themes), 'armoury_dark');
  $themeTokens = function_exists('ua_theme_design_tokens') ? ua_theme_design_tokens($theme) : [];
  $density = ua_design_choice($_POST['ui_density'] ?? 'comfy', ['comfy','compact'], 'comfy');
  $sidebar = ua_design_choice($_POST['ui_sidebar'] ?? 'hover', ['hover','pinned','compact'], 'hover');
  $fontFamily = ua_design_choice($_POST['ui_font_family'] ?? ($themeTokens['ui_font_family'] ?? 'system'), array_keys($fontFamilies), 'system');
  $fontWeight = ua_design_choice($_POST['ui_font_weight'] ?? ($themeTokens['ui_font_weight'] ?? '700'), array_keys($fontWeights), '700');
  $borderStyle = ua_design_choice($_POST['ui_border_style'] ?? 'solid', array_keys($borderStyles), 'solid');
  $cardStyle = ua_design_choice($_POST['ui_card_style'] ?? 'soft', array_keys($cardStyles), 'soft');
  $pageMaxWidth = ua_design_choice($_POST['ui_page_max_width'] ?? 'none', array_keys($pageWidths), 'none');
  $spacingScale = ua_design_choice($_POST['ui_spacing_scale'] ?? 'normal', array_keys($spacingScales), 'normal');

  $radius = ua_design_int_range($_POST['ui_radius'] ?? 16, 6, 30, 16);
  $fontSize = ua_design_int_range($_POST['ui_font_size'] ?? 15, 12, 20, 15);
  $borderWidth = ua_design_int_range($_POST['ui_border_width'] ?? 1, 1, 3, 1);
  $controlHeight = ua_design_int_range($_POST['ui_control_height'] ?? 40, 32, 54, 40);
  $tableRowHeight = ua_design_int_range($_POST['ui_table_row_height'] ?? 46, 36, 64, 46);
  $surfaceAlpha = ua_design_int_range($_POST['ui_surface_alpha'] ?? 82, 30, 96, 82);
  $menuAlpha = ua_design_int_range($_POST['ui_menu_alpha'] ?? 76, 30, 96, 76);

  $titleFontSize = ua_design_int_range($_POST['ui_title_font_size'] ?? 22, 16, 34, 22);
  $barFontSize = ua_design_int_range($_POST['ui_bar_font_size'] ?? 12, 10, 18, 12);
  $inputFontSize = ua_design_int_range($_POST['ui_input_font_size'] ?? 13, 11, 18, 13);
  $tableFontSize = ua_design_int_range($_POST['ui_table_font_size'] ?? 13, 10, 18, 13);
  $menuFontSize = ua_design_int_range($_POST['ui_menu_font_size'] ?? 13, 10, 18, 13);
  $modalFontSize = ua_design_int_range($_POST['ui_modal_font_size'] ?? 14, 12, 20, 14);

  $accent = $normalizeColor((string)($_POST['ui_accent'] ?? ''));
  $textColor = $normalizeColor((string)($_POST['ui_text_color'] ?? ''));
  $borderColor = $normalizeColor((string)($_POST['ui_border_color'] ?? ''));

  $bodyBg = $normalizeColor((string)($_POST['ui_body_bg'] ?? '#07111f')) ?: '#07111f';
  $surfaceColor = $normalizeColor((string)($_POST['ui_surface_color'] ?? '#071827')) ?: '#071827';
  $surfaceAltColor = $normalizeColor((string)($_POST['ui_surface_alt_color'] ?? '#0a2431')) ?: '#0a2431';
  $topbarColor = $normalizeColor((string)($_POST['ui_topbar_color'] ?? '#071a28')) ?: '#071a28';
  $windowbarColor = $normalizeColor((string)($_POST['ui_windowbar_color'] ?? '#071624')) ?: '#071624';
  $sidebarColor = $normalizeColor((string)($_POST['ui_sidebar_color'] ?? '#063238')) ?: '#063238';
  $sidebarItemColor = $normalizeColor((string)($_POST['ui_sidebar_item_color'] ?? '#0b4a4d')) ?: '#0b4a4d';
  $inputColor = $normalizeColor((string)($_POST['ui_input_color'] ?? '#061d2a')) ?: '#061d2a';
  $inputTextColor = $normalizeColor((string)($_POST['ui_input_text_color'] ?? '#eaf0ff')) ?: '#eaf0ff';
  $tableHeadColor = $normalizeColor((string)($_POST['ui_table_head_color'] ?? '#08373e')) ?: '#08373e';
  $tableRowColor = $normalizeColor((string)($_POST['ui_table_row_color'] ?? '#062532')) ?: '#062532';
  $tableRowAltColor = $normalizeColor((string)($_POST['ui_table_row_alt_color'] ?? '#082e3a')) ?: '#082e3a';
  $menuColor = $normalizeColor((string)($_POST['ui_menu_color'] ?? '#061923')) ?: '#061923';
  $modalColor = $normalizeColor((string)($_POST['ui_modal_color'] ?? '#071827')) ?: '#071827';
  $alertColor = $normalizeColor((string)($_POST['ui_alert_color'] ?? '#102b3f')) ?: '#102b3f';
  $securityAlertColor = $normalizeColor((string)($_POST['ui_security_alert_color'] ?? '#44151d')) ?: '#44151d';

  foreach ([
    'ui_design_mode' => $designMode,
    'ui_theme' => $theme,
    'ui_accent' => $accent,
    'ui_density' => $density,
    'ui_sidebar' => $sidebar,
    'ui_radius' => (string)$radius,
    'ui_font_family' => $fontFamily,
    'ui_font_size' => (string)$fontSize,
    'ui_font_weight' => $fontWeight,
    'ui_text_color' => $textColor,
    'ui_border_color' => $borderColor,
    'ui_border_style' => $borderStyle,
    'ui_border_width' => (string)$borderWidth,
    'ui_card_style' => $cardStyle,
    'ui_page_max_width' => $pageMaxWidth,
    'ui_control_height' => (string)$controlHeight,
    'ui_table_row_height' => (string)$tableRowHeight,
    'ui_surface_alpha' => (string)$surfaceAlpha,
    'ui_menu_alpha' => (string)$menuAlpha,
    'ui_spacing_scale' => $spacingScale,
    'ui_body_bg' => $bodyBg,
    'ui_surface_color' => $surfaceColor,
    'ui_surface_alt_color' => $surfaceAltColor,
    'ui_topbar_color' => $topbarColor,
    'ui_windowbar_color' => $windowbarColor,
    'ui_sidebar_color' => $sidebarColor,
    'ui_sidebar_item_color' => $sidebarItemColor,
    'ui_input_color' => $inputColor,
    'ui_input_text_color' => $inputTextColor,
    'ui_table_head_color' => $tableHeadColor,
    'ui_table_row_color' => $tableRowColor,
    'ui_table_row_alt_color' => $tableRowAltColor,
    'ui_menu_color' => $menuColor,
    'ui_modal_color' => $modalColor,
    'ui_alert_color' => $alertColor,
    'ui_security_alert_color' => $securityAlertColor,
    'ui_title_font_size' => (string)$titleFontSize,
    'ui_bar_font_size' => (string)$barFontSize,
    'ui_input_font_size' => (string)$inputFontSize,
    'ui_table_font_size' => (string)$tableFontSize,
    'ui_menu_font_size' => (string)$menuFontSize,
    'ui_modal_font_size' => (string)$modalFontSize,
  ] as $key => $value) {
    ua_set_ui_setting($conn, $key, $value);
  }

  $msg = 'تم حفظ قالب التصميم الموحد. جميع الصفحات التي تمر عبر الهيدر ستقرأ الألوان والخطوط من هذا القالب.';
}

$get = static function(string $key, string $default) use ($conn): string {
  if (!($conn instanceof mysqli)) return $default;
  $value = ua_get_ui_setting($conn, $key, $default);
  return is_scalar($value) ? (string)$value : $default;
};

$curDesignMode = ua_design_choice($get('ui_design_mode', 'v2'), array_keys($designModes), 'v2');
$curTheme = ua_design_choice($get('ui_theme', 'armoury_dark'), array_keys($themes), 'armoury_dark');
$curAccent = $normalizeColor($get('ui_accent', ''));
$curDensity = ua_design_choice($get('ui_density', 'comfy'), ['comfy','compact'], 'comfy');
$curSidebar = ua_design_choice($get('ui_sidebar', 'hover'), ['hover','pinned','compact'], 'hover');
$curRadius = ua_design_int_range($get('ui_radius', '16'), 6, 30, 16);
$curFontFamily = ua_design_choice($get('ui_font_family', 'system'), array_keys($fontFamilies), 'system');
$curFontSize = ua_design_int_range($get('ui_font_size', '15'), 12, 20, 15);
$curFontWeight = ua_design_choice($get('ui_font_weight', '700'), array_keys($fontWeights), '700');
$curTextColor = $normalizeColor($get('ui_text_color', ''));
$curBorderColor = $normalizeColor($get('ui_border_color', ''));
$curBorderStyle = ua_design_choice($get('ui_border_style', 'solid'), array_keys($borderStyles), 'solid');
$curBorderWidth = ua_design_int_range($get('ui_border_width', '1'), 1, 3, 1);
$curCardStyle = ua_design_choice($get('ui_card_style', 'soft'), array_keys($cardStyles), 'soft');
$curPageMaxWidth = ua_design_choice($get('ui_page_max_width', 'none'), array_keys($pageWidths), 'none');
$curControlHeight = ua_design_int_range($get('ui_control_height', '40'), 32, 54, 40);
$curTableRowHeight = ua_design_int_range($get('ui_table_row_height', '46'), 36, 64, 46);
$curSurfaceAlpha = ua_design_int_range($get('ui_surface_alpha', '82'), 30, 96, 82);
$curMenuAlpha = ua_design_int_range($get('ui_menu_alpha', '76'), 30, 96, 76);
$curSpacingScale = ua_design_choice($get('ui_spacing_scale', 'normal'), array_keys($spacingScales), 'normal');

$curBodyBg = $normalizeColor($get('ui_body_bg', '#07111f')) ?: '#07111f';
$curSurfaceColor = $normalizeColor($get('ui_surface_color', '#071827')) ?: '#071827';
$curSurfaceAltColor = $normalizeColor($get('ui_surface_alt_color', '#0a2431')) ?: '#0a2431';
$curTopbarColor = $normalizeColor($get('ui_topbar_color', '#071a28')) ?: '#071a28';
$curWindowbarColor = $normalizeColor($get('ui_windowbar_color', '#071624')) ?: '#071624';
$curSidebarColor = $normalizeColor($get('ui_sidebar_color', '#063238')) ?: '#063238';
$curSidebarItemColor = $normalizeColor($get('ui_sidebar_item_color', '#0b4a4d')) ?: '#0b4a4d';
$curInputColor = $normalizeColor($get('ui_input_color', '#061d2a')) ?: '#061d2a';
$curInputTextColor = $normalizeColor($get('ui_input_text_color', '#eaf0ff')) ?: '#eaf0ff';
$curTableHeadColor = $normalizeColor($get('ui_table_head_color', '#08373e')) ?: '#08373e';
$curTableRowColor = $normalizeColor($get('ui_table_row_color', '#062532')) ?: '#062532';
$curTableRowAltColor = $normalizeColor($get('ui_table_row_alt_color', '#082e3a')) ?: '#082e3a';
$curMenuColor = $normalizeColor($get('ui_menu_color', '#061923')) ?: '#061923';
$curModalColor = $normalizeColor($get('ui_modal_color', '#071827')) ?: '#071827';
$curAlertColor = $normalizeColor($get('ui_alert_color', '#102b3f')) ?: '#102b3f';
$curSecurityAlertColor = $normalizeColor($get('ui_security_alert_color', '#44151d')) ?: '#44151d';
$curTitleFontSize = ua_design_int_range($get('ui_title_font_size', '22'), 16, 34, 22);
$curBarFontSize = ua_design_int_range($get('ui_bar_font_size', '12'), 10, 18, 12);
$curInputFontSize = ua_design_int_range($get('ui_input_font_size', '13'), 11, 18, 13);
$curTableFontSize = ua_design_int_range($get('ui_table_font_size', '13'), 10, 18, 13);
$curMenuFontSize = ua_design_int_range($get('ui_menu_font_size', '13'), 10, 18, 13);
$curModalFontSize = ua_design_int_range($get('ui_modal_font_size', '14'), 12, 20, 14);

$uaAndroidTemplatePage = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$UA_PAGE_CSS = ['assets/css/ua_theme_studio.css'];
if ($uaAndroidTemplatePage) $UA_PAGE_CSS[] = 'assets/css/android_template_page.css';
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';

if (!function_exists('ua_ts_h')) {
  function ua_ts_h($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
  }
}
if ($uaAndroidTemplatePage) { require __DIR__ . '/android_template_page.php'; include __DIR__ . '/footer.php'; return; }
?>

<div class="content-wrapper ua-extracted-page ua-theme-studio">
  <section class="content p-3">
    <?php if (!($conn instanceof mysqli)): ?>
      <div class="alert alert-danger">تعذر الاتصال بقاعدة البيانات.</div>
    <?php else: ?>
      <form method="post" id="uaThemeStudioForm">
        <div class="ua-studio-head">
          <div>
            <div class="ua-studio-kicker">Design System</div>
            <h1>استوديو التصميم</h1>
          </div>
          <div class="ua-studio-actions">
            <a class="btn btn-outline-light" href="UI_DESIGN_SYSTEM_PROGRESS.txt" target="_blank" rel="noopener"><i class="fa fa-file-text-o"></i><span>ملف التقدم</span></a>
            <button class="btn btn-outline-warning" type="button" id="ua-reset"><i class="fa fa-undo"></i><span>إرجاع افتراضي</span></button>
            <button class="btn btn-primary" type="submit"><i class="fa fa-save"></i><span>حفظ وتطبيق</span></button>
          </div>
        </div>

        <?php if ($msg !== ''): ?>
          <div class="alert alert-success"><i class="fa fa-check"></i> <?= ua_ts_h($msg) ?></div>
        <?php endif; ?>
        <?php if ($err !== ''): ?>
          <div class="alert alert-danger"><i class="fa fa-exclamation-triangle"></i> <?= ua_ts_h($err) ?></div>
        <?php endif; ?>

        <div class="ua-studio-grid">
          <main class="ua-studio-main">
            <section class="ua-studio-panel">
              <div class="ua-panel-title">
                <div>
                  <h2>القوالب</h2>
                  <p>اختيار القالب العام، ثم ضبط التفاصيل من اللوحة الجانبية.</p>
                </div>
                <span class="ua-mode-pill"><?= $curDesignMode === 'v2' ? 'V2 مفعل' : 'Legacy آمن' ?></span>
              </div>
              <div class="ua-theme-grid" id="ua-theme-grid">
                <?php foreach ($themes as $id => $theme): ?>
                  <?php [$name, $desc, $css, $accentPreview] = $theme; ?>
                  <label class="ua-theme-option ua-theme-preview-<?= ua_ts_h(preg_replace('/[^a-z0-9_-]+/i', '-', (string)$id)) ?>">
                    <input type="radio" name="ui_theme" value="<?= ua_ts_h($id) ?>" <?= $curTheme === $id ? 'checked' : '' ?> data-theme-css="<?= ua_ts_h((string)$css) ?>">
                    <span class="ua-theme-preview" data-preview="<?= ua_ts_h($id) ?>">
                      <i></i><b></b><em></em>
                    </span>
                    <span class="ua-theme-copy">
                      <strong><?= ua_ts_h($name) ?></strong>
                      <small><?= ua_ts_h($desc) ?></small>
                    </span>
                  </label>
                <?php endforeach; ?>
              </div>
            </section>

            <section class="ua-studio-panel">
              <div class="ua-panel-title">
                <div>
                  <h2>معاينة موحدة</h2>
                  <p>نموذج مصغر للبطاقة، شريط الأدوات، الحقول، الجدول، والقائمة المنسدلة.</p>
                </div>
              </div>
              <div class="ua-preview-shell" id="uaPreviewShell">
                <aside>
                  <span></span><span></span><span></span><span></span>
                </aside>
                <div class="ua-preview-work">
                  <div class="ua-preview-toolbar">
                    <div>
                      <button type="button"><i class="fa fa-plus"></i><span>إضافة</span></button>
                      <button type="button"><i class="fa fa-filter"></i><span>فلترة</span></button>
                    </div>
                    <div class="ua-preview-search"><i class="fa fa-search"></i><span>بحث موحد...</span></div>
                  </div>
                  <div class="ua-preview-card">
                    <div class="ua-preview-card-head">
                      <strong>عنوان الصفحة</strong>
                      <button type="button"><i class="fa fa-ellipsis-v"></i></button>
                    </div>
                    <div class="ua-preview-fields">
                      <label>اسم المشترك <span>حقل إدخال</span></label>
                      <label>الباقة <span>قائمة اختيار</span></label>
                      <label>الحالة <span>محدد</span></label>
                    </div>
                    <table>
                      <thead><tr><th>#</th><th>الاسم</th><th>الحالة</th><th>إجراء</th></tr></thead>
                      <tbody>
                        <tr><td>101</td><td>محمد أحمد</td><td>متصل</td><td><i class="fa fa-eye"></i></td></tr>
                        <tr><td>102</td><td>فاطمة علي</td><td>غير متصل</td><td><i class="fa fa-pencil"></i></td></tr>
                      </tbody>
                    </table>
                  </div>
                  <div class="ua-preview-menu">
                    <a><i class="fa fa-sort"></i><span>الفرز الافتراضي</span></a>
                    <a><i class="fa fa-font"></i><span>حسب الأبجدية</span></a>
                    <a><i class="fa fa-ban"></i><span>المفصولين</span></a>
                  </div>
                </div>
              </div>
            </section>
          </main>

          <aside class="ua-studio-controls">
            <section class="ua-studio-panel">
              <h2>وضع القالب</h2>
              <div class="ua-field">
                <label>Design System Mode</label>
                <select class="form-select" name="ui_design_mode" id="ua-design-mode">
                  <?php foreach ($designModes as $k => $v): ?>
                    <option value="<?= ua_ts_h($k) ?>" <?= $curDesignMode === $k ? 'selected' : '' ?>><?= ua_ts_h($v) ?></option>
                  <?php endforeach; ?>
                </select>
                <small>تم تثبيت V2 كقالب موحد حتى لا تبقى الصفحات تتحكم بألوانها بشكل منفصل.</small>
              </div>
            </section>

            <section class="ua-studio-panel">
              <h2>الخطوط</h2>
              <div class="ua-two-cols">
                <div class="ua-field">
                  <label>نوع الخط</label>
                  <select class="form-select" name="ui_font_family" id="ua-font-family">
                    <?php foreach ($fontFamilies as $k => $v): ?>
                      <option value="<?= ua_ts_h($k) ?>" <?= $curFontFamily === $k ? 'selected' : '' ?>><?= ua_ts_h($v) ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="ua-field">
                  <label>السماكة</label>
                  <select class="form-select" name="ui_font_weight" id="ua-font-weight">
                    <?php foreach ($fontWeights as $k => $v): ?>
                      <option value="<?= ua_ts_h($k) ?>" <?= $curFontWeight === $k ? 'selected' : '' ?>><?= ua_ts_h($v) ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
              </div>
              <div class="ua-field">
                <label>حجم الخط العام <b id="ua-font-size-val"><?= (int)$curFontSize ?></b></label>
                <input class="form-range" type="range" min="12" max="20" step="1" name="ui_font_size" id="ua-font-size" value="<?= (int)$curFontSize ?>">
              </div>
              <div class="ua-two-cols ua-token-font-grid">
                <div class="ua-field">
                  <label>حجم العناوين <b id="ua-title-font-size-val"><?= (int)$curTitleFontSize ?></b></label>
                  <input class="form-range" type="range" min="16" max="34" step="1" name="ui_title_font_size" id="ua-title-font-size" value="<?= (int)$curTitleFontSize ?>">
                </div>
                <div class="ua-field">
                  <label>خط الأشرطة <b id="ua-bar-font-size-val"><?= (int)$curBarFontSize ?></b></label>
                  <input class="form-range" type="range" min="10" max="18" step="1" name="ui_bar_font_size" id="ua-bar-font-size" value="<?= (int)$curBarFontSize ?>">
                </div>
                <div class="ua-field">
                  <label>خط مربعات الإدخال <b id="ua-input-font-size-val"><?= (int)$curInputFontSize ?></b></label>
                  <input class="form-range" type="range" min="11" max="18" step="1" name="ui_input_font_size" id="ua-input-font-size" value="<?= (int)$curInputFontSize ?>">
                </div>
                <div class="ua-field">
                  <label>خط الجداول <b id="ua-table-font-size-val"><?= (int)$curTableFontSize ?></b></label>
                  <input class="form-range" type="range" min="10" max="18" step="1" name="ui_table_font_size" id="ua-table-font-size" value="<?= (int)$curTableFontSize ?>">
                </div>
                <div class="ua-field">
                  <label>خط القوائم <b id="ua-menu-font-size-val"><?= (int)$curMenuFontSize ?></b></label>
                  <input class="form-range" type="range" min="10" max="18" step="1" name="ui_menu_font_size" id="ua-menu-font-size" value="<?= (int)$curMenuFontSize ?>">
                </div>
                <div class="ua-field">
                  <label>خط النوافذ <b id="ua-modal-font-size-val"><?= (int)$curModalFontSize ?></b></label>
                  <input class="form-range" type="range" min="12" max="20" step="1" name="ui_modal_font_size" id="ua-modal-font-size" value="<?= (int)$curModalFontSize ?>">
                </div>
              </div>
              <div class="ua-field">
                <label>لون النص العام</label>
                <div class="ua-color-row">
                  <input type="color" id="ua-text-color-picker" value="<?= ua_ts_h($curTextColor !== '' ? $curTextColor : '#eaf0ff') ?>">
                  <input class="form-control" type="text" name="ui_text_color" id="ua-text-color" value="<?= ua_ts_h($curTextColor) ?>" placeholder="#eaf0ff">
                </div>
              </div>
            </section>

            <section class="ua-studio-panel">
              <h2>الألوان والأسطح</h2>
              <div class="ua-field">
                <label>لون التمييز الرئيسي</label>
                <div class="ua-color-row">
                  <input type="color" id="ua-accent-picker" value="<?= ua_ts_h($curAccent !== '' ? $curAccent : $themes[$curTheme][3]) ?>">
                  <input class="form-control" type="text" name="ui_accent" id="ua-accent" value="<?= ua_ts_h($curAccent) ?>" placeholder="لون القالب الافتراضي">
                </div>
              </div>

              <div class="ua-color-matrix">
                <div class="ua-field"><label>لون الواجهات</label><div class="ua-color-row"><input type="color" id="ua-body-bg-picker" value="<?= ua_ts_h($curBodyBg) ?>"><input class="form-control" type="text" name="ui_body_bg" id="ua-body-bg" value="<?= ua_ts_h($curBodyBg) ?>"></div></div>
                <div class="ua-field"><label>لون الكروت/الأسطح</label><div class="ua-color-row"><input type="color" id="ua-surface-color-picker" value="<?= ua_ts_h($curSurfaceColor) ?>"><input class="form-control" type="text" name="ui_surface_color" id="ua-surface-color" value="<?= ua_ts_h($curSurfaceColor) ?>"></div></div>
                <div class="ua-field"><label>لون الأسطح الثانوية</label><div class="ua-color-row"><input type="color" id="ua-surface-alt-color-picker" value="<?= ua_ts_h($curSurfaceAltColor) ?>"><input class="form-control" type="text" name="ui_surface_alt_color" id="ua-surface-alt-color" value="<?= ua_ts_h($curSurfaceAltColor) ?>"></div></div>
                <div class="ua-field"><label>لون الشريط العلوي</label><div class="ua-color-row"><input type="color" id="ua-topbar-color-picker" value="<?= ua_ts_h($curTopbarColor) ?>"><input class="form-control" type="text" name="ui_topbar_color" id="ua-topbar-color" value="<?= ua_ts_h($curTopbarColor) ?>"></div></div>
                <div class="ua-field"><label>لون شريط النوافذ</label><div class="ua-color-row"><input type="color" id="ua-windowbar-color-picker" value="<?= ua_ts_h($curWindowbarColor) ?>"><input class="form-control" type="text" name="ui_windowbar_color" id="ua-windowbar-color" value="<?= ua_ts_h($curWindowbarColor) ?>"></div></div>
                <div class="ua-field"><label>لون السايدبار</label><div class="ua-color-row"><input type="color" id="ua-sidebar-color-picker" value="<?= ua_ts_h($curSidebarColor) ?>"><input class="form-control" type="text" name="ui_sidebar_color" id="ua-sidebar-color" value="<?= ua_ts_h($curSidebarColor) ?>"></div></div>
                <div class="ua-field"><label>لون عناصر السايدبار</label><div class="ua-color-row"><input type="color" id="ua-sidebar-item-color-picker" value="<?= ua_ts_h($curSidebarItemColor) ?>"><input class="form-control" type="text" name="ui_sidebar_item_color" id="ua-sidebar-item-color" value="<?= ua_ts_h($curSidebarItemColor) ?>"></div></div>
                <div class="ua-field"><label>لون مربعات الإدخال</label><div class="ua-color-row"><input type="color" id="ua-input-color-picker" value="<?= ua_ts_h($curInputColor) ?>"><input class="form-control" type="text" name="ui_input_color" id="ua-input-color" value="<?= ua_ts_h($curInputColor) ?>"></div></div>
                <div class="ua-field"><label>لون نص الإدخال</label><div class="ua-color-row"><input type="color" id="ua-input-text-color-picker" value="<?= ua_ts_h($curInputTextColor) ?>"><input class="form-control" type="text" name="ui_input_text_color" id="ua-input-text-color" value="<?= ua_ts_h($curInputTextColor) ?>"></div></div>
                <div class="ua-field"><label>لون رأس الجدول</label><div class="ua-color-row"><input type="color" id="ua-table-head-color-picker" value="<?= ua_ts_h($curTableHeadColor) ?>"><input class="form-control" type="text" name="ui_table_head_color" id="ua-table-head-color" value="<?= ua_ts_h($curTableHeadColor) ?>"></div></div>
                <div class="ua-field"><label>لون صفوف الجدول</label><div class="ua-color-row"><input type="color" id="ua-table-row-color-picker" value="<?= ua_ts_h($curTableRowColor) ?>"><input class="form-control" type="text" name="ui_table_row_color" id="ua-table-row-color" value="<?= ua_ts_h($curTableRowColor) ?>"></div></div>
                <div class="ua-field"><label>لون الصف البديل</label><div class="ua-color-row"><input type="color" id="ua-table-row-alt-color-picker" value="<?= ua_ts_h($curTableRowAltColor) ?>"><input class="form-control" type="text" name="ui_table_row_alt_color" id="ua-table-row-alt-color" value="<?= ua_ts_h($curTableRowAltColor) ?>"></div></div>
                <div class="ua-field"><label>لون القوائم</label><div class="ua-color-row"><input type="color" id="ua-menu-color-picker" value="<?= ua_ts_h($curMenuColor) ?>"><input class="form-control" type="text" name="ui_menu_color" id="ua-menu-color" value="<?= ua_ts_h($curMenuColor) ?>"></div></div>
                <div class="ua-field"><label>لون النوافذ المنبثقة</label><div class="ua-color-row"><input type="color" id="ua-modal-color-picker" value="<?= ua_ts_h($curModalColor) ?>"><input class="form-control" type="text" name="ui_modal_color" id="ua-modal-color" value="<?= ua_ts_h($curModalColor) ?>"></div></div>
                <div class="ua-field"><label>لون الرسائل العامة</label><div class="ua-color-row"><input type="color" id="ua-alert-color-picker" value="<?= ua_ts_h($curAlertColor) ?>"><input class="form-control" type="text" name="ui_alert_color" id="ua-alert-color" value="<?= ua_ts_h($curAlertColor) ?>"></div></div>
                <div class="ua-field"><label>لون رسائل الحماية</label><div class="ua-color-row"><input type="color" id="ua-security-alert-color-picker" value="<?= ua_ts_h($curSecurityAlertColor) ?>"><input class="form-control" type="text" name="ui_security_alert_color" id="ua-security-alert-color" value="<?= ua_ts_h($curSecurityAlertColor) ?>"></div></div>
              </div>
              <div class="ua-two-cols">
                <div class="ua-field">
                  <label>شفافية البطاقات <b id="ua-surface-alpha-val"><?= (int)$curSurfaceAlpha ?></b>%</label>
                  <input class="form-range" type="range" min="30" max="96" step="1" name="ui_surface_alpha" id="ua-surface-alpha" value="<?= (int)$curSurfaceAlpha ?>">
                </div>
                <div class="ua-field">
                  <label>شفافية القوائم <b id="ua-menu-alpha-val"><?= (int)$curMenuAlpha ?></b>%</label>
                  <input class="form-range" type="range" min="30" max="96" step="1" name="ui_menu_alpha" id="ua-menu-alpha" value="<?= (int)$curMenuAlpha ?>">
                </div>
              </div>
            </section>

            <section class="ua-studio-panel">
              <h2>القياسات والتموضع</h2>
              <div class="ua-two-cols">
                <div class="ua-field">
                  <label>عرض الصفحة</label>
                  <select class="form-select" name="ui_page_max_width" id="ua-page-max-width">
                    <?php foreach ($pageWidths as $k => $v): ?>
                      <option value="<?= ua_ts_h($k) ?>" <?= $curPageMaxWidth === $k ? 'selected' : '' ?>><?= ua_ts_h($v) ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="ua-field">
                  <label>المسافات</label>
                  <select class="form-select" name="ui_spacing_scale" id="ua-spacing-scale">
                    <?php foreach ($spacingScales as $k => $v): ?>
                      <option value="<?= ua_ts_h($k) ?>" <?= $curSpacingScale === $k ? 'selected' : '' ?>><?= ua_ts_h($v) ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
              </div>
              <div class="ua-field">
                <label>ارتفاع مربعات الإدخال <b id="ua-control-height-val"><?= (int)$curControlHeight ?></b></label>
                <input class="form-range" type="range" min="32" max="54" step="1" name="ui_control_height" id="ua-control-height" value="<?= (int)$curControlHeight ?>">
              </div>
              <div class="ua-field">
                <label>ارتفاع صفوف الجداول <b id="ua-table-row-height-val"><?= (int)$curTableRowHeight ?></b></label>
                <input class="form-range" type="range" min="36" max="64" step="1" name="ui_table_row_height" id="ua-table-row-height" value="<?= (int)$curTableRowHeight ?>">
              </div>
            </section>

            <section class="ua-studio-panel">
              <h2>الحواف والإطار</h2>
              <div class="ua-field">
                <label>استدارة الزوايا <b id="ua-radius-val"><?= (int)$curRadius ?></b></label>
                <input class="form-range" type="range" min="6" max="30" step="1" name="ui_radius" id="ua-radius" value="<?= (int)$curRadius ?>">
              </div>
              <div class="ua-two-cols">
                <div class="ua-field">
                  <label>شكل الإطار</label>
                  <select class="form-select" name="ui_border_style" id="ua-border-style">
                    <?php foreach ($borderStyles as $k => $v): ?>
                      <option value="<?= ua_ts_h($k) ?>" <?= $curBorderStyle === $k ? 'selected' : '' ?>><?= ua_ts_h($v) ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="ua-field">
                  <label>سماكة الإطار</label>
                  <input class="form-control" type="number" min="1" max="3" name="ui_border_width" id="ua-border-width" value="<?= (int)$curBorderWidth ?>">
                </div>
              </div>
              <div class="ua-field">
                <label>لون الإطار</label>
                <div class="ua-color-row">
                  <input type="color" id="ua-border-color-picker" value="<?= ua_ts_h($curBorderColor !== '' ? $curBorderColor : '#d1d5db') ?>">
                  <input class="form-control" type="text" name="ui_border_color" id="ua-border-color" value="<?= ua_ts_h($curBorderColor) ?>" placeholder="لون القالب الافتراضي">
                </div>
              </div>
              <div class="ua-two-cols">
                <div class="ua-field">
                  <label>نمط الظل</label>
                  <select class="form-select" name="ui_card_style" id="ua-card-style">
                    <?php foreach ($cardStyles as $k => $v): ?>
                      <option value="<?= ua_ts_h($k) ?>" <?= $curCardStyle === $k ? 'selected' : '' ?>><?= ua_ts_h($v) ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="ua-field">
                  <label>كثافة الواجهة</label>
                  <select class="form-select" name="ui_density" id="ua-density">
                    <option value="comfy" <?= $curDensity === 'comfy' ? 'selected' : '' ?>>مريحة</option>
                    <option value="compact" <?= $curDensity === 'compact' ? 'selected' : '' ?>>مضغوطة</option>
                  </select>
                </div>
              </div>
              <div class="ua-field">
                <label>السايدبار</label>
                <select class="form-select" name="ui_sidebar" id="ua-sidebar">
                  <option value="hover" <?= $curSidebar === 'hover' ? 'selected' : '' ?>>توسع عند المرور</option>
                  <option value="pinned" <?= $curSidebar === 'pinned' ? 'selected' : '' ?>>مثبت</option>
                  <option value="compact" <?= $curSidebar === 'compact' ? 'selected' : '' ?>>أيقونات فقط</option>
                </select>
              </div>
            </section>
          </aside>
        </div>
      </form>
    <?php endif; ?>
  </section>
</div>

<?php
$ua_theme_token_map = [];
if (function_exists('ua_theme_design_tokens')) {
  foreach (array_keys($themes) as $ua_theme_id) {
    $ua_theme_token_map[$ua_theme_id] = ua_theme_design_tokens((string)$ua_theme_id);
  }
}
$ua_theme_token_json = json_encode($ua_theme_token_map, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
if (!is_string($ua_theme_token_json) || $ua_theme_token_json === '') $ua_theme_token_json = '{}';
?>
<script>
(() => {
  const root = document.documentElement;
  const body = document.body;
  const themeLink = document.getElementById('ua-theme-css');
  const $ = (id) => document.getElementById(id);
  const themeTokens = <?= $ua_theme_token_json ?>;
  const setVar = (name, value) => root.style.setProperty(name, value);
  const normalizeHex = (value) => {
    value = (value || '').trim();
    if (!value) return '';
    if (value[0] !== '#') value = '#' + value;
    return /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(value) ? value : '';
  };
  const alpha = (value) => Math.max(30, Math.min(96, parseInt(value || '80', 10))) / 100;

  function applyThemeCss(cssPath){
    if (!themeLink) return;
    if (!cssPath) {
      themeLink.removeAttribute('href');
      themeLink.setAttribute('disabled', 'disabled');
      return;
    }
    themeLink.removeAttribute('disabled');
    themeLink.setAttribute('href', cssPath + (cssPath.includes('?') ? '&' : '?') + 'pv=' + Date.now());
  }

  function syncColor(textId, pickerId, vars){
    const text = $(textId);
    const picker = $(pickerId);
    if (!text || !picker) return;
    const apply = () => {
      const hex = normalizeHex(text.value);
      if (hex) {
        picker.value = hex.length === 4 ? '#' + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3] : hex;
        vars(hex);
      }
    };
    picker.addEventListener('input', () => { text.value = picker.value; apply(); });
    text.addEventListener('input', apply);
    apply();
  }

  const tokenVars = {
    ui_accent: '--ua-accent',
    ui_text_color: '--ua-text',
    ui_border_color: '--ua-border',
    ui_body_bg: '--ua-theme-page-bg',
    ui_surface_color: '--ua-theme-surface',
    ui_surface_alt_color: '--ua-theme-surface-2',
    ui_topbar_color: '--ua-theme-topbar',
    ui_windowbar_color: '--ua-theme-windowbar',
    ui_sidebar_color: '--ua-theme-sidebar',
    ui_sidebar_item_color: '--ua-theme-sidebar-item',
    ui_input_color: '--ua-theme-input',
    ui_input_text_color: '--ua-theme-input-text',
    ui_table_head_color: '--ua-theme-table-head',
    ui_table_row_color: '--ua-theme-table-row',
    ui_table_row_alt_color: '--ua-theme-table-row-alt',
    ui_menu_color: '--ua-theme-menu',
    ui_modal_color: '--ua-theme-modal',
    ui_alert_color: '--ua-theme-alert',
    ui_security_alert_color: '--ua-theme-security-alert'
  };

  function applyTextColor(value){
    setVar('--ua-text', value);
    setVar('--ua-template-text', value);
    setVar('--ua-ds-text', value);
  }

  function applyBorderColor(value){
    setVar('--ua-border', value);
    setVar('--ua-border-strong', value);
    setVar('--ua-template-border', value);
    setVar('--ua-template-border-strong', value);
    setVar('--ua-ds-line', value);
    setVar('--ua-ds-line-strong', value);
    setVar('--ua-clean-frame-line', value);
  }

  function setFormField(name, value){
    const field = document.querySelector('[name="' + name + '"]');
    if (!field || value == null || value === '') return;
    field.value = value;
    field.dispatchEvent(new Event('input', { bubbles:true }));
    field.dispatchEvent(new Event('change', { bubbles:true }));
  }

  function applyThemePreset(themeId){
    const tokens = themeTokens[themeId] || {};
    Object.entries(tokens).forEach(([key, value]) => {
      setFormField(key, value);
      if (tokenVars[key]) setVar(tokenVars[key], value);
    });
    if (tokens.ui_text_color) applyTextColor(tokens.ui_text_color);
    if (tokens.ui_accent) setVar('--ua-accent-2', 'color-mix(in srgb,' + tokens.ui_accent + ' 75%, white)');
    if (tokens.ui_border_color) applyBorderColor(tokens.ui_border_color);
    if (tokens.ui_body_bg) setVar('--ua-bg', tokens.ui_body_bg);
    if (tokens.ui_sidebar_color) {
      setVar('--sb3-bg1', tokens.ui_sidebar_color);
      setVar('--sb3-bg2', tokens.ui_sidebar_color);
    }
    if (tokens.ui_sidebar_item_color) setVar('--sb3-panel', tokens.ui_sidebar_item_color);
    applyFont();
  }

  function applyThemeIdentity(themeId){
    const themeClassPrefix = 'ua-theme-';
    Array.from(body.classList).forEach((className) => {
      if (className.indexOf(themeClassPrefix) === 0) body.classList.remove(className);
    });
    const safeThemeId = String(themeId || '').toLowerCase().replace(/[^a-z0-9_-]+/g, '-');
    if (safeThemeId) body.classList.add(themeClassPrefix + safeThemeId);
    body.dataset.uaTheme = safeThemeId;
  }

  document.querySelectorAll('input[name="ui_theme"]').forEach((radio) => {
    radio.addEventListener('change', () => {
      applyThemeIdentity(radio.value);
      applyThemeCss(radio.getAttribute('data-theme-css') || '');
      applyThemePreset(radio.value);
    });
  });

  const mode = $('ua-design-mode');
  if (mode) mode.addEventListener('change', () => {
    body.classList.toggle('ua-design-v2', mode.value === 'v2');
    body.classList.toggle('ua-design-legacy', mode.value !== 'v2');
  });

  const fontMap = {
    system: 'system-ui, -apple-system, "Segoe UI", Tahoma, Arial, sans-serif',
    cairo: '"Cairo", "Noto Sans Arabic", "Segoe UI", Tahoma, Arial, sans-serif',
    tajawal: '"Tajawal", "Noto Sans Arabic", "Segoe UI", Tahoma, Arial, sans-serif',
    noto_kufi: '"Noto Kufi Arabic", "Noto Sans Arabic", Tahoma, Arial, sans-serif',
    ibm_plex_arabic: '"IBM Plex Sans Arabic", "Noto Sans Arabic", "Segoe UI", Tahoma, Arial, sans-serif',
    almarai: '"Almarai", "Noto Sans Arabic", "Segoe UI", Tahoma, Arial, sans-serif',
    tahoma: 'Tahoma, Arial, sans-serif',
    segoe: '"Segoe UI", Tahoma, Arial, sans-serif',
    arial: 'Arial, Tahoma, sans-serif'
  };
  function bindRange(id, outId, unit, cb){
    const input = $(id), out = $(outId);
    if (!input) return;
    const apply = () => {
      if (out) out.textContent = input.value;
      if (cb) cb(input.value + (unit || ''));
    };
    input.addEventListener('input', apply);
    apply();
  }

  const fontFamily = $('ua-font-family');
  const fontWeight = $('ua-font-weight');
  const applyFont = () => {
    if (fontFamily) {
      const family = fontMap[fontFamily.value] || fontMap.system;
      setVar('--ua-font-family', family);
      setVar('--ua-template-font-family', family);
      if (body) {
        body.style.setProperty('--ua-font-family', family);
        body.style.setProperty('--ua-template-font-family', family);
      }
    }
    if (fontWeight) {
      const weight = fontWeight.value || '700';
      setVar('--ua-font-weight', weight);
      setVar('--ua-template-font-weight', weight);
      if (body) {
        body.style.setProperty('--ua-font-weight', weight);
        body.style.setProperty('--ua-template-font-weight', weight);
      }
    }
  };
  if (fontFamily) fontFamily.addEventListener('change', applyFont);
  if (fontWeight) fontWeight.addEventListener('change', applyFont);
  applyFont();

  bindRange('ua-font-size', 'ua-font-size-val', 'px', (v) => { setVar('--ua-font-size', v); root.style.fontSize = v; });
  bindRange('ua-title-font-size', 'ua-title-font-size-val', 'px', (v) => { setVar('--ua-title-font-size', v); setVar('--ua-fs-page-title', v); });
  bindRange('ua-bar-font-size', 'ua-bar-font-size-val', 'px', (v) => setVar('--ua-bar-font-size', v));
  bindRange('ua-input-font-size', 'ua-input-font-size-val', 'px', (v) => { setVar('--ua-input-font-size', v); setVar('--ua-fs-control', v); });
  bindRange('ua-table-font-size', 'ua-table-font-size-val', 'px', (v) => { setVar('--ua-table-font-size', v); setVar('--ua-fs-table', v); });
  bindRange('ua-menu-font-size', 'ua-menu-font-size-val', 'px', (v) => { setVar('--ua-menu-font-size', v); setVar('--ua-fs-menu', v); });
  bindRange('ua-modal-font-size', 'ua-modal-font-size-val', 'px', (v) => setVar('--ua-modal-font-size', v));
  bindRange('ua-radius', 'ua-radius-val', 'px', (v) => setVar('--ua-radius', v));
  bindRange('ua-control-height', 'ua-control-height-val', 'px', (v) => setVar('--ua-ds-control-h', v));
  bindRange('ua-table-row-height', 'ua-table-row-height-val', 'px', (v) => setVar('--ua-ds-table-row-h', v));
  bindRange('ua-surface-alpha', 'ua-surface-alpha-val', '', (v) => {
    const a = alpha(v).toFixed(2);
    setVar('--ua-ds-surface', 'rgba(7,18,30,' + a + ')');
    setVar('--ua-ds-surface-2', 'rgba(9,28,42,' + Math.max(.30, alpha(v) - .08).toFixed(2) + ')');
  });
  bindRange('ua-menu-alpha', 'ua-menu-alpha-val', '', (v) => setVar('--ua-ds-menu', 'rgba(5,21,30,' + alpha(v).toFixed(2) + ')'));

  syncColor('ua-accent', 'ua-accent-picker', (hex) => {
    setVar('--ua-accent', hex);
    setVar('--ua-accent-2', 'color-mix(in srgb,' + hex + ' 75%, white)');
  });
  syncColor('ua-text-color', 'ua-text-color-picker', applyTextColor);
  syncColor('ua-border-color', 'ua-border-color-picker', applyBorderColor);

  syncColor('ua-body-bg', 'ua-body-bg-picker', (hex) => { setVar('--ua-theme-page-bg', hex); setVar('--ua-bg', hex); });
  syncColor('ua-surface-color', 'ua-surface-color-picker', (hex) => setVar('--ua-theme-surface', hex));
  syncColor('ua-surface-alt-color', 'ua-surface-alt-color-picker', (hex) => setVar('--ua-theme-surface-2', hex));
  syncColor('ua-topbar-color', 'ua-topbar-color-picker', (hex) => setVar('--ua-theme-topbar', hex));
  syncColor('ua-windowbar-color', 'ua-windowbar-color-picker', (hex) => setVar('--ua-theme-windowbar', hex));
  syncColor('ua-sidebar-color', 'ua-sidebar-color-picker', (hex) => { setVar('--ua-theme-sidebar', hex); setVar('--sb3-bg1', hex); setVar('--sb3-bg2', hex); });
  syncColor('ua-sidebar-item-color', 'ua-sidebar-item-color-picker', (hex) => { setVar('--ua-theme-sidebar-item', hex); setVar('--sb3-panel', hex); });
  syncColor('ua-input-color', 'ua-input-color-picker', (hex) => setVar('--ua-theme-input', hex));
  syncColor('ua-input-text-color', 'ua-input-text-color-picker', (hex) => setVar('--ua-theme-input-text', hex));
  syncColor('ua-table-head-color', 'ua-table-head-color-picker', (hex) => setVar('--ua-theme-table-head', hex));
  syncColor('ua-table-row-color', 'ua-table-row-color-picker', (hex) => setVar('--ua-theme-table-row', hex));
  syncColor('ua-table-row-alt-color', 'ua-table-row-alt-color-picker', (hex) => setVar('--ua-theme-table-row-alt', hex));
  syncColor('ua-menu-color', 'ua-menu-color-picker', (hex) => setVar('--ua-theme-menu', hex));
  syncColor('ua-modal-color', 'ua-modal-color-picker', (hex) => setVar('--ua-theme-modal', hex));
  syncColor('ua-alert-color', 'ua-alert-color-picker', (hex) => setVar('--ua-theme-alert', hex));
  syncColor('ua-security-alert-color', 'ua-security-alert-color-picker', (hex) => setVar('--ua-theme-security-alert', hex));

  const borderStyle = $('ua-border-style');
  const borderWidth = $('ua-border-width');
  const applyBorder = () => {
    if (borderStyle) setVar('--ua-border-style', borderStyle.value || 'solid');
    if (borderWidth) setVar('--ua-border-width', (borderWidth.value || '1') + 'px');
  };
  if (borderStyle) borderStyle.addEventListener('change', applyBorder);
  if (borderWidth) borderWidth.addEventListener('input', applyBorder);
  applyBorder();

  const cardStyle = $('ua-card-style');
  const applyShadow = () => {
    const map = { soft:'0 14px 34px rgba(0,0,0,.22)', flat:'none', strong:'0 24px 64px rgba(0,0,0,.34)' };
    if (cardStyle) setVar('--ua-card-shadow', map[cardStyle.value] || map.soft);
  };
  if (cardStyle) cardStyle.addEventListener('change', applyShadow);
  applyShadow();

  const density = $('ua-density');
  if (density) density.addEventListener('change', () => {
    body.classList.toggle('ua-density-compact', density.value === 'compact');
    body.classList.toggle('ua-density-comfy', density.value !== 'compact');
  });

  const spacing = $('ua-spacing-scale');
  if (spacing) spacing.addEventListener('change', () => {
    body.classList.remove('ua-spacing-tight','ua-spacing-normal','ua-spacing-roomy');
    body.classList.add('ua-spacing-' + spacing.value);
  });

  const reset = $('ua-reset');
  if (reset) reset.addEventListener('click', () => {
    const form = $('uaThemeStudioForm');
    if (!form) return;
    form.querySelector('[name="ui_design_mode"]').value = 'v2';
    const defTheme = form.querySelector('[name="ui_theme"][value="armoury_dark"]');
    if (defTheme) defTheme.checked = true;
    form.querySelector('[name="ui_accent"]').value = '';
    form.querySelector('[name="ui_text_color"]').value = '';
    form.querySelector('[name="ui_border_color"]').value = '';
    form.querySelector('[name="ui_density"]').value = 'comfy';
    form.querySelector('[name="ui_sidebar"]').value = 'hover';
    form.querySelector('[name="ui_font_family"]').value = 'system';
    form.querySelector('[name="ui_font_weight"]').value = '700';
    form.querySelector('[name="ui_font_size"]').value = '15';
    form.querySelector('[name="ui_radius"]').value = '16';
    form.querySelector('[name="ui_border_style"]').value = 'solid';
    form.querySelector('[name="ui_border_width"]').value = '1';
    form.querySelector('[name="ui_card_style"]').value = 'soft';
    form.querySelector('[name="ui_page_max_width"]').value = 'none';
    form.querySelector('[name="ui_spacing_scale"]').value = 'normal';
    form.querySelector('[name="ui_control_height"]').value = '40';
    form.querySelector('[name="ui_table_row_height"]').value = '46';
    form.querySelector('[name="ui_surface_alpha"]').value = '82';
    form.querySelector('[name="ui_menu_alpha"]').value = '76';
    form.querySelector('[name="ui_body_bg"]').value = '#07111f';
    form.querySelector('[name="ui_surface_color"]').value = '#071827';
    form.querySelector('[name="ui_surface_alt_color"]').value = '#0a2431';
    form.querySelector('[name="ui_topbar_color"]').value = '#071a28';
    form.querySelector('[name="ui_windowbar_color"]').value = '#071624';
    form.querySelector('[name="ui_sidebar_color"]').value = '#063238';
    form.querySelector('[name="ui_sidebar_item_color"]').value = '#0b4a4d';
    form.querySelector('[name="ui_input_color"]').value = '#061d2a';
    form.querySelector('[name="ui_input_text_color"]').value = '#eaf0ff';
    form.querySelector('[name="ui_table_head_color"]').value = '#08373e';
    form.querySelector('[name="ui_table_row_color"]').value = '#062532';
    form.querySelector('[name="ui_table_row_alt_color"]').value = '#082e3a';
    form.querySelector('[name="ui_menu_color"]').value = '#061923';
    form.querySelector('[name="ui_modal_color"]').value = '#071827';
    form.querySelector('[name="ui_alert_color"]').value = '#102b3f';
    form.querySelector('[name="ui_security_alert_color"]').value = '#44151d';
    form.querySelector('[name="ui_title_font_size"]').value = '22';
    form.querySelector('[name="ui_bar_font_size"]').value = '12';
    form.querySelector('[name="ui_input_font_size"]').value = '13';
    form.querySelector('[name="ui_table_font_size"]').value = '13';
    form.querySelector('[name="ui_menu_font_size"]').value = '13';
    form.querySelector('[name="ui_modal_font_size"]').value = '14';
    form.querySelectorAll('input,select').forEach((el) => el.dispatchEvent(new Event(el.type === 'range' ? 'input' : 'change', { bubbles:true })));
  });
})();
</script>

<?php include __DIR__ . '/footer.php'; ?>
