<?php
declare(strict_types=1);

require_once dirname(__DIR__, 2) . '/common/app_guard.php';
require_once dirname(__DIR__, 2) . '/common/url.php';
require_once dirname(__DIR__, 2) . '/common/config.php';
checkAppAccess();

function h(string $s): string
{
    return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

$roles = array_map('strtolower', (array)($_SESSION['roles'] ?? []));
$isAdmin = in_array('administradores', $roles, true);
if (!$isAdmin) {
    http_response_code(403);
    die('Acceso denegado');
}

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
if (empty($_SESSION['csrf_theme_color_manager'])) {
    $_SESSION['csrf_theme_color_manager'] = bin2hex(random_bytes(16));
}

// Referencia original del estilo corporativo.
const REF_PRIMARY = '#067B3B';
const REF_PRIMARY_DARK = '#045026';
const REF_PRIMARY_LIGHT = '#EAF8F0';
const REF_ACCENT = '#0A9D4C';
const REF_BG_SIDEBAR = '#03351A';
const REF_BORDER_DARK = '#056332';
const REF_BG_SIDEBAR_HEADER = 'rgba(0, 0, 0, 0.30)';
const REF_BORDER_FOCUS_ALPHA = 0.30;

function normalize_hex(string $hex, string $fallback = REF_PRIMARY): string
{
    $hex = trim($hex);
    if ($hex === '') {
        return strtoupper($fallback);
    }
    if ($hex[0] !== '#') {
        $hex = '#' . $hex;
    }
    if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $hex)) {
        return strtoupper($fallback);
    }
    return strtoupper($hex);
}

function hex_to_rgb(string $hex): array
{
    $hex = ltrim($hex, '#');
    return [
        hexdec(substr($hex, 0, 2)),
        hexdec(substr($hex, 2, 2)),
        hexdec(substr($hex, 4, 2)),
    ];
}

function rgb_to_hex(int $r, int $g, int $b): string
{
    $r = max(0, min(255, $r));
    $g = max(0, min(255, $g));
    $b = max(0, min(255, $b));
    return sprintf('#%02X%02X%02X', $r, $g, $b);
}

function rgb_to_hsl(int $r, int $g, int $b): array
{
    $r /= 255; $g /= 255; $b /= 255;
    $max = max($r, $g, $b);
    $min = min($r, $g, $b);
    $h = 0.0;
    $s = 0.0;
    $l = ($max + $min) / 2;

    if ($max !== $min) {
        $d = $max - $min;
        $s = $l > 0.5 ? $d / (2 - $max - $min) : $d / ($max + $min);
        switch ($max) {
            case $r:
                $h = ($g - $b) / $d + ($g < $b ? 6 : 0);
                break;
            case $g:
                $h = ($b - $r) / $d + 2;
                break;
            default:
                $h = ($r - $g) / $d + 4;
                break;
        }
        $h /= 6;
    }

    return [$h * 360, $s * 100, $l * 100];
}

function hue_to_rgb(float $p, float $q, float $t): float
{
    if ($t < 0) $t += 1;
    if ($t > 1) $t -= 1;
    if ($t < 1 / 6) return $p + ($q - $p) * 6 * $t;
    if ($t < 1 / 2) return $q;
    if ($t < 2 / 3) return $p + ($q - $p) * (2 / 3 - $t) * 6;
    return $p;
}

function hsl_to_rgb(float $h, float $s, float $l): array
{
    $h = fmod(($h + 360.0), 360.0) / 360.0;
    $s = max(0.0, min(100.0, $s)) / 100.0;
    $l = max(0.0, min(100.0, $l)) / 100.0;

    if ($s == 0.0) {
        $v = (int) round($l * 255);
        return [$v, $v, $v];
    }

    $q = $l < 0.5 ? $l * (1 + $s) : $l + $s - $l * $s;
    $p = 2 * $l - $q;

    $r = hue_to_rgb($p, $q, $h + 1 / 3);
    $g = hue_to_rgb($p, $q, $h);
    $b = hue_to_rgb($p, $q, $h - 1 / 3);

    return [(int) round($r * 255), (int) round($g * 255), (int) round($b * 255)];
}

function delta_from_reference(string $refTarget, string $refPrimary = REF_PRIMARY): array
{
    [$ph, $ps, $pl] = rgb_to_hsl(...hex_to_rgb($refPrimary));
    [$th, $ts, $tl] = rgb_to_hsl(...hex_to_rgb($refTarget));

    $dh = $th - $ph;
    while ($dh > 180) $dh -= 360;
    while ($dh < -180) $dh += 360;

    return [$dh, $ts - $ps, $tl - $pl];
}

function apply_hsl_delta(string $newPrimary, array $delta): string
{
    [$h, $s, $l] = rgb_to_hsl(...hex_to_rgb($newPrimary));
    [$dh, $ds, $dl] = $delta;
    [$r, $g, $b] = hsl_to_rgb($h + $dh, $s + $ds, $l + $dl);
    return rgb_to_hex($r, $g, $b);
}

function rgba_from_hex(string $hex, float $alpha): string
{
    [$r, $g, $b] = hex_to_rgb($hex);
    return sprintf('rgba(%d, %d, %d, %.2f)', $r, $g, $b, $alpha);
}

function build_palette(string $primary): array
{
    $primary = normalize_hex($primary);

    return [
        'primary' => $primary,
        'primary-dark' => apply_hsl_delta($primary, delta_from_reference(REF_PRIMARY_DARK)),
        'primary-light' => apply_hsl_delta($primary, delta_from_reference(REF_PRIMARY_LIGHT)),
        'accent' => apply_hsl_delta($primary, delta_from_reference(REF_ACCENT)),
        'bg-sidebar' => apply_hsl_delta($primary, delta_from_reference(REF_BG_SIDEBAR)),
        'border-dark' => apply_hsl_delta($primary, delta_from_reference(REF_BORDER_DARK)),
        'bg-sidebar-header' => REF_BG_SIDEBAR_HEADER,
        'border-focus' => rgba_from_hex($primary, REF_BORDER_FOCUS_ALPHA),
    ];
}

function theme_vars_path(): string
{
    return dirname(__DIR__, 2) . '/styles/css/theme-vars.css';
}

function read_current_primary(): string
{
    $path = theme_vars_path();
    if (!is_file($path)) {
        return REF_PRIMARY;
    }
    $content = file_get_contents($path);
    if ($content === false) {
        return REF_PRIMARY;
    }
    if (preg_match('/--primary:\s*(#[0-9A-Fa-f]{6})\s*;/', $content, $m)) {
        return normalize_hex($m[1]);
    }
    return REF_PRIMARY;
}

function render_theme_vars(array $palette): string
{
    return ":root {\n"
        . "    --primary: {$palette['primary']};\n"
        . "    --primary-dark: {$palette['primary-dark']};\n"
        . "    --primary-light: {$palette['primary-light']};\n"
        . "    --accent: {$palette['accent']};\n"
        . "    --bg-sidebar: {$palette['bg-sidebar']};\n"
        . "    --bg-sidebar-header: {$palette['bg-sidebar-header']};\n"
        . "    --border-dark: {$palette['border-dark']};\n"
        . "    --border-focus: {$palette['border-focus']};\n"
        . "}\n";
}

function write_theme_vars(array $palette): void
{
    $css = render_theme_vars($palette);
    $path = theme_vars_path();
    if (file_put_contents($path, $css) === false) {
        throw new RuntimeException('No se pudo escribir styles/css/theme-vars.css');
    }
}

function redirect_after_theme_change(): void
{
    $target = app_url('dashboard.php?open=' . rawurlencode('base/theme-color-manager/index.php') . '&full_reload=1&ts=' . time());
    header('Content-Type: text/html; charset=UTF-8');
    echo '<!DOCTYPE html><html lang="es"><head><meta charset="UTF-8"><title>Actualizando…</title></head><body>';
    echo '<script>';
    echo 'var target=' . json_encode($target, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . ';';
    echo 'if (window.top && window.top !== window) { window.top.location.href = target; } else { window.location.href = target; }';
    echo '</script>';
    echo '<noscript><meta http-equiv="refresh" content="0;url=' . h($target) . '"></noscript>';
    echo '</body></html>';
    exit;
}

$currentPrimary = read_current_primary();
$currentPalette = build_palette($currentPrimary);
$previewPrimary = $currentPrimary;
$previewPalette = $currentPalette;
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = (string)($_POST['csrf'] ?? '');
    if (!$csrf || !hash_equals((string)$_SESSION['csrf_theme_color_manager'], $csrf)) {
        $error = 'Token CSRF no válido.';
    } else {
        $action = (string)($_POST['action'] ?? 'preview');
        $primary = normalize_hex((string)($_POST['primary_color'] ?? REF_PRIMARY));
        $previewPrimary = $primary;
        $previewPalette = build_palette($primary);

        if ($action === 'save') {
            try {
                write_theme_vars($previewPalette);
                $_SESSION['theme_color_flash_message'] = 'La paleta se ha guardado correctamente en theme-vars.css.';
                redirect_after_theme_change();
            } catch (Throwable $e) {
                $error = $e->getMessage();
            }
        } elseif ($action === 'reset') {
            try {
                $previewPrimary = REF_PRIMARY;
                $previewPalette = build_palette(REF_PRIMARY);
                write_theme_vars($previewPalette);
                $_SESSION['theme_color_flash_message'] = 'Se ha restaurado la paleta original del estilo corporativo.';
                redirect_after_theme_change();
            } catch (Throwable $e) {
                $error = $e->getMessage();
            }
        }
    }
}

$swatches = [
    '#067B3B', '#006E90', '#1D4ED8', '#6D28D9', '#A21CAF', '#BE123C', '#C2410C', '#B45309',
    '#0F766E', '#166534', '#1E40AF', '#7C3AED', '#9333EA', '#C026D3', '#DC2626', '#EA580C',
    '#334155', '#111827', '#4F46E5', '#0284C7', '#0D9488', '#65A30D', '#CA8A04', '#E11D48'
];
?>
<!DOCTYPE html>
<html lang="es" class="app-html" <?= intranet_theme_html_attr(); ?>>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Gestor de colores</title>
  <?= intranet_theme_bootstrap_script_tag(); ?>
  <link rel="stylesheet" href="<?= h(asset_url('styles/css/style.css')) ?>">
  <style>
    .tc-shell { width: min(1360px, calc(100% - 28px)); margin: 14px auto 24px; }
    .tc-hero {
      background: linear-gradient(135deg, var(--primary-dark), var(--primary));
      color: #fff; border-radius: 18px; padding: 24px 26px; margin-bottom: 18px;
      box-shadow: 0 16px 36px rgba(15,23,42,.16);
    }
    .tc-hero-top { display:flex; justify-content:space-between; align-items:center; gap:16px; flex-wrap:wrap; }
    .tc-title { margin:0; font-size:2rem; font-weight:800; letter-spacing:-.02em; }
    .tc-subtitle { margin:8px 0 0; max-width:900px; line-height:1.5; color:rgba(255,255,255,.93); }
    .tc-back {
      display:inline-flex; align-items:center; gap:8px; text-decoration:none; color:#fff; font-weight:700;
      padding:10px 14px; border-radius:12px; background:rgba(255,255,255,.14); border:1px solid rgba(255,255,255,.24);
    }
    .tc-grid { display:grid; grid-template-columns: 1.05fr .95fr; gap:18px; }
    .tc-card {
      background:#fff; border:1px solid var(--border-light); border-radius:18px; padding:22px;
      box-shadow:0 10px 24px rgba(15,23,42,.06);
    }
    .tc-card h2 { margin:0 0 8px; font-size:1.3rem; }
    .tc-muted { color:var(--text-muted); line-height:1.5; }
    .tc-alert { border-radius:14px; padding:14px 16px; margin-bottom:16px; font-weight:700; }
    .tc-alert-ok { background:var(--success-bg); color:var(--success-text); border:1px solid var(--success-border); }
    .tc-alert-err { background:var(--error-bg); color:var(--error-text); border:1px solid var(--error-border); }
    .tc-form-grid { display:grid; grid-template-columns: 220px 1fr; gap:18px; align-items:start; }
    .tc-picker-wrap {
      background:linear-gradient(180deg, #fff 0%, #f8fafc 100%);
      border:1px solid var(--border-light); border-radius:18px; padding:16px; text-align:center;
    }
    .tc-color-input {
      -webkit-appearance:none; appearance:none; width:100%; height:160px; border:0; background:none; padding:0; cursor:pointer;
    }
    .tc-color-input::-webkit-color-swatch-wrapper { padding:0; }
    .tc-color-input::-webkit-color-swatch { border:none; border-radius:14px; }
    .tc-color-input::-moz-color-swatch { border:none; border-radius:14px; }
    .tc-hex-row { display:flex; gap:10px; margin-top:12px; }
    .tc-hex-row input { flex:1; text-transform:uppercase; letter-spacing:.06em; font-weight:700; }
    .tc-swatch-grid { display:grid; grid-template-columns: repeat(8, 1fr); gap:10px; margin-top:16px; }
    .tc-swatch {
      width:100%; aspect-ratio:1; border-radius:12px; border:2px solid rgba(255,255,255,.9); cursor:pointer;
      box-shadow:0 4px 10px rgba(15,23,42,.12);
    }
    .tc-swatch:hover { transform:translateY(-1px); }
    .tc-actions { display:flex; gap:10px; flex-wrap:wrap; margin-top:18px; }
    .tc-btn {
      appearance:none; border:0; border-radius:12px; padding:12px 16px; font-weight:800; cursor:pointer;
      display:inline-flex; align-items:center; justify-content:center; gap:8px;
    }
    .tc-btn-primary { background:var(--primary); color:#fff; }
    .tc-btn-primary:hover { background:var(--primary-dark); }
    .tc-btn-secondary { background:#f5f7fb; color:var(--text-main); border:1px solid var(--border-light); }
    .tc-preview-box { border:1px solid var(--border-light); border-radius:18px; overflow:hidden; }
    .tc-preview-top { padding:18px; color:#fff; }
    .tc-preview-top h3 { margin:0 0 8px; }
    .tc-preview-content { padding:18px; background:#fff; }
    .tc-preview-grid { display:grid; grid-template-columns: repeat(2, minmax(0,1fr)); gap:12px; margin-top:14px; }
    .tc-chip { border-radius:14px; padding:14px; color:#fff; font-weight:700; min-height:82px; display:flex; flex-direction:column; justify-content:space-between; }
    .tc-code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size:.86rem; }
    .tc-sidebar-demo { border-radius:14px; overflow:hidden; border:1px solid var(--border-light); margin-top:16px; }
    .tc-sidebar-head { padding:14px 16px; color:#fff; font-weight:800; }
    .tc-sidebar-body { padding:14px 16px; color:#fff; }
    .tc-note { margin-top:12px; padding:12px 14px; border-radius:12px; background:#f8fafc; border:1px solid var(--border-light); color:#334155; }
    .tc-form label { display:block; font-weight:800; margin-bottom:6px; }
    .tc-form small { color:var(--text-muted); }
    @media (max-width: 980px) {
      .tc-grid, .tc-form-grid { grid-template-columns: 1fr; }
      .tc-swatch-grid { grid-template-columns: repeat(6, 1fr); }
      .tc-shell { width: calc(100% - 20px); }
    }
  </style>
</head>
<body class="app-body">
  <div class="tc-shell">
    <section class="tc-hero">
      <div class="tc-hero-top">
        <div>
          <h1 class="tc-title">Gestor de colores de la intranet</h1>
          <p class="tc-subtitle">
            Elige un color principal y el plugin recalculará automáticamente toda la paleta derivada manteniendo las mismas relaciones del estilo corporativo original.
          </p>
        </div>
        <a class="tc-back" href="<?= h(asset_url('dashboard.php')) ?>" target="_top">← Volver al inicio</a>
      </div>
    </section>

    <?php if ($message): ?>
      <div class="tc-alert tc-alert-ok"><?php echo h($message); ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
      <div class="tc-alert tc-alert-err"><?php echo h($error); ?></div>
    <?php endif; ?>

    <div class="tc-grid">
      <section class="tc-card tc-form">
        <h2>Elegir color principal</h2>
        <p class="tc-muted">Tienes selector completo de color, edición manual del HEX y una paleta rápida como en cualquier editor gráfico.</p>

        <form method="post" id="themeColorForm">
          <input type="hidden" name="csrf" value="<?php echo h((string)$_SESSION['csrf_theme_color_manager']); ?>">
          <div class="tc-form-grid">
            <div class="tc-picker-wrap">
              <input class="tc-color-input" type="color" id="primary_color_picker" value="<?php echo h($previewPrimary); ?>">
              <div class="tc-hex-row">
                <input class="form-control" type="text" id="primary_color_text" name="primary_color" value="<?php echo h($previewPrimary); ?>" pattern="^#[0-9A-Fa-f]{6}$" maxlength="7">
              </div>
            </div>

            <div>
              <label for="primary_color_text">Color principal</label>
              <p class="tc-muted" style="margin-top:0;">Usa el selector grande, escribe el HEX manualmente o elige un color rápido de la paleta.</p>

              <div class="tc-swatch-grid" id="swatchGrid">
                <?php foreach ($swatches as $swatch): ?>
                  <button class="tc-swatch" type="button" data-color="<?php echo h($swatch); ?>" style="background: <?php echo h($swatch); ?>;" title="<?php echo h($swatch); ?>"></button>
                <?php endforeach; ?>
              </div>

              <div class="tc-note">
                <strong>Cómo calcula la paleta:</strong> toma el color principal original y conserva las diferencias relativas de tono, saturación y luminosidad para <code>--primary-dark</code>, <code>--primary-light</code>, <code>--accent</code>, <code>--bg-sidebar</code> y <code>--border-dark</code>.
              </div>

              <div class="tc-actions">
                <button class="tc-btn tc-btn-secondary" type="submit" name="action" value="preview">Previsualizar</button>
                <button class="tc-btn tc-btn-primary" type="submit" name="action" value="save">Guardar cambios</button>
                <button class="tc-btn tc-btn-secondary" type="submit" name="action" value="reset" onclick="return confirm('¿Restaurar la paleta original?');">Restaurar original</button>
              </div>
            </div>
          </div>
        </form>
      </section>

      <section class="tc-card">
        <h2>Vista previa</h2>
        <p class="tc-muted">Así quedaría la identidad visual principal con el color seleccionado.</p>

        <div class="tc-preview-box">
          <div class="tc-preview-top" style="background: linear-gradient(135deg, <?php echo h($previewPalette['primary-dark']); ?>, <?php echo h($previewPalette['primary']); ?>);">
            <h3>Cabecera principal</h3>
            <div class="tc-code">primary: <?php echo h($previewPalette['primary']); ?> · accent: <?php echo h($previewPalette['accent']); ?></div>
          </div>
          <div class="tc-preview-content">
            <div class="tc-preview-grid">
              <div class="tc-chip" style="background: <?php echo h($previewPalette['primary']); ?>;">
                <span>Primary</span>
                <span class="tc-code"><?php echo h($previewPalette['primary']); ?></span>
              </div>
              <div class="tc-chip" style="background: <?php echo h($previewPalette['primary-dark']); ?>;">
                <span>Primary dark</span>
                <span class="tc-code"><?php echo h($previewPalette['primary-dark']); ?></span>
              </div>
              <div class="tc-chip" style="background: <?php echo h($previewPalette['accent']); ?>;">
                <span>Accent</span>
                <span class="tc-code"><?php echo h($previewPalette['accent']); ?></span>
              </div>
              <div class="tc-chip" style="background: <?php echo h($previewPalette['border-dark']); ?>;">
                <span>Border dark</span>
                <span class="tc-code"><?php echo h($previewPalette['border-dark']); ?></span>
              </div>
            </div>

            <div class="tc-sidebar-demo">
              <div class="tc-sidebar-head" style="background: <?php echo h($previewPalette['bg-sidebar-header']); ?>; background-color: <?php echo h($previewPalette['bg-sidebar']); ?>;">Sidebar header</div>
              <div class="tc-sidebar-body" style="background: <?php echo h($previewPalette['bg-sidebar']); ?>;">
                Sidebar · navegación · menús
              </div>
            </div>

            <div class="tc-note" style="margin-top:16px; background: <?php echo h($previewPalette['primary-light']); ?>; border-color: <?php echo h($previewPalette['border-dark']); ?>;">
              <strong>Primary light:</strong> <?php echo h($previewPalette['primary-light']); ?><br>
              <strong>Border focus:</strong> <?php echo h($previewPalette['border-focus']); ?>
            </div>
          </div>
        </div>
      </section>
    </div>
  </div>

  <script>
    (function () {
      const picker = document.getElementById('primary_color_picker');
      const text = document.getElementById('primary_color_text');
      const swatches = document.querySelectorAll('.tc-swatch');

      function normalizeHex(v) {
        v = (v || '').trim().toUpperCase();
        if (v && v[0] !== '#') v = '#' + v;
        return v;
      }

      picker.addEventListener('input', function () {
        text.value = normalizeHex(this.value);
      });

      text.addEventListener('input', function () {
        const val = normalizeHex(this.value);
        if (/^#[0-9A-F]{6}$/.test(val)) {
          picker.value = val;
        }
      });

      swatches.forEach(btn => {
        btn.addEventListener('click', function () {
          const color = this.getAttribute('data-color');
          picker.value = color;
          text.value = color;
        });
      });
    })();
  </script>
</body>
</html>
