<?php

namespace auctionforge\inc\controllers;

class StyleSettings
{
    const SLUG_PAGE = 'bidspirit_style';
    const OPTION_KEY = 'bidspirit_styles';

    private static $defaults = null;

    public static function getDefaults()
    {
        if (self::$defaults !== null) {
            return self::$defaults;
        }

        self::$defaults = [
            // 1. Global / Base
            'global_primary_font'       => 'Roboto, sans-serif',
            'global_secondary_font'     => 'Roboto, sans-serif',
            'global_accent_color'       => '#f37725',
            'global_body_text_color'    => '#000000',
            'global_muted_text_color'   => '#7a838f',
            'global_loader_color'       => '#003f91',

            // 2. Buttons - Primary
            'btn_primary_bg'            => '#000000',
            'btn_primary_text'          => '#ffffff',
            'btn_primary_border'        => '#000000',
            'btn_primary_hover_bg'      => '#ffffff',
            'btn_primary_hover_text'    => '#000000',
            'btn_primary_hover_border'  => '#000000',
            'btn_primary_font_size'     => '14',
            'btn_primary_text_transform'=> 'uppercase',

            // 3. Buttons - Outline
            'btn_outline_bg'            => '#ffffff',
            'btn_outline_text'          => '#000000',
            'btn_outline_border'        => '#000000',
            'btn_outline_hover_bg'      => '#000000',
            'btn_outline_hover_text'    => '#ffffff',

            // 4. Buttons - Login & Register
            'btn_login_bg'              => '#f37725',
            'btn_login_text'            => '#ffffff',
            'btn_login_hover_bg'        => '#f37725',
            'btn_register_bg'           => '#282828',
            'btn_register_text'         => '#ffffff',
            'btn_register_hover_bg'     => '#282828',

            // 5. Buttons - Bid
            'btn_bid_bg'                => '#000000',
            'btn_bid_text'              => '#ffffff',
            'btn_bid_font_size'         => '18',

            // 6. Auction Cards
            'auction_card_shadow'       => 'medium',
            'auction_card_shadow_color' => 'rgba(0,0,0,0.16)',
            'auction_card_hover_shadow' => 'heavy',
            'auction_card_hover_shadow_color' => 'rgba(0,0,0,0.14)',
            'auction_card_bg'           => '#ffffff',
            'auction_card_title_color'  => '#282828',
            'auction_card_title_size'   => '24',
            'auction_card_date_color'   => '#000000',

            // 7. Catalog/Lot Cards
            'lot_card_hover_shadow'     => 'medium',
            'lot_card_hover_shadow_color'=> 'rgba(0,0,0,0.14)',
            'lot_title_color'           => '#f37725',
            'lot_title_font_size'       => '16',
            'lot_desc_color'            => '#7a838f',
            'lot_desc_border_color'     => '#e2e2e2',
            'lot_tool_text_color'       => '#a1a1a1',
            'lot_price_color'           => '#000000',
            'lot_lead_bg'               => '#003f91',
            'lot_lead_text'             => '#ffffff',

            // 8. Countdown
            'countdown_bg'              => '#e34444',
            'countdown_text_color'      => '#ffffff',
            'countdown_number_size'     => '28',
            'countdown_label_size'      => '14',

            // 9. Single Lot Page
            'single_heading_color'      => '#f37725',
            'single_heading_size'       => '30',
            'single_panel_shadow'       => 'medium',
            'single_panel_shadow_color' => 'rgba(0,0,0,0.16)',
            'single_panel_bg'           => '#ffffff',
            'single_commission_color'   => '#757575',
            'single_notice_bg'          => '#3e3e3e',
            'single_notice_text'        => '#ffffff',
            'single_bid_highlight'      => '#f37725',

            // 10. Modals
            'modal_overlay_bg'          => 'rgba(0,0,0,0.4)',
            'modal_container_bg'        => '#ffffff',
            'modal_shadow'              => 'medium',
            'modal_shadow_color'        => 'rgba(0,0,0,0.16)',
            'modal_title_color'         => '#000000',
            'modal_title_size'          => '32',
            'modal_link_color'          => '#636363',
            'modal_btn_bg'              => '#00449e',

            // 11. Wishlist Heart
            'heart_outline_color'       => '#cc0000',
            'heart_active_color'        => '#cc0000',
            'heart_bg'                  => 'rgba(255,255,255,0.7)',

            // 12. Forms
            'form_input_border'         => '#707070',
            'form_input_bg'             => '#ffffff',
            'form_input_text'           => '#000000',
            'form_input_font_size'      => '18',
            'form_label_color'          => '#7a838f',
            'form_error_color'          => '#ff0000',
            'form_checkbox_border'      => '#000000',
        ];

        return self::$defaults;
    }

    public static function getSections()
    {
        return [
            'global' => [
                'label' => 'Global / Base',
                'icon'  => 'dashicons-admin-site',
                'fields' => [
                    'global_primary_font'    => ['label' => 'Primary Font Family',    'type' => 'font'],
                    'global_secondary_font'  => ['label' => 'Secondary Font Family',  'type' => 'font'],
                    'global_accent_color'    => ['label' => 'Primary Accent Color',   'type' => 'color'],
                    'global_body_text_color' => ['label' => 'Body Text Color',        'type' => 'color'],
                    'global_muted_text_color'=> ['label' => 'Muted Text Color',       'type' => 'color'],
                    'global_loader_color'    => ['label' => 'Loader Spinner Color',   'type' => 'color'],
                ],
            ],
            'btn_primary' => [
                'label' => 'Buttons - Primary',
                'icon'  => 'dashicons-button',
                'fields' => [
                    'btn_primary_bg'            => ['label' => 'Background Color',       'type' => 'color'],
                    'btn_primary_text'          => ['label' => 'Text Color',             'type' => 'color'],
                    'btn_primary_border'        => ['label' => 'Border Color',           'type' => 'color'],
                    'btn_primary_hover_bg'      => ['label' => 'Hover Background',       'type' => 'color'],
                    'btn_primary_hover_text'    => ['label' => 'Hover Text Color',       'type' => 'color'],
                    'btn_primary_hover_border'  => ['label' => 'Hover Border Color',     'type' => 'color'],
                    'btn_primary_font_size'     => ['label' => 'Font Size (px)',          'type' => 'number', 'min' => 10, 'max' => 36],
                    'btn_primary_text_transform'=> ['label' => 'Text Transform',         'type' => 'select', 'options' => ['none' => 'None', 'uppercase' => 'Uppercase', 'lowercase' => 'Lowercase', 'capitalize' => 'Capitalize']],
                ],
            ],
            'btn_outline' => [
                'label' => 'Buttons - Outline',
                'icon'  => 'dashicons-button',
                'fields' => [
                    'btn_outline_bg'          => ['label' => 'Background Color',       'type' => 'color'],
                    'btn_outline_text'        => ['label' => 'Text Color',             'type' => 'color'],
                    'btn_outline_border'      => ['label' => 'Border Color',           'type' => 'color'],
                    'btn_outline_hover_bg'    => ['label' => 'Hover Background',       'type' => 'color'],
                    'btn_outline_hover_text'  => ['label' => 'Hover Text Color',       'type' => 'color'],
                ],
            ],
            'btn_login' => [
                'label' => 'Buttons - Login & Register',
                'icon'  => 'dashicons-admin-users',
                'fields' => [
                    'btn_login_bg'            => ['label' => 'Login Background',        'type' => 'color'],
                    'btn_login_text'          => ['label' => 'Login Text Color',        'type' => 'color'],
                    'btn_login_hover_bg'      => ['label' => 'Login Hover Background',  'type' => 'color'],
                    'btn_register_bg'         => ['label' => 'Register Background',     'type' => 'color'],
                    'btn_register_text'       => ['label' => 'Register Text Color',     'type' => 'color'],
                    'btn_register_hover_bg'   => ['label' => 'Register Hover Background','type' => 'color'],
                ],
            ],
            'btn_bid' => [
                'label' => 'Buttons - Bid',
                'icon'  => 'dashicons-money-alt',
                'fields' => [
                    'btn_bid_bg'        => ['label' => 'Background Color',  'type' => 'color'],
                    'btn_bid_text'      => ['label' => 'Text Color',        'type' => 'color'],
                    'btn_bid_font_size' => ['label' => 'Font Size (px)',     'type' => 'number', 'min' => 12, 'max' => 36],
                ],
            ],
            'auction_cards' => [
                'label' => 'Auction Cards',
                'icon'  => 'dashicons-format-gallery',
                'fields' => [
                    'auction_card_shadow'            => ['label' => 'Card Shadow',          'type' => 'shadow'],
                    'auction_card_shadow_color'      => ['label' => 'Card Shadow Color',    'type' => 'color_alpha'],
                    'auction_card_hover_shadow'      => ['label' => 'Card Hover Shadow',    'type' => 'shadow'],
                    'auction_card_hover_shadow_color'=> ['label' => 'Hover Shadow Color',   'type' => 'color_alpha'],
                    'auction_card_bg'                => ['label' => 'Card Background',      'type' => 'color'],
                    'auction_card_title_color'       => ['label' => 'Title Color',          'type' => 'color'],
                    'auction_card_title_size'        => ['label' => 'Title Font Size (px)', 'type' => 'number', 'min' => 14, 'max' => 48],
                    'auction_card_date_color'        => ['label' => 'Date Text Color',      'type' => 'color'],
                ],
            ],
            'lot_cards' => [
                'label' => 'Catalog / Lot Cards',
                'icon'  => 'dashicons-grid-view',
                'fields' => [
                    'lot_card_hover_shadow'       => ['label' => 'Card Hover Shadow',       'type' => 'shadow'],
                    'lot_card_hover_shadow_color' => ['label' => 'Hover Shadow Color',      'type' => 'color_alpha'],
                    'lot_title_color'             => ['label' => 'Lot Title Color',         'type' => 'color'],
                    'lot_title_font_size'         => ['label' => 'Lot Title Font Size (px)','type' => 'number', 'min' => 12, 'max' => 36],
                    'lot_desc_color'              => ['label' => 'Description Color',       'type' => 'color'],
                    'lot_desc_border_color'       => ['label' => 'Description Border',      'type' => 'color'],
                    'lot_tool_text_color'          => ['label' => 'Tool/Subtitle Color',    'type' => 'color'],
                    'lot_price_color'             => ['label' => 'Price Color',             'type' => 'color'],
                    'lot_lead_bg'                 => ['label' => 'Leading Bidder BG',       'type' => 'color'],
                    'lot_lead_text'               => ['label' => 'Leading Bidder Text',     'type' => 'color'],
                ],
            ],
            'countdown' => [
                'label' => 'Countdown Timer',
                'icon'  => 'dashicons-clock',
                'fields' => [
                    'countdown_bg'          => ['label' => 'Background Color', 'type' => 'color'],
                    'countdown_text_color'  => ['label' => 'Text Color',       'type' => 'color'],
                    'countdown_number_size' => ['label' => 'Number Size (px)', 'type' => 'number', 'min' => 14, 'max' => 72],
                    'countdown_label_size'  => ['label' => 'Label Size (px)',  'type' => 'number', 'min' => 10, 'max' => 36],
                ],
            ],
            'single_lot' => [
                'label' => 'Item / Single Lot Page',
                'icon'  => 'dashicons-format-image',
                'fields' => [
                    'single_heading_color'      => ['label' => 'Heading Color',         'type' => 'color'],
                    'single_heading_size'       => ['label' => 'Heading Size (px)',      'type' => 'number', 'min' => 18, 'max' => 60],
                    'single_panel_shadow'       => ['label' => 'Bid Panel Shadow',       'type' => 'shadow'],
                    'single_panel_shadow_color' => ['label' => 'Panel Shadow Color',     'type' => 'color_alpha'],
                    'single_panel_bg'           => ['label' => 'Panel Background',       'type' => 'color'],
                    'single_commission_color'   => ['label' => 'Commission Text Color',  'type' => 'color'],
                    'single_notice_bg'          => ['label' => 'Notice Bar Background',  'type' => 'color'],
                    'single_notice_text'        => ['label' => 'Notice Bar Text Color',  'type' => 'color'],
                    'single_bid_highlight'      => ['label' => 'Bid Price Highlight',    'type' => 'color'],
                ],
            ],
            'modals' => [
                'label' => 'Modals',
                'icon'  => 'dashicons-editor-expand',
                'fields' => [
                    'modal_overlay_bg'     => ['label' => 'Overlay Background',     'type' => 'color_alpha'],
                    'modal_container_bg'   => ['label' => 'Container Background',   'type' => 'color'],
                    'modal_shadow'         => ['label' => 'Container Shadow',        'type' => 'shadow'],
                    'modal_shadow_color'   => ['label' => 'Shadow Color',            'type' => 'color_alpha'],
                    'modal_title_color'    => ['label' => 'Title Color',             'type' => 'color'],
                    'modal_title_size'     => ['label' => 'Title Font Size (px)',     'type' => 'number', 'min' => 18, 'max' => 60],
                    'modal_link_color'     => ['label' => 'Footer Link Color',       'type' => 'color'],
                    'modal_btn_bg'         => ['label' => 'Primary Button BG',       'type' => 'color'],
                ],
            ],
            'wishlist' => [
                'label' => 'Wishlist Heart',
                'icon'  => 'dashicons-heart',
                'fields' => [
                    'heart_outline_color' => ['label' => 'Heart Outline Color', 'type' => 'color'],
                    'heart_active_color'  => ['label' => 'Heart Active Fill',   'type' => 'color'],
                    'heart_bg'            => ['label' => 'Heart Background',    'type' => 'color_alpha'],
                ],
            ],
            'forms' => [
                'label' => 'Forms & Inputs',
                'icon'  => 'dashicons-editor-table',
                'fields' => [
                    'form_input_border'    => ['label' => 'Input Border Color',   'type' => 'color'],
                    'form_input_bg'        => ['label' => 'Input Background',     'type' => 'color'],
                    'form_input_text'      => ['label' => 'Input Text Color',     'type' => 'color'],
                    'form_input_font_size' => ['label' => 'Input Font Size (px)', 'type' => 'number', 'min' => 12, 'max' => 24],
                    'form_label_color'     => ['label' => 'Label Color',          'type' => 'color'],
                    'form_error_color'     => ['label' => 'Error Text Color',     'type' => 'color'],
                    'form_checkbox_border' => ['label' => 'Checkbox Border Color','type' => 'color'],
                ],
            ],
        ];
    }

    public static function getFonts()
    {
        return [
            'Roboto, sans-serif'                                      => 'Roboto',
            'Arial, Helvetica, sans-serif'                            => 'Arial',
            '"Helvetica Neue", Helvetica, Arial, sans-serif'          => 'Helvetica Neue',
            'Georgia, "Times New Roman", Times, serif'                => 'Georgia',
            '"Times New Roman", Times, serif'                         => 'Times New Roman',
            'Verdana, Geneva, sans-serif'                             => 'Verdana',
            'Tahoma, Geneva, sans-serif'                              => 'Tahoma',
            '"Trebuchet MS", Helvetica, sans-serif'                   => 'Trebuchet MS',
            '"Lucida Sans", "Lucida Grande", sans-serif'              => 'Lucida Sans',
            '"Courier New", Courier, monospace'                       => 'Courier New',
            '"Palatino Linotype", "Book Antiqua", Palatino, serif'    => 'Palatino',
            'Impact, Charcoal, sans-serif'                            => 'Impact',
            '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif'         => 'Segoe UI',
            'system-ui, -apple-system, sans-serif'                    => 'System Default',
        ];
    }

    public static function getShadowPresets()
    {
        return [
            'none'   => 'None',
            'light'  => 'Light',
            'medium' => 'Medium',
            'heavy'  => 'Heavy',
        ];
    }

    public static function buildShadowValue($preset, $color = 'rgba(0,0,0,0.16)')
    {
        switch ($preset) {
            case 'none':
                return 'none';
            case 'light':
                return '0 2px 4px ' . $color;
            case 'medium':
                return '0 3px 12px ' . $color;
            case 'heavy':
                return '0 6px 20px ' . $color;
            default:
                return '0 3px 12px ' . $color;
        }
    }

    public static function getOption($key = null)
    {
        $saved = get_option(self::OPTION_KEY, []);
        $defaults = self::getDefaults();
        $merged = wp_parse_args($saved, $defaults);

        if ($key !== null) {
            return isset($merged[$key]) ? $merged[$key] : null;
        }

        return $merged;
    }

    public function init()
    {
        add_action('admin_menu', [$this, 'register_admin_page']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
        add_action('wp_ajax_bidspirit_save_styles', [$this, 'ajax_save']);
        add_action('wp_ajax_bidspirit_reset_styles', [$this, 'ajax_reset']);
        add_action('wp_ajax_bidspirit_reset_section', [$this, 'ajax_reset_section']);
    }

    public function register_admin_page()
    {
        add_submenu_page(
            'edit.php?post_type=lot',
            __('Style Settings', 'auctionforge'),
            __('Style', 'auctionforge'),
            'administrator',
            self::SLUG_PAGE,
            [$this, 'render_page']
        );
    }

    public function enqueue_admin_assets($hook)
    {
        if (strpos($hook, self::SLUG_PAGE) === false) {
            return;
        }

        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');

        wp_enqueue_style(
            'bidspirit-style-settings',
            plugin_dir_url(dirname(dirname(__FILE__))) . 'admin/assets/css/style-settings.css',
            [],
            '1.0.0'
        );

        wp_enqueue_script(
            'bidspirit-style-settings',
            plugin_dir_url(dirname(dirname(__FILE__))) . 'admin/assets/js/style-settings.js',
            ['jquery', 'wp-color-picker'],
            '1.0.0',
            true
        );

        wp_localize_script('bidspirit-style-settings', 'bsStyleSettings', [
            'ajaxUrl'  => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('bidspirit_style_nonce'),
            'defaults' => self::getDefaults(),
        ]);
    }

    public function render_page()
    {
        $styles   = self::getOption();
        $sections = self::getSections();
        $fonts    = self::getFonts();
        $shadows  = self::getShadowPresets();

        include plugin_dir_path(dirname(dirname(__FILE__))) . 'admin/view/style-settings.php';
    }

    public function ajax_save()
    {
        check_ajax_referer('bidspirit_style_nonce', 'nonce');

        if (!current_user_can('administrator')) {
            wp_send_json_error('Unauthorized');
        }

        $data = [];
        $defaults = self::getDefaults();

        if (isset($_POST['styles']) && is_array($_POST['styles'])) {
            foreach ($_POST['styles'] as $key => $value) {
                if (array_key_exists($key, $defaults)) {
                    $data[$key] = sanitize_text_field($value);
                }
            }
        }

        update_option(self::OPTION_KEY, $data);
        wp_send_json_success(['message' => 'Styles saved successfully.']);
    }

    public function ajax_reset()
    {
        check_ajax_referer('bidspirit_style_nonce', 'nonce');

        if (!current_user_can('administrator')) {
            wp_send_json_error('Unauthorized');
        }

        delete_option(self::OPTION_KEY);
        wp_send_json_success([
            'message'  => 'All styles reset to defaults.',
            'defaults' => self::getDefaults(),
        ]);
    }

    public function ajax_reset_section()
    {
        check_ajax_referer('bidspirit_style_nonce', 'nonce');

        if (!current_user_can('administrator')) {
            wp_send_json_error('Unauthorized');
        }

        $section = sanitize_text_field($_POST['section'] ?? '');
        $sections = self::getSections();

        if (!isset($sections[$section])) {
            wp_send_json_error('Invalid section');
        }

        $current  = get_option(self::OPTION_KEY, []);
        $defaults = self::getDefaults();

        foreach ($sections[$section]['fields'] as $key => $field) {
            $current[$key] = $defaults[$key];
        }

        update_option(self::OPTION_KEY, $current);
        wp_send_json_success([
            'message'  => 'Section reset to defaults.',
            'defaults' => $defaults,
        ]);
    }
}
