<?php
/**
 * Plugin Name: Mati — Booking Inteligente
 * Plugin URI: https://localhost:3000
 * Description: Sistema de reservas con agente IA. Panel de administración 100% funcional dentro de WordPress. Conectado a mati.com vía API.
 * Version: 7.0.0
 * Author: Mati
 * License: GPL-2.0+
 * Text Domain: mati-booking
 * Domain Path: /languages
 */

if (!defined('ABSPATH')) exit;

// Load translations
add_action('plugins_loaded', function() {
    load_plugin_textdomain('mati-booking', false, dirname(plugin_basename(__FILE__)) . '/languages/');
});

define('MATI_VERSION', '7.0.0');
define('MATI_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('MATI_PLUGIN_URL', plugin_dir_url(__FILE__));
define('MATI_LOCAL_DEV', true);
define('MATI_API_URL', MATI_LOCAL_DEV ? 'http://172.19.0.1:3000/api/public/workspace' : 'https://mati.app/api/public/workspace');
define('MATI_DASHBOARD_URL', MATI_LOCAL_DEV ? 'http://localhost:3000/dashboard' : 'https://mati.app/dashboard');
define('MATI_SCRIPT_URL', MATI_LOCAL_DEV ? 'http://localhost:3000/mati-widget.min.js' : 'https://mati.app/mati-widget.min.js');
define('MATI_BROWSER_URL', MATI_LOCAL_DEV ? 'http://localhost:3000' : 'https://mati.app');
define('MATI_DEFAULT_COLOR', '#0722BC');
define('MATI_DEFAULT_LANG', 'es');
define('MATI_MU_GUARD', WPMU_PLUGIN_DIR . '/mati-uninstall-guard.php');

// ═══════════════════════════════════════════════════════════
// API HELPERS
// ═══════════════════════════════════════════════════════════
function mati_api_key() { return get_option('mati_api_key', ''); }
function mati_api_slug() { return get_option('mati_slug', ''); }
function mati_plan() { if (MATI_LOCAL_DEV) return 'BUSINESS'; $v = get_option('mati_plan', 'BUSINESS'); return in_array($v, ['FREE','STARTER','PROFESSIONAL','BUSINESS']) ? $v : 'BUSINESS'; }
/**
 * Plan-based feature restrictions
 *
 * FREE       — Basic widget only
 * STARTER    — Widget + calendar sync + email notifications
 * PROFESSIONAL — All STARTER features + payments + SMS + multi-provider
 * BUSINESS   — Everything (custom branding, advanced analytics, API access)
 */
function mati_plan_can($feature) {
    $plan = mati_plan();
    $plans = ['FREE' => 0, 'STARTER' => 1, 'PROFESSIONAL' => 2, 'BUSINESS' => 3];
    $level = $plans[$plan] ?? 3;

    $requirements = [
        'widget'         => 0, // FREE
        'calendar'       => 1, // STARTER
        'bookings'       => 0, // FREE
        'services'       => 0, // FREE
        'providers'      => 0, // FREE
        'customers'      => 1, // STARTER
        'payments'       => 2, // PROFESSIONAL
        'sms'            => 2, // PROFESSIONAL
        'notifications'  => 1, // STARTER
        'custom_branding'=> 3, // BUSINESS
        'analytics'      => 2, // PROFESSIONAL
        'api_access'     => 3, // BUSINESS
        'multi_location' => 3, // BUSINESS
    ];

    $required = $requirements[$feature] ?? 0;
    return $level >= $required;
}
// SVG del personaje Mati (cálido, amigable, confiable)
// Logo de Mati — usa la imagen real del proyecto
function mati_logo_img($size = 24, $bg = true) {
    $bg_style = $bg ? 'background:white;border-radius:50%;padding:2px;' : '';
    return '<span style="display:inline-flex;align-items:center;justify-content:center;' . $bg_style . '"><img src="' . esc_url(MATI_PLUGIN_URL . 'assets/mati-logo.png') . '" width="' . $size . '" alt="Mati" style="display:block;max-width:' . $size . 'px" /></span>';
}

function mati_plan_badge() {
    $plan = mati_plan(); $colors = ['FREE'=>'#64748b','STARTER'=>'#2563eb','PROFESSIONAL'=>'#d97706','BUSINESS'=>'#16a34a'];
    return '<span class="mati-plan-badge" style="background:'.$colors[$plan].'">'.$plan.'</span>';
}

function mati_api_fetch($method, $path, $data = null) {
    $api_key = mati_api_key();
    if (empty($api_key)) return null;
    $url = MATI_API_URL . $path;
    $args = ['method' => $method, 'headers' => [
        'Content-Type' => 'application/json',
        'x-mati-api-key' => $api_key,
    ], 'timeout' => 15];
    if ($data !== null) $args['body'] = json_encode($data);
    $response = wp_remote_request($url, $args);
    if (is_wp_error($response)) return null;
    return json_decode(wp_remote_retrieve_body($response), true);
}

function mati_api_get($path) { return mati_api_fetch('GET', $path); }
function mati_api_post($path, $data) { return mati_api_fetch('POST', $path, ['data' => $data]); }
function mati_api_validate_key($api_key) {
    $r = wp_remote_post(MATI_API_URL, ['headers' => ['Content-Type' => 'application/json'], 'body' => json_encode(['apiKey' => $api_key]), 'timeout' => 15]);
    return is_wp_error($r) ? null : json_decode(wp_remote_retrieve_body($r), true);
}

/**
 * Verifica si la API Key guardada sigue siendo válida.
 * Cachea el resultado por 60 segundos para no hacer requests en cada carga.
 */
function mati_is_api_key_valid($skip_cache = false) {
    $api_key = mati_api_key();
    if (empty($api_key)) return false;

    if (!$skip_cache) {
        $cached = get_transient('mati_api_key_valid');
        if ($cached !== false) return $cached === 'yes';
    }

    $result = mati_api_validate_key($api_key);
    // Si el servidor respondió, obedecer. Si no respondió (null),
    // mantener el último estado conocido para no romper por error de red.
    if ($result !== null) {
        $is_valid = isset($result['success']) && $result['success'] === true;
        set_transient('mati_api_key_valid', $is_valid ? 'yes' : 'no', 120);
        return $is_valid;
    }

    // Servidor inalcanzable: confiar en caché o拒绝
    $cached = get_transient('mati_api_key_valid');
    return $cached === 'yes';
}

/**
 * Limpia el caché de validación de API Key.
 */
function mati_clear_api_key_cache() {
    delete_transient('mati_api_key_valid');
}

// ═══════════════════════════════════════════════════════════
// ACTIVACIÓN / DESACTIVACIÓN (MU-plugin guardián)
// ═══════════════════════════════════════════════════════════
register_activation_hook(__FILE__, function() {
    if (!file_exists(WPMU_PLUGIN_DIR)) @mkdir(WPMU_PLUGIN_DIR, 0755, true);
    @file_put_contents(MATI_MU_GUARD, '<?php if(!defined("ABSPATH"))exit;add_action("admin_footer",function(){$a=admin_url("admin-ajax.php");?><div id="mati-delete-modal" style="display:none;position:fixed;z-index:100000;left:0;top:0;width:100%;height:100%;background:rgba(0,0,0,0.7);align-items:center;justify-content:center"><div style="background:white;border-radius:1.5rem;padding:2.5rem;max-width:530px;width:90%;box-shadow:0 20px 60px rgba(0,0,0,0.35);text-align:center"><div style="font-size:3.5rem;margin-bottom:1rem">⚠️</div><h2 style="margin:0 0 .5rem;font-size:1.35rem;font-weight:900">¿Eliminar datos de Mati?</h2><p style="color:#64748b;font-size:.9rem;line-height:1.55;margin-bottom:1.5rem">Estás por eliminar el plugin. ¿Qué hacer con la configuración?</p><div style="display:flex;flex-direction:column;gap:.7rem;text-align:left;margin-bottom:.5rem"><label style="display:flex;align-items:flex-start;gap:.75rem;padding:1rem 1.25rem;border:2px solid #10b981;border-radius:1rem;background:#f0fdf4;cursor:pointer"><input type="radio" name="mc" value="keep" checked style="margin-top:.2rem;width:18px;height:18px;accent-color:#10b981"/><div><strong style="color:#065f46">💾 Conservar datos</strong><br><span style="font-size:.78rem;color:#64748b">Eliminar el plugin manteniendo la API Key.</span></div></label><label style="display:flex;align-items:flex-start;gap:.75rem;padding:1rem 1.25rem;border:2px solid #ef4444;border-radius:1rem;background:#fef2f2;cursor:pointer"><input type="radio" name="mc" value="delete" style="margin-top:.2rem;width:18px;height:18px;accent-color:#ef4444"/><div><strong style="color:#991b1b">🗑️ Eliminar todo</strong><br><span style="font-size:.78rem;color:#64748b">Borrar plugin y datos locales.</span></div></label></div><div style="display:flex;gap:.75rem;justify-content:center;margin-top:1.5rem"><button id="mdc" style="flex:1;padding:.85rem 1.5rem;border-radius:.85rem;border:none;background:linear-gradient(135deg,#1A5D4A,#2D8A6E);color:white;font-weight:800;cursor:pointer;font-size:.95rem">Confirmar</button><button id="mdx" style="padding:.85rem 1.5rem;border-radius:.85rem;border:2px solid #e2e8f0;background:#fff;color:#475569;font-weight:700;cursor:pointer">✖️ Cancelar</button></div></div></div><script>!function(){var e=document.querySelectorAll("tr[data-plugin]"),t=null;e.forEach(function(e){e.getAttribute("data-plugin").indexOf("mati-booking")!==-1&&(t=e)});if(!t)return;var d=t.querySelector(".delete a");if(!d)return;var o=document.getElementById("mati-delete-modal"),l=d.href;d.addEventListener("click",function(e){e.preventDefault(),o.style.display="flex"}),document.getElementById("mdx").addEventListener("click",function(){o.style.display="none"}),document.getElementById("mdc").addEventListener("click",function(){var e=document.querySelector("input[name=\'mc\']:checked"),t=e?e.value:"keep";o.style.display="none",fetch("<?php echo $a; ?>",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"action=mati_mu_"+(t==="delete"?"set":"keep")+"_data_flag",keepalive:!0}).then(function(){window.location.href=l}).catch(function(){window.location.href=l})})}();</script><?php });add_action("wp_ajax_mati_mu_set_delete_flag",function(){update_option("mati_delete_data_on_uninstall","yes");wp_die();});add_action("wp_ajax_mati_mu_keep_data_flag",function(){update_option("mati_delete_data_on_uninstall","no");wp_die();});');
});
register_deactivation_hook(__FILE__, function() { if (file_exists(MATI_MU_GUARD)) @unlink(MATI_MU_GUARD); });

// ═══════════════════════════════════════════════════════════
// DESINSTALACIÓN — Respeta la elección del usuario en el modal
// ═══════════════════════════════════════════════════════════
register_uninstall_hook(__FILE__, 'mati_uninstall');
function mati_uninstall() {
    // Si el usuario eligió "Eliminar todo" en el modal de desinstalación,
    // borramos todas las opciones de Mati de la base de datos.
    if (get_option('mati_delete_data_on_uninstall', 'no') === 'yes') {
        $all_options = [
            'mati_api_key','mati_slug','mati_plan','mati_position','mati_theme',
            'mati_language','mati_color','mati_button_text','mati_greeting',
            'mati_auto_open','mati_agent_mode','mati_voice','mati_setup_complete',
            'mati_widget_variant','mati_panels_enabled','mati_had_api_key',
            'mati_delete_data_on_uninstall','mati_business_name','mati_business_type',
            'mati_business_color','mati_business_schedule_start','mati_business_schedule_end',
            'mati_business_days','mati_business_providers','mati_business_specialty',
        ];
        foreach ($all_options as $opt) {
            delete_option($opt);
        }
        delete_transient('mati_api_key_valid');
    }
    // Si eligió "Conservar datos", no se borra nada.
    // Las opciones quedan en la BD por si reinstala el plugin más tarde.
}

// ═══════════════════════════════════════════════════════════
// MENÚ
// ═══════════════════════════════════════════════════════════
add_action('admin_menu', function() {
    add_menu_page('Mati', 'Mati', 'manage_options', 'mati-welcome', 'mati_render_welcome',
        plugins_url('assets/mati-icon.png', __FILE__), 2);
    $pages = [
        ['welcome','Inicio','Inicio','mati_render_welcome'],
        ['bookings','Reservas','Reservas','mati_render_bookings'],
        ['customers','Clientes','Clientes','mati_render_customers'],
        ['services','Servicios','Servicios','mati_render_services'],
        ['providers','Profesionales','Profesionales','mati_render_providers'],
        ['calendar','Calendario','Calendario','mati_render_calendar'],
        ['schedule','Horarios','Horarios','mati_render_schedule'],
        ['payments','Pagos','Pagos','mati_render_payments'],
        ['widget','🪄 Widget & Shortcodes','Widget & Shortcodes','mati_render_widget_unified'],
        ['integrations','Integraciones','Integraciones','mati_render_integrations'],
        ['settings','Configuración','Configuración','mati_render_settings'],
        ['benefits','Beneficios','Beneficios','mati_render_benefits'],
    ];
    foreach ($pages as $p) {
        add_submenu_page('mati-welcome', $p[1], $p[2], 'manage_options', "mati-{$p[0]}", $p[3]);
    }
});

// ═══════════════════════════════════════════════════════════
// SETTINGS + ASSETS
// ═══════════════════════════════════════════════════════════
add_action('admin_init', function() {
    foreach (['mati_api_key','mati_slug','mati_plan','mati_position','mati_theme','mati_language','mati_color','mati_button_text','mati_greeting','mati_auto_open','mati_agent_mode','mati_voice','mati_setup_complete','mati_delete_data_on_uninstall','mati_widget_variant','mati_panels_enabled','mati_auto_inject'] as $o) register_setting('mati_settings', $o);
});

// ═══════════════════════════════════════════════════════════
// GUTENBERG BLOCK
// ═══════════════════════════════════════════════════════════
add_action('init', function() {
    if (!function_exists('register_block_type')) return;
    $block_dir = MATI_PLUGIN_DIR . 'blocks/mati-widget';
    if (file_exists($block_dir . '/block.json')) {
        register_block_type($block_dir, [
            'render_callback' => 'mati_render_block_widget',
        ]);
    }
});

function mati_render_block_widget($attributes) {
    $slug = mati_api_slug();
    if (empty($slug)) return '<p style="color:#64748b;text-align:center;padding:1rem">' . esc_html__('Configurá tu API Key en Mati → Inicio para activar el widget.', 'mati-booking') . '</p>';

    $position  = !empty($attributes['position']) ? sanitize_text_field($attributes['position']) : 'inline';
    $variant   = !empty($attributes['variant']) ? sanitize_text_field($attributes['variant']) : 'default';
    $theme     = 'light';
    $lang      = !empty($attributes['language']) ? sanitize_text_field($attributes['language']) : 'es';
    $color     = !empty($attributes['color']) ? sanitize_hex_color($attributes['color']) : get_option('mati_color', MATI_DEFAULT_COLOR);

    $btnText   = get_option('mati_button_text', 'Reservar');
    $greeting  = get_option('mati_greeting', '¡Hola! ¿En qué puedo ayudarte?');
    $autoOpen  = get_option('mati_auto_open', 'no');
    $agentMode = get_option('mati_agent_mode', 'on');

    ob_start();
    if ($position === 'inline') {
        echo '<div id="mati-inline" class="mati-w-full mati-mw-420 mati-mx-auto mati-my-2"></div>';
    }
    echo '<script src="' . MATI_SCRIPT_URL . '" data-slug="' . esc_attr($slug) . '" data-variant="' . esc_attr($variant) . '" data-position="' . esc_attr($position) . '" data-theme="' . esc_attr($theme) . '" data-language="' . esc_attr($lang) . '" data-primary-color="' . esc_attr($color) . '" data-button-text="' . esc_attr($btnText) . '" data-greeting="' . esc_attr($greeting) . '" data-auto-open="' . esc_attr($autoOpen) . '" data-agent-mode="' . esc_attr($agentMode) . '" async></script>';
    return ob_get_clean();
}

add_action('admin_enqueue_scripts', function($hook) {
    if (strpos($hook, 'mati-') === false) return;
    wp_enqueue_style('mati-admin', MATI_PLUGIN_URL . 'assets/admin.css', [], MATI_VERSION);
    wp_enqueue_script('mati-admin', MATI_PLUGIN_URL . 'assets/admin.js', [], MATI_VERSION, true);
    wp_localize_script('mati-admin', 'matiData', ['ajaxurl'=>admin_url('admin-ajax.php'),'nonce'=>wp_create_nonce('mati_nonce'),'apiUrl'=>MATI_BROWSER_URL.'/api/public/workspace','apiKey'=>mati_api_key(),'slug'=>mati_api_slug(),'dashboardUrl'=>MATI_DASHBOARD_URL,'scriptUrl'=>MATI_SCRIPT_URL,'version'=>MATI_VERSION]);
});

// ═══════════════════════════════════════════════════════════
// HELPERS UI
// ═══════════════════════════════════════════════════════════
function mati_page_header($title, $desc = '') {
    echo '<div class="mati-page-header"><div><h1>'.esc_html($title).' '.mati_plan_badge().'</h1>'; if($desc) echo '<p>'.esc_html($desc).'</p>'; echo '</div>';
    if (!empty(mati_api_key())) {
        echo '<div class="mati-page-header-actions">';
        echo '<a href="' . MATI_BROWSER_URL . '/dashboard/' . esc_attr(mati_api_slug()) . '" target="_blank" class="mati-btn mati-btn-primary mati-btn-sm" style="margin-right:.5rem">Abrir panel →</a>';
        echo '<button class="mati-btn mati-btn-outline mati-btn-sm" id="mati-disconnect-btn" onclick="matiDisconnect()">' . esc_html__('⚠️ Desconectar / Cambiar API Key', 'mati-booking') . '</button>';
        echo '</div>';
    }
    echo '</div>';
}

function mati_require_api_key() {
    $api_key = mati_api_key();
    if (empty($api_key)) {
        echo '<div class="mati-wrap"><div class="mati-setup-container mati-text-center mati-p-xl">';
        echo '<div class="mati-orb mati-mx-auto mati-mb-2"><div class="mati-orb-ring"></div><div class="mati-orb-ring"></div><div class="mati-orb-ring"></div><div class="mati-orb-core"><svg class="mati-orb-icon" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="1.5"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg></div></div>';
        echo '<h1 class="mati-hero-title">' . esc_html__('Conectar con', 'mati-booking') . ' <span>Mati</span></h1>';
        echo '<p class="mati-text-dim mati-mb-2">' . esc_html__('Para acceder a esta sección, primero conectá tu API Key.', 'mati-booking') . '</p>';
        echo '<a href="'.admin_url('admin.php?page=mati-welcome').'" class="mati-btn mati-btn-primary mati-btn-lg">' . esc_html__('Ir a Configurar API Key →', 'mati-booking') . '</a>';
        echo '</div></div>';
        return true;
    }
    // API Key exists — validate it
    if (!mati_is_api_key_valid()) {
        echo '<div class="mati-wrap">';
        echo '<div class="mati-alert mati-alert-danger mati-mb-2">';
        echo '<strong>⚠️ ' . esc_html__('API Key inválida o eliminada', 'mati-booking') . '</strong><br>';
        echo esc_html__('La API Key guardada ya no es válida. Esto puede ocurrir si la eliminaste desde mati.com o si cambiaste de workspace.', 'mati-booking') . '<br>';
        echo '<button class="mati-btn mati-btn-danger mati-btn-sm mati-mt-75" onclick="matiDisconnect()">' . esc_html__('Desconectar y configurar nueva API Key', 'mati-booking') . '</button>';
        echo '</div>';
        echo '</div>';
        return true;
    }
    return false;
}

function mati_data_table($headers, $rows, $empty = 'Sin datos') {
    if (empty($rows)) { echo '<div class="mati-card mati-text-center mati-p-2 mati-text-dim">'.$empty.'</div>'; return; }
    echo '<div class="mati-card mati-p-0 mati-overflow-x-auto"><table class="mati-table"><thead><tr>';
    foreach ($headers as $h) echo '<th>'.esc_html($h).'</th>';
    echo '</tr></thead><tbody>';
    foreach ($rows as $row) { echo '<tr>'; foreach ($row as $cell) echo '<td>'.$cell.'</td>'; echo '</tr>'; }
    echo '</tbody></table></div>';
}

function mati_stats_cards($cards) { echo '<div class="mati-stats-row">'; foreach ($cards as $c) echo '<div class="mati-stat-card"><div class="mati-stat-icon">'.$c['icon'].'</div><div class="mati-stat-num">'.$c['value'].'</div><div class="mati-stat-label">'.$c['label'].'</div></div>'; echo '</div>'; }
// ─── Calendar month grid (v6.3 redesigned) ─────────
function mati_calendar_month_grid($year, $month, $bookingMap) {
    $firstDay = date("N", strtotime("$year-$month-01")) - 1;
    $daysInMonth = date("t", strtotime("$year-$month-01"));
    $today = date("Y-m-d");

    $html = "<div class=\"mati-cal-grid\">";

    $dayHeaders = ["Lun","Mar","Mi\u{00E9}","Jue","Vie","S\u{00E1}b","Dom"];
    foreach ($dayHeaders as $di => $dh) {
        $weClass = ($di >= 5) ? " weekend-header" : "";
        $html .= "<div class=\"mati-cal-day-header" . $weClass . "\">" . $dh . "</div>";
    }

    for ($i = 0; $i < $firstDay; $i++) {
        $html .= "<div class=\"mati-cal-day other-month\"><div class=\"mati-cal-day-num\"></div></div>";
    }

    for ($d = 1; $d <= $daysInMonth; $d++) {
        $dateKey = sprintf("%04d-%02d-%02d", $year, $month, $d);
        $info = $bookingMap[$dateKey] ?? null;
        $dow = (int)date("N", strtotime($dateKey));
        $isWeekend = ($dow >= 6);
        $classes = "mati-cal-day";
        if ($dateKey === $today) $classes .= " today";
        if ($isWeekend) $classes .= " weekend";
        if ($info && $info["count"] > 0) $classes .= " has-bookings";
        $html .= "<div class=\"" . $classes . "\" data-date=\"" . $dateKey . "\">";
        $html .= "<div class=\"mati-cal-day-num\">" . $d . "</div>";
        if ($info && $info["count"] > 0) {
            $html .= "<div class=\"mati-cal-dots\">";
            $shown = 0; $maxDots = 3;
            $statusOrder = ["CONFIRMED" => "dot-confirmed", "PENDING" => "dot-pending", "CANCELLED" => "dot-cancelled"];
            foreach ($statusOrder as $st => $dotClass) {
                if ($shown >= $maxDots) break;
                $cnt = $info[$st] ?? 0;
                for ($j = 0; $j < $cnt && $shown < $maxDots; $j++) {
                    $html .= "<span class=\"mati-cal-dot " . $dotClass . "\"></span>";
                    $shown++;
                }
            }
            $remaining = $info["count"] - $shown;
            if ($remaining > 0) $html .= "<span class=\"mati-cal-dot more\">+" . $remaining . "</span>";
            $html .= "</div>";
        }
        $html .= "</div>";
    }
    $html .= "</div>";
    return $html;
}
function mati_monthly_chart($monthlyData) {
    $months = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];
    $maxVal = max(array_merge($monthlyData, [1]));
    $html = '<div class="mati-chart-bar">';
    foreach ($monthlyData as $i => $val) {
        $h = $maxVal > 0 ? ($val / $maxVal) * 100 : 0;
        $html .= '<div style="flex:1;text-align:center"><div class="mati-chart-bar-col" style="height:'.max($h, 3).'%" title="'.$months[$i].': '.$val.'"></div><div class="mati-chart-bar-label">'.$months[$i].'</div></div>';
    }
    return $html . '</div>';
}
function mati_payment_icon($method) { $icons = ['stripe'=>'💳','mercadopago'=>'🟦','paypal'=>'🅿️','cash'=>'💵','transfer'=>'🏦']; return $icons[strtolower($method ?? '')] ?? '💰'; }
function mati_completion_ring($percentage) {
    $pct = max(0, min(100, intval($percentage)));
    $color = $pct >= 80 ? '#16a34a' : ($pct >= 50 ? '#f59e0b' : '#ef4444');
    return '<div style="text-align:center"><svg width="100" height="100" viewBox="0 0 36 36" style="display:inline-block"><circle cx="18" cy="18" r="14" fill="none" stroke="#e5e7eb" stroke-width="3"/><circle cx="18" cy="18" r="14" fill="none" stroke="'.$color.'" stroke-width="3" stroke-dasharray="'.$pct.', '.(100-$pct).'" stroke-dashoffset="22" stroke-linecap="round" transform="rotate(-90 18 18)" style="transition:all .5s"/><text x="18" y="20" text-anchor="middle" font-size="8" font-weight="700" fill="#1e293b">'.$pct.'%</text></svg></div>';
}

// ═══════════════════════════════════════════════════════════
// 1. INICIO
// ═══════════════════════════════════════════════════════════
function mati_render_welcome() {
    if (empty(mati_api_key())) { mati_render_api_key_screen(); return; }
    // Forzar validación sin caché: si la key se eliminó en mati.com, se detecta al instante
    if (!mati_is_api_key_valid(true)) { mati_render_api_key_screen(); return; }
    if (!get_option('mati_setup_complete', false)) { mati_render_setup_wizard(); return; }
    mati_render_dashboard();
}

function mati_render_api_key_screen() {
    $had_key = get_option('mati_had_api_key', false);
    $old_invalid = !empty(mati_api_key()) && !mati_is_api_key_valid(true);
    ?>
    <div class="mati-wrap mati-setup"><div class="mati-setup-container">
        <div class="mati-setup-hero mati-text-center mati-my-3">
            <div class="mati-orb mati-mx-auto mati-mb-2"><div class="mati-orb-ring"></div><div class="mati-orb-ring"></div><div class="mati-orb-ring"></div><div class="mati-orb-core"><svg class="mati-orb-icon" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="1.5"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg></div></div>
            <h1 class="mati-hero-title"><?php echo esc_html__('Conectar con', 'mati-booking'); ?> <span>Mati</span></h1>
            <?php if ($old_invalid): ?>
                <div class="mati-alert mati-alert-danger mati-mx-auto mati-mw-500 mati-mb-2">
                    <strong>⚠️ <?php echo esc_html__('API Key anterior inválida', 'mati-booking'); ?></strong><br>
                    <?php echo esc_html__('La API Key que tenías guardada ya no es válida. Ingresá una nueva para continuar.', 'mati-booking'); ?>
                </div>
            <?php else: ?>
                <p class="mati-mx-auto mati-mb-2 mati-text-dim mati-mw-500"><?php echo wp_kses_post(__('Ingresá tu <strong>API Key</strong> de mati.com para conectar este sitio.', 'mati-booking')); ?></p>
            <?php endif; ?>
        </div>
        <div class="mati-card mati-mx-auto mati-mw-500">
            <div id="mati-apikey-form"><label class="mati-label">API Key</label>
            <div class="mati-flex mati-gap-50"><input type="text" id="mati-apikey-input" class="mati-chat-input mati-flex-1 mati-font-mono" placeholder="mat_sk_..." value="" /><button class="mati-btn mati-btn-primary mati-btn-lg" id="mati-apikey-submit">Conectar</button></div>
            <p id="mati-apikey-status" class="mati-mt-75 mati-text-sm"></p></div>
        </div>
    </div></div>
    <script>document.getElementById('mati-apikey-submit').addEventListener('click',function(){var k=document.getElementById('mati-apikey-input').value.trim(),b=this,s=document.getElementById('mati-apikey-status');if(!k){s.textContent='⚠️ Ingresá tu API Key';s.style.color='#ef4444';return}b.disabled=true;b.textContent='⏳...';s.textContent='';fetch(matiData.apiUrl,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({apiKey:k})}).then(function(r){return r.json()}).then(function(d){if(d.success){s.textContent='✅ Conectado a «'+d.workspace.name+'». Redirigiendo...';s.style.color='#16A34A';var fd=new FormData();fd.append('action','mati_save_apikey');fd.append('nonce',matiData.nonce);fd.append('api_key',k);fd.append('slug',d.workspace.slug);fd.append('plan',d.workspace.plan);fetch(matiData.ajaxurl,{method:'POST',body:fd}).then(function(){setTimeout(function(){location.reload()},1000)})}else{s.textContent='❌ API Key inválida';s.style.color='#ef4444';b.disabled=false;b.textContent='Conectar'}}).catch(function(){s.textContent='❌ Error de conexión';s.style.color='#ef4444';b.disabled=false;b.textContent='Conectar'})});document.getElementById('mati-apikey-input').addEventListener('keydown',function(e){if(e.key==='Enter')document.getElementById('mati-apikey-submit').click()});</script>
<?php }

function mati_render_setup_wizard() { ?>
    <div class="mati-wrap mati-setup"><div class="mati-particles" id="mati-particles"></div><div class="mati-setup-container">
        <div class="mati-setup-hero"><div class="mati-orb"><div class="mati-orb-ring"></div><div class="mati-orb-ring"></div><div class="mati-orb-ring"></div><div class="mati-orb-core"><svg class="mati-orb-icon" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="1.5"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg></div></div><h1 class="mati-hero-title">Bienvenido a <span>Mati</span></h1><p class="mati-hero-sub">Tu asistente inteligente de reservas.</p></div>
        <div class="mati-agent-card" id="mati-agent"><div class="mati-agent-header"><div class="mati-agent-avatar mati-agent-pulse"><?php echo mati_logo_img(24); ?></div><div><strong>Mati</strong><span class="mati-agent-status" id="mati-status-text">Conectado vía API</span></div></div><div class="mati-agent-body" id="mati-agent-messages"><div class="mati-typing" id="mati-typing"><span></span><span></span><span></span></div></div><div class="mati-agent-footer" id="mati-agent-footer"><div class="mati-text-center mati-p-1 mati-text-muted">Conectando...</div></div></div>
    </div></div>
<?php }

function mati_render_dashboard() {
    $data = mati_api_get('/data?section=stats');
    $stats = $data['data']['stats'] ?? [];
    $sync = mati_api_get('/sync');
    $plugin = $sync['data'] ?? [];
    $svcs = $plugin['services'] ?? [];
    $provs = $plugin['providers'] ?? [];
    $businessName = esc_html($plugin['businessName'] ?? 'Tu negocio');
    mati_page_header($businessName, 'Panel de bienvenida conectado a Mati.');

    // Welcome banner
    echo '<div class="mati-welcome-banner">';
    echo '<div class="mati-welcome-content">';
    echo '<h2>👋 ¡Hola! Este es el panel de <strong>' . $businessName . '</strong></h2>';
    echo '<p>Desde aquí podés ver el resumen de reservas, clientes e ingresos. Para gestionar servicios, profesionales y configuraciones avanzadas, usá el dashboard completo de Mati.</p>';
    echo '<a href="' . MATI_BROWSER_URL . '/dashboard/' . esc_attr(mati_api_slug()) . '" target="_blank" class="mati-btn mati-btn-primary">Abrir dashboard completo →</a>';
    echo '</div>';
    echo '<div class="mati-welcome-orb">' . mati_logo_img(48) . '</div>';
    echo '</div>';

    $totalBookings = intval($stats['totalBookings'] ?? 0);
    $totalCustomers = intval($stats['totalCustomers'] ?? 0);
    $completionRate = intval($stats['completionRate'] ?? 0);
    $totalRevenue = floatval($stats['totalRevenue'] ?? 0);
    $monthRevenue = floatval($stats['monthRevenue'] ?? 0);
    $pendingBookings = intval($stats['pendingBookings'] ?? 0);
    $confirmedBookings = intval($stats['confirmedBookings'] ?? 0);
    $cancelledBookings = intval($stats['cancelledBookings'] ?? 0);
    // Row 1: KPI Cards
    echo '<div class="mati-kpi-grid">';
    echo '<div class="mati-kpi-card kpi-blue"><div class="mati-kpi-top"><span class="mati-kpi-icon">📅</span></div><div class="mati-kpi-value">' . $totalBookings . '</div><div class="mati-kpi-label">Reservas Totales</div><div class="mati-kpi-sub">' . $confirmedBookings . ' confirmadas · ' . $cancelledBookings . ' canceladas</div></div>';
    echo '<div class="mati-kpi-card kpi-green"><div class="mati-kpi-top"><span class="mati-kpi-icon">✅</span><span class="mati-kpi-trend ' . ($completionRate >= 80 ? 'up' : 'down') . '">' . $completionRate . '%</span></div><div class="mati-kpi-value">' . $completionRate . '%</div><div class="mati-kpi-label">Tasa de Conversión</div><div class="mati-kpi-sub">Reservas confirmadas / total</div></div>';
    echo '<div class="mati-kpi-card kpi-teal"><div class="mati-kpi-top"><span class="mati-kpi-icon">💰</span></div><div class="mati-kpi-value">$' . number_format($totalRevenue, 0) . '</div><div class="mati-kpi-label">Ingresos Totales</div><div class="mati-kpi-sub">$' . number_format($monthRevenue, 0) . ' este mes</div></div>';
    echo '<div class="mati-kpi-card kpi-purple"><div class="mati-kpi-top"><span class="mati-kpi-icon">👥</span></div><div class="mati-kpi-value">' . $totalCustomers . '</div><div class="mati-kpi-label">Clientes</div><div class="mati-kpi-sub">' . count($svcs) . ' servicios · ' . count($provs) . ' profesionales</div></div>';
    echo '<div class="mati-kpi-card kpi-orange"><div class="mati-kpi-top"><span class="mati-kpi-icon">⏳</span></div><div class="mati-kpi-value">' . $pendingBookings . '</div><div class="mati-kpi-label">Pendientes</div><div class="mati-kpi-sub">Requieren acción</div></div>';
    echo '</div>';
    // Row 2: Charts
    echo '<div class="mati-db-charts">';
    echo '<div class="mati-card"><h3 style="margin-top:0">📊 Reservas por Mes</h3>';
    $monthly = $stats['monthlyStats'] ?? [];
    $monthlyVals = array_fill(0, 12, 0);
    foreach ($monthly as $m) { $idx = intval(($m['month'] ?? '1')) - 1; if ($idx >= 0 && $idx < 12) $monthlyVals[$idx] = intval($m['count'] ?? 0); }
    echo mati_monthly_chart($monthlyVals);
    echo '</div>';
    echo '<div class="mati-card" style="text-align:center"><h3 style="margin-top:0">🎯 Tasa de Finalización</h3>';
    echo mati_completion_ring($completionRate);
    echo '<p class="mati-text-dim mati-text-sm" style="margin-top:.5rem">' . $confirmedBookings . ' de ' . $totalBookings . ' reservas confirmadas</p>';
    echo '</div></div>';
    // Row 3: Recent Bookings
    echo '<div class="mati-card"><h3 style="margin-top:0">📋 Últimas Reservas</h3>';
    $recent = $stats['recentBookings'] ?? [];
    if (empty($recent)) {
        echo '<p class="mati-text-dim mati-text-center mati-p-2">No hay reservas todavía. ¡Creá tu primer servicio y empezá a recibir clientes!</p>';
    } else {
        echo '<ul class="mati-recent-list">';
        foreach (array_slice($recent, 0, 8) as $b) {
            $name = esc_html($b['customerName'] ?? 'Sin nombre');
            $service = esc_html($b['serviceName'] ?? '—');
            $date = date('d/m/Y H:i', strtotime($b['startTime'] ?? ''));
            $st = $b['status'] ?? 'PENDING';
            $statusClass = $st === 'CONFIRMED' ? 'mati-status-confirmed' : ($st === 'CANCELLED' ? 'mati-status-cancelled' : 'mati-status-pending');
            $statusLabel = $st === 'CONFIRMED' ? 'Confirmada' : ($st === 'CANCELLED' ? 'Cancelada' : 'Pendiente');
            $initial = strtoupper(mb_substr($name, 0, 1));
            echo '<li class="mati-recent-item"><div class="mati-recent-avatar">' . $initial . '</div><div class="mati-recent-info"><div class="mati-recent-name">' . $name . '</div><div class="mati-recent-detail">' . $service . '</div></div><div class="mati-recent-time"><div>' . $date . '</div><span class="mati-badge-status ' . $statusClass . '" style="font-size:.65rem">' . $statusLabel . '</span></div></li>';
        }
        echo '</ul>';
    }
    echo '</div>';
    // Row 4: Quick Links
    echo '<div class="mati-quick-links mati-mt-1">';
    foreach ([['Reservas','mati-bookings','📋'],['Clientes','mati-customers','👥'],['Calendario','mati-calendar','📅'],['Servicios','mati-services','🔧'],['Profesionales','mati-providers','👤'],['Pagos','mati-payments','💳'],['Widget','mati-widget','🪄']] as $l)
        echo '<a href="'.admin_url('admin.php?page='.$l[1]).'" class="mati-quick-card"><span class="mati-quick-icon">'.$l[2].'</span><span>'.$l[0].'</span></a>';
    echo '</div>';
    echo '<div class="mati-status-bar mati-mt-50"><div class="mati-status-item"><span class="mati-status-dot mati-status-dot-green"></span>Conectado a mati.com vía API</div><div class="mati-status-item"><span class="mati-status-dot mati-status-dot-green"></span>Widget activo en frontend</div><div class="mati-status-item"><span>v'.MATI_VERSION.'</span></div></div>';
}
// ═══════════════════════════════════════════════════════════
// 2. RESERVAS (nativo via API)
// ═══════════════════════════════════════════════════════════
function mati_render_bookings() {
    if (mati_require_api_key()) return;
    $data = mati_api_get('/data?section=bookings');
    $bookings = $data['data']['bookings'] ?? [];
    mati_page_header('Reservas', 'Todas las reservas de tu workspace.');
    $rows = [];
    foreach ($bookings as $b) {
        $status_badge = $b['status'] === 'CONFIRMED' ? '<span class="mati-badge-status mati-status-confirmed">Confirmada</span>' : ($b['status'] === 'CANCELLED' ? '<span class="mati-badge-status mati-status-cancelled">Cancelada</span>' : '<span class="mati-badge-status mati-status-pending">Pendiente</span>');
        $rows[] = [
            esc_html($b['customerName'] ?? '—'),
            esc_html($b['serviceName'] ?? '—'),
            esc_html($b['providerName'] ?? '—'),
            date('d/m/Y H:i', strtotime($b['startTime'] ?? '')),
            $status_badge,
        ];
    }
    mati_data_table(['Cliente','Servicio','Profesional','Fecha','Estado'], $rows, 'No hay reservas todavía.');
}

// ═══════════════════════════════════════════════════════════
// 3. CLIENTES (nativo via API)
// ═══════════════════════════════════════════════════════════
function mati_render_customers() {
    if (mati_require_api_key()) return;
    $data = mati_api_get('/data?section=customers');
    $customers = $data['data']['customers'] ?? [];
    mati_page_header('Clientes', 'Base de clientes.');
    $rows = [];
    foreach ($customers as $c) {
        $rows[] = [esc_html($c['name'] ?? '—'), esc_html($c['email'] ?? '—'), esc_html($c['phone'] ?? '—'), esc_html((string)($c['totalBookings'] ?? 0)), esc_html($c['lastBookingAt'] ? date('d/m/Y', strtotime($c['lastBookingAt'])) : '—')];
    }
    mati_data_table(['Nombre','Email','Teléfono','Reservas','Última'], $rows, 'No hay clientes todavía.');
}

// ═══════════════════════════════════════════════════════════
// 4. SERVICIOS
// ═══════════════════════════════════════════════════════════
function mati_render_services() {
    if (mati_require_api_key()) return;
    $sync = mati_api_get('/sync');
    $svcs = $sync['data']['services'] ?? [];
    mati_page_header('Servicios', 'Configurá tus servicios. Cada uno puede tener precio, duración, descripción y más.');
    ?>
    <div id="mati-services-app-v2">
        <div class="mati-services-grid" id="mati-services-grid">
            <?php if (empty($svcs)): ?>
                <div class="mati-card mati-text-center mati-p-2 mati-text-dim" style="grid-column:1/-1">🎯 No hay servicios. Agregá el primero para empezar.</div>
            <?php else: foreach ($svcs as $i => $s): ?>
            <div class="mati-svc-card" data-index="<?php echo $i; ?>">
                <div class="mati-svc-card-header" onclick="this.parentElement.querySelector('.mati-svc-card-body').classList.toggle('collapsed')">
                    <span class="mati-svc-card-name"><?php echo esc_html($s['name'] ?? 'Servicio ' . ($i+1)); ?></span>
                    <label class="mati-toggle-switch" style="margin:0" onclick="event.stopPropagation()">
                        <input type="checkbox" class="mati-svc-active" <?php echo (!isset($s['active']) || $s['active']) ? 'checked' : ''; ?>>
                        <span class="mati-toggle-slider"></span>
                    </label>
                </div>
                <div class="mati-svc-card-body">
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem">
                        <div><label>Nombre</label><input type="text" class="mati-svc-name" value="<?php echo esc_attr($s['name'] ?? ''); ?>"></div>
                        <div><label>Duración (min)</label><input type="number" class="mati-svc-duration" value="<?php echo esc_attr($s['duration'] ?? '30'); ?>" min="5" step="5"></div>
                        <div><label>Precio</label><input type="number" class="mati-svc-price" value="<?php echo esc_attr($s['price'] ?? '0'); ?>" min="0" step="0.01"></div>
                        <div><label>Moneda</label><select class="mati-svc-currency"><option value="USD" <?php selected($s['currency'] ?? 'USD', 'USD'); ?>>USD</option><option value="EUR" <?php selected($s['currency'] ?? '', 'EUR'); ?>>EUR</option><option value="ARS" <?php selected($s['currency'] ?? '', 'ARS'); ?>>ARS</option><option value="MXN" <?php selected($s['currency'] ?? '', 'MXN'); ?>>MXN</option><option value="BRL" <?php selected($s['currency'] ?? '', 'BRL'); ?>>BRL</option></select></div>
                        <div style="grid-column:1/-1"><label>Descripción</label><textarea class="mati-svc-desc" rows="2"><?php echo esc_textarea($s['description'] ?? ''); ?></textarea></div>
                        <div><label>Categoría</label><input type="text" class="mati-svc-category" value="<?php echo esc_attr($s['category'] ?? ''); ?>" placeholder="Ej: Consultas"></div>
                        <div><label>Color</label><input type="text" class="mati-svc-color" value="<?php echo esc_attr($s['color'] ?? '#3b82f6'); ?>" placeholder="#3b82f6"></div>
                        <div><label>Buffer entre citas (min)</label><input type="number" class="mati-svc-buffer" value="<?php echo esc_attr($s['bufferTime'] ?? '0'); ?>" min="0" step="5"></div>
                        <div><label>Seña / Depósito ($)</label><input type="number" class="mati-svc-deposit" value="<?php echo esc_attr($s['deposit'] ?? '0'); ?>" min="0" step="0.01"></div>
                    </div>
                    <div class="mati-svc-card-actions"><button type="button" class="mati-btn mati-btn-danger mati-btn-sm mati-svc-delete">🗑 Eliminar</button></div>
                </div>
                <div class="mati-svc-card-footer">
                    <span class="mati-svc-card-price">$<?php echo number_format(floatval($s['price'] ?? 0), 2); ?></span>
                    <span class="mati-svc-badge"><?php echo esc_html($s['category'] ?? 'Sin categoría'); ?></span>
                    <span style="color:var(--mati-text-dim);font-size:.8rem;margin-left:auto"><?php echo esc_html($s['duration'] ?? '30'); ?> min</span>
                </div>
            </div>
            <?php endforeach; endif; ?>
        </div>
        <div class="mati-section-actions">
            <button type="button" class="mati-btn mati-btn-primary" id="mati-add-service-v2">+ Agregar Servicio</button>
            <button type="button" class="mati-btn mati-btn-primary mati-btn-lg" id="mati-save-services-v2">💾 Guardar Todo</button>
            <span id="mati-services-status-v2" style="margin-left:.5rem;font-size:.85rem"></span>
        </div>
    </div>
    <script>
    (function(){var grid=document.getElementById('mati-services-grid'),addBtn=document.getElementById('mati-add-service-v2'),saveBtn=document.getElementById('mati-save-services-v2'),statusEl=document.getElementById('mati-services-status-v2');addBtn.addEventListener('click',function(){var empty=grid.querySelector('.mati-text-dim');if(empty)empty.remove();var d=document.createElement('div');d.className='mati-svc-card';d.setAttribute('data-index',grid.children.length);d.innerHTML='<div class="mati-svc-card-header" onclick="this.parentElement.querySelector(\'.mati-svc-card-body\').classList.toggle(\'collapsed\')"><span class="mati-svc-card-name">Nuevo Servicio</span><label class="mati-toggle-switch" style="margin:0" onclick="event.stopPropagation()"><input type="checkbox" class="mati-svc-active" checked><span class="mati-toggle-slider"></span></label></div><div class="mati-svc-card-body"><div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem"><div><label>Nombre</label><input type="text" class="mati-svc-name" value="Nuevo Servicio"></div><div><label>Duración (min)</label><input type="number" class="mati-svc-duration" value="30" min="5" step="5"></div><div><label>Precio</label><input type="number" class="mati-svc-price" value="0" min="0" step="0.01"></div><div><label>Moneda</label><select class="mati-svc-currency"><option value="USD">USD</option><option value="EUR">EUR</option><option value="ARS">ARS</option><option value="MXN">MXN</option><option value="BRL">BRL</option></select></div><div style="grid-column:1/-1"><label>Descripción</label><textarea class="mati-svc-desc" rows="2"></textarea></div><div><label>Categoría</label><input type="text" class="mati-svc-category" placeholder="Ej: Consultas"></div><div><label>Color</label><input type="text" class="mati-svc-color" value="#3b82f6" placeholder="#3b82f6"></div><div><label>Buffer entre citas (min)</label><input type="number" class="mati-svc-buffer" value="0" min="0" step="5"></div><div><label>Seña / Depósito ($)</label><input type="number" class="mati-svc-deposit" value="0" min="0" step="0.01"></div></div><div class="mati-svc-card-actions"><button type="button" class="mati-btn mati-btn-danger mati-btn-sm mati-svc-delete">🗑 Eliminar</button></div></div><div class="mati-svc-card-footer"><span class="mati-svc-card-price">$0.00</span><span class="mati-svc-badge">Sin categoría</span><span style="color:var(--mati-text-dim);font-size:.8rem;margin-left:auto">30 min</span></div>';grid.appendChild(d)});grid.addEventListener('click',function(e){if(e.target.classList.contains('mati-svc-delete')){e.target.closest('.mati-svc-card').remove();if(!grid.querySelector('.mati-svc-card'))grid.innerHTML='<div class="mati-card mati-text-center mati-p-2 mati-text-dim" style="grid-column:1/-1">🎯 No hay servicios. Agregá el primero para empezar.</div>'}});saveBtn.addEventListener('click',function(){var svcs=[];grid.querySelectorAll('.mati-svc-card').forEach(function(c){svcs.push({name:c.querySelector('.mati-svc-name').value.trim(),duration:parseInt(c.querySelector('.mati-svc-duration').value)||30,price:parseFloat(c.querySelector('.mati-svc-price').value)||0,currency:c.querySelector('.mati-svc-currency').value,description:c.querySelector('.mati-svc-desc').value.trim(),category:c.querySelector('.mati-svc-category').value.trim(),color:c.querySelector('.mati-svc-color').value.trim()||'#3b82f6',bufferTime:parseInt(c.querySelector('.mati-svc-buffer').value)||0,deposit:parseFloat(c.querySelector('.mati-svc-deposit').value)||0,active:c.querySelector('.mati-svc-active').checked})});var fd=new FormData();fd.append('action','mati_save_services_v2');fd.append('nonce',matiData.nonce);fd.append('services',JSON.stringify(svcs));saveBtn.disabled=true;saveBtn.textContent='⏳...';fetch(matiData.ajaxurl,{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(){statusEl.textContent='✅ Guardado en mati.com.';statusEl.style.color='#16A34A';saveBtn.disabled=false;saveBtn.textContent='💾 Guardar Todo';setTimeout(function(){statusEl.textContent=''},3000)}).catch(function(){statusEl.textContent='❌ Error';statusEl.style.color='#EF4444';saveBtn.disabled=false;saveBtn.textContent='💾 Guardar Todo'})})})();
    </script>
    <?php
}
// ═══════════════════════════════════════════════════════════
// 5. PROFESIONALES
// ═══════════════════════════════════════════════════════════
function mati_render_providers() {
    if (mati_require_api_key()) return;
    $sync = mati_api_get('/sync');
    $provs = $sync['data']['providers'] ?? [];
    $data = mati_api_get('/data?section=bookings');
    $bookings = $data['data']['bookings'] ?? [];
    $provStats = [];
    foreach ($bookings as $b) { $pn = $b['providerName'] ?? 'Sin asignar'; if (!isset($provStats[$pn])) $provStats[$pn] = ['total' => 0, 'confirmed' => 0]; $provStats[$pn]['total']++; if ($b['status'] === 'CONFIRMED') $provStats[$pn]['confirmed']++; }
    mati_page_header('Profesionales', 'Gestioná tu equipo. Cada profesional puede tener su propio horario y servicios asignados.');
    ?>
    <div id="mati-providers-app-v2">
        <div class="mati-providers-grid" id="mati-providers-grid">
            <?php if (empty($provs)): ?>
                <div class="mati-card mati-text-center mati-p-2 mati-text-dim" style="grid-column:1/-1">👥 No hay profesionales. Agregá el primero.</div>
            <?php else: foreach ($provs as $i => $p): $pn = $p['name'] ?? ''; $stt = $provStats[$pn] ?? ['total' => 0, 'confirmed' => 0]; $comp = $stt['total'] > 0 ? round(($stt['confirmed'] / $stt['total']) * 100) : 0; $init = strtoupper(mb_substr($pn, 0, 1)); ?>
            <div class="mati-prov-card" data-index="<?php echo $i; ?>" onclick="if(!event.target.closest('input,button,label'))this.classList.toggle('expanded')">
                <div class="mati-prov-card-top">
                    <div class="mati-prov-avatar"><?php echo $init ?: '?'; ?></div>
                    <div style="flex:1;min-width:0">
                        <strong style="font-size:1rem"><?php echo esc_html($pn ?: 'Profesional ' . ($i+1)); ?></strong>
                        <div style="font-size:.8rem;color:var(--mati-text-dim)"><?php echo esc_html($p['role'] ?? 'Profesional'); ?></div>
                        <label class="mati-toggle-switch" style="margin-top:.35rem" onclick="event.stopPropagation()"><input type="checkbox" class="mati-prov-active" <?php echo (!isset($p['active']) || $p['active']) ? 'checked' : ''; ?>><span class="mati-toggle-slider"></span><span style="font-size:.75rem;margin-left:.35rem;color:var(--mati-text-dim)">Activo</span></label>
                    </div>
                </div>
                <div class="mati-prov-stats"><div class="mati-prov-stat"><div class="mati-prov-stat-val"><?php echo $stt['total']; ?></div><div class="mati-prov-stat-lbl">Reservas</div></div><div class="mati-prov-stat"><div class="mati-prov-stat-val"><?php echo $comp; ?>%</div><div class="mati-prov-stat-lbl">Conversión</div></div></div>
                <div class="mati-prov-body">
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem">
                        <div><label>Nombre</label><input type="text" class="mati-prov-name" value="<?php echo esc_attr($pn); ?>"></div>
                        <div><label>Email</label><input type="email" class="mati-prov-email" value="<?php echo esc_attr($p['email'] ?? ''); ?>"></div>
                        <div><label>Teléfono</label><input type="text" class="mati-prov-phone" value="<?php echo esc_attr($p['phone'] ?? ''); ?>"></div>
                        <div><label>Rol</label><input type="text" class="mati-prov-role" value="<?php echo esc_attr($p['role'] ?? ''); ?>"></div>
                        <div><label>Zona Horaria</label><input type="text" class="mati-prov-tz" value="<?php echo esc_attr($p['timezone'] ?? 'America/Argentina/Buenos_Aires'); ?>"></div>
                        <div><label>Color</label><input type="text" class="mati-prov-color" value="<?php echo esc_attr($p['color'] ?? '#3b82f6'); ?>"></div>
                        <div style="grid-column:1/-1"><label>Bio / Especialidad</label><textarea class="mati-prov-bio" rows="2"><?php echo esc_textarea($p['bio'] ?? ''); ?></textarea></div>
                    </div>
                    <button type="button" class="mati-btn mati-btn-danger mati-btn-sm mati-prov-delete" style="margin-top:.75rem">🗑 Eliminar</button>
                </div>
            </div>
            <?php endforeach; endif; ?>
        </div>
        <div class="mati-section-actions">
            <button type="button" class="mati-btn mati-btn-primary" id="mati-add-provider-v2">+ Agregar Profesional</button>
            <button type="button" class="mati-btn mati-btn-primary mati-btn-lg" id="mati-save-providers-v2">💾 Guardar Todo</button>
            <span id="mati-providers-status-v2" style="margin-left:.5rem;font-size:.85rem"></span>
        </div>
    </div>
    <script>
    (function(){var grid=document.getElementById('mati-providers-grid'),addBtn=document.getElementById('mati-add-provider-v2'),saveBtn=document.getElementById('mati-save-providers-v2'),statusEl=document.getElementById('mati-providers-status-v2');addBtn.addEventListener('click',function(){var empty=grid.querySelector('.mati-text-dim');if(empty)empty.remove();var d=document.createElement('div');d.className='mati-prov-card expanded';d.setAttribute('data-index',grid.children.length);d.innerHTML='<div class="mati-prov-card-top"><div class="mati-prov-avatar">?</div><div style="flex:1;min-width:0"><strong style="font-size:1rem">Nuevo Profesional</strong><div style="font-size:.8rem;color:var(--mati-text-dim)">Profesional</div><label class="mati-toggle-switch" style="margin-top:.35rem" onclick="event.stopPropagation()"><input type="checkbox" class="mati-prov-active" checked><span class="mati-toggle-slider"></span><span style="font-size:.75rem;margin-left:.35rem;color:var(--mati-text-dim)">Activo</span></label></div></div><div class="mati-prov-stats"><div class="mati-prov-stat"><div class="mati-prov-stat-val">0</div><div class="mati-prov-stat-lbl">Reservas</div></div><div class="mati-prov-stat"><div class="mati-prov-stat-val">0%</div><div class="mati-prov-stat-lbl">Conversión</div></div></div><div class="mati-prov-body" style="display:block"><div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem"><div><label>Nombre</label><input type="text" class="mati-prov-name" value="Nuevo Profesional"></div><div><label>Email</label><input type="email" class="mati-prov-email"></div><div><label>Teléfono</label><input type="text" class="mati-prov-phone"></div><div><label>Rol</label><input type="text" class="mati-prov-role" value="Profesional"></div><div><label>Zona Horaria</label><input type="text" class="mati-prov-tz" value="America/Argentina/Buenos_Aires"></div><div><label>Color</label><input type="text" class="mati-prov-color" value="#3b82f6"></div><div style="grid-column:1/-1"><label>Bio / Especialidad</label><textarea class="mati-prov-bio" rows="2"></textarea></div></div><button type="button" class="mati-btn mati-btn-danger mati-btn-sm mati-prov-delete" style="margin-top:.75rem">🗑 Eliminar</button></div>';grid.appendChild(d)});grid.addEventListener('click',function(e){if(e.target.classList.contains('mati-prov-delete')){e.target.closest('.mati-prov-card').remove();if(!grid.querySelector('.mati-prov-card'))grid.innerHTML='<div class="mati-card mati-text-center mati-p-2 mati-text-dim" style="grid-column:1/-1">👥 No hay profesionales. Agregá el primero.</div>'}});saveBtn.addEventListener('click',function(){var pvs=[];grid.querySelectorAll('.mati-prov-card').forEach(function(c){pvs.push({name:c.querySelector('.mati-prov-name').value.trim(),email:c.querySelector('.mati-prov-email').value.trim(),phone:c.querySelector('.mati-prov-phone').value.trim(),role:c.querySelector('.mati-prov-role').value.trim(),timezone:c.querySelector('.mati-prov-tz').value.trim(),color:c.querySelector('.mati-prov-color').value.trim()||'#3b82f6',bio:c.querySelector('.mati-prov-bio').value.trim(),active:c.querySelector('.mati-prov-active').checked})});var fd=new FormData();fd.append('action','mati_save_providers_v2');fd.append('nonce',matiData.nonce);fd.append('providers',JSON.stringify(pvs));saveBtn.disabled=true;saveBtn.textContent='⏳...';fetch(matiData.ajaxurl,{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(){statusEl.textContent='✅ Guardado en mati.com.';statusEl.style.color='#16A34A';saveBtn.disabled=false;saveBtn.textContent='💾 Guardar Todo';setTimeout(function(){statusEl.textContent=''},3000)}).catch(function(){statusEl.textContent='❌ Error';statusEl.style.color='#EF4444';saveBtn.disabled=false;saveBtn.textContent='💾 Guardar Todo'})})})();
    </script>
    <?php
}
// ═══════════════════════════════════════════════════════════
// 6. CALENDARIO (nativo via API) — v6.3 redesigned
// ═══════════════════════════════════════════════════════════
function mati_render_calendar() {
    if (mati_require_api_key()) return;

    $data = mati_api_get("/data?section=bookings");
    $bookings = $data["data"]["bookings"] ?? [];
    $ym = $_GET["ym"] ?? date("Y-m");
    list($year, $month) = explode("-", $ym);
    $year = intval($year); $month = intval($month);

    mati_page_header("Calendario", "Visualiza todas las reservas en el calendario mensual. Hace clic en un dia para ver los detalles.");

    // Build enriched booking map with status breakdown
    $bookingMap = []; $allBookingMap = []; $providerNames = [];
    foreach ($bookings as $b) {
        $day = date("Y-m-d", strtotime($b["startTime"] ?? ""));
        $status = $b["status"] ?? "PENDING";
        if (!isset($bookingMap[$day])) $bookingMap[$day] = ["count" => 0, "CONFIRMED" => 0, "PENDING" => 0, "CANCELLED" => 0, "items" => []];
        $bookingMap[$day]["count"]++;
        $bookingMap[$day][$status] = ($bookingMap[$day][$status] ?? 0) + 1;
        $bookingMap[$day]["items"][] = $b;
        if (!isset($allBookingMap[$day])) $allBookingMap[$day] = [];
        $allBookingMap[$day][] = $b;
        $pn = $b["providerName"] ?? "";
        if ($pn && !in_array($pn, $providerNames)) $providerNames[] = $pn;
    }
    sort($providerNames);

    $monthNames = ["","Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"];
    $prevM = $month == 1 ? 12 : $month - 1; $prevY = $month == 1 ? $year - 1 : $year;
    $nextM = $month == 12 ? 1 : $month + 1; $nextY = $month == 12 ? $year + 1 : $year;
    $monthTotal = 0;
    foreach ($bookingMap as $info) $monthTotal += $info["count"];

    // ── CSS ──
    ?>
    <style>
    .mati-cal-wrapper { display: flex; flex-direction: column; gap: 1rem; }
    .mati-cal-topbar { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; padding: .75rem 1.1rem; background: var(--mati-surface); border-radius: 1rem; box-shadow: var(--mati-shadow); }
    .mati-cal-stats { display: flex; align-items: center; gap: .5rem; font-weight: 600; color: var(--mati-text); font-size: .9rem; }
    .mati-cal-stats-icon { font-size: 1.15rem; }
    .mati-cal-legend { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; }
    .mati-legend-item { display: flex; align-items: center; gap: .35rem; font-size: .78rem; color: var(--mati-text-dim); }
    .mati-legend-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; flex-shrink: 0; }
    .mati-legend-dot.legend-confirmed { background: var(--mati-teal); }
    .mati-legend-dot.legend-pending { background: var(--mati-orange); }
    .mati-legend-dot.legend-cancelled { background: #EF4444; }
    .mati-cal-filter { display: flex; align-items: center; gap: .4rem; }
    .mati-cal-filter select { padding: .35rem .6rem; border: 1px solid var(--mati-border); border-radius: .5rem; font-size: .78rem; background: var(--mati-bg); color: var(--mati-text); }
    .mati-cal-navbar { display: flex; align-items: center; justify-content: space-between; gap: .75rem; }
    .mati-cal-nav-btn { display: flex; align-items: center; justify-content: center; width: 44px; height: 44px; border-radius: 50%; background: var(--mati-surface); border: 1px solid var(--mati-border); color: var(--mati-text); font-size: 1.2rem; text-decoration: none; cursor: pointer; transition: all .18s ease; box-shadow: 0 2px 8px rgba(0,0,0,.04); }
    .mati-cal-nav-btn:hover { background: var(--mati-blue); color: #fff; border-color: var(--mati-blue); transform: scale(1.06); box-shadow: 0 4px 14px rgba(7,34,188,.22); }
    .mati-cal-nav-center { display: flex; align-items: center; gap: .75rem; }
    .mati-cal-month-title { margin: 0; font-size: 1.5rem; font-weight: 700; color: var(--mati-text); letter-spacing: -.01em; }
    .mati-cal-today-btn { display: inline-flex; align-items: center; padding: .4rem .9rem; background: var(--mati-blue); color: #fff; border-radius: 2rem; font-size: .8rem; font-weight: 600; text-decoration: none; transition: all .18s ease; }
    .mati-cal-today-btn:hover { background: var(--mati-blue-dark); transform: translateY(-1px); box-shadow: 0 4px 12px rgba(7,34,188,.25); color: #fff; }
    .mati-cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 3px; background: var(--mati-border); border-radius: 1rem; overflow: hidden; box-shadow: var(--mati-shadow); }
    .mati-cal-day-header { background: var(--mati-bg); padding: .7rem .4rem; text-align: center; font-size: .72rem; font-weight: 700; color: var(--mati-text-dim); text-transform: uppercase; letter-spacing: .03em; }
    .mati-cal-day-header.weekend-header { color: #94A3B8; }
    .mati-cal-day { background: var(--mati-surface); min-height: 90px; padding: .5rem; position: relative; cursor: pointer; transition: all .18s ease; display: flex; flex-direction: column; }
    .mati-cal-day:hover { background: #EEF2FF; transform: scale(1.01); z-index: 2; box-shadow: 0 4px 16px rgba(7,34,188,.08); border-radius: .35rem; }
    .mati-cal-day:active { transform: scale(.98); }
    .mati-cal-day.other-month { opacity: .25; pointer-events: none; }
    .mati-cal-day.weekend { background: #FAFBFC; }
    .mati-cal-day.weekend:hover { background: #F0F3F8; }
    .mati-cal-day.today { box-shadow: inset 0 0 0 2.5px var(--mati-blue); border-radius: .35rem; background: #F5F7FF; }
    .mati-cal-day.today .mati-cal-day-num { color: var(--mati-blue); font-weight: 800; }
    .mati-cal-day.has-bookings { border-left: 3px solid var(--mati-teal); padding-left: calc(.5rem - 3px); }
    .mati-cal-day-num { font-size: .85rem; font-weight: 600; margin-bottom: .3rem; color: var(--mati-text); }
    .mati-cal-dots { display: flex; gap: 3px; flex-wrap: wrap; align-items: center; margin-top: auto; padding-top: .2rem; }
    .mati-cal-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
    .mati-cal-dot.dot-confirmed { background: var(--mati-teal); }
    .mati-cal-dot.dot-pending { background: var(--mati-orange); }
    .mati-cal-dot.dot-cancelled { background: #EF4444; opacity: .6; }
    .mati-cal-dot.more { width: auto; height: auto; background: none !important; font-size: .62rem; font-weight: 700; color: var(--mati-text-dim); margin-left: 1px; line-height: 1; }
    @media (max-width: 768px) { .mati-cal-topbar { flex-direction: column; align-items: flex-start; gap: .5rem; } .mati-cal-legend { gap: .6rem; } .mati-cal-month-title { font-size: 1.15rem; } .mati-cal-nav-btn { width: 36px; height: 36px; font-size: 1rem; } .mati-cal-day { min-height: 65px; padding: .3rem; } .mati-cal-day-num { font-size: .75rem; } .mati-cal-dot { width: 6px; height: 6px; } .mati-cal-day-header { font-size: .62rem; padding: .5rem .2rem; } }
    @media (max-width: 480px) { .mati-cal-grid { gap: 1px; border-radius: .5rem; } .mati-cal-day { min-height: 50px; padding: .2rem; } .mati-cal-day-num { font-size: .68rem; } .mati-cal-dot { width: 5px; height: 5px; } .mati-cal-dot.more { font-size: .55rem; } .mati-cal-month-title { font-size: 1rem; } .mati-cal-navbar { gap: .3rem; } }
    .mati-cal-detail-wrapper { display: none; animation: matiSlideUp .3s ease-out; }
    @keyframes matiSlideUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
    .mati-cal-detail-wrapper.active { display: block; }
    .mati-cal-detail-card { background: var(--mati-surface); border-radius: 1rem; padding: 1.5rem; box-shadow: var(--mati-shadow); }
    .mati-cal-detail-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem; }
    .mati-cal-detail-title { font-size: 1.15rem; font-weight: 700; margin: 0; color: var(--mati-text); }
    .mati-cal-detail-close { background: none; border: 1px solid var(--mati-border); border-radius: 50%; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 1.1rem; color: var(--mati-text-dim); transition: all .15s; }
    .mati-cal-detail-close:hover { background: #FEE2E2; border-color: #FCA5A5; color: #EF4444; }
    .mati-booking-card { display: flex; align-items: center; gap: .85rem; padding: .8rem .9rem; background: var(--mati-bg); border-radius: .75rem; margin-bottom: .45rem; transition: all .15s; }
    .mati-booking-card:hover { background: #EEF2FF; box-shadow: 0 2px 8px rgba(7,34,188,.05); }
    .mati-booking-card:last-child { margin-bottom: 0; }
    .mati-booking-card-avatar { width: 40px; height: 40px; border-radius: 50%; background: linear-gradient(135deg, var(--mati-blue), var(--mati-teal)); color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: .95rem; flex-shrink: 0; }
    .mati-booking-card-body { flex: 1; min-width: 0; }
    .mati-booking-card-name { font-weight: 600; font-size: .9rem; color: var(--mati-text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .mati-booking-card-meta { font-size: .78rem; color: var(--mati-text-dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .mati-booking-card-right { display: flex; flex-direction: column; align-items: flex-end; gap: .25rem; flex-shrink: 0; }
    .mati-booking-card-time { font-weight: 700; font-size: .9rem; color: var(--mati-text); }
    .mati-booking-card-status { font-size: .68rem; padding: .15rem .5rem; border-radius: 1rem; font-weight: 600; text-transform: uppercase; letter-spacing: .02em; }
    .mati-booking-card-status.status-confirmed { background: #D1FAE5; color: #065F46; }
    .mati-booking-card-status.status-pending { background: #FFF7ED; color: #9A3412; }
    .mati-booking-card-status.status-cancelled { background: #FEE2E2; color: #991B1B; }
    @media (max-width: 480px) { .mati-booking-card { flex-wrap: wrap; } .mati-booking-card-right { flex-direction: row; align-items: center; gap: .5rem; } }
    .mati-cal-empty-day { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 2rem 1rem; color: var(--mati-text-dim); text-align: center; }
    .mati-cal-empty-day-icon { font-size: 2.5rem; margin-bottom: .5rem; opacity: .45; }
    .mati-cal-empty-day-text { font-size: .9rem; font-weight: 500; }
    </style>
    <?php

    // ── Top bar ──
    echo "<div class=\"mati-cal-wrapper\">";
    echo "<div class=\"mati-cal-topbar\">";
    echo "<div class=\"mati-cal-stats\"><span class=\"mati-cal-stats-icon\">&#x1F4C5;</span><span class=\"mati-cal-stats-text\">" . $monthTotal . " reserva" . ($monthTotal !== 1 ? "s" : "") . " este mes</span></div>";
    echo "<div class=\"mati-cal-legend\">";
    echo "<span class=\"mati-legend-item\"><span class=\"mati-legend-dot legend-confirmed\"></span> Confirmada</span>";
    echo "<span class=\"mati-legend-item\"><span class=\"mati-legend-dot legend-pending\"></span> Pendiente</span>";
    echo "<span class=\"mati-legend-item\"><span class=\"mati-legend-dot legend-cancelled\"></span> Cancelada</span>";
    echo "</div>";
    if (!empty($providerNames)) {
        echo "<div class=\"mati-cal-filter\"><span style=\"font-size:.75rem;color:var(--mati-text-dim)\">Filtrar:</span><select id=\"mati-provider-filter\"><option value=\"\">Todos los profesionales</option>";
        foreach ($providerNames as $pn) echo "<option value=\"" . esc_attr($pn) . "\">" . esc_html($pn) . "</option>";
        echo "</select></div>";
    }
    echo "</div>";

    // ── Navigation ──
    echo "<div class=\"mati-cal-navbar\">";
    echo "<a href=\"?page=mati-calendar&ym=" . $prevY . "-" . str_pad($prevM, 2, "0", STR_PAD_LEFT) . "\" class=\"mati-cal-nav-btn\" title=\"" . $monthNames[$prevM] . "\">&larr;</a>";
    echo "<div class=\"mati-cal-nav-center\">";
    echo "<h2 class=\"mati-cal-month-title\">" . $monthNames[(int)$month] . " " . $year . "</h2>";
    echo "<a href=\"?page=mati-calendar&ym=" . date("Y-m") . "\" class=\"mati-cal-today-btn\">Hoy</a>";
    echo "</div>";
    echo "<a href=\"?page=mati-calendar&ym=" . $nextY . "-" . str_pad($nextM, 2, "0", STR_PAD_LEFT) . "\" class=\"mati-cal-nav-btn\" title=\"" . $monthNames[$nextM] . "\">&rarr;</a>";
    echo "</div>";

    // ── Grid ──
    echo mati_calendar_month_grid($year, $month, $bookingMap);

    // ── Detail panel ──
    ?>
    <div class="mati-cal-detail-wrapper" id="mati-cal-detail">
        <div class="mati-cal-detail-card">
            <div class="mati-cal-detail-header">
                <h3 class="mati-cal-detail-title" id="mati-cal-detail-title"></h3>
                <button class="mati-cal-detail-close" id="mati-cal-detail-close" title="Cerrar">&times;</button>
            </div>
            <div id="mati-cal-detail-list"></div>
        </div>
    </div>
    </div><!-- .mati-cal-wrapper -->

    <script>
    (function(){
        var allBookings = <?php echo json_encode($allBookingMap); ?>;
        var detail = document.getElementById("mati-cal-detail"),
            titleEl = document.getElementById("mati-cal-detail-title"),
            list = document.getElementById("mati-cal-detail-list"),
            closeBtn = document.getElementById("mati-cal-detail-close"),
            filterSelect = document.getElementById("mati-provider-filter");
        var days = ["Domingo","Lunes","Martes","Miercoles","Jueves","Viernes","Sabado"];
        var currentFilter = "";

        function renderDetail(date) {
            var rawBookings = allBookings[date] || [];
            var filtered = currentFilter ? rawBookings.filter(function(b) { return (b.providerName || "") === currentFilter; }) : rawBookings;
            var d = new Date(date + "T00:00:00");
            titleEl.textContent = days[d.getDay()] + " " + date;
            if (!filtered.length) {
                list.innerHTML = "<div class=\"mati-cal-empty-day\"><div class=\"mati-cal-empty-day-icon\">&#x1F4ED;</div><div class=\"mati-cal-empty-day-text\">Sin reservas este dia</div></div>";
            } else {
                list.innerHTML = filtered.map(function(b) {
                    var status = b.status || "PENDING";
                    var statusLabel = status === "CONFIRMED" ? "Confirmada" : (status === "CANCELLED" ? "Cancelada" : "Pendiente");
                    var statusColor = status === "CONFIRMED" ? "status-confirmed" : (status === "CANCELLED" ? "status-cancelled" : "status-pending");
                    var time = (b.startTime || "").split("T")[1] ? (b.startTime || "").split("T")[1].substring(0, 5) : "--:--";
                    var initial = (b.customerName || "?")[0].toUpperCase();
                    return "<div class=\"mati-booking-card\">" +
                        "<div class=\"mati-booking-card-avatar\">" + initial + "</div>" +
                        "<div class=\"mati-booking-card-body\">" +
                            "<div class=\"mati-booking-card-name\">" + (b.customerName || "—") + "</div>" +
                            "<div class=\"mati-booking-card-meta\">" + (b.serviceName || "—") + " · " + (b.providerName || "—") + "</div>" +
                        "</div>" +
                        "<div class=\"mati-booking-card-right\">" +
                            "<div class=\"mati-booking-card-time\">" + time + "</div>" +
                            "<span class=\"mati-booking-card-status " + statusColor + "\">" + statusLabel + "</span>" +
                        "</div>" +
                    "</div>";
                }).join("");
            }
            detail.classList.add("active");
            detail.scrollIntoView({behavior: "smooth", block: "nearest"});
        }

        document.querySelectorAll(".mati-cal-day:not(.other-month)").forEach(function(day) {
            day.addEventListener("click", function() { renderDetail(this.dataset.date); });
        });

        closeBtn.addEventListener("click", function() { detail.classList.remove("active"); });

        if (filterSelect) {
            filterSelect.addEventListener("change", function() {
                currentFilter = this.value;
                document.querySelectorAll(".mati-cal-day.has-bookings").forEach(function(day) {
                    var date = day.dataset.date;
                    var bkgs = allBookings[date] || [];
                    var filteredBooks = currentFilter ? bkgs.filter(function(b) { return (b.providerName || "") === currentFilter; }) : bkgs;
                    if (filteredBooks.length > 0) day.classList.add("has-bookings");
                    else day.classList.remove("has-bookings");
                    var dotsContainer = day.querySelector(".mati-cal-dots");
                    if (dotsContainer) {
                        var shown = 0, maxDots = 3, html = "";
                        var confirmed = filteredBooks.filter(function(b){return b.status==="CONFIRMED"}).length;
                        var pending   = filteredBooks.filter(function(b){return b.status==="PENDING"}).length;
                        var cancelled = filteredBooks.filter(function(b){return b.status==="CANCELLED"}).length;
                        for (var i = 0; i < confirmed  && shown < maxDots; i++) { html += "<span class=\"mati-cal-dot dot-confirmed\"></span>"; shown++; }
                        for (var i = 0; i < pending    && shown < maxDots; i++) { html += "<span class=\"mati-cal-dot dot-pending\"></span>";   shown++; }
                        for (var i = 0; i < cancelled  && shown < maxDots; i++) { html += "<span class=\"mati-cal-dot dot-cancelled\"></span>"; shown++; }
                        var remaining = filteredBooks.length - shown;
                        if (remaining > 0) html += "<span class=\"mati-cal-dot more\">+" + remaining + "</span>";
                        dotsContainer.innerHTML = html;
                    }
                });
                if (detail.classList.contains("active")) {
                    var activeDay = document.querySelector(".mati-cal-day.today");
                    if (activeDay) renderDetail(activeDay.dataset.date);
                }
            });
        }
    })();
    </script>
    <?php
}
// ═══════════════════════════════════════════════════════════
// 7. HORARIOS
// ═══════════════════════════════════════════════════════════
function mati_render_schedule() {
    if (mati_require_api_key()) return;
    $sync = mati_api_get('/sync');
    $sched = $sync['data']['schedule'] ?? [];
    $provs = $sync['data']['providers'] ?? [];
    if (isset($sched['Lun']) && !isset($sched['global'])) { $sched = ['global' => $sched, 'providers' => [], 'breaks' => [], 'exceptions' => []]; }
    $global = $sched['global'] ?? []; $provSchedule = $sched['providers'] ?? []; $breaks = $sched['breaks'] ?? []; $exceptions = $sched['exceptions'] ?? [];
    mati_page_header('Horarios', 'Configurá horarios generales y por profesional, pausas y días no laborables.');
    $days = ['Lun','Mar','Mié','Jue','Vie','Sáb','Dom'];
    $tabs = [['id'=>'global','label'=>'🌐 General','schedule'=>$global]];
    foreach ($provs as $idx => $p) { $pid = 'provider_' . $idx; $tabs[] = ['id'=>$pid, 'label'=>'👤 '.($p['name'] ?? 'Prof. '.($idx+1)), 'schedule'=>$provSchedule[$pid] ?? []]; }
    ?>
    <div id="mati-schedule-app-v2">
        <div class="mati-sched-tabs"><?php foreach ($tabs as $ti => $t): ?><button class="mati-sched-tab<?php echo $ti === 0 ? ' active' : ''; ?>" onclick="document.querySelectorAll('.mati-sched-tab').forEach(function(t){t.classList.remove('active')});this.classList.add('active');document.querySelectorAll('.mati-sched-panel').forEach(function(p){p.style.display=p.dataset.panel===this.dataset.tab?'block':'none'}.bind(this))" data-tab="<?php echo $t['id']; ?>"><?php echo esc_html($t['label']); ?></button><?php endforeach; ?></div>
        <?php foreach ($tabs as $ti => $t): ?>
        <div class="mati-sched-panel" data-panel="<?php echo $t['id']; ?>" style="<?php echo $ti === 0 ? '' : 'display:none'; ?>">
            <div class="mati-sched-week-overview">
                <?php foreach ($days as $d): $dd = $t['schedule'][$d] ?? ['active'=>true,'start'=>'09:00','end'=>'18:00']; $active = !empty($dd['active']); ?>
                <div class="mati-sched-week-day<?php echo $active ? '' : ' inactive'; ?>"><div class="mati-sched-week-day-label"><?php echo $d; ?></div><div><?php echo $active ? ($dd['start']??'09:00').'-'.($dd['end']??'18:00') : '—'; ?></div></div>
                <?php endforeach; ?>
            </div>
            <div class="mati-card"><div class="mati-schedule-grid">
                <?php foreach ($days as $d): $dd = $t['schedule'][$d] ?? ['active'=>true,'start'=>'09:00','end'=>'18:00']; ?>
                <div class="mati-schedule-day" data-day="<?php echo $d; ?>" data-panel="<?php echo $t['id']; ?>">
                    <label class="mati-schedule-toggle"><input type="checkbox" class="mati-sched-active" <?php echo !empty($dd['active'])?'checked':''; ?> /> <?php echo $d; ?></label>
                    <div class="mati-schedule-times"><input type="time" class="mati-sched-start" value="<?php echo esc_attr($dd['start']??'09:00'); ?>"><span>a</span><input type="time" class="mati-sched-end" value="<?php echo esc_attr($dd['end']??'18:00'); ?>"></div>
                </div>
                <?php endforeach; ?>
            </div></div>
        </div>
        <?php endforeach; ?>
        <div class="mati-card mati-mt-1"><h3 style="margin-top:0">⏸️ Pausas / Descansos</h3>
            <div id="mati-breaks-list">
                <?php foreach ($breaks as $bi => $br): ?>
                <div class="mati-break-slot"><select class="mati-break-day"><?php foreach ($days as $d): ?><option value="<?php echo $d; ?>" <?php selected($br['day'] ?? '', $d); ?>><?php echo $d; ?></option><?php endforeach; ?></select><input type="time" class="mati-break-start" value="<?php echo esc_attr($br['start'] ?? '12:00'); ?>"><span>a</span><input type="time" class="mati-break-end" value="<?php echo esc_attr($br['end'] ?? '13:00'); ?>"><input type="text" class="mati-break-label" value="<?php echo esc_attr($br['label'] ?? ''); ?>" placeholder="Ej: Almuerzo" style="max-width:120px"><button type="button" class="mati-btn mati-btn-danger mati-btn-sm" onclick="this.closest('.mati-break-slot').remove()">×</button></div>
                <?php endforeach; ?>
            </div>
            <button type="button" class="mati-btn mati-btn-outline mati-btn-sm" id="mati-add-break" style="margin-top:.5rem">+ Agregar Pausa</button>
        </div>
        <div class="mati-card mati-mt-50"><h3 style="margin-top:0">📅 Días No Laborables</h3>
            <div id="mati-exceptions-list">
                <?php foreach ($exceptions as $ei => $ex): ?>
                <div class="mati-exception-date"><input type="date" class="mati-exc-date" value="<?php echo esc_attr($ex['date'] ?? ''); ?>"><input type="text" class="mati-exc-reason" value="<?php echo esc_attr($ex['reason'] ?? ''); ?>" placeholder="Motivo" style="flex:1"><button type="button" class="mati-btn mati-btn-danger mati-btn-sm" onclick="this.closest('.mati-exception-date').remove()">×</button></div>
                <?php endforeach; ?>
            </div>
            <button type="button" class="mati-btn mati-btn-outline mati-btn-sm" id="mati-add-exception" style="margin-top:.5rem">+ Agregar Excepción</button>
        </div>
        <div class="mati-section-actions"><button type="button" class="mati-btn mati-btn-primary mati-btn-lg" id="mati-save-schedule-v2">💾 Guardar Horarios</button><span id="mati-schedule-status-v2" style="margin-left:.5rem;font-size:.85rem"></span></div>
    </div>
    <script>
    (function(){var days='<?php echo implode(",",$days); ?>'.split(',');document.getElementById('mati-add-break').addEventListener('click',function(){var d=document.createElement('div');d.className='mati-break-slot';d.innerHTML='<select class="mati-break-day">'+days.map(function(dd){return '<option value="'+dd+'">'+dd+'</option>'}).join('')+'</select><input type="time" class="mati-break-start" value="12:00"><span>a</span><input type="time" class="mati-break-end" value="13:00"><input type="text" class="mati-break-label" placeholder="Ej: Almuerzo" style="max-width:120px"><button type="button" class="mati-btn mati-btn-danger mati-btn-sm" onclick="this.closest(\'.mati-break-slot\').remove()">×</button>';document.getElementById('mati-breaks-list').appendChild(d)});document.getElementById('mati-add-exception').addEventListener('click',function(){var d=document.createElement('div');d.className='mati-exception-date';d.innerHTML='<input type="date" class="mati-exc-date"><input type="text" class="mati-exc-reason" placeholder="Motivo" style="flex:1"><button type="button" class="mati-btn mati-btn-danger mati-btn-sm" onclick="this.closest(\'.mati-exception-date\').remove()">×</button>';document.getElementById('mati-exceptions-list').appendChild(d)});document.getElementById('mati-save-schedule-v2').addEventListener('click',function(){var sch={global:{},providers:{},breaks:[],exceptions:[]};document.querySelectorAll('.mati-sched-panel').forEach(function(panel){var pid=panel.dataset.panel,obj={};panel.querySelectorAll('.mati-schedule-day').forEach(function(row){var day=row.dataset.day;obj[day]={active:row.querySelector('.mati-sched-active').checked,start:row.querySelector('.mati-sched-start').value,end:row.querySelector('.mati-sched-end').value}});if(pid==='global')sch.global=obj;else sch.providers[pid]=obj});document.querySelectorAll('.mati-break-slot').forEach(function(slot){sch.breaks.push({day:slot.querySelector('.mati-break-day').value,start:slot.querySelector('.mati-break-start').value,end:slot.querySelector('.mati-break-end').value,label:slot.querySelector('.mati-break-label').value.trim()})});document.querySelectorAll('.mati-exception-date').forEach(function(exc){var dt=exc.querySelector('.mati-exc-date').value;if(dt)sch.exceptions.push({date:dt,reason:exc.querySelector('.mati-exc-reason').value.trim()})});var fd=new FormData();fd.append('action','mati_save_schedule_v2');fd.append('nonce',matiData.nonce);fd.append('schedule',JSON.stringify(sch));var btn=document.getElementById('mati-save-schedule-v2'),st=document.getElementById('mati-schedule-status-v2');btn.disabled=true;btn.textContent='⏳...';fetch(matiData.ajaxurl,{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(){st.textContent='✅ Guardado en mati.com.';st.style.color='#16A34A';btn.disabled=false;btn.textContent='💾 Guardar Horarios';setTimeout(function(){st.textContent=''},3000)}).catch(function(){st.textContent='❌ Error';st.style.color='#EF4444';btn.disabled=false;btn.textContent='💾 Guardar Horarios'})})})();
    </script>
    <?php
}
// ═══════════════════════════════════════════════════════════
// 8. PAGOS (nativo via API)
// ═══════════════════════════════════════════════════════════
function mati_render_payments() {
    if (mati_require_api_key()) return;
    mati_page_header('Pagos', 'Historial completo de pagos con filtros y resumen.');
    if (!mati_plan_can('payments')) { echo '<div class="mati-card mati-text-center mati-p-lg"><div style="font-size:3rem;margin-bottom:1rem">💳</div><h2>Pagos — Plan '.mati_plan().'</h2><p class="mati-text-dim mati-mb-1-5">Los pagos integrados requieren un plan STARTER o superior.</p><a href="' . MATI_BROWSER_URL . '/account/plans" class="mati-btn mati-btn-primary mati-btn-lg" target="_blank">Actualizar Plan ↗</a></div>'; return; }
    $data = mati_api_get('/data?section=payments');
    $payments = $data['data']['payments'] ?? [];
    $totalRev = 0; $monthRev = 0; $pendingTotal = 0;
    $now = new DateTime(); $monthStart = new DateTime($now->format('Y-m-01'));
    foreach ($payments as $p) { $amt = floatval($p['amount'] ?? 0); $st = $p['status'] ?? ''; if ($st === 'COMPLETED') { $totalRev += $amt; if (new DateTime($p['createdAt'] ?? '') >= $monthStart) $monthRev += $amt; } if ($st === 'PENDING') $pendingTotal += $amt; }
    echo '<div class="mati-pay-summary">';
    echo '<div class="mati-kpi-card kpi-teal"><div class="mati-kpi-top"><span class="mati-kpi-icon">💰</span></div><div class="mati-kpi-value">$' . number_format($totalRev, 0) . '</div><div class="mati-kpi-label">Ingresos Totales</div></div>';
    echo '<div class="mati-kpi-card kpi-blue"><div class="mati-kpi-top"><span class="mati-kpi-icon">📅</span></div><div class="mati-kpi-value">$' . number_format($monthRev, 0) . '</div><div class="mati-kpi-label">Este Mes</div></div>';
    echo '<div class="mati-kpi-card kpi-orange"><div class="mati-kpi-top"><span class="mati-kpi-icon">⏳</span></div><div class="mati-kpi-value">$' . number_format($pendingTotal, 0) . '</div><div class="mati-kpi-label">Pendiente</div></div>';
    echo '<div class="mati-kpi-card kpi-purple"><div class="mati-kpi-top"><span class="mati-kpi-icon">📊</span></div><div class="mati-kpi-value">' . count($payments) . '</div><div class="mati-kpi-label">Transacciones</div></div>';
    echo '</div>';
    echo '<div class="mati-pay-filter-tabs"><button class="mati-pay-filter-tab active" data-filter="all">Todas</button><button class="mati-pay-filter-tab" data-filter="COMPLETED">Completadas</button><button class="mati-pay-filter-tab" data-filter="PENDING">Pendientes</button><button class="mati-pay-filter-tab" data-filter="REFUNDED">Reembolsadas</button></div>';
    echo '<div class="mati-card mati-p-0 mati-overflow-x-auto"><table class="mati-table" id="mati-payments-table"><thead><tr><th>Cliente</th><th>Método</th><th>Monto</th><th>Fecha</th><th>Estado</th></tr></thead><tbody>';
    if (empty($payments)) { echo '<tr><td colspan="5" class="mati-text-center mati-text-dim mati-p-2">No hay pagos registrados.</td></tr>'; }
    else { foreach ($payments as $p) { $st = $p['status'] ?? 'PENDING'; $statusHtml = $st === 'COMPLETED' ? '<span class="mati-badge-status mati-status-confirmed">Completado</span>' : ($st === 'REFUNDED' ? '<span class="mati-badge-status mati-status-cancelled">Reembolsado</span>' : '<span class="mati-badge-status mati-status-pending">Pendiente</span>'); $method = '<span class="mati-pay-method"><span class="mati-pay-method-icon">' . mati_payment_icon($p['paymentMethod'] ?? $p['provider'] ?? '') . '</span> ' . esc_html($p['paymentMethod'] ?? $p['provider'] ?? '—') . '</span>'; $amt = '<span style="color:var(--mati-teal);font-weight:600">$' . number_format(floatval($p['amount'] ?? 0), 2) . ' ' . esc_html($p['currency'] ?? 'USD') . '</span>'; echo '<tr data-status="' . esc_attr($st) . '"><td>' . esc_html($p['customerName'] ?? '—') . '</td><td>' . $method . '</td><td>' . $amt . '</td><td>' . date('d/m/Y', strtotime($p['createdAt'] ?? '')) . '</td><td>' . $statusHtml . '</td></tr>'; } }
    echo '</tbody></table></div>'; ?>
    <script>
    (function(){document.querySelectorAll('.mati-pay-filter-tab').forEach(function(f){f.addEventListener('click',function(){document.querySelectorAll('.mati-pay-filter-tab').forEach(function(ff){ff.classList.remove('active')});this.classList.add('active');var filter=this.dataset.filter;document.querySelectorAll('#mati-payments-table tbody tr').forEach(function(tr){tr.style.display=(filter==='all'||tr.dataset.status===filter)?'':'none'});});});})();
    </script>
    <?php
}
// ═══════════════════════════════════════════════════════════
// 9. WIDGET — Configuración completa e interactiva
// ═══════════════════════════════════════════════════════════
function mati_render_widget_unified() {
    if (mati_require_api_key()) return;
    $slug    = mati_api_slug();
    $variant = get_option('mati_widget_variant', 'default');
    $panels  = json_decode(get_option('mati_panels_enabled', '{"admin":true,"provider":true,"customer":true}'), true);
    if (!is_array($panels)) $panels = ['admin'=>true,'provider'=>true,'customer'=>true];
    $color   = get_option('mati_color', '#1A5D4A');
    $greeting= get_option('mati_greeting', '¡Hola! ¿En qué puedo ayudarte?');
    $position= get_option('mati_position', 'bottom-right');
    $lang    = get_option('mati_language', 'es');
    $btnText = get_option('mati_button_text', 'Reservar');
    $autoOpen= get_option('mati_auto_open', 'no');
    $agentMode=get_option('mati_agent_mode', 'on');
    $voice   = get_option('mati_voice', 'no');
    $autoInject = get_option('mati_auto_inject', 'off');

    mati_page_header('Widget & Embed', 'Personalizá cómo se ve, funciona y se integra tu widget de reservas en cualquier sitio.');
    ?>
    <form method="post" action="options.php" class="mati-settings-form"><?php settings_fields('mati_settings'); ?>
    <input type="hidden" name="mati_api_key" value="<?php echo esc_attr(mati_api_key()); ?>" />
    <input type="hidden" name="mati_slug" value="<?php echo esc_attr($slug); ?>" />
    <input type="hidden" name="mati_plan" value="<?php echo esc_attr(get_option('mati_plan','BUSINESS')); ?>" />
    <input type="hidden" name="mati_setup_complete" value="<?php echo esc_attr(get_option('mati_setup_complete','1')); ?>" />

    <div style="display:grid;grid-template-columns:360px 1fr;gap:1.5rem;align-items:start">

        <!-- ===== LEFT COLUMN: Configuration ===== -->
        <div style="display:flex;flex-direction:column;gap:1rem">

            <!-- Templates -->
            <div class="mati-card">
                <h3 style="margin-top:0">🎨 Plantillas</h3>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:.4rem">
                    <?php
                    $templates = [
                        'clasico'   => ['Clásico', '#1A5D4A', '¡Hola! ¿En qué puedo ayudarte?', 'default'],
                        'moderno'   => ['Moderno', '#6366F1', 'Bienvenido/a. Reservá tu cita en segundos.', 'modern'],
                        'minimal'   => ['Minimal', '#334155', 'Hacé tu reserva.', 'minimal'],
                        'salud'     => ['Salud', '#0D9488', '¡Hola! Agenda tu consulta médica hoy.', 'default'],
                        'belleza'   => ['Belleza', '#DB2777', '¡Bienvenida! Reservá tu turno de belleza.', 'default'],
                        'fitness'   => ['Fitness', '#EA580C', '¡Vamos! Reservá tu clase de entrenamiento.', 'default'],
                        'educacion' => ['Educación', '#7C3AED', '¡Hola! Reservá tu clase o tutoría.', 'default'],
                        'custom'    => ['Custom', $color, $greeting, $variant],
                    ];
                    foreach ($templates as $key => $t):
                        $active = ($key === 'custom') ? true : ($variant === $t[3] && $color === $t[1]);
                    ?>
                    <button type="button" class="mati-template-card<?php echo $active ? ' active' : ''; ?>"
                        data-color="<?php echo esc_attr($t[1]); ?>"
                        data-greeting="<?php echo esc_attr($t[2]); ?>"
                        data-variant="<?php echo esc_attr($t[3]); ?>"
                        onclick="applyTemplate(event,'<?php echo esc_js($t[1]); ?>','<?php echo esc_js($t[2]); ?>','<?php echo esc_js($t[3]); ?>')">
                        <span class="mati-template-swatch" style="background:<?php echo esc_attr($t[1]); ?>"></span>
                        <span class="mati-template-name"><?php echo esc_html($t[0]); ?></span>
                    </button>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Appearance -->
            <div class="mati-card">
                <h3 style="margin-top:0">✨ Apariencia</h3>
                <div class="mati-svc-card-field"><label>Color Principal</label>
                    <div style="display:flex;gap:.5rem;align-items:center">
                        <input type="color" name="mati_color" id="mati-color-picker" value="<?php echo esc_attr($color); ?>" onchange="onConfigChange()" style="width:44px;height:38px;padding:2px;border:1px solid var(--mati-border);border-radius:.4rem;cursor:pointer">
                        <input type="text" id="mati-color-text" value="<?php echo esc_attr($color); ?>" onchange="onConfigChange()" style="flex:1;font-family:monospace;font-size:.85rem" maxlength="7" placeholder="#1A5D4A">
                    </div>
                </div>
                <div class="mati-svc-card-field"><label>Variante Visual</label>
                    <select name="mati_widget_variant" id="mati-variant" onchange="onConfigChange()" style="width:100%">
                        <?php foreach (['default'=>'Por defecto','classic'=>'Clásico','modern'=>'Moderno','minimal'=>'Minimal'] as $k=>$v): ?>
                        <option value="<?php echo $k; ?>" <?php selected($variant,$k); ?>><?php echo $v; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mati-svc-card-field"><label>Posición</label>
                    <select name="mati_position" id="mati-position" onchange="onConfigChange()" style="width:100%">
                        <?php foreach (['bottom-right'=>'Abajo derecha','bottom-left'=>'Abajo izquierda','inline'=>'En línea (shortcode)'] as $k=>$v): ?>
                        <option value="<?php echo $k; ?>" <?php selected($position,$k); ?>><?php echo $v; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mati-svc-card-field"><label>Idioma</label>
                    <select name="mati_language" id="mati-language" onchange="onConfigChange()" style="width:100%">
                        <?php foreach (['es'=>'Español','en'=>'English','pt'=>'Português','fr'=>'Français','de'=>'Deutsch','it'=>'Italiano'] as $k=>$v): ?>
                        <option value="<?php echo $k; ?>" <?php selected($lang,$k); ?>><?php echo $v; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mati-svc-card-field"><label>Texto del Botón Flotante</label>
                    <input type="text" name="mati_button_text" id="mati-button-text" value="<?php echo esc_attr($btnText); ?>" onchange="onConfigChange()" oninput="onConfigChange()" style="width:100%" maxlength="30">
                </div>
                <div class="mati-svc-card-field"><label>Mensaje de Bienvenida</label>
                    <textarea name="mati_greeting" id="mati-greeting" onchange="onConfigChange()" oninput="onConfigChange()" style="width:100%" rows="2" maxlength="120"><?php echo esc_textarea($greeting); ?></textarea>
                </div>
            </div>

            <!-- Behavior -->
            <div class="mati-card">
                <h3 style="margin-top:0">🧠 Comportamiento</h3>
                <div class="mati-svc-card-field"><label>Apertura Automática</label>
                    <select name="mati_auto_open" id="mati-auto-open" onchange="onConfigChange()" style="width:100%">
                        <option value="no" <?php selected($autoOpen,'no'); ?>>No — Solo al hacer clic</option>
                        <option value="yes" <?php selected($autoOpen,'yes'); ?>>Sí — Abrir al cargar</option>
                        <option value="delay" <?php selected($autoOpen,'delay'); ?>>Con delay — 5 segundos</option>
                    </select>
                </div>
                <div class="mati-svc-card-field"><label>Modo Agente IA</label>
                    <select name="mati_agent_mode" id="mati-agent-mode" onchange="onConfigChange()" style="width:100%">
                        <option value="on" <?php selected($agentMode,'on'); ?>>Activado — El agente conversa con clientes</option>
                        <option value="off" <?php selected($agentMode,'off'); ?>>Desactivado — Solo selector de servicios</option>
                    </select>
                </div>
                <div class="mati-svc-card-field"><label>Entrada por Voz</label>
                    <select name="mati_voice" id="mati-voice" onchange="onConfigChange()" style="width:100%">
                        <option value="no" <?php selected($voice,'no'); ?>>No</option>
                        <option value="yes" <?php selected($voice,'yes'); ?>>Sí (Premium)</option>
                    </select>
                </div>
                <div class="mati-svc-card-field"><label>Inyección automática</label>
                    <select name="mati_auto_inject" id="mati-auto-inject" onchange="onConfigChange()" style="width:100%">
                        <option value="off" <?php selected($autoInject,'off'); ?>>Desactivada — Usar solo shortcode</option>
                        <option value="on" <?php selected($autoInject,'on'); ?>>Activada — Mostrar botón flotante en todo el sitio</option>
                    </select>
                </div>
            </div>

            <!-- Panels -->
            <div class="mati-card">
                <h3 style="margin-top:0">🖥️ Paneles Habilitados</h3>
                <input type="hidden" name="mati_panels_enabled" id="mati-panels-json" value='<?php echo esc_attr(json_encode($panels)); ?>'>
                <?php foreach (['admin'=>'Admin Dashboard','provider'=>'Panel Profesional','customer'=>'Portal Cliente'] as $pk=>$pl): ?>
                <label style="display:flex;align-items:center;justify-content:space-between;padding:.6rem 0;border-bottom:1px solid var(--mati-border);cursor:pointer">
                    <span style="font-size:.9rem"><?php echo $pl; ?></span>
                    <input type="checkbox" data-panel="<?php echo $pk; ?>" <?php checked(!empty($panels[$pk])); ?> onchange="updatePanels()" style="width:18px;height:18px;accent-color:var(--mati-teal)">
                </label>
                <?php endforeach; ?>
            </div>

            <!-- Save -->
            <button type="submit" class="mati-btn mati-btn-primary mati-btn-lg" style="width:100%;padding:.9rem">💾 Guardar Configuración</button>
        </div>

        <!-- ===== RIGHT COLUMN: Preview + Embed ===== -->
        <div style="display:flex;flex-direction:column;gap:1rem">

            <!-- Live Preview -->
            <div class="mati-card" style="overflow:hidden">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.75rem">
                    <h3 style="margin:0">👁️ Vista Previa en Vivo</h3>
                    <div style="display:flex;gap:.25rem">
                        <?php foreach (['widget'=>'Widget','admin'=>'Admin','provider'=>'Profesional','customer'=>'Cliente'] as $tk=>$tl): ?>
                        <button type="button" class="mati-preview-tab<?php echo $tk==='widget'?' active':''; ?>" data-tab="<?php echo $tk; ?>" onclick="switchPreviewTab('<?php echo $tk; ?>')" style="padding:.3rem .7rem;font-size:.75rem;border:1px solid var(--mati-border);border-radius:1rem;background:white;cursor:pointer"><?php echo $tl; ?></button>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div style="background:linear-gradient(135deg,#f1f5f9,#e2e8f0);border-radius:.75rem;padding:.5rem;min-height:420px;display:flex;align-items:center;justify-content:center">
                    <iframe id="mati-preview-iframe" src="<?php echo esc_url(MATI_BROWSER_URL . '/widget/'.urlencode($slug).'?variant='.urlencode($variant).'&theme=light&color='.urlencode($color).'&greeting='.urlencode($greeting)); ?>" style="width:100%;height:420px;border:none;border-radius:.5rem;background:white;box-shadow:0 4px 24px rgba(0,0,0,0.08)" loading="lazy" title="Widget Preview" allow="clipboard-write"></iframe>
                </div>
            </div>

            <!-- Embed Code -->
            <div class="mati-card">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.75rem">
                    <h3 style="margin:0">💻 Código Embed</h3>
                    <button type="button" class="mati-btn mati-btn-primary mati-btn-sm" onclick="copyEmbedCode(event)">📋 Copiar</button>
                </div>
                <div style="background:#0f172a;color:#e2e8f0;padding:1.25rem;border-radius:.75rem;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;font-size:.8rem;overflow-x:auto;position:relative;line-height:1.7" id="mati-embed-code">
&lt;script src="<?php echo MATI_SCRIPT_URL; ?>"<br>
&nbsp;&nbsp;data-slug="<?php echo esc_attr($slug); ?>"<br>
&nbsp;&nbsp;data-variant="<?php echo esc_attr($variant); ?>"<br>
&nbsp;&nbsp;data-position="<?php echo esc_attr($position); ?>"<br>
&nbsp;&nbsp;data-theme="light"<br>
&nbsp;&nbsp;data-language="<?php echo esc_attr($lang); ?>"<br>
&nbsp;&nbsp;data-primary-color="<?php echo esc_attr($color); ?>"<br>
&nbsp;&nbsp;data-button-text="<?php echo esc_attr($btnText); ?>"<br>
&nbsp;&nbsp;data-greeting="<?php echo esc_attr($greeting); ?>"<br>
&nbsp;&nbsp;data-auto-open="<?php echo esc_attr($autoOpen); ?>"<br>
&nbsp;&nbsp;data-agent-mode="<?php echo esc_attr($agentMode); ?>"<br>
&nbsp;&nbsp;async&gt;&lt;/script&gt;
                </div>
                <p style="font-size:.75rem;color:var(--mati-text-dim);margin-top:.5rem">Pegá este código en cualquier sitio web (WordPress, Shopify, Wix, HTML) antes de <code>&lt;/body&gt;</code>.</p>
            </div>

            <!-- Shortcodes Reference -->
            <div class="mati-card">
                <h3 style="margin-top:0">ð Shortcodes para WordPress</h3>
                <p style="font-size:.82rem;color:var(--mati-text-dim);margin-bottom:1rem">CopiÃ¡ y pegÃ¡ cualquiera de estos shortcodes en tus pÃ¡ginas o entradas. Cada uno abre un panel especÃ­fico de Mati directamente en el frontend.</p>
                <div style="display:flex;flex-direction:column;gap:1rem">

                    <?php
                    $colorEg = get_option('mati_color', '#1A5D4A');
                    $slugSc = mati_api_slug();

                    $sc_items = [
                        [
                            'shortcode' => '[mati_widget position="bottom-right" color="'.$colorEg.'" language="es"]',
                            'title'     => 'Widget flotante de reservas',
                            'desc'      => 'BotÃ³n flotante con el asistente IA. Los clientes reservan turnos, hacen preguntas al agente y completan todo el proceso sin salir de tu web.',
                            'params'    => [
                                'position'    => '"bottom-right" | "bottom-left" | "inline" â Donde aparece el botÃ³n.',
                                'color'       => '"'.$colorEg.'" â Color principal del widget (hex).',
                                'language'    => '"es" | "en" | "pt" | "fr" | "de" | "it" â Idioma.',
                                'variant'     => '"default" | "modern" | "minimal" â Estilo visual.',
                                'greeting'    => '"Â¡Hola! Â¿En quÃ© puedo ayudarte?" â Mensaje de bienvenida.',
                                'button_text' => '"Reservar" â Texto del botÃ³n flotante.',
                                'auto_open'   => '"no" | "yes" | "delay" â Abrir automÃ¡ticamente.',
                                'agent_mode'  => '"on" | "off" â Activa o desactiva el agente IA.',
                            ],
                        ],
                        [
                            'shortcode' => '[mati_panel section="dashboard" color="'.$colorEg.'" height="900px"]',
                            'title'     => 'Panel de administraciÃ³n completo',
                            'desc'      => 'Dashboard de gestiÃ³n con mÃ©tricas, reservas, clientes, servicios, y mÃ¡s. Solo visible para administradores de WordPress logueados.',
                            'params'    => [
                                'section' => '"dashboard" | "bookings" | "calendar" | "services" | "customers" | "providers" | "payments" â SecciÃ³n a mostrar.',
                                'color'   => '"'.$colorEg.'" â Color del encabezado y acentos.',
                                'height'  => '"900px" â Altura del iframe (ej. "800px", "100vh").',
                                'lang'    => '"es" | "en" | "pt" â Idioma del panel.',
                            ],
                        ],
                        [
                            'shortcode' => '[mati_panel section="bookings" height="800px"]',
                            'title'     => 'GestiÃ³n de reservas en frontend',
                            'desc'      => 'Listado completo de reservas con filtros, bÃºsqueda y acciones (confirmar, cancelar, reprogramar). Solo administradores.',
                            'params'    => [
                                'section' => '"bookings" â Muestra la grilla de reservas.',
                                'height'  => '"800px" â Altura del panel.',
                                'color'   => '"'.$colorEg.'" â Color de acentos.',
                            ],
                        ],
                        [
                            'shortcode' => '[mati_panel section="calendar" height="800px"]',
                            'title'     => 'Calendario mensual en frontend',
                            'desc'      => 'Vista de calendario con reservas del mes. NavegaciÃ³n entre meses, filtros por profesional, y creaciÃ³n rÃ¡pida de citas.',
                            'params'    => [
                                'section' => '"calendar" â Vista calendario mensual.',
                                'height'  => '"800px" â Altura del panel.',
                                'color'   => '"'.$colorEg.'" â Color de acentos.',
                            ],
                        ],
                        [
                            'shortcode' => '[mati_provider_panel provider_id="" color="'.$colorEg.'" height="800px"]',
                            'title'     => 'Panel del profesional',
                            'desc'      => 'Panel reducido para que cada profesional vea su agenda, disponibilidad, y reserve bloques de tiempo.',
                            'params'    => [
                                'provider_id' => '"abc123" â ID del profesional (obligatorio). Obtenelo en Mati â Proveedores.',
                                'color'       => '"'.$colorEg.'" â Color de acentos.',
                                'height'      => '"800px" â Altura del panel.',
                            ],
                        ],
                        [
                            'shortcode' => '[mati_customer_portal color="'.$colorEg.'" height="700px"]',
                            'title'     => 'Portal del cliente',
                            'desc'      => 'Tus clientes pueden ver sus reservas, cancelar, reprogramar, y dejar reseÃ±as desde esta pÃ¡gina.',
                            'params'    => [
                                'color'  => '"'.$colorEg.'" â Color de acentos del portal.',
                                'height' => '"700px" â Altura del panel.',
                                'lang'   => '"es" | "en" | "pt" â Idioma del portal.',
                            ],
                        ],
                    ];

                    foreach ($sc_items as $item):
                        $scFull = $item['shortcode'];
                    ?>
                    <!-- Shortcode card -->
                    <div style="border:1px solid var(--mati-border);border-radius:.6rem;padding:1rem;background:var(--mati-bg)">
                        <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:.5rem">
                            <div style="flex:1">
                                <strong style="font-size:.88rem"><?php echo esc_html($item['title']); ?></strong>
                                <p style="font-size:.78rem;color:var(--mati-text-dim);margin:.25rem 0 .5rem"><?php echo esc_html($item['desc']); ?></p>
                            </div>
                            <button type="button" class="mati-btn mati-btn-primary mati-btn-sm"
                                onclick="copyText('<?php echo esc_js($scFull); ?>',this)"
                                style="flex-shrink:0;margin-left:.75rem;white-space:nowrap">ð Copiar</button>
                        </div>
                        <pre style="background:#0f172a;color:#e2e8f0;padding:.75rem;border-radius:.4rem;font-size:.78rem;overflow-x:auto;margin:.5rem 0 0;line-height:1.5;white-space:pre-wrap;word-break:break-all"><?php echo esc_html($scFull); ?></pre>
                        <details style="margin-top:.5rem;font-size:.78rem">
                            <summary style="cursor:pointer;color:var(--mati-blue);font-weight:500">ParÃ¡metros disponibles</summary>
                            <ul style="margin:.5rem 0 0 1.2rem;color:var(--mati-text-dim);line-height:1.6">
                                <?php foreach ($item['params'] as $p): ?>
                                <li><code style="background:var(--mati-bg);padding:.1rem .35rem;border-radius:.2rem;font-size:.75rem"><?php echo esc_html($p); ?></code></li>
                                <?php endforeach; ?>
                            </ul>
                        </details>
                    </div>
                    <?php endforeach; ?>

                </div>
            </div>
        </div>

    </div>
    </form>

    <script>
    // âââ Real-time preview & embed updates âââ
    var slug = '<?php echo esc_js($slug); ?>';
    var browserUrl = '<?php echo esc_js(MATI_BROWSER_URL); ?>';
    var scriptUrl = '<?php echo esc_js(MATI_SCRIPT_URL); ?>';
    var activePreviewTab = 'widget';

    function $el(id) { return document.getElementById(id); }
    function $val(id) { var e = $el(id); return e ? e.value : ''; }

    function getConfig() {
        return {
            color: $val('mati-color-picker'),
            variant: $val('mati-variant'),
            position: $val('mati-position'),
            language: $val('mati-language'),
            buttonText: $val('mati-button-text'),
            greeting: $val('mati-greeting'),
            autoOpen: $val('mati-auto-open'),
            agentMode: $val('mati-agent-mode')
        };
    }

    function onConfigChange() {
        var cp = $el('mati-color-picker');
        var ct = $el('mati-color-text');
        if (cp && ct) {
            if (document.activeElement === ct) {
                var v = ct.value.trim();
                if (/^#[0-9A-Fa-f]{3,6}$/.test(v)) { cp.value = v; }
            } else {
                ct.value = cp.value;
            }
        }
        updatePreview();
        updateEmbedCode();
    }

    $el('mati-color-text').addEventListener('input', function() {
        var v = this.value.trim();
        if (/^#[0-9A-Fa-f]{3,6}$/.test(v)) {
            var cp = $el('mati-color-picker');
            if (cp) cp.value = v;
            updatePreview();
            updateEmbedCode();
        }
    });

    $el('mati-color-picker').addEventListener('input', function() {
        var ct = $el('mati-color-text');
        if (ct) ct.value = this.value;
        updatePreview();
        updateEmbedCode();
    });

    function switchPreviewTab(tab) {
        activePreviewTab = tab;
        document.querySelectorAll('.mati-preview-tab').forEach(function(t) {
            var isActive = t.dataset.tab === tab;
            t.style.background = isActive ? 'var(--mati-blue)' : 'white';
            t.style.color = isActive ? 'white' : 'var(--mati-text)';
            t.style.fontWeight = isActive ? '600' : '400';
        });
        updatePreview();
    }

    function updatePreview() {
        var iframe = $el('mati-preview-iframe');
        if (!iframe) return;
        var c = getConfig();
        var apiKey = '<?php echo esc_js(mati_api_key()); ?>';
        var url = browserUrl;
        if (activePreviewTab === 'widget') {
            url += '/widget/' + encodeURIComponent(slug) + '?variant=' + encodeURIComponent(c.variant) + '&theme=light&color=' + encodeURIComponent(c.color) + '&greeting=' + encodeURIComponent(c.greeting) + '&lang=' + encodeURIComponent(c.language);
        } else if (activePreviewTab === 'admin') {
            url += '/widget/panel/admin/' + encodeURIComponent(slug) + '?apiKey=' + encodeURIComponent(apiKey) + '&theme=light&color=' + encodeURIComponent(c.color);
        } else if (activePreviewTab === 'provider') {
            url += '/widget/panel/provider/' + encodeURIComponent(slug) + '?apiKey=' + encodeURIComponent(apiKey) + '&theme=light&color=' + encodeURIComponent(c.color);
        } else if (activePreviewTab === 'customer') {
            url += '/widget/panel/customer/' + encodeURIComponent(slug) + '?apiKey=' + encodeURIComponent(apiKey) + '&theme=light&color=' + encodeURIComponent(c.color);
        }
        iframe.src = url;
    }

    function updateEmbedCode() {
        var c = getConfig();
        var el = $el('mati-embed-code');
        if (!el) return;
        el.innerHTML = '&lt;script src="' + scriptUrl + '"<br>' +
            '&nbsp;&nbsp;data-slug="' + slug + '"<br>' +
            '&nbsp;&nbsp;data-variant="' + c.variant + '"<br>' +
            '&nbsp;&nbsp;data-position="' + c.position + '"<br>' +
            '&nbsp;&nbsp;data-theme="light"<br>' +
            '&nbsp;&nbsp;data-language="' + c.language + '"<br>' +
            '&nbsp;&nbsp;data-primary-color="' + c.color + '"<br>' +
            '&nbsp;&nbsp;data-button-text="' + c.buttonText + '"<br>' +
            '&nbsp;&nbsp;data-greeting="' + c.greeting + '"<br>' +
            '&nbsp;&nbsp;data-auto-open="' + c.autoOpen + '"<br>' +
            '&nbsp;&nbsp;data-agent-mode="' + c.agentMode + '"<br>' +
            '&nbsp;&nbsp;async&gt;&lt;/script&gt;';
    }

    function applyTemplate(ev, color, greeting, variant) {
        document.querySelectorAll('.mati-template-card').forEach(function(c) { c.classList.remove('active'); });
        if (ev && ev.target) {
            var card = ev.target.closest('.mati-template-card');
            if (card) card.classList.add('active');
        }
        var cp = $el('mati-color-picker');
        var ct = $el('mati-color-text');
        var vs = $el('mati-variant');
        var gr = $el('mati-greeting');
        if (cp) cp.value = color;
        if (ct) ct.value = color;
        if (vs) vs.value = variant;
        if (gr) gr.value = greeting;
        updatePreview();
        updateEmbedCode();
    }

    function updatePanels() {
        var panels = {};
        document.querySelectorAll('[data-panel]').forEach(function(cb) {
            panels[cb.dataset.panel] = cb.checked;
        });
        var jsonEl = $el('mati-panels-json');
        if (jsonEl) jsonEl.value = JSON.stringify(panels);
    }

    function copyEmbedCode(ev) {
        var el = $el('mati-embed-code');
        if (!el) return;
        var text = el.innerText
            .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
            .replace(/ /g, ' ').replace(/<br>/g, '\n');
        navigator.clipboard.writeText(text).then(function() {
            var btn = (ev && ev.target) ? ev.target : null;
            if (!btn) return;
            var orig = btn.textContent;
            btn.textContent = 'â Copiado!';
            setTimeout(function() { btn.textContent = orig; }, 1500);
        }).catch(function() {
            var ta = document.createElement('textarea');
            ta.value = text; ta.style.position = 'fixed'; ta.style.left = '-9999px';
            document.body.appendChild(ta); ta.select();
            document.execCommand('copy'); document.body.removeChild(ta);
        });
    }

    function copyText(text, btn) {
        navigator.clipboard.writeText(text).then(function() {
            var orig = btn.textContent;
            btn.textContent = 'â';
            setTimeout(function() { btn.textContent = orig; }, 1200);
        }).catch(function() {
            var ta = document.createElement('textarea');
            ta.value = text; ta.style.position = 'fixed'; ta.style.left = '-9999px';
            document.body.appendChild(ta); ta.select();
            document.execCommand('copy'); document.body.removeChild(ta);
        });
    }

    // Init: activate first preview tab
    switchPreviewTab('widget');
    </script>
    <?php
}

// Redirect old separate page slugs to unified page
function mati_render_widget() { mati_render_widget_unified(); }
function mati_render_widget_config() { mati_render_widget_unified(); }

// INTEGRACIONES — Todas las plataformas y conexiones
// ═══════════════════════════════════════════════════════════
function mati_render_integrations() {
    if (mati_require_api_key()) return;
    mati_page_header('Integraciones', 'Conectá Mati con todas tus plataformas y herramientas.');
    $slug = mati_api_slug();
    ?>
    <div class="mati-db-grid">
        <?php
        $integrations = [
            ['wordpress', 'WordPress', 'Plugin nativo con panel de administración, shortcodes y configuración visual. Instalado y activo.', true],
            ['shopify', 'Shopify', 'Liquid snippet para Theme Editor. Widget flotante con panel de configuración.', false],
            ['wix', 'Wix', 'Código embed compatible con Wix Custom Code. Botón flotante en todas las páginas.', false],
            ['squarespace', 'Squarespace', 'Code Injection para footer. Widget flotante y bloque inline.', false],
            ['google-calendar', 'Google Calendar', 'Sincronización bidireccional de agenda. Conectá tu Google Calendar.', false],
            ['zoom', 'Zoom', 'Videollamadas automáticas para consultas online. Requiere cuenta Zoom.', false],
            ['google-meet', 'Google Meet', 'Reuniones virtuales con Google Meet. Se crean automáticamente.', false],
            ['stripe', 'Stripe', 'Procesamiento de pagos con tarjeta. Checkout integrado en el widget.', false],
            ['mercadopago', 'MercadoPago', 'Pagos en Latinoamérica. Tarjeta, PIX, transferencia.', false],
            ['whatsapp', 'WhatsApp Business', 'Notificaciones y recordatorios por WhatsApp. Reducción de no-shows.', false],
        ];
        foreach ($integrations as $int):
            list($id, $name, $desc, $active) = $int;
        ?>
        <div class="mati-card" style="border-left:4px solid <?php echo $active ? '#16A34A' : '#e2e8f0'; ?>">
            <div class="mati-integ-header">
                <div>
                    <h3 class="mati-integ-title">
                        <?php echo $active ? '✅ ' : '📦 '; ?><?php echo esc_html($name); ?>
                        <?php if ($active): ?><span class="mati-plan-badge" style="background:#16A34A">Activo</span><?php endif; ?>
                    </h3>
                    <p class="mati-integ-desc"><?php echo esc_html($desc); ?></p>
                </div>
            </div>
            <?php if (!$active): ?>
            <div class="mati-integ-actions">
                <a href="' . MATI_BROWSER_URL . '/dashboard/<?php echo esc_attr($slug); ?>/integrations" class="mati-btn mati-btn-primary mati-integ-btn" target="_blank" rel="noopener">Configurar en Mati ↗</a>
            </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>

    <div class="mati-card mati-mt-1">
        <h2>🪄 Shortcodes para Frontend</h2>
        <p class="mati-text-sm mati-text-dim mati-mb-1">Creá páginas en WordPress con estos shortcodes para tener paneles completos en el frontend:</p>
        <table class="mati-table">
            <thead><tr><th>Shortcode</th><th>Panel</th><th>Acceso</th><th>Uso</th></tr></thead>
            <tbody>
                <tr><td><code>[mati_widget]</code></td><td>Widget de Reservas</td><td>Público</td><td>Widget flotante o inline para que clientes reserven</td></tr>
                <tr><td><code>[mati_panel section="dashboard"]</code></td><td>Admin Dashboard</td><td>Admin WP</td><td>Espejo del panel admin en frontend</td></tr>
                <tr><td><code>[mati_panel section="bookings"]</code></td><td>Reservas</td><td>Admin WP</td><td>Gestión de reservas en frontend</td></tr>
                <tr><td><code>[mati_panel section="services"]</code></td><td>Servicios</td><td>Admin WP</td><td>Gestión de servicios en frontend</td></tr>
                <tr><td><code>[mati_provider_panel]</code></td><td>Panel Profesional</td><td>Empleados</td><td>Panel reducido para profesionales</td></tr>
                <tr><td><code>[mati_customer_portal]</code></td><td>Portal Cliente</td><td>Clientes</td><td>Auto-gestión de reservas</td></tr>
            </tbody>
        </table>
    </div>
    <?php
}

// ═══════════════════════════════════════════════════════════
// 10. CONFIGURACIÓN
// ═══════════════════════════════════════════════════════════
function mati_render_settings() {
    if (mati_require_api_key()) return;
    mati_page_header('Configuración', 'Conexión API y apariencia.');
    ?><form method="post" action="options.php" class="mati-settings-form"><?php settings_fields('mati_settings'); ?>
    <input type="hidden" name="mati_api_key" value="<?php echo esc_attr(mati_api_key()); ?>" />
    <input type="hidden" name="mati_slug" value="<?php echo esc_attr(mati_api_slug()); ?>" />
    <input type="hidden" name="mati_plan" value="<?php echo esc_attr(get_option('mati_plan','FREE')); ?>" />
    <input type="hidden" name="mati_setup_complete" value="<?php echo esc_attr(get_option('mati_setup_complete','1')); ?>" />
    <div class="mati-card"><h2>Conexión API</h2><table class="form-table">
        <tr><th><label>API Key</label></th><td><input type="text" name="mati_api_key" value="<?php echo esc_attr(mati_api_key()); ?>" class="regular-text mati-font-mono" /></td></tr>
        <tr><th><label>Slug</label></th><td><input type="text" name="mati_slug" value="<?php echo esc_attr(mati_api_slug()); ?>" class="regular-text" /></td></tr>
    </table></div>
    <div class="mati-card"><h2>Widget</h2><table class="form-table">
        <?php foreach (['position'=>['Posición',['bottom-right'=>'Abajo derecha','bottom-left'=>'Abajo izquierda','inline'=>'En línea']],'theme'=>['Tema',['light'=>'Claro']],'language'=>['Idioma',['es'=>'Español','en'=>'English','pt'=>'Português','fr'=>'Français','de'=>'Deutsch','it'=>'Italiano']]] as $k=>$cfg): ?>
        <tr><th><label><?php echo $cfg[0]; ?></label></th><td><select name="mati_<?php echo $k; ?>"><?php foreach ($cfg[1] as $v=>$l): ?><option value="<?php echo $v; ?>" <?php selected(get_option('mati_'.$k),$v); ?>><?php echo $l; ?></option><?php endforeach; ?></select></td></tr>
        <?php endforeach; ?>
        <tr><th><label>Color</label></th><td><input type="color" name="mati_color" value="<?php echo esc_attr(get_option('mati_color',MATI_DEFAULT_COLOR)); ?>" /></td></tr>
    </table></div>
    <p class="submit"><button type="submit" class="mati-btn mati-btn-primary mati-btn-lg">Guardar</button></p></form><?php
}

// ═══════════════════════════════════════════════════════════
// 11. BENEFICIOS
// ═══════════════════════════════════════════════════════════
function mati_render_benefits() {
    if (mati_require_api_key()) return;
    mati_page_header('Beneficios', 'Compará planes.');
    ?><div class="mati-benefits-grid"><?php foreach ([['⚡','Panel Completo','Dashboard con métricas.','Premium'],['💳','Pagos Integrados','Tarjeta, MercadoPago.','Premium'],['📅','Reservas Ilimitadas','Sin límite.','Free'],['🤖','Agente AI','Reducción 64% no-shows.','Premium'],['📊','Métricas','KPIs, revenue.','Premium'],['🎨','Customización','Sin marca, CSS propio.','Premium']] as $b): ?><div class="mati-benefit-card <?php echo $b[3]==='Premium'?'mati-benefit-premium':'mati-benefit-free'; ?>"><span class="mati-benefit-icon"><?php echo $b[0]; ?></span><h3><?php echo $b[1]; ?></h3><p><?php echo $b[2]; ?></p><span class="mati-badge"><?php echo $b[3]; ?></span></div><?php endforeach; ?></div>
    <div class="mati-text-center mati-mt-2"><a href="' . MATI_BROWSER_URL . '/account/plans" class="mati-btn mati-btn-primary mati-btn-lg" target="_blank">Ver Planes ↗</a></div><?php
}

// ═══════════════════════════════════════════════════════════
// AJAX HANDLERS
// ═══════════════════════════════════════════════════════════
add_action('wp_ajax_mati_save_apikey', function() { check_ajax_referer('mati_nonce','nonce'); if(!empty($_POST['api_key'])) { update_option('mati_api_key',sanitize_text_field($_POST['api_key'])); update_option('mati_had_api_key', true); mati_clear_api_key_cache(); } if(!empty($_POST['slug'])) update_option('mati_slug',sanitize_text_field($_POST['slug'])); if(!empty($_POST['plan'])) update_option('mati_plan',sanitize_text_field($_POST['plan'])); wp_send_json_success(); });
add_action('wp_ajax_mati_disconnect', function() {
    check_ajax_referer('mati_nonce','nonce');
    // Solo eliminar datos de conexión. Toda la configuración
    // (posición, tema, idioma, color, textos, variante, paneles)
    // se conserva para cuando se conecte una nueva API Key.
    delete_option('mati_api_key');
    delete_option('mati_slug');
    delete_option('mati_plan');
    delete_option('mati_had_api_key');
    mati_clear_api_key_cache();
    wp_send_json_success(['redirect' => admin_url('admin.php?page=mati-welcome')]);
});
add_action('wp_ajax_mati_save_setup', function() {
    check_ajax_referer('mati_nonce','nonce');
    mati_api_post('/sync', [
        'businessName'=>sanitize_text_field($_POST['business_name']??''),'businessType'=>sanitize_text_field($_POST['business_type']??''),
        'businessColor'=>sanitize_text_field($_POST['business_color']??''),'specialty'=>sanitize_text_field($_POST['business_specialty']??''),
        'scheduleStart'=>sanitize_text_field($_POST['business_schedule_start']??''),'scheduleEnd'=>sanitize_text_field($_POST['business_schedule_end']??''),
        'days'=>sanitize_text_field($_POST['business_days']??''),'providersCount'=>intval($_POST['business_providers']??1),
        'services'=>json_decode(wp_unslash($_POST['services']??'[]'),true)?:[]
    ]);
    update_option('mati_setup_complete',true);
    wp_send_json_success(['redirect'=>admin_url('admin.php?page=mati-welcome')]);
});
add_action('wp_ajax_mati_save_services', function() { check_ajax_referer('mati_nonce','nonce'); $cur=mati_api_get('/sync'); $d=$cur['data']??[]; $d['services']=json_decode(wp_unslash($_POST['services']??'[]'),true)?:[]; mati_api_post('/sync',$d); wp_send_json_success(); });
add_action('wp_ajax_mati_save_providers', function() { check_ajax_referer('mati_nonce','nonce'); $cur=mati_api_get('/sync'); $d=$cur['data']??[]; $d['providers']=json_decode(wp_unslash($_POST['providers']??'[]'),true)?:[]; $d['providersCount']=count($d['providers']); mati_api_post('/sync',$d); wp_send_json_success(); });
add_action('wp_ajax_mati_save_schedule', function() { check_ajax_referer('mati_nonce','nonce'); $cur=mati_api_get('/sync'); $d=$cur['data']??[]; $d['schedule']=json_decode(wp_unslash($_POST['schedule']??'{}'),true)?:[]; mati_api_post('/sync',$d); wp_send_json_success(); });
// v2 AJAX handlers for richer service/provider/schedule data
add_action('wp_ajax_mati_save_services_v2', function() { check_ajax_referer('mati_nonce','nonce'); $cur=mati_api_get('/sync'); $d=$cur['data']??[]; $d['services']=json_decode(wp_unslash($_POST['services']??'[]'),true)?:[]; mati_api_post('/sync',$d); wp_send_json_success(); });
add_action('wp_ajax_mati_save_providers_v2', function() { check_ajax_referer('mati_nonce','nonce'); $cur=mati_api_get('/sync'); $d=$cur['data']??[]; $d['providers']=json_decode(wp_unslash($_POST['providers']??'[]'),true)?:[]; $d['providersCount']=count($d['providers']); mati_api_post('/sync',$d); wp_send_json_success(); });
add_action('wp_ajax_mati_save_schedule_v2', function() { check_ajax_referer('mati_nonce','nonce'); $cur=mati_api_get('/sync'); $d=$cur['data']??[]; $d['schedule']=json_decode(wp_unslash($_POST['schedule']??'{}'),true)?:[]; mati_api_post('/sync',$d); wp_send_json_success(); });

// ═══════════════════════════════════════════════════════════
// SHORTCODES FRONTEND — Cada uno es REALMENTE diferente
// ═══════════════════════════════════════════════════════════

/**
 * [mati_booking] — Formulario de reservas INLINE (sin chrome, embebido directo en la página)
 * Ejemplo: [mati_booking variant="modern" color="#0722BC" height="800px" greeting="¡Hola! Reservá tu cita."]
 */
add_shortcode('mati_booking', function($atts) {
    $atts = shortcode_atts([
        'variant'   => 'default',
        'theme'     => 'light',
        'color'     => '',
        'lang'      => 'es',
        'greeting'  => '',
        'height'    => '700px',
        'agent'     => 'false',
    ], $atts, 'mati_booking');

    $api = mati_api_key();
    $slug = mati_api_slug();
    if (empty($api) || empty($slug)) {
        return '<div style="padding:2rem;text-align:center;background:#f8fafc;border-radius:1rem;border:1px solid #e2e8f0;"><p>🔌 Conectá tu API Key en <a href="'.admin_url('admin.php?page=mati-welcome').'">Mati → Inicio</a> para usar este shortcode.</p></div>';
    }

    $base = str_replace('/dashboard', '', MATI_BROWSER_URL);
    $url = $base . '/widget/' . urlencode($slug)
        . '?chromeless=1'
        . '&variant=' . urlencode(sanitize_text_field($atts['variant']))
        . '&theme=' . urlencode(sanitize_text_field($atts['theme']))
        . '&lang=' . urlencode(sanitize_text_field($atts['lang']));
    if ($atts['color'])  $url .= '&color=' . urlencode(sanitize_text_field($atts['color']));
    if ($atts['greeting']) $url .= '&greeting=' . urlencode(sanitize_text_field($atts['greeting']));
    if ($atts['agent'] === 'true') $url .= '&agent=true';

    $h = sanitize_text_field($atts['height']);
    return '<iframe src="' . esc_url($url) . '" style="width:100%;max-width:100%;height:' . esc_attr($h) . ';border:none;border-radius:.75rem;box-shadow:0 4px 24px rgba(0,0,0,0.06);" loading="lazy" title="Reservar con Mati" allow="clipboard-write"></iframe>';
});

/**
 * [mati_panel section="dashboard"] — Panel Admin COMPLETO (solo admins logueados)
 * Secciones: dashboard, bookings, customers, services, providers, calendar, schedule, payments
 * Ejemplo: [mati_panel section="bookings" color="#0722BC" height="900px"]
 */
add_shortcode('mati_panel', function($atts) {
    $atts = shortcode_atts([
        'section' => 'dashboard',
        'theme'   => 'light',
        'color'   => '',
        'lang'    => 'es',
        'height'  => '900px',
    ], $atts, 'mati_panel');

    $api = mati_api_key();
    $slug = mati_api_slug();
    if (empty($api) || empty($slug)) {
        return '<div style="padding:2rem;text-align:center;background:#f8fafc;border-radius:1rem;border:1px solid #e2e8f0;"><p>🔌 Conectá tu API Key en <a href="'.admin_url('admin.php?page=mati-welcome').'">Mati → Inicio</a>.</p></div>';
    }
    if (!is_user_logged_in() || !current_user_can('manage_options')) {
        return '<div style="padding:2rem;text-align:center;background:#fff7ed;border-radius:1rem;border:1px solid #fed7aa;"><p>🔒 Este panel es solo para administradores. <a href="'.wp_login_url().'">Iniciar sesión</a></p></div>';
    }

    $base = str_replace('/dashboard', '', MATI_BROWSER_URL);
    $section = sanitize_text_field($atts['section']);
    $url = $base . '/widget/panel/admin/' . urlencode($slug)
        . '?apiKey=' . urlencode($api)
        . '&section=' . urlencode($section)
        . '&theme=' . urlencode(sanitize_text_field($atts['theme']))
        . '&lang=' . urlencode(sanitize_text_field($atts['lang']));
    if ($atts['color']) $url .= '&color=' . urlencode(sanitize_text_field($atts['color']));

    $h = sanitize_text_field($atts['height']);
    return '<iframe src="' . esc_url($url) . '" style="width:100%;max-width:100%;height:' . esc_attr($h) . ';border:none;border-radius:.75rem;box-shadow:0 4px 24px rgba(0,0,0,0.06);" loading="lazy" title="Mati Admin Panel" allow="clipboard-write"></iframe>';
});

/**
 * [mati_customer_portal] — Portal del Cliente (mis reservas, cancelar, reprogramar)
 * Ejemplo: [mati_customer_portal color="#0722BC" height="700px"]
 */
add_shortcode('mati_customer_portal', function($atts) {
    $atts = shortcode_atts([
        'theme'   => 'light',
        'color'   => '',
        'lang'    => 'es',
        'height'  => '700px',
    ], $atts, 'mati_customer_portal');

    $api = mati_api_key();
    $slug = mati_api_slug();
    if (empty($api) || empty($slug)) {
        return '<div style="padding:2rem;text-align:center;background:#f8fafc;border-radius:1rem;border:1px solid #e2e8f0;"><p>🔌 Conectá tu API Key en <a href="'.admin_url('admin.php?page=mati-welcome').'">Mati → Inicio</a>.</p></div>';
    }

    $base = str_replace('/dashboard', '', MATI_BROWSER_URL);
    $url = $base . '/widget/panel/customer/' . urlencode($slug)
        . '?apiKey=' . urlencode($api)
        . '&theme=' . urlencode(sanitize_text_field($atts['theme']))
        . '&lang=' . urlencode(sanitize_text_field($atts['lang']));
    if ($atts['color']) $url .= '&color=' . urlencode(sanitize_text_field($atts['color']));

    $h = sanitize_text_field($atts['height']);
    return '<iframe src="' . esc_url($url) . '" style="width:100%;max-width:100%;height:' . esc_attr($h) . ';border:none;border-radius:.75rem;box-shadow:0 4px 24px rgba(0,0,0,0.06);" loading="lazy" title="Mi Cuenta — Mati" allow="clipboard-write"></iframe>';
});

/**
 * [mati_provider_panel provider_id="123"] — Panel del Profesional (su agenda, disponibilidad)
 * Ejemplo: [mati_provider_panel provider_id="abc123" color="#0722BC" height="800px"]
 */
add_shortcode('mati_provider_panel', function($atts) {
    $atts = shortcode_atts([
        'provider_id' => '',
        'theme'       => 'light',
        'color'       => '',
        'lang'        => 'es',
        'height'      => '800px',
    ], $atts, 'mati_provider_panel');

    $api = mati_api_key();
    $slug = mati_api_slug();
    if (empty($api) || empty($slug)) {
        return '<div style="padding:2rem;text-align:center;background:#f8fafc;border-radius:1rem;border:1px solid #e2e8f0;"><p>🔌 Conectá tu API Key en <a href="'.admin_url('admin.php?page=mati-welcome').'">Mati → Inicio</a>.</p></div>';
    }

    $base = str_replace('/dashboard', '', MATI_BROWSER_URL);
    $url = $base . '/widget/panel/provider/' . urlencode($slug)
        . '?apiKey=' . urlencode($api)
        . '&theme=' . urlencode(sanitize_text_field($atts['theme']))
        . '&lang=' . urlencode(sanitize_text_field($atts['lang']));
    if ($atts['color']) $url .= '&color=' . urlencode(sanitize_text_field($atts['color']));
    if ($atts['provider_id']) $url .= '&providerId=' . urlencode(sanitize_text_field($atts['provider_id']));

    $h = sanitize_text_field($atts['height']);
    return '<iframe src="' . esc_url($url) . '" style="width:100%;max-width:100%;height:' . esc_attr($h) . ';border:none;border-radius:.75rem;box-shadow:0 4px 24px rgba(0,0,0,0.06);" loading="lazy" title="Panel del Profesional — Mati" allow="clipboard-write"></iframe>';
});

// ═══════════════════════════════════════════════════════════
// MATI COPILOT — Asistente flotante en todo WordPress
// ═══════════════════════════════════════════════════════════
add_action('admin_footer', function() {
    $api_key = mati_api_key();
    $slug = mati_api_slug();
    $biz_name = get_option('mati_business_name', '');
    $connected = !empty($api_key);
    ?>
    <div id="mati-copilot" style="position:fixed;bottom:20px;right:20px;z-index:99999;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif">
        <!-- Botón flotante: el mismo orbe de Mati -->
        <button id="mati-copilot-btn" class="mati-copilot-btn">
            <?php echo mati_logo_img(26); ?>
            <?php if ($connected): ?><span style="position:absolute;bottom:-2px;right:-2px;width:14px;height:14px;background:#16A34A;border-radius:50%;border:2px solid white"></span><?php endif; ?>
        </button>

        <!-- Panel de chat -->
        <div id="mati-copilot-panel" class="mati-copilot-panel">
            <div class="mati-copilot-header">
                <div class="mati-copilot-avatar">
                    <?php echo mati_logo_img(21); ?>
                </div>
                <div class="mati-copilot-title">
                    <strong>Mati</strong>
                    <span><?php echo $connected ? 'Asistente · '.esc_html($biz_name ?: $slug) : 'Asistente · Sin configurar'; ?></span>
                </div>
                <button id="mati-copilot-close" class="mati-copilot-close">✕</button>
            </div>
            <div id="mati-copilot-messages" class="mati-copilot-messages">
                <?php if (!$connected): ?>
                <div class="mati-copilot-empty">
                    <div class="mati-copilot-empty-orb">🔮</div>
                    <p class="mati-copilot-empty-title">¡Conectá tu API Key!</p>
                    <p class="mati-copilot-empty-text">Ingresá tu API Key de mati.com para desbloquear todo el poder de la plataforma.</p>
                    <a href="<?php echo admin_url('admin.php?page=mati-welcome'); ?>" class="mati-copilot-empty-btn">Conectar Ahora →</a>
                </div>
                <?php else: ?>
                <div class="mati-copilot-msg"><span>👋 ¡Hola! Soy <strong>Mati</strong>. Estoy conectado a <strong><?php echo esc_html($biz_name ?: $slug); ?></strong>. ¿En qué puedo ayudarte?</span></div>
                <div class="mati-copilot-msg"><span>Podés preguntarme por:<br>· 📋 Cómo ver tus reservas<br>· 🪄 Cómo personalizar el widget<br>· 📅 Cómo funciona el calendario<br>· ⚙️ Cómo cambiar la configuración</span></div>
                <?php endif; ?>
            </div>
            <div class="mati-copilot-footer">
                <?php if ($connected): ?>
                <a href="<?php echo admin_url('admin.php?page=mati-bookings'); ?>" class="mati-copilot-pill">📋 Reservas</a>
                <a href="<?php echo admin_url('admin.php?page=mati-calendar'); ?>" class="mati-copilot-pill">📅 Calendario</a>
                <a href="<?php echo admin_url('admin.php?page=mati-widget-config'); ?>" class="mati-copilot-pill">🪄 Widget</a>
                <a href="' . MATI_BROWSER_URL . '/dashboard/<?php echo esc_attr($slug); ?>" target="_blank" class="mati-copilot-pill">Abrir Mati ↗</a>
                <?php else: ?>
                <a href="<?php echo admin_url('admin.php?page=mati-welcome'); ?>" class="mati-copilot-pill">Conectar →</a>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <style>
    @keyframes matiGradient { 0%,100%{background-position:0% 50%} 50%{background-position:100% 50%} }
    @keyframes matiPulse { 0%,100%{box-shadow:0 0 0 0 rgba(255,255,255,.3)} 50%{box-shadow:0 0 0 14px rgba(255,255,255,0)} }
    @keyframes matiOrbGlow { 0%,100%{box-shadow:0 4px 24px rgba(26,93,74,.35)} 50%{box-shadow:0 4px 40px rgba(26,93,74,.55),0 0 60px rgba(13,148,136,.2)} }
    .mati-avatar-copilot { backdrop-filter:blur(4px); }
    </style>
    <script>
    (function(){
        var btn = document.getElementById('mati-copilot-btn');
        var panel = document.getElementById('mati-copilot-panel');
        var close = document.getElementById('mati-copilot-close');
        if (!btn || !panel) return;
        btn.addEventListener('click', function(e){ e.stopPropagation(); var o=panel.style.display==='flex'; panel.style.display=o?'none':'flex'; });
        close.addEventListener('click', function(){ panel.style.display='none'; });
        document.addEventListener('click', function(e){ if(!e.target.closest('#mati-copilot')) panel.style.display='none'; });
    })();
    </script>
    <?php
});

// ─── Disconnect Modal + Script ──────────────────────
add_action('admin_footer', function() {
    if (empty(mati_api_key())) return;
    ?>
    <div id="mati-disconnect-modal" class="mati-modal-overlay" onclick="if(event.target===this)document.getElementById('mati-disconnect-modal').classList.remove('mati-active')">
        <div class="mati-modal">
            <div class="mati-modal-icon">⚠️</div>
            <h3><?php echo esc_html__('¿Desconectar Mati?', 'mati-booking'); ?></h3>
            <p><?php echo esc_html__('Se eliminará la API Key y toda la configuración local. Podrás conectar una nueva API Key después.', 'mati-booking'); ?></p>
            <div class="mati-modal-actions">
                <button class="mati-btn mati-btn-outline" onclick="document.getElementById('mati-disconnect-modal').classList.remove('mati-active')"><?php echo esc_html__('Cancelar', 'mati-booking'); ?></button>
                <button class="mati-btn mati-btn-danger" id="mati-disconnect-confirm"><?php echo esc_html__('Desconectar', 'mati-booking'); ?></button>
            </div>
        </div>
    </div>
    <script>
    function matiDisconnect() {
        document.getElementById('mati-disconnect-modal').classList.add('mati-active');
    }
    document.getElementById('mati-disconnect-confirm').addEventListener('click', function() {
        var btn = this;
        btn.disabled = true;
        btn.textContent = '⏳...';
        var fd = new FormData();
        fd.append('action', 'mati_disconnect');
        fd.append('nonce', matiData.nonce);
        fetch(matiData.ajaxurl, { method: 'POST', body: fd })
            .then(function(r){ return r.json(); })
            .then(function(d){
                if (d.success && d.data.redirect) {
                    window.location.href = d.data.redirect;
                } else {
                    alert('Error al desconectar. Recargá la página e intentá de nuevo.');
                    btn.disabled = false;
                    btn.textContent = 'Desconectar';
                }
            })
            .catch(function(){
                alert('Error de conexión. Recargá la página e intentá de nuevo.');
                btn.disabled = false;
                btn.textContent = 'Desconectar';
            });
    });
    </script>
    <?php
});

// ═══════════════════════════════════════════════════════════
// MATI EN TODO WORDPRESS — Dashboard widget + Admin notices
// ═══════════════════════════════════════════════════════════

// Dashboard Widget en el escritorio principal de WordPress
add_action('wp_dashboard_setup', function() {
    wp_add_dashboard_widget('mati_dashboard_widget', '🤖 Mati — Estado de tu Sistema de Reservas', function() {
        $api = mati_api_key();
        if (empty($api)) {
            echo '<div class="mati-text-center mati-p-2">';
            echo '<div class="mati-text-3xl">🔮</div>';
            echo '<h3>¡Mati está instalado pero no configurado!</h3>';
            echo '<p>Conectá tu API Key para activar el sistema de reservas inteligente.</p>';
            echo '<a href="'.admin_url('admin.php?page=mati-welcome').'" class="mati-btn mati-btn-primary mati-mt-50">Configurar Mati →</a>';
            echo '</div>';
            return;
        }
        $data = mati_api_get('/data?section=stats');
        $stats = $data['data']['stats'] ?? [];
        $sync = mati_api_get('/sync');
        $plugin = $sync['data'] ?? [];
        $slug     = mati_api_slug();
        $color    = get_option('mati_color', '#1A5D4A');
        $variant  = get_option('mati_widget_variant', 'default');
        $theme    = get_option('mati_theme', 'auto');
        $greeting = get_option('mati_greeting', '¡Hola! ¿En qué puedo ayudarte?');
        ?>
        <div class="mati-db-widget-stats">
            <div class="mati-db-widget-stat mati-db-widget-stat-green">
                <div class="mati-db-widget-stat-num" style="color:#1A5D4A"><?php echo $stats['totalBookings'] ?? 0; ?></div>
                <div class="mati-db-widget-stat-label">Reservas</div>
            </div>
            <div class="mati-db-widget-stat mati-db-widget-stat-blue">
                <div class="mati-db-widget-stat-num" style="color:#2563eb"><?php echo $stats['totalCustomers'] ?? 0; ?></div>
                <div class="mati-db-widget-stat-label">Clientes</div>
            </div>
            <div class="mati-db-widget-stat mati-db-widget-stat-amber">
                <div class="mati-db-widget-stat-num" style="color:#d97706"><?php echo count($plugin['services'] ?? []); ?></div>
                <div class="mati-db-widget-stat-label">Servicios</div>
            </div>
        </div>
        <!-- Mini preview del widget -->
        <div class="mati-db-widget-preview">
            <div class="mati-db-widget-preview-header">
                <span class="mati-db-widget-preview-dot" style="background:<?php echo esc_attr($color); ?>"></span>
                <span class="mati-db-widget-preview-label">Widget actual · <?php echo esc_html(ucfirst($variant)); ?></span>
            </div>
            <iframe src="<?php echo esc_url('' . MATI_BROWSER_URL . '/widget/'.urlencode($slug).'?variant='.urlencode($variant).'&theme='.urlencode($theme).'&color='.urlencode($color).'&greeting='.urlencode($greeting).'&mini=1'); ?>"
                class="mati-w-full" style="height:180px;border:0;border-radius:0.5rem;background:white"
                loading="lazy" title="Mini Widget Preview" allow="clipboard-write"></iframe>
        </div>
        <div class="mati-db-widget-footer">
            <a href="<?php echo admin_url('admin.php?page=mati-bookings'); ?>">📋 Reservas</a>
            <span class="mati-db-widget-sep">|</span>
            <a href="<?php echo admin_url('admin.php?page=mati-calendar'); ?>">📅 Calendario</a>
            <span class="mati-db-widget-sep">|</span>
            <a href="<?php echo admin_url('admin.php?page=mati-widget-config'); ?>">🪄 Widget</a>
            <span class="mati-db-widget-sep">|</span>
            <a href="' . MATI_BROWSER_URL . '/dashboard/<?php echo esc_attr($slug); ?>" target="_blank">Abrir Mati ↗</a>
        </div>
        <?php
    });
});

// Admin notice: recordatorio si Mati no está configurado
add_action('admin_notices', function() {
    if (empty(mati_api_key())) {
        echo '<div class="notice notice-info is-dismissible mati-notice mati-notice-info">';
        echo '<p><strong>🤖 Mati está instalado</strong> — Conectá tu API Key para activar el sistema de reservas inteligente con agente IA. <a href="'.admin_url('admin.php?page=mati-welcome').'" class="button button-primary mati-ml-50">Configurar Ahora</a></p>';
        echo '</div>';
    }
});

// Admin bar: acceso rápido a Mati desde cualquier página
add_action('admin_bar_menu', function($admin_bar) {
    $admin_bar->add_menu([
        'id' => 'mati-quick',
        'title' => '🤖 Mati',
        'href' => admin_url('admin.php?page=mati-welcome'),
        'meta' => ['class' => 'mati-admin-bar'],
    ]);
    if (!empty(mati_api_key())) {
        $admin_bar->add_menu([
            'id' => 'mati-quick-bookings',
            'parent' => 'mati-quick',
            'title' => '📋 Reservas',
            'href' => admin_url('admin.php?page=mati-bookings'),
        ]);
        $admin_bar->add_menu([
            'id' => 'mati-quick-calendar',
            'parent' => 'mati-quick',
            'title' => '📅 Calendario',
            'href' => admin_url('admin.php?page=mati-calendar'),
        ]);
        $admin_bar->add_menu([
            'id' => 'mati-quick-widget',
            'parent' => 'mati-quick',
            'title' => '🪄 Widget',
            'href' => admin_url('admin.php?page=mati-widget-config'),
        ]);
    }
}, 100);

// ═══════════════════════════════════════════════════════════
// WIDGET FRONTEND (inyección automática)
// ═══════════════════════════════════════════════════════════
$GLOBALS['mati_widget_rendered'] = false;

add_action('wp_footer', function() {
    // Avoid double-injecting the widget when it was already rendered via shortcode
    if (!empty($GLOBALS['mati_widget_rendered'])) return;

    // Auto-injection is now opt-in so the widget is not intrusive by default.
    if (get_option('mati_auto_inject', 'off') !== 'on') return;

    $slug = mati_api_slug(); if (empty($slug)) return;
    $pos       = get_option('mati_position', 'bottom-right');
    $theme     = get_option('mati_theme', 'auto');
    $lang      = get_option('mati_language', MATI_DEFAULT_LANG);
    $color     = get_option('mati_color', MATI_DEFAULT_COLOR);
    $variant   = get_option('mati_widget_variant', 'default');
    $btnText   = get_option('mati_button_text', 'Reservar');
    $greeting  = get_option('mati_greeting', '¡Hola! ¿En qué puedo ayudarte?');
    $autoOpen  = get_option('mati_auto_open', 'no');
    $agentMode = get_option('mati_agent_mode', 'on');
    if ($pos === 'inline') echo '<div id="mati-inline" class="mati-widget-inline"></div>';
    echo '<script src="'.MATI_SCRIPT_URL.'" data-slug="'.esc_attr($slug).'" data-variant="'.esc_attr($variant).'" data-position="'.esc_attr($pos).'" data-theme="'.esc_attr($theme).'" data-language="'.esc_attr($lang).'" data-primary-color="'.esc_attr($color).'" data-button-text="'.esc_attr($btnText).'" data-greeting="'.esc_attr($greeting).'" data-auto-open="'.esc_attr($autoOpen).'" data-agent-mode="'.esc_attr($agentMode).'" async></script>';
});
add_shortcode('mati_widget', function($atts) {
    $atts = shortcode_atts([
        'slug'=>mati_api_slug(),
        'position'=>'inline',
        'theme'=>'light',
        'language'=>get_option('mati_language',MATI_DEFAULT_LANG),
        'color'=>get_option('mati_color',MATI_DEFAULT_COLOR),
        'variant'=>get_option('mati_widget_variant','default'),
        'button_text'=>get_option('mati_button_text','Reservar'),
        'greeting'=>get_option('mati_greeting','¡Hola! ¿En qué puedo ayudarte?'),
        'auto_open'=>get_option('mati_auto_open','no'),
        'agent_mode'=>get_option('mati_agent_mode','on'),
        'title'=>'',
        'class'=>'',
    ],$atts);
    if (empty($atts['slug'])) return '';
    $GLOBALS['mati_widget_rendered'] = true;
    $wrapperClass = 'mati-widget-wrapper';
    if (!empty($atts['class'])) $wrapperClass .= ' ' . esc_attr($atts['class']);
    ob_start();
    if (empty($GLOBALS['mati_widget_styles_printed'])) {
        $GLOBALS['mati_widget_styles_printed'] = true;
        echo '<style>.mati-widget-wrapper{max-width:420px;margin:1rem 0}.mati-widget-wrapper.mati-widget-center{margin-left:auto;margin-right:auto}.mati-widget-title{font-size:1.1rem;font-weight:800;margin:0 0 .75rem;color:#1E293B}.mati-widget-inline{width:100%;min-height:120px;border-radius:1.25rem;background:#F5F7FA;border:1px solid #E2E8F0}</style>';
    }
    echo '<div class="'.$wrapperClass.'">';
    if (!empty($atts['title'])) echo '<h3 class="mati-widget-title">'.esc_html($atts['title']).'</h3>';
    if ($atts['position']==='inline') echo '<div id="mati-inline" class="mati-widget-inline"></div>';
    echo '<script src="'.MATI_SCRIPT_URL.'" data-slug="'.esc_attr($atts['slug']).'" data-variant="'.esc_attr($atts['variant']).'" data-position="'.esc_attr($atts['position']).'" data-theme="'.esc_attr($atts['theme']).'" data-language="'.esc_attr($atts['language']).'" data-primary-color="'.esc_attr($atts['color']).'" data-button-text="'.esc_attr($atts['button_text']).'" data-greeting="'.esc_attr($atts['greeting']).'" data-auto-open="'.esc_attr($atts['auto_open']).'" data-agent-mode="'.esc_attr($atts['agent_mode']).'" async></script>';
    echo '</div>';
    return ob_get_clean();
});
