<?php

namespace App\Services\Ui;

use App\Models\Preferences;

class UiStyleService
{
    public function update(int $userId, array $payload): Preferences
    {
        $updates = $this->buildUpdates($payload);

        $prefs = Preferences::query()->where('user_id', $userId)->first();
        if ($prefs) {
            $prefs->fill($updates)->save();
            return $prefs->fresh();
        }

        $updates['user_id'] = $userId;
        return Preferences::query()->create($updates);
    }

    public function buildUpdates(array $payload): array
    {
        $updates = [];
        $accent = $this->sanitizePaletteKey($payload['accent'] ?? null);
        $menu = $this->sanitizePaletteKey($payload['menu'] ?? null);
        $menuBg = $this->normalizeHex($payload['menu_bg'] ?? null);
        $menuTx = $this->normalizeHex($payload['menu_text'] ?? null);
        $menuMode = $this->normalizeMenuMode($payload['menu_mode'] ?? null);

        $stylePalettes = (array) config('ui.style_palettes', []);
        $menuPalettes = (array) config('ui.menu_palettes', []);

        if ($accent !== null && (empty($stylePalettes) || array_key_exists($accent, $stylePalettes))) {
            $updates['style_color'] = $accent;
        }

        if ($menu !== null && (empty($menuPalettes) || array_key_exists($menu, $menuPalettes))) {
            $updates['menu_color'] = $menu;
            $updates['menu_custom_bg'] = null;
            $updates['menu_custom_text'] = null;
            $updates['menu_custom_mode'] = null;
        }

        if ($menu === 'custom' || $menuBg !== null || $menuTx !== null) {
            if ($menuBg === null && $menuTx === null) {
                return $updates;
            }
            $updates['menu_color'] = 'custom';
            $updates['menu_custom_bg'] = $menuBg ?: '#0F172A';
            $updates['menu_custom_text'] = $menuTx ?: '#FFFFFF';
            $updates['menu_custom_mode'] = $menuMode;
        }

        return $updates;
    }

    private function sanitizePaletteKey(?string $value): ?string
    {
        $value = trim((string) $value);
        return $value === '' ? null : $value;
    }

    private function normalizeMenuMode(?string $mode): string
    {
        $mode = strtolower(trim((string) $mode));
        if (in_array($mode, ['light', 'dark', 'auto'], true)) {
            return $mode;
        }
        return 'auto';
    }

    private function normalizeHex(?string $hex): ?string
    {
        $h = trim((string) $hex);
        if ($h === '') {
            return null;
        }
        if ($h[0] !== '#') {
            $h = '#' . $h;
        }
        if (preg_match('/^#([0-9a-fA-F]{3})$/', $h, $m)) {
            $r = $m[1][0];
            $g = $m[1][1];
            $b = $m[1][2];
            return strtoupper('#' . $r . $r . $g . $g . $b . $b);
        }
        if (preg_match('/^#([0-9a-fA-F]{6})$/', $h)) {
            return strtoupper($h);
        }
        return null;
    }
}
