<?php
/**
 * Name: Auto Dark Mode
 * Description: Add dark mode toggle to your site with automatic theme switching based on system preferences and floating button for visitors to switch between modes
 * Category: Utilities
 * Icon: -
 * Beta: true
 * Disabled: true
 * UseCases: [
 *   {
 *     "title": "Add Useful Functionality",
 *     "description": "Extend WordPress with helpful tools that make site management easier."
 *   },
 *   {
 *     "title": "Save Time",
 *     "description": "Automate or simplify tasks that would otherwise require manual work or additional tools."
 *   }
 * ]
 * Added: 2025-09-04
 * Tags: dark-mode, theme, toggle, accessibility, ux, night-mode
 * WhereToFind: {
 *   "location": "Frontend (Dark Mode Toggle)",
 *   "url": "/",
 *   "instructions": "Look for dark mode toggle button on frontend",
 *   "newTab": true
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardAutoDarkMode {
    
    public function __construct() {
        add_action('wp_head', [$this, 'add_dark_mode_styles'], 1);
        add_action('wp_footer', [$this, 'add_dark_mode_script']);
        add_action('wp_footer', [$this, 'add_toggle_button']);
    }

    /**
     * Register data locations for this module
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_auto-dark-mode_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => []
        ];
    }
    
    /**
     * Render settings panel for Auto Dark Mode
     *
     * Displays comprehensive settings interface for dark mode configuration with:
     * - Toggle button position selector (bottom-right, bottom-left, top-right, top-left)
     * - Default mode dropdown (Auto/System, Light, Dark) with detailed explanations
     * - Remember user choice checkbox for localStorage persistence
     * - Transition speed selector (Fast, Normal, Slow) with timing values
     * - Usage instructions panel with step-by-step guidance
     * - Form table layout for clean, organized presentation
     *
     * The interface provides complete dark mode configuration following WordPress admin
     * UI conventions. The default mode supports three options: Auto (respects system
     * dark mode preference via prefers-color-scheme media query), Light (always starts
     * light), or Dark (always starts dark). The remember choice option uses localStorage
     * to persist user's manual toggle selections across sessions. Transition speed controls
     * CSS animation duration for smooth theme switching. The floating toggle button appears
     * on all frontend pages with moon/sun icons for intuitive mode switching. The module
     * automatically generates CSS variables for dark mode colors and applies them via
     * JavaScript based on user preference. Essential for modern websites offering
     * accessibility and user experience enhancements through theme customization.
     *
     * @param array $settings Current module settings with 'toggle_position', 'default_mode', 'remember_choice', 'transition_speed' keys
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        $toggle_position = isset($settings['toggle_position']) ? $settings['toggle_position'] : 'bottom-right';
        $default_mode = isset($settings['default_mode']) ? $settings['default_mode'] : 'auto';
        $remember_choice = isset($settings['remember_choice']) ? $settings['remember_choice'] : 'yes';
        $transition_speed = isset($settings['transition_speed']) ? $settings['transition_speed'] : 'normal';
        ?>
        <input type="hidden" name="module" value="<?php echo esc_attr('auto-dark-mode'); ?>">

        <h3><?php esc_html_e('Dark Mode Settings', 'wpswitchboard'); ?></h3>
        <p class="sb-sp-description"><?php esc_html_e('Configure how dark mode appears and behaves on your site.', 'wpswitchboard'); ?></p>

        <table class="form-table">
            <tr>
                <th scope="row">
                    <label for="setting_toggle_position"><?php esc_html_e('Toggle Button Position', 'wpswitchboard'); ?></label>
                </th>
                <td>
                    <select name="setting_toggle_position" id="setting_toggle_position" class="sb-sp-select">
                        <option value="bottom-right" <?php selected($toggle_position, 'bottom-right'); ?>><?php esc_html_e('Bottom Right (Recommended)', 'wpswitchboard'); ?></option>
                        <option value="bottom-left" <?php selected($toggle_position, 'bottom-left'); ?>><?php esc_html_e('Bottom Left', 'wpswitchboard'); ?></option>
                        <option value="top-right" <?php selected($toggle_position, 'top-right'); ?>><?php esc_html_e('Top Right', 'wpswitchboard'); ?></option>
                        <option value="top-left" <?php selected($toggle_position, 'top-left'); ?>><?php esc_html_e('Top Left', 'wpswitchboard'); ?></option>
                    </select>
                    <p class="sb-sp-description"><?php esc_html_e('Where to display the floating dark mode toggle button on your site.', 'wpswitchboard'); ?></p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="setting_default_mode"><?php esc_html_e('Default Mode', 'wpswitchboard'); ?></label>
                </th>
                <td>
                    <select name="setting_default_mode" id="setting_default_mode" class="sb-sp-select">
                        <option value="auto" <?php selected($default_mode, 'auto'); ?>><?php esc_html_e('Auto (Follow System Preference) - Recommended', 'wpswitchboard'); ?></option>
                        <option value="light" <?php selected($default_mode, 'light'); ?>><?php esc_html_e('Light Mode', 'wpswitchboard'); ?></option>
                        <option value="dark" <?php selected($default_mode, 'dark'); ?>><?php esc_html_e('Dark Mode', 'wpswitchboard'); ?></option>
                    </select>
                    <p class="sb-sp-description">
                        <strong><?php esc_html_e('Auto:', 'wpswitchboard'); ?></strong> <?php esc_html_e('Automatically matches user\'s system dark mode setting', 'wpswitchboard'); ?><br>
                        <strong><?php esc_html_e('Light:', 'wpswitchboard'); ?></strong> <?php esc_html_e('Always starts in light mode (users can toggle)', 'wpswitchboard'); ?><br>
                        <strong><?php esc_html_e('Dark:', 'wpswitchboard'); ?></strong> <?php esc_html_e('Always starts in dark mode (users can toggle)', 'wpswitchboard'); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="setting_remember_choice"><?php esc_html_e('Remember User Choice', 'wpswitchboard'); ?></label>
                </th>
                <td>
                    <label class="sb-sp-label">
                        <input type="checkbox" name="setting_remember_choice" id="setting_remember_choice" value="yes" <?php checked($remember_choice, 'yes'); ?> class="sb-sp-checkbox">
                        <?php esc_html_e('Save user\'s dark mode preference in their browser', 'wpswitchboard'); ?>
                    </label>
                    <p class="sb-sp-description"><?php esc_html_e('When enabled, the user\'s choice (light/dark) will be remembered across page visits.', 'wpswitchboard'); ?></p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="setting_transition_speed"><?php esc_html_e('Transition Speed', 'wpswitchboard'); ?></label>
                </th>
                <td>
                    <select name="setting_transition_speed" id="setting_transition_speed" class="sb-sp-select">
                        <option value="fast" <?php selected($transition_speed, 'fast'); ?>><?php esc_html_e('Fast (0.2s)', 'wpswitchboard'); ?></option>
                        <option value="normal" <?php selected($transition_speed, 'normal'); ?>><?php esc_html_e('Normal (0.3s) - Recommended', 'wpswitchboard'); ?></option>
                        <option value="slow" <?php selected($transition_speed, 'slow'); ?>><?php esc_html_e('Slow (0.5s)', 'wpswitchboard'); ?></option>
                    </select>
                    <p class="sb-sp-description"><?php esc_html_e('Animation speed when switching between light and dark modes.', 'wpswitchboard'); ?></p>
                </td>
            </tr>
        </table>

        <div class="sb-sp-alert sb-sp-alert-info">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('How to Use', 'wpswitchboard'); ?></h4>
            <ol class="sb-sp-my-3">
                <li><?php esc_html_e('Save these settings', 'wpswitchboard'); ?></li>
                <li><?php esc_html_e('Visit your website', 'wpswitchboard'); ?></li>
                <li><?php esc_html_e('Look for the floating toggle button (moon or sun icon)', 'wpswitchboard'); ?></li>
                <li><?php esc_html_e('Click it to switch between light and dark modes', 'wpswitchboard'); ?></li>
            </ol>
            <p class="sb-sp-mb-0"><strong><?php esc_html_e('Note:', 'wpswitchboard'); ?></strong> <?php esc_html_e('The toggle button will appear on all pages of your site. Admins and visitors can both use it.', 'wpswitchboard'); ?></p>
        </div>
        <?php
    }
    
    private function get_settings() {
        $modules = get_option('switchboard_modules', []);
        return isset($modules['auto-dark-mode']['settings']) ? $modules['auto-dark-mode']['settings'] : [];
    }
    
    public function add_dark_mode_styles() {
        $settings = $this->get_settings();
        $speed = isset($settings['transition_speed']) ? $settings['transition_speed'] : 'normal';
        
        $speeds = [
            'fast' => '0.2s',
            'normal' => '0.3s',
            'slow' => '0.5s'
        ];
        $transition = $speeds[$speed] ?? '0.3s';
        ?>
        <style id="switchboard-dark-mode-styles">
        :root {
            --dark-mode-transition: <?php echo esc_attr($transition); ?>;
        }
        
        * {
            transition: background-color var(--dark-mode-transition) ease, 
                        color var(--dark-mode-transition) ease,
                        border-color var(--dark-mode-transition) ease !important;
        }
        
        body.dark-mode {
            background-color: #1a1a1a !important;
            color: #e0e0e0 !important;
        }
        
        body.dark-mode a {
            color: #6ea8fe !important;
        }
        
        body.dark-mode a:hover {
            color: #9ec5fe !important;
        }
        
        body.dark-mode h1, body.dark-mode h2, body.dark-mode h3, 
        body.dark-mode h4, body.dark-mode h5, body.dark-mode h6 {
            color: #f8f9fa !important;
        }
        
        body.dark-mode p, body.dark-mode li, body.dark-mode span, body.dark-mode div {
            color: #e0e0e0 !important;
        }
        
        body.dark-mode .site-header, body.dark-mode header, body.dark-mode nav {
            background-color: #2d2d2d !important;
            border-color: #404040 !important;
        }
        
        body.dark-mode .site-footer, body.dark-mode footer {
            background-color: #0d0d0d !important;
            border-color: #404040 !important;
        }
        
        body.dark-mode article, body.dark-mode .post, 
        body.dark-mode .entry, body.dark-mode .content {
            background-color: #242424 !important;
            border-color: #404040 !important;
        }
        
        body.dark-mode .sidebar, body.dark-mode aside, body.dark-mode .widget {
            background-color: #2d2d2d !important;
            border-color: #404040 !important;
        }
        
        body.dark-mode input, body.dark-mode textarea, body.dark-mode select {
            background-color: #2d2d2d !important;
            color: #e0e0e0 !important;
            border-color: #404040 !important;
        }
        
        body.dark-mode button, body.dark-mode .button, body.dark-mode .btn {
            background-color: #404040 !important;
            color: #e0e0e0 !important;
            border-color: #555 !important;
        }
        
        body.dark-mode button:hover, body.dark-mode .button:hover, body.dark-mode .btn:hover {
            background-color: #555 !important;
        }
        
        body.dark-mode table {
            background-color: #242424 !important;
            border-color: #404040 !important;
        }
        
        body.dark-mode th {
            background-color: #2d2d2d !important;
            color: #f8f9fa !important;
        }
        
        body.dark-mode td {
            border-color: #404040 !important;
        }
        
        body.dark-mode blockquote {
            background-color: #2d2d2d !important;
            border-left-color: #6ea8fe !important;
        }
        
        body.dark-mode code, body.dark-mode pre {
            background-color: #0d0d0d !important;
            color: #f8f9fa !important;
            border-color: #404040 !important;
        }
        
        body.dark-mode img {
            opacity: 0.9;
        }
        
        body.dark-mode img:hover {
            opacity: 1;
        }
        </style>
        <?php
    }
    
    public function add_dark_mode_script() {
        $settings = $this->get_settings();
        $default_mode = isset($settings['default_mode']) ? $settings['default_mode'] : 'auto';
        $remember = isset($settings['remember_choice']) ? $settings['remember_choice'] : 'yes';

        // Prepare i18n strings for JavaScript
        $i18n = [
            'switchToLight' => __('Switch to light mode', 'wpswitchboard'),
            'switchToDark' => __('Switch to dark mode', 'wpswitchboard')
        ];
        ?>
        <script id="switchboard-dark-mode-script">
        (function() {
            const defaultMode = '<?php echo esc_js($default_mode); ?>';
            const rememberChoice = <?php echo $remember === 'yes' ? 'true' : 'false'; ?>;
            const i18n = <?php echo wp_json_encode($i18n); ?>;

            function initDarkMode() {
                let mode = defaultMode;

                if (rememberChoice && localStorage.getItem('switchboardDarkMode')) {
                    mode = localStorage.getItem('switchboardDarkMode');
                } else if (defaultMode === 'auto') {
                    mode = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
                }

                if (mode === 'dark') {
                    document.body.classList.add('dark-mode');
                }
            }

            function toggleDarkMode() {
                const isDark = document.body.classList.toggle('dark-mode');

                if (rememberChoice) {
                    localStorage.setItem('switchboardDarkMode', isDark ? 'dark' : 'light');
                }

                updateToggleIcon(isDark);
            }

            function updateToggleIcon(isDark) {
                const button = document.getElementById('switchboard-dark-mode-toggle');
                if (button) {
                    button.innerHTML = isDark ? '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg>' : '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg>';
                    button.setAttribute('aria-label', isDark ? i18n.switchToLight : i18n.switchToDark);
                    button.setAttribute('title', isDark ? i18n.switchToLight : i18n.switchToDark);
                }
            }
            
            initDarkMode();
            
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', function() {
                    const button = document.getElementById('switchboard-dark-mode-toggle');
                    if (button) {
                        button.addEventListener('click', toggleDarkMode);
                        updateToggleIcon(document.body.classList.contains('dark-mode'));
                    }
                });
            } else {
                const button = document.getElementById('switchboard-dark-mode-toggle');
                if (button) {
                    button.addEventListener('click', toggleDarkMode);
                    updateToggleIcon(document.body.classList.contains('dark-mode'));
                }
            }
            
            if (defaultMode === 'auto') {
                window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function(e) {
                    if (!rememberChoice || !localStorage.getItem('switchboardDarkMode')) {
                        if (e.matches) {
                            document.body.classList.add('dark-mode');
                        } else {
                            document.body.classList.remove('dark-mode');
                        }
                        updateToggleIcon(e.matches);
                    }
                });
            }
            
            window.switchboardToggleDarkMode = toggleDarkMode;
        })();
        </script>
        <?php
    }
    
    public function add_toggle_button() {
        $settings = $this->get_settings();
        $position = isset($settings['toggle_position']) ? $settings['toggle_position'] : 'bottom-right';
        
        $positions = [
            'bottom-right' => 'bottom: 20px; right: 20px;',
            'bottom-left' => 'bottom: 20px; left: 20px;',
            'top-right' => 'top: 20px; right: 20px;',
            'top-left' => 'top: 20px; left: 20px;'
        ];
        
        $position_style = $positions[$position] ?? $positions['bottom-right'];
        ?>
        <button
            id="switchboard-dark-mode-toggle"
            aria-label="<?php echo esc_attr__('Toggle dark mode', 'wpswitchboard'); ?>"
            title="<?php echo esc_attr__('Toggle dark mode', 'wpswitchboard'); ?>"
            style="
                position: fixed;
                <?php echo esc_attr($position_style); ?>
                z-index: 9999;
                width: 50px;
                height: 50px;
                border-radius: 50%;
                border: 2px solid #ddd;
                background: #fff;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                cursor: pointer;
                font-size: 24px;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all 0.3s ease;
                padding: 0;
            "
            onmouseover="this.style.transform='scale(1.1)'; this.style.boxShadow='0 6px 16px rgba(0,0,0,0.2)';"
            onmouseout="this.style.transform='scale(1)'; this.style.boxShadow='0 4px 12px rgba(0,0,0,0.15)';"
        >
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg>
        </button>
        
        <style>
        body.dark-mode #switchboard-dark-mode-toggle {
            background: #2d2d2d !important;
            border-color: #555 !important;
        }
        
        #switchboard-dark-mode-toggle:focus {
            outline: 2px solid #6ea8fe;
            outline-offset: 2px;
        }
        
        #switchboard-dark-mode-toggle:active {
            transform: scale(0.95) !important;
        }
        </style>
        <?php
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardAutoDarkMode();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
