<?php
// phpcs:ignoreFile -- WordPress.org free package uses custom booking tables and template-scoped variables.
if ( ! defined( 'ABSPATH' ) ) { exit; }
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
$service_categories = array();
$service_category_counts = array();
foreach ((array) $services as $sbs_service_for_filter) {
    $sbs_category_name = trim((string) ($sbs_service_for_filter->category ?? ''));
    if ($sbs_category_name !== '') {
        if (!in_array($sbs_category_name, $service_categories, true)) {
            $service_categories[] = $sbs_category_name;
            $service_category_counts[$sbs_category_name] = 0;
        }
        $service_category_counts[$sbs_category_name]++;
    }
}
sort($service_categories, SORT_NATURAL | SORT_FLAG_CASE);
$is_pro = class_exists( 'YATOON_License' ) ? YATOON_License::is_pro() : false;
$service_count = count( $services ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
?>
<div class="wrap sbs-admin-page sbs-services-page">
    <script>
        try {
            const yatoonServicesWidthKey = 'yatoon-admin-table-widths:' + location.pathname + ':' + (new URLSearchParams(location.search).get('page') || 'page') + ':sbs-services-table';
            const yatoonServicesResetKey = yatoonServicesWidthKey + ':3.4.0-service-cards';
            if (!localStorage.getItem(yatoonServicesResetKey)) {
                localStorage.removeItem(yatoonServicesWidthKey);
                localStorage.setItem(yatoonServicesResetKey, '1');
            }
        } catch (err) {}
    </script>
            <style>
        .sbs-admin-table-wrap {
            width: 100%;
            overflow-x: visible !important;
            overflow-y: visible;
            padding-bottom: 8px;
        }
        #sbs-services-table {
            display: block !important;
            width: 100% !important;
            min-width: 0 !important;
            table-layout: auto !important;
            border-collapse: separate !important;
        }
        #sbs-services-table thead { display: none !important; }
        #sbs-services-table tbody {
            display: block !important;
            width: 100% !important;
        }
        #sbs-services-table tr.sbs-main-service-row {
            display: grid !important;
            grid-template-columns: 44px 34px 76px minmax(280px, 1fr) 88px 88px 132px 88px;
            align-items: center;
            gap: 0;
            width: 100% !important;
            min-width: 0 !important;
            cursor: pointer;
            border-bottom: 1px solid #eef2f7;
            background: #fff;
        }
        #sbs-services-table tr.sbs-main-service-row:nth-child(4n+1) {
            background: #fbfdff;
        }
        #sbs-services-table tr.sbs-main-service-row.has-design-upload {
            box-shadow: inset 4px 0 0 #f59e0b;
        }
        #sbs-services-table tr.sbs-main-service-row.has-design-upload td {
            background: #fffbeb !important;
        }
        #sbs-services-table tr.sbs-main-service-row.has-design-upload:hover td {
            background: #fef3c7 !important;
        }
        #sbs-services-table tr.sbs-main-service-row:hover td {
            background: #f8fafc !important;
        }
        #sbs-services-table tr.is-selected td {
            background: #f0fdf4 !important;
        }
        #sbs-services-table tr.sbs-main-service-row td {
            display: flex !important;
            align-items: center;
            min-width: 0 !important;
            max-width: none !important;
            width: auto !important;
            height: 72px;
            box-sizing: border-box;
            overflow: hidden;
            white-space: normal !important;
            text-overflow: clip !important;
            padding: 10px 12px !important;
            border-bottom: 0 !important;
            vertical-align: middle;
        }
        #sbs-services-table tr.sbs-main-service-row td:nth-child(1),
        #sbs-services-table tr.sbs-main-service-row td:nth-child(2) {
            justify-content: center;
            padding-left: 6px !important;
            padding-right: 6px !important;
        }
        #sbs-services-table tr.sbs-main-service-row td:nth-child(3) {
            justify-content: center;
        }
        #sbs-services-table tr.sbs-main-service-row td:nth-child(5) {
            display: block !important;
            padding-top: 12px !important;
        }
        #sbs-services-table tr.sbs-main-service-row td:nth-child(5) strong {
            display: inline-block;
            max-width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            vertical-align: middle;
        }
        #sbs-services-table tr.sbs-main-service-row td:nth-child(6),
        #sbs-services-table tr.sbs-main-service-row td:nth-child(7),
        #sbs-services-table tr.sbs-main-service-row td:nth-child(8),
        #sbs-services-table tr.sbs-main-service-row td:nth-child(10) {
            color: #4b5563;
            font-weight: 650;
        }
        #sbs-services-table tr.sbs-main-service-row td:nth-child(4),
        #sbs-services-table tr.sbs-main-service-row td:nth-child(9),
        #sbs-services-table tr.sbs-main-service-row td:nth-child(11),
        #sbs-services-table .sbs-toggle-options,
        #sbs-services-table .sbs-options-row {
            display: none !important;
        }
        #sbs-services-table input.sbs-service-row-checkbox,
        #sbs-select-all-services-main {
            width: 22px !important;
            height: 22px !important;
            min-width: 22px !important;
            cursor: pointer;
        }
        #sbs-services-table .sbs-order-input {
            width: 58px !important;
            min-width: 58px !important;
            max-width: 58px !important;
            text-align: center;
        }
        #sbs-services-table td:nth-child(5) strong::after {
            content: "Edit";
            display: inline-flex;
            margin-left: 10px;
            padding: 2px 8px;
            border: 1px solid #bfdbfe;
            border-radius: 999px;
            color: #2563eb;
            background: #eff6ff;
            font-size: 12px;
            line-height: 1.3;
            font-weight: 700;
            vertical-align: 1px;
        }
        #sbs-services-table .sbs-service-actions { display: none !important; }
        .sbs-services-page .yatoon-table-x-scrollbar { display: none !important; }
        .sbs-selected-service-actions {
            display: flex;
            gap: 10px;
            align-items: center;
            justify-content: flex-end;
            flex-wrap: wrap;
        }
        .sbs-selected-services-summary {
            color: #4b5563;
            font-weight: 700;
            margin-right: 4px;
        }
        .sbs-selected-service-actions .button { min-width: 112px; }
        .sbs-option-save-state { color: #6b7280; font-size: 12px; font-weight: 600; }
        .sbs-option-save-state.is-dirty { color: #b45309; }
        .sbs-option-save-state.is-saved { color: #047857; }
        .sbs-rule-pill.design-upload {
            background: #fef3c7;
            border: 1px solid #f59e0b;
            color: #92400e;
            font-weight: 800;
        }
        .sbs-design-upload-inline-badge {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            margin-left: 8px;
            padding: 2px 8px;
            border-radius: 999px;
            border: 1px solid #f59e0b;
            background: #fef3c7;
            color: #92400e;
            font-size: 12px;
            line-height: 1.3;
            font-weight: 800;
            vertical-align: 2px;
            white-space: nowrap;
        }
        @media (max-width: 1200px) {
            #sbs-services-table tr.sbs-main-service-row {
                grid-template-columns: 44px 30px 66px minmax(220px, 1fr) 78px 76px 112px 74px;
            }
            #sbs-services-table tr.sbs-main-service-row td { padding-left: 8px !important; padding-right: 8px !important; }
        }
        @media (max-width: 900px) {
            #sbs-services-table tr.sbs-main-service-row {
                grid-template-columns: 38px 28px 58px minmax(180px, 1fr) 70px 70px 66px;
            }
            #sbs-services-table tr.sbs-main-service-row td:nth-child(8) { display: none !important; }
            #sbs-services-table tr.sbs-main-service-row td { height: 78px; }
        }
    
        .sbs-status-toggle {
            min-width: 72px;
            border: 1px solid #bbf7d0;
            border-radius: 999px;
            padding: 6px 12px;
            font-size: 12px;
            font-weight: 800;
            line-height: 1;
            cursor: pointer;
            background: #dcfce7;
            color: #15803d;
        }
        .sbs-status-toggle.is-hidden {
            border-color: #e5e7eb;
            background: #f3f4f6;
            color: #6b7280;
        }
        .sbs-status-toggle.is-saving {
            opacity: .65;
            cursor: wait;
        }
        #sbs-service-modal {
            padding: 24px;
            box-sizing: border-box;
            overflow-y: auto;
        }
        .sbs-service-modal-panel {
            position: relative;
            background: #fff;
            margin: 24px auto;
            padding: 30px;
            width: min(1080px, calc(100vw - 88px));
            max-width: 1080px;
            border-radius: 10px;
            max-height: calc(100vh - 72px);
            overflow-y: auto;
            overflow-x: hidden;
            box-sizing: border-box;
        }
        .sbs-service-modal-close {
            position: sticky;
            top: 0;
            float: right;
            z-index: 2;
            width: 34px;
            height: 34px;
            margin: -12px -12px 4px 12px;
            border: 1px solid #e5e7eb;
            border-radius: 999px;
            background: #fff;
            color: #6b7280;
            font-size: 22px;
            line-height: 28px;
            cursor: pointer;
        }
        .sbs-service-modal-close:hover {
            color: #111827;
            border-color: #cbd5e1;
        }
        #sbs-modal-options-table { table-layout: fixed; }
        #sbs-modal-options-table input,
        #sbs-modal-options-table select { box-sizing: border-box; max-width: 100%; }
        #sbs-modal-options-table th:nth-child(1),
        #sbs-modal-options-table td:nth-child(1) { width: 34%; }
        #sbs-modal-options-table th:nth-child(2),
        #sbs-modal-options-table td:nth-child(2) { width: 110px; }
        #sbs-modal-options-table th:nth-child(3),
        #sbs-modal-options-table td:nth-child(3) { width: 126px; }
        #sbs-modal-options-table th:nth-child(4),
        #sbs-modal-options-table td:nth-child(4) { width: 150px; }
        #sbs-modal-options-table th:nth-child(5),
        #sbs-modal-options-table td:nth-child(5) { width: 168px; }
        @media (max-width: 900px) {
            .sbs-service-modal-panel { width: calc(100vw - 32px); padding: 20px; }
            #sbs-modal-options-table { display: block; overflow-x: auto; white-space: nowrap; }
        }
    </style>
    <h1>
        Services
        <button type="button" id="sbs-add-service" class="page-title-action">Add New</button>
        <button type="button" id="sbs-manage-categories" class="page-title-action">Manage Categories</button>
        <?php if ( $is_pro ) : ?>
            <button type="button" id="sbs-sync-services" class="page-title-action">Sync from Square</button>
        <?php else : ?>
            <a href="<?php echo esc_url( YATOON_License::get_upgrade_url() ); ?>" target="_blank" rel="noopener noreferrer" class="page-title-action">Sync from Square - Pro</a>
        <?php endif; ?>
    </h1>

    <p class="description sbs-admin-page-description">
        Click any service row to edit details, options, add-ons, and category.
        Drag rows to reorder services. Changes save automatically.
    </p>

    <?php if (empty($services)) : ?>
        <div class="notice notice-warning">
            <p>No services found. Click "Add New" to create a service or "Sync from Square".</p>
        </div>
    <?php else : ?>
        <div class="sbs-table-toolbar">
            <div class="sbs-table-search">
                <input type="search" id="sbs-service-search" class="regular-text" autocomplete="off" placeholder="Search services, descriptions, or IDs">
                <select id="sbs-service-category-filter">
                    <option value="">All categories</option>
                    <?php foreach ($service_categories as $filter_category) : ?>
                        <option value="<?php echo esc_attr(strtolower($filter_category)); ?>"><?php echo esc_html($filter_category); ?></option>
                    <?php endforeach; ?>
                </select>
                <select id="sbs-service-status-filter">
                    <option value="">All statuses</option>
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                </select>
                <select id="sbs-service-design-upload-filter">
                    <option value="">All upload settings</option>
                    <option value="1">Photo upload enabled</option>
                    <option value="0">No photo upload</option>
                </select>
                <button type="button" id="sbs-service-clear-filters" class="button">Clear</button>
            </div>
            <div class="sbs-table-actions sbs-selected-service-actions">
                <span id="sbs-selected-services-summary" class="sbs-selected-services-summary">Select a service or click a row to edit.</span>
                <button type="button" id="sbs-edit-selected-service" class="button" disabled>Edit Selected</button>
                <button type="button" id="sbs-add-addon-selected-service" class="button" disabled>Add Add-on</button>
                <button type="button" id="sbs-delete-selected-services" class="button" disabled>Delete Selected</button>
            </div>
        </div>
        <div class="sbs-admin-table-wrap">
        <table class="wp-list-table widefat fixed striped" id="sbs-services-table">
            <thead>
                <tr>
                    <th class="sbs-col-check"><input type="checkbox" id="sbs-select-all-services-main" aria-label="<?php esc_attr_e('Select all services', 'yatoon-booking-system'); ?>"></th>
                    <th style="width:36px;">&#9776;</th>
                    <th style="width:72px;">Order</th>
                    <th style="width:56px;">ID</th>
                    <th>Service Name</th>
                    <th style="width:86px;">Duration</th>
                    <th style="width:82px;">Price</th>
                    <th style="width:128px;">Category</th>
                    <th style="width:110px;">Rules</th>
                    <th style="width:82px;">Status</th>
                    <th style="width:238px;">Actions</th>
                </tr>
            </thead>
            <tbody id="sbs-sortable-services">
                <?php // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
                <?php foreach ($services as $service) : ?>
                <tr data-id="<?php echo esc_html( $service->id ); ?>"
                    data-order="<?php echo esc_html( $service->sort_order ); ?>"
                    data-category="<?php echo esc_attr(strtolower($service->category ?: '')); ?>"
                    data-status="<?php echo esc_attr($service->is_active ? 'active' : 'inactive'); ?>"
                    data-design-upload="<?php echo esc_attr(!empty($service->allow_design_upload) ? '1' : '0'); ?>"
                    data-search="<?php echo esc_attr(strtolower($service->id . ' ' . $service->name . ' ' . $service->description . ' ' . $service->category)); ?>"
                    class="sbs-main-service-row <?php echo !empty($service->allow_design_upload) ? 'has-design-upload' : ''; ?>"
                    data-service-name="<?php echo esc_attr($service->name); ?>">
                    <td><input type="checkbox" class="sbs-service-row-checkbox" value="<?php echo esc_attr($service->id); ?>" aria-label="Select service <?php echo esc_attr($service->name); ?>"></td>
                    <td class="sbs-drag-handle" style="cursor:move; text-align:center; color:#999;">⋮⋮</td>
                    <td><input type="number" class="sbs-order-input" value="<?php echo esc_html( $service->sort_order ); ?>" min="0"></td>
                    <td><?php echo esc_html($service->id); ?></td>
                    <td>
                        <strong><?php echo esc_html($service->name); ?></strong>
                        <?php if (!empty($service->allow_design_upload)) : ?>
                            <span class="sbs-design-upload-inline-badge">Photo upload</span>
                        <?php endif; ?>
                        <?php if ($service->description) : ?>
                            <br><small class="sbs-row-muted"><?php echo esc_html(wp_trim_words($service->description, 10)); ?></small>
                        <?php endif; ?>
                        <?php 
                        // Fetch options
                        global $wpdb;
                        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
                        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                        $options = $wpdb->get_results($wpdb->prepare(
                            "SELECT * FROM {$wpdb->prefix}yatoon_service_options WHERE service_id = %d ORDER BY sort_order",
                            $service->id
                        ));
                        if (!empty($options)) :
                        ?>
                            <button type="button" class="button button-small sbs-toggle-options" data-service-id="<?php echo esc_html( $service->id ); ?>">
                                <span class="dashicons dashicons-arrow-down-alt2" aria-hidden="true"></span>
                                <span class="sbs-toggle-text">Show Options (<?php echo esc_html( count($options) ); ?>)</span>
                            </button>
                        <?php endif; ?>
                    </td>
                    <td><?php echo esc_html($service->duration_minutes); ?> min</td>
                    <td>$<?php echo number_format($service->price, 2); ?></td>
                    <td><?php echo esc_html($service->category ?: '-'); ?></td>
                    <td>
                        <?php if (!empty($service->require_policy)) : ?><span class="sbs-rule-pill">Policy</span><?php endif; ?>
                        <?php if (!empty($service->require_consent)) : ?><span class="sbs-rule-pill consent">Consent</span><?php endif; ?>
                        <?php if (!empty($service->is_featured)) : ?><span class="sbs-rule-pill featured">Popular</span><?php endif; ?>
                        <?php if (!empty($service->allow_design_upload)) : ?><span class="sbs-rule-pill design-upload">Photo upload</span><?php endif; ?>
                        <?php if (empty($service->allow_staff_select)) : ?><span class="sbs-rule-pill any">Any staff</span><?php endif; ?>
                        <?php if (empty($service->require_policy) && empty($service->require_consent) && empty($service->is_featured) && empty($service->allow_design_upload) && !empty($service->allow_staff_select)) : ?>-<?php endif; ?>
                    </td>
                    <td>
                        <button type="button" class="sbs-status-toggle <?php echo $service->is_active ? 'is-active' : 'is-hidden'; ?>" data-id="<?php echo esc_attr( $service->id ); ?>" data-active="<?php echo esc_attr( $service->is_active ? 1 : 0 ); ?>" aria-pressed="<?php echo esc_attr( $service->is_active ? 'true' : 'false' ); ?>"><?php echo esc_html( $service->is_active ? 'Active' : 'Hidden' ); ?></button>
                    </td>
                    <td class="sbs-service-actions">
                        <button type="button" class="button button-small sbs-edit-service" data-id="<?php echo esc_html( $service->id ); ?>">Edit</button>
                        <button type="button" class="button button-small sbs-copy-addon-btn" data-service-id="<?php echo esc_html( $service->id ); ?>" data-service-name="<?php echo esc_attr($service->name); ?>">Add Add-on</button>
                        <button type="button" class="button button-small sbs-delete-service" data-id="<?php echo esc_html( $service->id ); ?>">Delete</button>
                    </td>
                </tr>
                <?php if (!empty($options)) : ?>
                <tr class="sbs-options-row" data-service-id="<?php echo esc_html( $service->id ); ?>" style="display:none;">
                    <td colspan="11" style="padding:0 20px 20px 60px; background:#f9f9f9;">
                        <table class="sbs-options-inline-table">
                            <thead>
                                <tr style="border-bottom:2px solid #ddd;">
                                    <th style="padding:8px; text-align:left; width:44px;"></th>
                                    <th style="padding:8px; text-align:left; width:40%;">Option Name</th>
                                    <th style="padding:8px; text-align:left;">Duration</th>
                                    <th style="padding:8px; text-align:left;">Price</th>
                                    <th style="padding:8px; text-align:left;">Group</th>
                                    <th style="padding:8px; text-align:left;">Badge</th>
                                    <th style="padding:8px; text-align:left;">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="sbs-options-sortable" data-service-id="<?php echo esc_html( $service->id ); ?>">
                                <?php // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
                                <?php foreach ($options as $option) : ?>
                                <tr class="sbs-option-row" data-option-id="<?php echo esc_html( $option->id ); ?>">
                                    <td style="padding:4px 8px; width:20px; cursor:grab; color:#aaa; text-align:center;" class="sbs-option-drag-handle" title="Drag to reorder">&#9776;</td>
                                    <td style="padding:8px;">
                                        <input type="text" 
                                               class="sbs-option-name" 
                                               value="<?php echo esc_attr($option->name); ?>" 
                                               data-option-id="<?php echo esc_html( $option->id ); ?>"
                                               style="width:100%; padding:6px; border:1px solid #ddd; border-radius:4px;">
                                    </td>
                                    <td style="padding:8px;"><input type="number"
                                               class="sbs-option-duration"
                                               value="<?php echo esc_attr($option->duration_minutes); ?>"
                                               data-option-id="<?php echo esc_html( $option->id ); ?>"
                                               min="1" step="1"
                                               style="width:65px; padding:6px; border:1px solid #ddd; border-radius:4px;"> min</td>
                                    <td style="padding:8px;">
                                        <?php // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
                                        <?php $is_addon_opt = ( ( $option->group_name ?? '' ) === 'Add-on' ); ?>
                                        <input type="number"
                                               class="sbs-option-price"
                                               value="<?php echo number_format( $is_addon_opt ? floatval($option->price_modifier) : ( floatval($service->price) + floatval($option->price_modifier) ), 2, '.', ''); ?>"
                                               data-option-id="<?php echo esc_html( $option->id ); ?>"
                                               data-base-price="<?php echo esc_attr(floatval($service->price)); ?>"
                                               step="0.01"
                                               min="0"
                                               style="width:80px; padding:6px; border:1px solid #ddd; border-radius:4px;">
                                    </td>
                                    <td style="padding:8px;">
                                        <select class="sbs-option-group" data-option-id="<?php echo esc_html( $option->id ); ?>" style="padding:5px 6px; border:1px solid #ddd; border-radius:4px; font-size:13px;">
                                            <option value="" <?php selected($option->group_name ?? '', ''); ?>>Main (single select)</option>
                                            <option value="Add-on" <?php selected($option->group_name ?? '', 'Add-on'); ?>>Add-on (multi-select)</option>
                                        </select>
                                    </td>
                                    <td style="padding:8px;">
                                        <select class="sbs-option-badge" data-option-id="<?php echo esc_html( $option->id ); ?>" style="padding:5px 6px; border:1px solid #ddd; border-radius:4px; font-size:13px;">
                                            <option value="" <?php selected($option->badge_label ?? '', ''); ?>>Auto</option>
                                            <option value="recommended" <?php selected($option->badge_label ?? '', 'recommended'); ?>>Recommended</option>
                                            <option value="popular" <?php selected($option->badge_label ?? '', 'popular'); ?>>Popular</option>
                                            <option value="addon" <?php selected($option->badge_label ?? '', 'addon'); ?>>Add-on</option>
                                            <option value="none" <?php selected($option->badge_label ?? '', 'none'); ?>>None</option>
                                        </select>
                                    </td>
                                    <td style="padding:8px;">
                                        <div class="sbs-option-actions">
                                        <button type="button" class="button button-small sbs-save-option" data-option-id="<?php echo esc_html( $option->id ); ?>">Save</button>
                                        <button type="button" class="button button-small sbs-delete-option" data-option-id="<?php echo esc_html( $option->id ); ?>">Delete</button>
                                        <span class="sbs-option-save-state" aria-live="polite"></span>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        <!-- Copy Add-on button -->
                        <div style="padding:8px 0 4px;">
                            <button type="button" class="button sbs-copy-addon-btn"
                                data-service-id="<?php echo esc_html( $service->id ); ?>"
                                data-service-name="<?php echo esc_attr($service->name); ?>"
                                style="font-size:12px;">
                                + Copy Add-on from another service
                            </button>
                        </div>
                    </td>
                </tr>
                <?php else: ?>
                <tr class="sbs-options-row" id="options-<?php echo esc_html( $service->id ); ?>" style="display:none;">
                    <td colspan="11" style="padding:0 20px 12px 40px;">
                        <div style="padding:8px 0 4px;">
                            <button type="button" class="button sbs-copy-addon-btn"
                                data-service-id="<?php echo esc_html( $service->id ); ?>"
                                data-service-name="<?php echo esc_attr($service->name); ?>"
                                style="font-size:12px;">
                                + Copy Add-on from another service
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endif; ?>
                <?php endforeach; ?>
            </tbody>
        </table>
        </div>
    <?php endif; ?>
</div>

<!-- Category Manager Modal -->
<div id="sbs-category-modal" style="display:none; position:fixed; z-index:100001; left:0; top:0; width:100%; height:100%; background:rgba(0,0,0,0.5);">
    <div style="background:white; margin:80px auto; padding:28px; max-width:560px; border-radius:8px; max-height:80vh; overflow-y:auto;">
        <h3 style="margin-top:0;">Manage Categories</h3>
        <p class="description" style="margin-top:0;">Categories are built from services. Rename a category to update every service using it, or delete it to clear that category from those services.</p>
        <div id="sbs-category-list">
            <?php if (empty($service_categories)) : ?>
                <p style="color:#666;">No categories yet. Add one while creating or editing a service.</p>
            <?php else : ?>
                <?php foreach ($service_categories as $category_name) : ?>
                    <div class="sbs-category-manager-row" data-category="<?php echo esc_attr($category_name); ?>">
                        <input type="text" class="regular-text sbs-category-name-input" value="<?php echo esc_attr($category_name); ?>">
                        <span class="sbs-category-count"><?php echo esc_html((int) ($service_category_counts[$category_name] ?? 0)); ?> services</span>
                        <button type="button" class="button button-small sbs-save-category">Save</button>
                        <button type="button" class="button button-small sbs-delete-category">Delete</button>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        <div id="sbs-category-msg" style="margin:12px 0; font-size:13px;"></div>
        <div style="display:flex; justify-content:flex-end;">
            <button type="button" id="sbs-category-close" class="button">Close</button>
        </div>
    </div>
</div>

<!-- Copy Add-on Modal -->
<div id="sbs-copy-addon-modal" style="display:none; position:fixed; z-index:100001; left:0; top:0; width:100%; height:100%; background:rgba(0,0,0,0.5);">
    <div style="background:white; margin:80px auto; padding:28px; max-width:520px; border-radius:8px; max-height:80vh; overflow-y:auto;">
        <h3 style="margin-top:0;">Copy Add-on to <span id="sbs-addon-target-name"></span></h3>
        <p style="color:#666; font-size:13px;">Copy an option from another service, or enter a name, duration, and price below to create a new Add-on.</p>

        <div style="margin-bottom:16px;">
            <label style="font-weight:600; display:block; margin-bottom:6px;">Optional: copy from existing service</label>
            <select id="sbs-addon-source-service" style="width:100%; padding:7px; border:1px solid #ccc; border-radius:4px;">
                <option value="">-- Loading... --</option>
            </select>
            <p id="sbs-addon-source-empty" class="description" style="display:none;margin:6px 0 0;">No reusable options found yet. You can still type a new Add-on below.</p>
        </div>

        <div id="sbs-addon-options-list" style="margin-bottom:16px; display:none;">
            <label style="font-weight:600; display:block; margin-bottom:6px;">Select Option</label>
            <select id="sbs-addon-source-option" style="width:100%; padding:7px; border:1px solid #ccc; border-radius:4px;">
                <option value="">-- Please select a source service first --</option>
            </select>
            <div id="sbs-addon-option-preview" style="margin-top:8px; padding:8px 12px; background:#f7f7f7; border-radius:4px; font-size:12px; color:#555; display:none;"></div>
        </div>

        <div style="margin-bottom:16px;">
            <label style="font-weight:600; display:block; margin-bottom:6px;">Display Name (editable)</label>
            <input type="text" id="sbs-addon-name" style="width:100%; padding:7px; border:1px solid #ccc; border-radius:4px;" placeholder="e.g. Custom Design / Nail Art">
        </div>

        <div style="display:flex; gap:12px; margin-bottom:16px;">
            <div style="flex:1;">
                <label style="font-weight:600; display:block; margin-bottom:6px;">Duration (min)</label>
                <input type="number" id="sbs-addon-duration" min="5" step="5" style="width:100%; padding:7px; border:1px solid #ccc; border-radius:4px;">
            </div>
            <div style="flex:1;">
                <label style="font-weight:600; display:block; margin-bottom:6px;">Price ($)</label>
                <input type="number" id="sbs-addon-price" min="0" step="0.01" style="width:100%; padding:7px; border:1px solid #ccc; border-radius:4px;">
            </div>
        </div>

        <div id="sbs-addon-sq-id-row" style="margin-bottom:16px; padding:8px 12px; background:#e8f4fd; border-radius:4px; font-size:12px; color:#0073aa;">
            <strong>Square Variation ID: </strong><span id="sbs-addon-sq-id-display">(optional; copied when available)</span>
        </div>

        <div id="sbs-addon-msg" style="margin-bottom:12px; font-size:13px;"></div>

        <div style="display:flex; gap:10px; justify-content:flex-end;">
            <button type="button" id="sbs-addon-cancel" class="button">Cancel</button>
            <button type="button" id="sbs-addon-confirm" class="button button-primary" disabled>Add</button>
        </div>
    </div>
</div>

<!-- Add/Edit Service Modal -->
<div id="sbs-service-modal" style="display:none; position:fixed; z-index:100000; left:0; top:0; width:100%; height:100%; background:rgba(0,0,0,0.5);">
    <div class="sbs-service-modal-panel">
        <button type="button" class="sbs-service-modal-close" aria-label="Close">&times;</button>
        <h2 id="sbs-modal-title">Add Service</h2>
        <form id="sbs-service-form">
            <input type="hidden" id="service-id" value="">
            
            <p>
                <label><strong>Service Name *</strong></label>
                <input type="text" id="service-name" class="regular-text" required tabindex="1">
            </p>
            
            <p>
                <label><strong>Description</strong></label>
                <textarea id="service-description" rows="3" class="large-text" tabindex="2"></textarea>
                <span style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:8px;">
                    <button type="button" class="button button-secondary" id="yatoon-ai-desc-btn">Improve with AI</button>
                    <span class="description" id="yatoon-ai-desc-status">Uses this service's name, category, price, duration, and current description.</span>
                </span>
            </p>
            
            <p style="display:flex; gap:20px; align-items:flex-start;">
                <span style="flex:0 0 48%;">
                    <label><strong>Duration (minutes) *</strong></label>
                    <input type="number" id="service-duration" class="regular-text" min="5" step="5" required tabindex="3" style="width:100%;box-sizing:border-box;">
                </span>
                <span style="flex:0 0 48%;">
                    <label><strong>Price ($) *</strong></label>
                    <input type="number" id="service-price" class="regular-text" min="0" step="0.01" required tabindex="4" style="width:100%;box-sizing:border-box;">
                </span>
            </p>
            
            <p>
                <label><strong>Category</strong></label>
                <span class="sbs-category-picker">
                    <select id="service-category-select" class="regular-text" tabindex="5">
                        <option value="">No category</option>
                        <?php foreach ($service_categories as $category_name) : ?>
                            <option value="<?php echo esc_attr($category_name); ?>"><?php echo esc_html($category_name); ?></option>
                        <?php endforeach; ?>
                        <option value="__new">+ Add new category</option>
                    </select>
                    <input type="text" id="service-category-new" class="regular-text" placeholder="New category name" style="display:none;" tabindex="6">
                    <input type="hidden" id="service-category" value="">
                </span>
            </p>

            <div class="sbs-service-image-field">
                <label><strong>Cover Image</strong></label>
                <p class="description" style="margin:3px 0 10px;">Recommended: a bright square or 4:3 service photo, at least 900px wide. This image is used on the mobile booking card, so close-up nail or treatment photos convert best.</p>
                <input type="hidden" id="service-image-url" value="">
                <div id="service-image-preview" class="sbs-service-image-preview" style="display:none;">
                    <img src="" alt="" style="width:120px;height:120px;object-fit:cover;border-radius:8px;border:1px solid #dcdcde;background:#f6f7f7;">
                </div>
                <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:8px;">
                    <button type="button" class="button" id="service-image-upload">Upload / Choose Image</button>
                    <button type="button" class="button" id="service-image-remove" style="display:none;">Remove Image</button>
                    <span class="description">No image? Yatoon will show a polished placeholder card automatically.</span>
                </div>
            </div>

            <!-- Gallery images -->
            <div class="sbs-service-gallery-field" style="margin:16px 0;">
                <label><strong>Gallery Images</strong></label>
                <p class="description" style="margin:2px 0 10px;">These appear in the Catalog gallery view and the <code>[yatoon_gallery]</code> homepage slider. Drag to reorder.</p>
                <div id="service-gallery-grid" class="sbs-gallery-grid"></div>
                <div style="display:flex;gap:8px;margin-top:10px;">
                    <button type="button" class="button" id="service-gallery-add">+ Add Images</button>
                    <span class="description" style="align-self:center;">Select multiple at once from Media Library</span>
                </div>
            </div>
            
            <p>
                <label>
                    <input type="checkbox" id="service-active" checked>
                    <strong>Active (visible on booking page)</strong>
                </label>
            </p>

            <div style="border:1px solid #e5e7eb;border-radius:8px;padding:14px;margin:14px 0;background:#f9fafb;">
                <h3 style="margin:0 0 10px;font-size:14px;">Booking Rules</h3>
                <p style="margin:8px 0;">
                    <label><input type="checkbox" id="service-require-policy"> Require cancellation / no-show policy acknowledgement for this service</label>
                </p>
                <p style="margin:8px 0;">
                    <label><input type="checkbox" id="service-require-consent"> Require consent / waiver signature for this service</label>
                </p>
                <p style="margin:8px 0;">
                    <label><input type="checkbox" id="service-allow-staff-select" checked> Let customers choose staff for this service</label>
                </p>
                <p style="margin:8px 0;">
                    <label><input type="checkbox" id="service-allow-design-upload"> Allow customer design image upload</label>
                    <span class="description" style="display:block;margin:4px 0 0 24px;">Use for Custom Design / Nail Art services. The General upload switch must also be enabled.</span>
                </p>
                <p style="margin:8px 0;">
                    <label><input type="checkbox" id="service-is-featured"> Show Popular badge on the booking page</label>
                </p>
                <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-top:12px;">
                    <label>Buffer before (min)<input type="number" id="service-buffer-before" min="0" step="5" value="0" style="width:100%;"></label>
                    <label>Buffer after (min)<input type="number" id="service-buffer-after" min="0" step="5" value="0" style="width:100%;"></label>
                    <label>Lead time (min)<input type="number" id="service-lead-time" min="0" step="15" value="0" style="width:100%;"></label>
                </div>
                <p class="description" style="margin:10px 0 0;">Buffers and lead time are stored now for scheduling/reporting; Square availability remains the final source when Square mode is active.</p>
            </div>
            
            <p>
                <button type="submit" class="button button-primary">Save Service</button>
                <button type="button" class="button sbs-service-modal-cancel">Cancel</button>
            </p>
        </form>

        <!-- Manual Options Manager (only shown when editing an existing service) -->
        <div id="sbs-modal-options-section" style="display:none; margin-top:20px; border-top:1px solid #e5e7eb; padding-top:20px;">
            <h3 style="margin:0 0 10px; font-size:14px;">Service Options / Variations</h3>
            <p class="description" style="margin:0 0 12px;">Add options like "Hands" / "Feet" so customers can choose when booking.</p>

            <table id="sbs-modal-options-table" style="width:100%; border-collapse:collapse; margin-bottom:12px; font-size:13px;">
                <thead>
                    <tr style="background:#f9fafb; border-bottom:1px solid #e5e7eb;">
                        <th style="padding:6px 8px; text-align:left;">Name</th>
                        <th style="padding:6px 8px; text-align:left; width:80px;">Duration<br><span style="font-weight:normal;color:#888;">(min)</span></th>
                        <th style="padding:6px 8px; text-align:left; width:80px;">Price<br><span style="font-weight:normal;color:#888;">($)</span></th>
                        <th style="padding:6px 8px; text-align:left; width:110px;">Type</th>
                        <th style="padding:6px 8px; width:160px; text-align:right;">Actions</th>
                    </tr>
                </thead>
                <tbody id="sbs-modal-options-body">
                    <tr id="sbs-modal-options-empty"><td colspan="5" style="padding:10px 8px; color:#888; text-align:center;">No options yet.</td></tr>
                </tbody>
            </table>

            <!-- Add new option row -->
            <div style="background:#f9fafb; border:1px solid #e5e7eb; border-radius:6px; padding:12px; margin-top:4px;">
                <strong style="font-size:13px; display:block; margin-bottom:8px;">+ Add New Option</strong>
                <div style="margin-bottom:10px;">
                    <label for="sbs-new-option-existing" style="display:block;font-size:12px;font-weight:700;color:#374151;margin-bottom:5px;">Reuse existing item</label>
                    <select id="sbs-new-option-existing" style="width:100%;max-width:560px;">
                        <option value="">Manual - create a new option</option>
                    </select>
                    <input type="hidden" id="sbs-new-option-source-service" value="">
                    <input type="hidden" id="sbs-new-option-source-option" value="">
                    <p id="sbs-new-option-link-note" class="description" style="margin:5px 0 0;">Choose an existing service or option to reuse its shared ID, or enter a new option manually below.</p>
                </div>
                <div style="display:flex; gap:8px; flex-wrap:wrap; align-items:flex-end;">
                    <label style="flex:2; min-width:120px;">
                        <span style="font-size:12px; color:#555;">Name *</span>
                        <input type="text" id="sbs-new-option-name" placeholder="e.g. Hands" style="width:100%; padding:5px 7px; border:1px solid #ccc; border-radius:4px; font-size:13px;">
                    </label>
                    <label style="flex:1; min-width:70px;">
                        <span style="font-size:12px; color:#555;">Duration (min)</span>
                        <input type="number" id="sbs-new-option-duration" min="5" step="5" value="10" style="width:100%; padding:5px 7px; border:1px solid #ccc; border-radius:4px; font-size:13px;">
                    </label>
                    <label style="flex:1; min-width:70px;">
                        <span style="font-size:12px; color:#555;">Price ($)</span>
                        <input type="number" id="sbs-new-option-price" min="0" step="0.01" value="0" style="width:100%; padding:5px 7px; border:1px solid #ccc; border-radius:4px; font-size:13px;">
                    </label>
                    <label style="flex:1; min-width:100px;">
                        <span style="font-size:12px; color:#555;">Type</span>
                        <select id="sbs-new-option-group" style="width:100%; padding:5px 7px; border:1px solid #ccc; border-radius:4px; font-size:13px;">
                            <option value="">Main (single)</option>
                            <option value="Add-on">Add-on (multi)</option>
                        </select>
                    </label>
                    <button type="button" id="sbs-modal-add-option-btn" class="button button-primary" style="height:30px; align-self:flex-end;">Add</button>
                </div>
                <div id="sbs-modal-option-msg" style="margin-top:8px; font-size:12px; display:none;"></div>
            </div>
        </div>
    </div>
</div>

        <style>
        .sbs-admin-table-wrap {
            width: 100%;
            overflow-x: visible !important;
            overflow-y: visible;
            padding-bottom: 8px;
        }
        #sbs-services-table {
            display: block !important;
            width: 100% !important;
            min-width: 0 !important;
            table-layout: auto !important;
            border-collapse: separate !important;
        }
        #sbs-services-table thead { display: none !important; }
        #sbs-services-table tbody {
            display: block !important;
            width: 100% !important;
        }
        #sbs-services-table tr.sbs-main-service-row {
            display: grid !important;
            grid-template-columns: 44px 34px 76px minmax(280px, 1fr) 88px 88px 132px 88px;
            align-items: center;
            gap: 0;
            width: 100% !important;
            min-width: 0 !important;
            cursor: pointer;
            border-bottom: 1px solid #eef2f7;
            background: #fff;
        }
        #sbs-services-table tr.sbs-main-service-row:nth-child(4n+1) {
            background: #fbfdff;
        }
        #sbs-services-table tr.sbs-main-service-row:hover td {
            background: #f8fafc !important;
        }
        #sbs-services-table tr.is-selected td {
            background: #f0fdf4 !important;
        }
        #sbs-services-table tr.sbs-main-service-row td {
            display: flex !important;
            align-items: center;
            min-width: 0 !important;
            max-width: none !important;
            width: auto !important;
            height: 72px;
            box-sizing: border-box;
            overflow: hidden;
            white-space: normal !important;
            text-overflow: clip !important;
            padding: 10px 12px !important;
            border-bottom: 0 !important;
            vertical-align: middle;
        }
        #sbs-services-table tr.sbs-main-service-row td:nth-child(1),
        #sbs-services-table tr.sbs-main-service-row td:nth-child(2) {
            justify-content: center;
            padding-left: 6px !important;
            padding-right: 6px !important;
        }
        #sbs-services-table tr.sbs-main-service-row td:nth-child(3) {
            justify-content: center;
        }
        #sbs-services-table tr.sbs-main-service-row td:nth-child(5) {
            display: block !important;
            padding-top: 12px !important;
        }
        #sbs-services-table tr.sbs-main-service-row td:nth-child(5) strong {
            display: inline-block;
            max-width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            vertical-align: middle;
        }
        #sbs-services-table tr.sbs-main-service-row td:nth-child(6),
        #sbs-services-table tr.sbs-main-service-row td:nth-child(7),
        #sbs-services-table tr.sbs-main-service-row td:nth-child(8),
        #sbs-services-table tr.sbs-main-service-row td:nth-child(10) {
            color: #4b5563;
            font-weight: 650;
        }
        #sbs-services-table tr.sbs-main-service-row td:nth-child(4),
        #sbs-services-table tr.sbs-main-service-row td:nth-child(9),
        #sbs-services-table tr.sbs-main-service-row td:nth-child(11),
        #sbs-services-table .sbs-toggle-options,
        #sbs-services-table .sbs-options-row {
            display: none !important;
        }
        #sbs-services-table input.sbs-service-row-checkbox,
        #sbs-select-all-services-main {
            width: 22px !important;
            height: 22px !important;
            min-width: 22px !important;
            cursor: pointer;
        }
        #sbs-services-table .sbs-order-input {
            width: 58px !important;
            min-width: 58px !important;
            max-width: 58px !important;
            text-align: center;
        }
        #sbs-services-table td:nth-child(5) strong::after {
            content: "Edit";
            display: inline-flex;
            margin-left: 10px;
            padding: 2px 8px;
            border: 1px solid #bfdbfe;
            border-radius: 999px;
            color: #2563eb;
            background: #eff6ff;
            font-size: 12px;
            line-height: 1.3;
            font-weight: 700;
            vertical-align: 1px;
        }
        #sbs-services-table .sbs-service-actions { display: none !important; }
        .sbs-services-page .yatoon-table-x-scrollbar { display: none !important; }
        .sbs-selected-service-actions {
            display: flex;
            gap: 10px;
            align-items: center;
            justify-content: flex-end;
            flex-wrap: wrap;
        }
        .sbs-selected-services-summary {
            color: #4b5563;
            font-weight: 700;
            margin-right: 4px;
        }
        .sbs-selected-service-actions .button { min-width: 112px; }
        .sbs-option-save-state { color: #6b7280; font-size: 12px; font-weight: 600; }
        .sbs-option-save-state.is-dirty { color: #b45309; }
        .sbs-option-save-state.is-saved { color: #047857; }
        @media (max-width: 1200px) {
            #sbs-services-table tr.sbs-main-service-row {
                grid-template-columns: 44px 30px 66px minmax(220px, 1fr) 78px 76px 112px 74px;
            }
            #sbs-services-table tr.sbs-main-service-row td { padding-left: 8px !important; padding-right: 8px !important; }
        }
        @media (max-width: 900px) {
            #sbs-services-table tr.sbs-main-service-row {
                grid-template-columns: 38px 28px 58px minmax(180px, 1fr) 70px 70px 66px;
            }
            #sbs-services-table tr.sbs-main-service-row td:nth-child(8) { display: none !important; }
            #sbs-services-table tr.sbs-main-service-row td { height: 78px; }
        }
    
        .sbs-status-toggle {
            min-width: 72px;
            border: 1px solid #bbf7d0;
            border-radius: 999px;
            padding: 6px 12px;
            font-size: 12px;
            font-weight: 800;
            line-height: 1;
            cursor: pointer;
            background: #dcfce7;
            color: #15803d;
        }
        .sbs-status-toggle.is-hidden {
            border-color: #e5e7eb;
            background: #f3f4f6;
            color: #6b7280;
        }
        .sbs-status-toggle.is-saving {
            opacity: .65;
            cursor: wait;
        }
        #sbs-service-modal {
            padding: 24px;
            box-sizing: border-box;
            overflow-y: auto;
        }
        .sbs-service-modal-panel {
            position: relative;
            background: #fff;
            margin: 24px auto;
            padding: 30px;
            width: min(1080px, calc(100vw - 88px));
            max-width: 1080px;
            border-radius: 10px;
            max-height: calc(100vh - 72px);
            overflow-y: auto;
            overflow-x: hidden;
            box-sizing: border-box;
        }
        .sbs-service-modal-close {
            position: sticky;
            top: 0;
            float: right;
            z-index: 2;
            width: 34px;
            height: 34px;
            margin: -12px -12px 4px 12px;
            border: 1px solid #e5e7eb;
            border-radius: 999px;
            background: #fff;
            color: #6b7280;
            font-size: 22px;
            line-height: 28px;
            cursor: pointer;
        }
        .sbs-service-modal-close:hover {
            color: #111827;
            border-color: #cbd5e1;
        }
        #sbs-modal-options-table { table-layout: fixed; }
        #sbs-modal-options-table input,
        #sbs-modal-options-table select { box-sizing: border-box; max-width: 100%; }
        #sbs-modal-options-table th:nth-child(1),
        #sbs-modal-options-table td:nth-child(1) { width: 34%; }
        #sbs-modal-options-table th:nth-child(2),
        #sbs-modal-options-table td:nth-child(2) { width: 110px; }
        #sbs-modal-options-table th:nth-child(3),
        #sbs-modal-options-table td:nth-child(3) { width: 126px; }
        #sbs-modal-options-table th:nth-child(4),
        #sbs-modal-options-table td:nth-child(4) { width: 150px; }
        #sbs-modal-options-table th:nth-child(5),
        #sbs-modal-options-table td:nth-child(5) { width: 168px; }
        @media (max-width: 900px) {
            .sbs-service-modal-panel { width: calc(100vw - 32px); padding: 20px; }
            #sbs-modal-options-table { display: block; overflow-x: auto; white-space: nowrap; }
        }
    </style>

<script>
jQuery(function($){
    let serviceImageFrame  = null;
    let galleryImageFrame  = null;
    let galleryImages      = []; // [{url, caption}]
    const serviceCategories = <?php echo wp_json_encode(array_values($service_categories)); ?>;
    const categoryNonce = '<?php echo esc_js(wp_create_nonce("yatoon_service_category")); ?>';

    function setCategoryField(category) {
        category = category || '';
        if (category && serviceCategories.indexOf(category) === -1) {
            $('#service-category-select').val('__new');
            $('#service-category-new').val(category).show();
        } else {
            $('#service-category-select').val(category);
            $('#service-category-new').val('').hide();
        }
        $('#service-category').val(category);
    }

    $('#service-category-select').on('change', function() {
        if ($(this).val() === '__new') {
            $('#service-category-new').show().focus();
            $('#service-category').val($('#service-category-new').val().trim());
        } else {
            $('#service-category-new').hide().val('');
            $('#service-category').val($(this).val() || '');
        }
    });

    $('#service-category-new').on('input', function() {
        $('#service-category').val($(this).val().trim());
    });

    $('#sbs-manage-categories').on('click', function() {
        $('#sbs-category-msg').text('').css('color', '');
        $('#sbs-category-modal').show();
    });

    $('#sbs-category-close').on('click', function() {
        $('#sbs-category-modal').hide();
    });

    $('#sbs-category-modal').on('click', function(e) {
        if (e.target === this) {
            $(this).hide();
        }
    });

    $(document).on('click', '.sbs-save-category', function() {
        const $row = $(this).closest('.sbs-category-manager-row');
        const oldName = String($row.data('category') || '');
        const newName = $row.find('.sbs-category-name-input').val().trim();
        if (!newName) {
            $('#sbs-category-msg').text('Category name cannot be empty.').css('color', '#c00');
            return;
        }
        const $btn = $(this).prop('disabled', true).text('Saving...');
        $.post(ajaxurl, {
            action: 'yatoon_rename_service_category',
            nonce: categoryNonce,
            old_category: oldName,
            new_category: newName
        }, function(resp) {
            if (resp.success) {
                location.reload();
            } else {
                $('#sbs-category-msg').text(resp.data || 'Failed to rename category.').css('color', '#c00');
                $btn.prop('disabled', false).text('Save');
            }
        });
    });

    $(document).on('click', '.sbs-delete-category', function() {
        const $row = $(this).closest('.sbs-category-manager-row');
        const category = String($row.data('category') || '');
        if (!confirm('Delete category "' + category + '"? Services using it will keep the service, but their category will be cleared.')) {
            return;
        }
        const $btn = $(this).prop('disabled', true).text('Deleting...');
        $.post(ajaxurl, {
            action: 'yatoon_delete_service_category',
            nonce: categoryNonce,
            category: category
        }, function(resp) {
            if (resp.success) {
                location.reload();
            } else {
                $('#sbs-category-msg').text(resp.data || 'Failed to delete category.').css('color', '#c00');
                $btn.prop('disabled', false).text('Delete');
            }
        });
    });

    // -- Gallery helpers ------------------------------------------------
    function renderGalleryGrid() {
        const $grid = $('#service-gallery-grid');
        if (!galleryImages.length) {
            $grid.html('<p style="color:#9ca3af;font-size:13px;margin:0;">No gallery images yet.</p>');
            return;
        }
        let html = '';
        galleryImages.forEach(function(img, i) {
            html += `<div class="sbs-gallery-item" data-index="${i}">
                <img src="${img.url}" alt="">
                <div class="sbs-gallery-item-actions">
                    <button type="button" class="sbs-gallery-remove" data-index="${i}" title="Remove">&times;</button>
                </div>
            </div>`;
        });
        $grid.html(html);
        // Make sortable
        if ($.fn.sortable) {
            $grid.sortable({
                items: '.sbs-gallery-item',
                cursor: 'grabbing',
                update: function() {
                    const newOrder = [];
                    $grid.find('.sbs-gallery-item').each(function() {
                        newOrder.push(galleryImages[parseInt($(this).data('index'))]);
                    });
                    galleryImages = newOrder;
                    renderGalleryGrid();
                }
            });
        }
    }

    function loadGalleryImages(serviceId) {
        if (!serviceId) { galleryImages = []; renderGalleryGrid(); return; }
        $.get(ajaxurl, {
            action: 'yatoon_get_service_images',
            nonce: '<?php echo esc_js(wp_create_nonce("yatoon_service")); ?>',
            service_id: serviceId
        }, function(resp) {
            galleryImages = resp.success ? resp.data.images.map(function(i){ return {url: i.image_url, caption: i.caption}; }) : [];
            renderGalleryGrid();
        });
    }

    function saveGalleryImages(serviceId, callback) {
        $.post(ajaxurl, {
            action: 'yatoon_save_service_images',
            nonce: '<?php echo esc_js(wp_create_nonce("yatoon_service")); ?>',
            service_id: serviceId,
            images: galleryImages
        }, function(resp) {
            if (callback) callback(resp);
        });
    }

    // Add gallery images
    $('#service-gallery-add').on('click', function(e) {
        e.preventDefault();
        if (galleryImageFrame) { galleryImageFrame.open(); return; }
        galleryImageFrame = wp.media({
            title: 'Choose Gallery Images',
            button: { text: 'Add to gallery' },
            library: { type: 'image' },
            multiple: true
        });
        galleryImageFrame.on('select', function() {
            const selected = galleryImageFrame.state().get('selection').toJSON();
            selected.forEach(function(att) {
                const url = att.sizes && att.sizes.large ? att.sizes.large.url : att.url;
                if (!galleryImages.find(function(g){ return g.url === url; })) {
                    galleryImages.push({ url: url, caption: '' });
                }
            });
            renderGalleryGrid();
        });
        galleryImageFrame.open();
    });

    // Remove gallery image
    $(document).on('click', '.sbs-gallery-remove', function() {
        const idx = parseInt($(this).data('index'));
        galleryImages.splice(idx, 1);
        renderGalleryGrid();
    });

    // -- Gallery CSS ---------------------------------------------------
    $('<style>')
        .text('.sbs-gallery-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(90px,1fr));gap:8px;padding:4px 0;}'
            + '.sbs-gallery-item{position:relative;border-radius:8px;overflow:hidden;aspect-ratio:1;background:#f3f4f6;cursor:grab;}'
            + '.sbs-gallery-item img{width:100%;height:100%;object-fit:cover;display:block;}'
            + '.sbs-gallery-item-actions{position:absolute;top:4px;right:4px;}'
            + '.sbs-gallery-remove{background:rgba(0,0,0,.55);color:#fff;border:none;border-radius:50%;width:22px;height:22px;font-size:14px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;}'
            + '.sbs-gallery-remove:hover{background:#dc2626;}')
        .appendTo('head');

    function setServiceImage(url) {
        url = url || '';
        $('#service-image-url').val(url);
        if (url) {
            $('#service-image-preview').show().find('img').attr('src', url).attr('alt', $('#service-name').val() || 'Service image');
            $('#service-image-remove').show();
        } else {
            $('#service-image-preview').hide().find('img').attr('src', '').attr('alt', '');
            $('#service-image-remove').hide();
        }
    }

    $('#service-image-upload').on('click', function(e) {
        e.preventDefault();

        if (serviceImageFrame) {
            serviceImageFrame.open();
            return;
        }

        serviceImageFrame = wp.media({
            title: 'Choose Service Image',
            button: { text: 'Use this image' },
            library: { type: 'image' },
            multiple: false
        });

        serviceImageFrame.on('select', function() {
            const attachment = serviceImageFrame.state().get('selection').first().toJSON();
            const url = (attachment.sizes && attachment.sizes.medium ? attachment.sizes.medium.url : attachment.url);
            setServiceImage(url);
        });

        serviceImageFrame.open();
    });

    $('#service-image-remove').on('click', function(e) {
        e.preventDefault();
        setServiceImage('');
    });

    // Make table sortable with drag handle
    $('#sbs-sortable-services').sortable({
        handle: '.sbs-drag-handle',
        items: '> tr.sbs-main-service-row',
        axis: 'y',
        cursor: 'grabbing',
        placeholder: 'sbs-service-sort-placeholder',
        helper: function(e, tr) {
            const $originals = tr.children();
            const $helper = tr.clone();
            $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width());
            });
            return $helper;
        },
        start: function(event, ui) {
            ui.placeholder.html('<td colspan="11"></td>');
            ui.placeholder.height(ui.item.outerHeight());
        },
        update: function(event, ui) {
            saveOrder(true);
        }
    });

    // Manual order input
    $(document).on('change', '.sbs-order-input', function(){
        saveOrder(false);
    });

    function saveOrder(useVisualOrder) {
        const order = [];
        $('#sbs-sortable-services tr.sbs-main-service-row').each(function(index){
            const id = $(this).data('id');
            const manualOrder = useVisualOrder ? index + 1 : (parseInt($(this).find('.sbs-order-input').val(), 10) || index + 1);
            if (useVisualOrder) {
                $(this).find('.sbs-order-input').val(manualOrder);
            }
            order.push({ id: id, sort_order: manualOrder });
        });

        $.post(ajaxurl, {
            action: 'yatoon_update_service_order',
            nonce: '<?php echo esc_html( wp_create_nonce("yatoon_service_order") ); ?>',
            order: order
        }, function(resp){
            if (resp.success) {
                // Update visual order numbers
                if (useVisualOrder) {
                    $('#sbs-sortable-services tr.sbs-main-service-row').each(function(i){
                        $(this).find('.sbs-order-input').val(i + 1);
                    });
                }
            }
        });
    }

    function updateSelectedServicesState() {
        const total = $('.sbs-service-row-checkbox').length;
        const checked = $('.sbs-service-row-checkbox:checked').length;
        const selectedRows = $('.sbs-service-row-checkbox:checked').closest('tr.sbs-main-service-row');
        const oneSelected = checked === 1;
        $('#sbs-delete-selected-services').prop('disabled', checked === 0);
        $('#sbs-edit-selected-service, #sbs-add-addon-selected-service').prop('disabled', !oneSelected);
        if (checked === 0) {
            $('#sbs-selected-services-summary').text('Select a service or click a row to edit.');
        } else if (oneSelected) {
            $('#sbs-selected-services-summary').text('Selected: ' + (selectedRows.first().data('service-name') || '1 service'));
        } else {
            $('#sbs-selected-services-summary').text(checked + ' services selected');
        }
        $('#sbs-select-all-services-main')
            .prop('checked', total > 0 && checked === total)
            .prop('indeterminate', checked > 0 && checked < total);
        $('.sbs-service-row-checkbox').each(function() {
            $(this).closest('tr.sbs-main-service-row').toggleClass('is-selected', $(this).is(':checked'));
        });
    }

    $('#sbs-select-all-services-main').on('click', function(e) {
        e.stopPropagation();
        $('.sbs-service-row-checkbox').prop('checked', $(this).is(':checked'));
        updateSelectedServicesState();
    });

    $(document).on('click', '.sbs-service-row-checkbox', function(e) {
        e.stopPropagation();
        updateSelectedServicesState();
    });

    $(document).on('click', '#sbs-services-table tbody tr.sbs-main-service-row td:first-child', function(e) {
        if ($(e.target).is('.sbs-service-row-checkbox')) {
            return;
        }
        e.stopPropagation();
        const checkbox = $(this).find('.sbs-service-row-checkbox');
        checkbox.prop('checked', !checkbox.prop('checked'));
        updateSelectedServicesState();
    });

    $('#sbs-edit-selected-service').on('click', function() {
        const row = $('.sbs-service-row-checkbox:checked').closest('tr.sbs-main-service-row').first();
        if (!row.length) {
            return;
        }
        row.find('.sbs-edit-service').trigger('click');
    });

    $('#sbs-add-addon-selected-service').on('click', function() {
        const row = $('.sbs-service-row-checkbox:checked').closest('tr.sbs-main-service-row').first();
        if (!row.length) {
            return;
        }
        row.find('.sbs-copy-addon-btn').first().trigger('click');
    });
    $(document).on('click', '#sbs-services-table tbody tr.sbs-main-service-row', function(e) {
        if ($(e.target).closest('input, button, select, textarea, a, .sbs-drag-handle, .yatoon-col-resizer, .sbs-switch, .sbs-slider, .sbs-status-toggle').length) {
            return;
        }
        $(this).find('.sbs-edit-service').trigger('click');
    });

    function applyServiceFilters() {
        const q = ($('#sbs-service-search').val() || '').toLowerCase().trim();
        const cat = ($('#sbs-service-category-filter').val() || '').toLowerCase();
        const status = ($('#sbs-service-status-filter').val() || '').toLowerCase();
        const designUpload = ($('#sbs-service-design-upload-filter').val() || '');

        $('#sbs-sortable-services tr.sbs-main-service-row').each(function() {
            const $row = $(this);
            const serviceId = $row.data('id');
            const matchesText = !q || String($row.data('search') || '').indexOf(q) !== -1;
            const matchesCat = !cat || String($row.data('category') || '') === cat;
            const matchesStatus = !status || String($row.data('status') || '') === status;
            const matchesDesignUpload = !designUpload || String($row.data('design-upload') || '0') === designUpload;
            const visible = matchesText && matchesCat && matchesStatus && matchesDesignUpload;
            $row.toggle(visible);
            if (!visible) {
                $('#sbs-sortable-services tr.sbs-options-row[data-service-id="' + serviceId + '"], #options-' + serviceId).hide();
            }
        });
    }

    $('#sbs-service-search, #sbs-service-category-filter, #sbs-service-status-filter, #sbs-service-design-upload-filter').on('input change', applyServiceFilters);
    $('#sbs-service-clear-filters').on('click', function() {
        $('#sbs-service-search').val('');
        $('#sbs-service-category-filter').val('');
        $('#sbs-service-status-filter').val('');
        $('#sbs-service-design-upload-filter').val('');
        applyServiceFilters();
    });

    $('#sbs-delete-selected-services').on('click', function() {
        const ids = $('.sbs-service-row-checkbox:checked').map(function() {
            return parseInt($(this).val(), 10);
        }).get().filter(Boolean);

        if (!ids.length) {
            return;
        }

        if (!confirm('Delete selected services? This cannot be undone.')) {
            return;
        }

        const $btn = $(this).prop('disabled', true).text('Deleting...');

        $.post(ajaxurl, {
            action: 'yatoon_delete_service',
            nonce: '<?php echo esc_html( wp_create_nonce("yatoon_admin_nonce") ); ?>',
            service_ids: ids
        }, function(resp) {
            if (resp.success) {
                ids.forEach(function(id) {
                    $('#sbs-sortable-services tr.sbs-main-service-row[data-id="' + id + '"]').remove();
                    $('#sbs-sortable-services tr.sbs-options-row[data-service-id="' + id + '"], #options-' + id).remove();
                });
                updateSelectedServicesState();
                if (!$('.sbs-service-row-checkbox').length) {
                    location.reload();
                }
            } else {
                alert(resp.data && resp.data.message ? resp.data.message : 'Failed to delete selected services.');
            }
        }).fail(function() {
            alert('Network error. Please try again.');
        }).always(function() {
            $btn.text('Delete Selected');
            updateSelectedServicesState();
        });
    });
    
    // Toggle options expand/collapse
    $(document).on('click', '.sbs-toggle-options', function() {
        const btn = $(this);
        const serviceId = btn.data('service-id');
        const optionsRow = $('.sbs-options-row[data-service-id="' + serviceId + '"]');
        const icon = btn.find('.dashicons');
        const textSpan = btn.find('.sbs-toggle-text');
        
        if (optionsRow.is(':visible')) {
            optionsRow.slideUp(200);
            icon.removeClass('dashicons-arrow-up-alt2').addClass('dashicons-arrow-down-alt2');
            textSpan.text('Show Options (' + optionsRow.find('tbody tr').length + ')');
        } else {
            optionsRow.slideDown(200);
            icon.removeClass('dashicons-arrow-down-alt2').addClass('dashicons-arrow-up-alt2');
            textSpan.text('Hide Options');
        }
    });
    
    $(document).on('input change', '.sbs-option-name, .sbs-option-duration, .sbs-option-price, .sbs-option-group, .sbs-option-badge', function() {
        const optionId = $(this).data('option-id');
        const row = $('tr.sbs-option-row[data-option-id="' + optionId + '"]');
        row.find('.sbs-option-save-state').removeClass('is-saved').addClass('is-dirty').text('Unsaved');
    });

    function updateInlineOptionCount(serviceId) {
        const optionsRow = $('.sbs-options-row[data-service-id="' + serviceId + '"]');
        const count = optionsRow.find('tbody tr.sbs-option-row').length;
        const toggle = $('.sbs-toggle-options[data-service-id="' + serviceId + '"] .sbs-toggle-text');
        if (toggle.length && !optionsRow.is(':visible')) {
            toggle.text('Show Options (' + count + ')');
        }
        if (count === 0) {
            optionsRow.find('tbody').append('<tr class="sbs-options-empty"><td colspan="7" style="padding:16px 8px; color:#6b7280; text-align:center;">No options yet. Use Add Add-on or edit the service to add one.</td></tr>');
        }
    }

    // Save option name, price and duration
    $(document).on('click', '.sbs-save-option', function() {
        const btn = $(this);
        const optionId = btn.data('option-id');
        const nameInput = $('.sbs-option-name[data-option-id="' + optionId + '"]');
        const priceInput = $('.sbs-option-price[data-option-id="' + optionId + '"]');
        const groupSelect = $('.sbs-option-group[data-option-id="' + optionId + '"]');
        const badgeSelect = $('.sbs-option-badge[data-option-id="' + optionId + '"]');
        const durationInput = $('.sbs-option-duration[data-option-id="' + optionId + '"]');
        const newName = nameInput.val().trim();
        const newPrice = parseFloat(priceInput.val());
        const groupName = groupSelect.length ? groupSelect.val() : '';
        const badgeLabel = badgeSelect.length ? badgeSelect.val() : '';
        const newDuration = parseInt(durationInput.val()) || 0;
        
        if (!newName) {
            alert('Option name cannot be empty');
            return;
        }
        
        if (isNaN(newPrice) || newPrice < 0) {
            alert('Please enter a valid price');
            return;
        }

        if (newDuration < 1) {
            alert('Duration must be at least 1 minute');
            return;
        }
        
        btn.prop('disabled', true).text('Saving...');
        
        const basePrice = parseFloat(priceInput.data('base-price')) || 0;
        // Add-on options stack on top of whatever Main option is selected, so their
        // modifier must be the flat amount to add - not relative to the base price
        // (which is only correct for Main options that replace/modify the base once).
        const priceModifier = (groupName === 'Add-on') ? newPrice : (newPrice - basePrice);
        $.post(ajaxurl, {
            action: 'yatoon_update_option',
            nonce: '<?php echo esc_html( wp_create_nonce("yatoon_option") ); ?>',
            option_id: optionId,
            name: newName,
            price: newPrice,
            price_modifier: priceModifier,
            group_name: groupName,
            badge_label: badgeLabel,
            duration_minutes: newDuration
        }, function(resp) {
            btn.prop('disabled', false).text('Save');
            
            if (resp.success) {
                // Show success notification
                nameInput.css('border-color', '#10B981');
                priceInput.css('border-color', '#10B981');
                durationInput.css('border-color', '#10B981');
                $('tr.sbs-option-row[data-option-id="' + optionId + '"] .sbs-option-save-state').removeClass('is-dirty').addClass('is-saved').text('Saved');
                setTimeout(function() {
                    nameInput.css('border-color', '');
                    priceInput.css('border-color', '');
                    durationInput.css('border-color', '');
                }, 1500);
            } else {
                alert('Failed to save: ' + (resp.data || 'Unknown error'));
                nameInput.css('border-color', '#dc2626');
                priceInput.css('border-color', '#dc2626');
                durationInput.css('border-color', '#dc2626');
            }
        });
    });

    $(document).on('click', '.sbs-delete-option', function() {
        const btn = $(this);
        const optionId = btn.data('option-id');
        const row = btn.closest('tr.sbs-option-row');
        const serviceId = row.closest('.sbs-options-sortable').data('service-id');

        if (!confirm('Delete this option? This cannot be undone.')) {
            return;
        }

        btn.prop('disabled', true).text('Deleting...');
        $.post(ajaxurl, {
            action: 'yatoon_delete_option',
            nonce: '<?php echo esc_html( wp_create_nonce("yatoon_option") ); ?>',
            option_id: optionId
        }, function(resp) {
            if (resp.success) {
                row.fadeOut(160, function() {
                    $(this).remove();
                    updateInlineOptionCount(serviceId);
                });
            } else {
                btn.prop('disabled', false).text('Delete');
                alert('Failed to delete: ' + (resp.data || 'Unknown error'));
            }
        }).fail(function() {
            btn.prop('disabled', false).text('Delete');
            alert('Network error. Please try again.');
        });
    });
    
    // -- Edit Service Modal: Options Manager ---------------------------------
    var modalOptionsNonce = '<?php echo esc_attr( wp_create_nonce("yatoon_option") ); ?>';
    var yatoonAiDescNonce = '<?php echo esc_attr( wp_create_nonce("yatoon_ai_service_description") ); ?>';
    var modalOptionsServiceId = 0;
    var reusableOptionItems = [];

    function populateReusableOptionSelect(serviceId) {
        var select = $('#sbs-new-option-existing');
        select.empty().append($('<option>', {
            value: '',
            text: 'Manual - create a new option'
        }));
        var groups = {};
        reusableOptionItems.forEach(function(item) {
            if (parseInt(item.service_id, 10) === parseInt(serviceId, 10)) return;
            var groupLabel = item.group_label || 'Existing items';
            if (!groups[groupLabel]) {
                groups[groupLabel] = $('<optgroup>').attr('label', groupLabel);
                select.append(groups[groupLabel]);
            }
            groups[groupLabel].append($('<option>', {
                value: item.key,
                text: item.label + ' - ' + item.duration_minutes + ' min - $' + parseFloat(item.price || 0).toFixed(2)
            }));
        });
    }

    function loadReusableOptionItems(serviceId) {
        $.post(ajaxurl, {
            action: 'yatoon_get_addon_options',
            nonce: modalOptionsNonce
        }, function(resp) {
            if (resp.success) {
                reusableOptionItems = resp.data.items || [];
                populateReusableOptionSelect(serviceId);
            }
        });
    }

    $('#sbs-new-option-existing').on('change', function() {
        var key = String($(this).val() || '');
        var item = reusableOptionItems.find(function(candidate) {
            return String(candidate.key) === key;
        });
        $('#sbs-new-option-source-service, #sbs-new-option-source-option').val('');
        if (!item) {
            $('#sbs-new-option-link-note').text('Manual mode: enter a new name, duration, price, and type below.');
            return;
        }
        $('#sbs-new-option-name').val(item.name || '');
        $('#sbs-new-option-duration').val(parseInt(item.duration_minutes, 10) || 10);
        $('#sbs-new-option-price').val(parseFloat(item.price || 0).toFixed(2));
        $('#sbs-new-option-group').val('Add-on');
        if (item.source_type === 'service') {
            $('#sbs-new-option-source-service').val(item.source_id);
        } else {
            $('#sbs-new-option-source-option').val(item.source_id);
        }
        $('#sbs-new-option-link-note').text(
            item.shared_id
                ? 'Linked to shared ID: ' + item.shared_id + '. You may adjust the display name, duration, or price.'
                : 'This item has no shared ID yet. One will be created automatically when you add it.'
        );
    });

    // Add Service
    $('#sbs-add-service').on('click', function() {
        $('#sbs-modal-title').text('Add Service');
        $('#sbs-service-form')[0].reset();
        modalOptionsServiceId = 0;
        $('#sbs-modal-options-section').hide();
        $('#service-id').val('');
        $('#service-active').prop('checked', true);
        $('#service-require-policy').prop('checked', false);
        $('#service-require-consent').prop('checked', false);
        $('#service-allow-staff-select').prop('checked', true);
        $('#service-allow-design-upload').prop('checked', false);
        $('#service-is-featured').prop('checked', false);
        $('#service-buffer-before').val(0);
        $('#service-buffer-after').val(0);
        $('#service-lead-time').val(0);
        setCategoryField('');
        setServiceImage('');
        $('#yatoon-ai-desc-status').text("Uses this service's name, category, price, duration, and current description.");
        galleryImages = [];
        renderGalleryGrid();
        $('#sbs-service-modal').show();
    });

    $('#yatoon-ai-desc-btn').on('click', function() {
        const btn = $(this);
        const status = $('#yatoon-ai-desc-status');
        const serviceName = ($('#service-name').val() || '').trim();

        if (!serviceName) {
            status.text('Enter a service name first.');
            $('#service-name').focus();
            return;
        }

        btn.prop('disabled', true).text('Improving...');
        status.text('AI is writing a clearer customer-facing description...');

        $.post(ajaxurl, {
            action: 'yatoon_ai_service_description',
            nonce: yatoonAiDescNonce,
            service_name: serviceName,
            category: $('#service-category').val(),
            price: $('#service-price').val(),
            duration: $('#service-duration').val(),
            description: $('#service-description').val()
        }, function(resp) {
            if (resp && resp.success && resp.data && resp.data.description) {
                $('#service-description').val(resp.data.description);
                status.text('Description updated. Review it, then save the service.');
            } else {
                status.text((resp && resp.data && resp.data.message) ? resp.data.message : 'AI could not improve this description right now.');
            }
        }).fail(function() {
            status.text('AI request failed. Please try again.');
        }).always(function() {
            btn.prop('disabled', false).text('Improve with AI');
        });
    });
    
    // Edit Service
    $(document).on('click', '.sbs-edit-service', function() {
        const serviceId = $(this).data('id');
        
        $('#sbs-modal-title').text('Edit Service');
        $('#service-id').val(serviceId);
        
        $.post(ajaxurl, {
            action: 'yatoon_get_service',
            nonce: '<?php echo esc_html( wp_create_nonce("yatoon_service") ); ?>',
            service_id: serviceId
        }, function(resp) {
            if (resp.success) {
                const s = resp.data;
                $('#service-name').val(s.name);
                $('#service-description').val(s.description || '');
                $('#yatoon-ai-desc-status').text("Uses this service's name, category, price, duration, and current description.");
                $('#service-duration').val(s.duration_minutes);
                $('#service-price').val(s.price);
                setCategoryField(s.category || '');
                $('#service-active').prop('checked', s.is_active == 1);
                $('#service-require-policy').prop('checked', s.require_policy == 1);
                $('#service-require-consent').prop('checked', s.require_consent == 1);
                $('#service-allow-staff-select').prop('checked', s.allow_staff_select != 0);
                $('#service-allow-design-upload').prop('checked', s.allow_design_upload == 1);
                $('#service-is-featured').prop('checked', s.is_featured == 1);
                $('#service-buffer-before').val(s.buffer_before_min || 0);
                $('#service-buffer-after').val(s.buffer_after_min || 0);
                $('#service-lead-time').val(s.min_lead_time_min || 0);
                setServiceImage(s.image_url || '');
                loadGalleryImages(serviceId);
                $('#sbs-modal-options-section').show();
                loadModalOptions(serviceId);
                $('#sbs-service-modal').show();
            } else {
                alert('Failed to load service data');
            }
        });
    });
    
    // Save Service (Add or Update)
    $('#sbs-service-form').on('submit', function(e) {
        e.preventDefault();
        
        const submitBtn = $(this).find('button[type="submit"]');
        submitBtn.prop('disabled', true).text('Saving...');
        
        $.post(ajaxurl, {
            action: 'yatoon_save_service',
            nonce: '<?php echo esc_html( wp_create_nonce("yatoon_service") ); ?>',
            id: $('#service-id').val(),
            name: $('#service-name').val(),
            description: $('#service-description').val(),
            duration: $('#service-duration').val(),
            price: $('#service-price').val(),
            category: $('#service-category').val(),
            is_active: $('#service-active').is(':checked') ? 1 : 0,
            require_policy: $('#service-require-policy').is(':checked') ? 1 : 0,
            require_consent: $('#service-require-consent').is(':checked') ? 1 : 0,
            allow_staff_select: $('#service-allow-staff-select').is(':checked') ? 1 : 0,
            allow_design_upload: $('#service-allow-design-upload').is(':checked') ? 1 : 0,
            is_featured: $('#service-is-featured').is(':checked') ? 1 : 0,
            buffer_before_min: $('#service-buffer-before').val(),
            buffer_after_min: $('#service-buffer-after').val(),
            min_lead_time_min: $('#service-lead-time').val(),
            image_url: $('#service-image-url').val()
        }, function(resp) {
            if (resp.success) {
                // Save gallery images then reload
                const savedId = resp.data.service_id || parseInt($('#service-id').val()) || 0;
                if (savedId && galleryImages.length > 0) {
                    saveGalleryImages(savedId, function() { location.reload(); });
                } else if (savedId && galleryImages.length === 0 && parseInt($('#service-id').val()) > 0) {
                    // Editing existing - still save (may be clearing images)
                    saveGalleryImages(savedId, function() { location.reload(); });
                } else {
                    location.reload();
                }
            } else {
                alert('Failed: ' + (resp.data || 'Unknown error'));
                submitBtn.prop('disabled', false).text('Save Service');
            }
        });
    });
    
    function setServiceStatusButton(btn, isActive) {
        btn.data('active', isActive ? 1 : 0)
            .attr('data-active', isActive ? 1 : 0)
            .attr('aria-pressed', isActive ? 'true' : 'false')
            .toggleClass('is-active', !!isActive)
            .toggleClass('is-hidden', !isActive)
            .text(isActive ? 'Active' : 'Hidden');
    }

    // Toggle Service Active/Inactive
    $(document).on('click', '.sbs-status-toggle', function(e) {
        e.preventDefault();
        e.stopPropagation();
        const btn = $(this);
        if (btn.hasClass('is-saving')) { return; }
        const serviceId = btn.data('id');
        const previousActive = parseInt(btn.attr('data-active'), 10) === 1;
        const nextActive = !previousActive;
        setServiceStatusButton(btn, nextActive);
        btn.addClass('is-saving').prop('disabled', true);

        $.post(ajaxurl, {
            action: 'yatoon_toggle_service',
            nonce: '<?php echo esc_html( wp_create_nonce("yatoon_service") ); ?>',
            service_id: serviceId,
            is_active: nextActive ? 1 : 0
        }, function(resp) {
            btn.removeClass('is-saving').prop('disabled', false);
            if (!resp.success) {
                setServiceStatusButton(btn, previousActive);
                alert('Failed to update status');
                return;
            }
            btn.closest('tr.sbs-main-service-row').attr('data-status', nextActive ? 'active' : 'inactive').data('status', nextActive ? 'active' : 'inactive');
            applyServiceFilters();
        }).fail(function() {
            btn.removeClass('is-saving').prop('disabled', false);
            setServiceStatusButton(btn, previousActive);
            alert('Failed to update status');
        });
    });
    
    // Close modal when clicking outside
    $('#sbs-service-modal').on('click', function(e) {
        if (e.target === this) {
            $(this).hide();
        }
    });

    // Close modal via the X button or Cancel button
    $('.sbs-service-modal-close, .sbs-service-modal-cancel').on('click', function(e) {
        e.preventDefault();
        $('#sbs-service-modal').hide();
    });

    function loadModalOptions(serviceId) {
        modalOptionsServiceId = serviceId;
        loadReusableOptionItems(serviceId);
        $.post(ajaxurl, {
            action: 'yatoon_get_service_options',
            nonce: modalOptionsNonce,
            service_id: serviceId
        }, function(resp) {
            var $tbody = $('#sbs-modal-options-body');
            $tbody.empty();
            if (resp.success && resp.data.options && resp.data.options.length > 0) {
                var basePrice = parseFloat($('#service-price').val()) || 0;
                $.each(resp.data.options, function(i, opt) {
                    var groupName = opt.group_name ? opt.group_name : '';
                    // Add-on modifier is already the flat add-on amount; Main modifier
                    // is relative to the base service price.
                    var absPrice = (groupName === 'Add-on' ? parseFloat(opt.price_modifier) : (parseFloat(opt.price_modifier) + basePrice)).toFixed(2);
                    var safeName = String(opt.name || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#039;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                    var row = '' +
                        '<tr class="sbs-modal-option-row" data-option-id="' + opt.id + '" style="border-bottom:1px solid #f0f0f0;">' +
                        '<td style="padding:6px 8px;">' +
                            '<input type="text" class="sbs-modal-option-name" value="' + safeName + '" style="width:100%; min-width:170px; padding:6px 8px; border:1px solid #d1d5db; border-radius:6px;">' +
                        '</td>' +
                        '<td style="padding:6px 8px;">' +
                            '<input type="number" class="sbs-modal-option-duration" min="1" step="1" value="' + (parseInt(opt.duration_minutes, 10) || 10) + '" style="width:74px; padding:6px 8px; border:1px solid #d1d5db; border-radius:6px;">' +
                        '</td>' +
                        '<td style="padding:6px 8px;">' +
                            '<input type="number" class="sbs-modal-option-price" min="0" step="0.01" value="' + absPrice + '" style="width:86px; padding:6px 8px; border:1px solid #d1d5db; border-radius:6px;">' +
                        '</td>' +
                        '<td style="padding:6px 8px;">' +
                            '<select class="sbs-modal-option-group" style="width:120px; padding:6px 8px; border:1px solid #d1d5db; border-radius:6px;">' +
                                '<option value=""' + (groupName === '' ? ' selected' : '') + '>Main (single)</option>' +
                                '<option value="Add-on"' + (groupName === 'Add-on' ? ' selected' : '') + '>Add-on (multi)</option>' +
                            '</select>' +
                        '</td>' +
                        '<td style="padding:6px 8px; text-align:right; white-space:nowrap;">' +
                            '<button type="button" class="button button-small sbs-modal-save-option" data-option-id="' + opt.id + '">Save</button> ' +
                            '<button type="button" class="button button-small sbs-modal-delete-option" data-option-id="' + opt.id + '" style="color:#c00; border-color:#c00;">Delete</button>' +
                            '<div class="sbs-modal-option-state" style="font-size:11px; color:#6b7280; margin-top:4px; min-height:14px;"></div>' +
                        '</td></tr>';
                    $tbody.append(row);
                });
            } else {
                $tbody.append('<tr id="sbs-modal-options-empty"><td colspan="5" style="padding:10px 8px; color:#888; text-align:center;">No options yet.</td></tr>');
            }
        });
    }

    $(document).on('input change', '.sbs-modal-option-name, .sbs-modal-option-duration, .sbs-modal-option-price, .sbs-modal-option-group', function() {
        $(this).closest('tr.sbs-modal-option-row').find('.sbs-modal-option-state').css('color', '#b45309').text('Unsaved');
    });

    $(document).on('click', '.sbs-modal-save-option', function() {
        var btn = $(this);
        var row = btn.closest('tr.sbs-modal-option-row');
        var optionId = btn.data('option-id');
        var name = row.find('.sbs-modal-option-name').val().trim();
        var duration = parseInt(row.find('.sbs-modal-option-duration').val(), 10) || 0;
        var price = parseFloat(row.find('.sbs-modal-option-price').val());
        var group = row.find('.sbs-modal-option-group').val();
        var basePrice = parseFloat($('#service-price').val()) || 0;
        var state = row.find('.sbs-modal-option-state');

        if (!name) {
            state.css('color', '#c00').text('Name is required');
            return;
        }
        if (!duration || duration < 1) {
            state.css('color', '#c00').text('Duration is required');
            return;
        }
        if (isNaN(price) || price < 0) {
            state.css('color', '#c00').text('Price is required');
            return;
        }

        btn.prop('disabled', true).text('Saving...');
        state.css('color', '#6b7280').text('Saving');
        $.post(ajaxurl, {
            action: 'yatoon_update_option',
            nonce: modalOptionsNonce,
            option_id: optionId,
            name: name,
            duration_minutes: duration,
            price: price,
            price_modifier: (group === 'Add-on' ? price : (price - basePrice)).toFixed(2),
            group_name: group
        }, function(resp) {
            btn.prop('disabled', false).text('Save');
            if (resp.success) {
                state.css('color', '#047857').text('Saved');
                setTimeout(function(){ state.text(''); }, 1800);
            } else {
                state.css('color', '#c00').text(resp.data || 'Failed');
            }
        }).fail(function() {
            btn.prop('disabled', false).text('Save');
            state.css('color', '#c00').text('Failed');
        });
    });
    // Add new option from modal
    $('#sbs-modal-add-option-btn').on('click', function() {
        var name = $('#sbs-new-option-name').val().trim();
        var duration = parseInt($('#sbs-new-option-duration').val()) || 10;
        var price = parseFloat($('#sbs-new-option-price').val()) || 0;
        var group = $('#sbs-new-option-group').val();
        var basePrice = parseFloat($('#service-price').val()) || 0;
        var $msg = $('#sbs-modal-option-msg');

        if (!name) {
            $msg.text('Warning: Option name is required.').css('color','#c00').show();
            return;
        }
        if (!modalOptionsServiceId) {
            $msg.text('Warning: Please save the service first.').css('color','#c00').show();
            return;
        }

        var btn = $(this);
        btn.prop('disabled', true).text('Adding...');
        $msg.hide();

        $.post(ajaxurl, {
            action: 'yatoon_add_option',
            nonce: modalOptionsNonce,
            service_id: modalOptionsServiceId,
            name: name,
            duration_minutes: duration,
            price_modifier: (group === 'Add-on' ? price : (price - basePrice)).toFixed(2),
            group_name: group,
            square_id: '',
            source_service_id: parseInt($('#sbs-new-option-source-service').val(), 10) || 0,
            source_option_id: parseInt($('#sbs-new-option-source-option').val(), 10) || 0
        }, function(resp) {
            btn.prop('disabled', false).text('Add');
            if (resp.success) {
                $msg.text('Yes Option added!').css('color','green').show();
                $('#sbs-new-option-name').val('');
                $('#sbs-new-option-price').val('0');
                $('#sbs-new-option-existing').val('');
                $('#sbs-new-option-source-service, #sbs-new-option-source-option').val('');
                $('#sbs-new-option-link-note').text('Choose an existing service or option to reuse its shared ID, or enter a new option manually below.');
                loadModalOptions(modalOptionsServiceId);
                setTimeout(function(){ $msg.hide(); }, 2000);
            } else {
                $msg.text('Warning: ' + (resp.data || 'Failed')).css('color','#c00').show();
            }
        });
    });

    // Delete option from modal
    $(document).on('click', '.sbs-modal-delete-option', function() {
        var optionId = $(this).data('option-id');
        if (!confirm('Delete this option?')) return;
        var btn = $(this);
        btn.prop('disabled', true);
        $.post(ajaxurl, {
            action: 'yatoon_delete_option',
            nonce: modalOptionsNonce,
            option_id: optionId
        }, function(resp) {
            if (resp.success) {
                btn.closest('tr').fadeOut(200, function(){ $(this).remove(); });
            } else {
                btn.prop('disabled', false);
                alert('Failed: ' + (resp.data || 'Unknown error'));
            }
        });
    });


    var addonAllOptions = [];   // all option rows from server
    var addonTargetServiceId = 0;
    var addonNonce = '<?php echo esc_attr( wp_create_nonce("yatoon_option") ); ?>';

    // Open modal
    $(document).on('click', '.sbs-copy-addon-btn', function() {
        addonTargetServiceId = parseInt($(this).data('service-id'));
        var svcName = $(this).data('service-name');
        $('#sbs-addon-target-name').text(svcName);
        $('#sbs-addon-msg').text('');
        $('#sbs-addon-confirm').prop('disabled', true);
        $('#sbs-addon-option-preview').hide();
        $('#sbs-addon-options-list').hide();
        $('#sbs-addon-source-empty').hide();
        $('#sbs-addon-name').val('');
        $('#sbs-addon-duration').val('');
        $('#sbs-addon-price').val('');
        $('#sbs-addon-sq-id-display').text('(optional; copied when available)');

        // Load all options if not yet loaded
        if (addonAllOptions.length === 0) {
            $.post(ajaxurl, { action: 'yatoon_get_addon_options', nonce: addonNonce }, function(resp) {
                if (resp.success) {
                    addonAllOptions = resp.data.options;
                    populateAddonServiceSelect();
                }
            });
        } else {
            populateAddonServiceSelect();
        }
        $('#sbs-copy-addon-modal').show();
    });

    function populateAddonServiceSelect() {
        var $sel = $('#sbs-addon-source-service');
        $sel.empty().append('<option value="">-- Select source service --</option>');
        // Group by service
        var seen = {};
        var count = 0;
        addonAllOptions.forEach(function(o) {
            if (!seen[o.service_id]) {
                seen[o.service_id] = true;
                // Don't show the target service itself
                if (o.service_id != addonTargetServiceId) {
                    $sel.append('<option value="' + o.service_id + '">' + o.service_name + '</option>');
                    count++;
                }
            }
        });
        $('#sbs-addon-source-empty').toggle(count === 0);
        validateAddonManualFields();
    }

    function validateAddonManualFields() {
        var name = $('#sbs-addon-name').val().trim();
        var duration = parseInt($('#sbs-addon-duration').val(), 10);
        var priceRaw = $('#sbs-addon-price').val();
        var price = parseFloat(priceRaw);
        var valid = !!name && duration > 0 && priceRaw !== '' && !isNaN(price) && price >= 0;
        $('#sbs-addon-confirm').prop('disabled', !valid);
        return valid;
    }

    $('#sbs-addon-name, #sbs-addon-duration, #sbs-addon-price').on('input', validateAddonManualFields);

    // When source service changes, populate option list
    $('#sbs-addon-source-service').on('change', function() {
        var svcId = parseInt($(this).val());
        var $optSel = $('#sbs-addon-source-option');
        $optSel.empty().append('<option value="">-- Select option --</option>');
        $('#sbs-addon-option-preview').hide();
        validateAddonManualFields();
        if (!svcId) { $('#sbs-addon-options-list').hide(); return; }

        addonAllOptions.forEach(function(o) {
            if (o.service_id == svcId) {
                $optSel.append('<option value="' + o.option_id + '">' + o.option_name + ' (' + o.duration_minutes + 'min, $' + parseFloat(o.price_modifier >= 0 ? o.price_modifier : 0).toFixed(2) + ')</option>');
            }
        });
        $('#sbs-addon-options-list').show();
    });

    // When option selected, fill preview fields
    $('#sbs-addon-source-option').on('change', function() {
        var optId = parseInt($(this).val());
        if (!optId) { $('#sbs-addon-option-preview').hide(); validateAddonManualFields(); return; }
        var opt = addonAllOptions.find(function(o){ return o.option_id == optId; });
        if (!opt) return;
        $('#sbs-addon-name').val(opt.option_name);
        $('#sbs-addon-duration').val(opt.duration_minutes);
        $('#sbs-addon-price').val(parseFloat(opt.price_modifier >= 0 ? opt.price_modifier : 0).toFixed(2));
        $('#sbs-addon-sq-id-display').text(opt.square_id || '(no Square ID)');
        var preview = 'Source: ' + opt.service_name + ' -> ' + opt.option_name;
        if (opt.square_id) preview += ' | Square ID: ' + opt.square_id;
        $('#sbs-addon-option-preview').text(preview).show();
        validateAddonManualFields();
        if (!opt.square_id) {
            $('#sbs-addon-msg').text('This option has no Square ID, so it will be added as a local Add-on.').css('color','#666');
        } else {
            $('#sbs-addon-msg').text('').css('color','');
        }
    });

    // Confirm add
    $('#sbs-addon-confirm').on('click', function() {
        var optId = parseInt($('#sbs-addon-source-option').val());
        var opt = addonAllOptions.find(function(o){ return o.option_id == optId; });

        var name     = $('#sbs-addon-name').val().trim() || (opt ? opt.option_name : '');
        var duration = parseInt($('#sbs-addon-duration').val()) || (opt ? opt.duration_minutes : 0);
        var price    = parseFloat($('#sbs-addon-price').val()) || 0;

        if (!name || duration <= 0 || price < 0) {
            $('#sbs-addon-msg').text('Enter an Add-on name, duration, and price.').css('color','#c00');
            validateAddonManualFields();
            return;
        }

        $(this).prop('disabled', true).text('Adding...');
        $('#sbs-addon-msg').text('').css('color','');

        $.post(ajaxurl, {
            action:           'yatoon_add_option',
            nonce:            addonNonce,
            service_id:       addonTargetServiceId,
            name:             name,
            duration_minutes: duration,
            price_modifier:   price,
            group_name:       'Add-on',
            square_id:        opt && opt.square_id ? opt.square_id : '',
            square_version:   opt && opt.square_version ? opt.square_version : '',
        }, function(resp) {
            if (resp.success) {
                $('#sbs-addon-msg').text('Added successfully. Refreshing...').css('color','green');
                // Reload after 1.2s
                setTimeout(function(){ location.reload(); }, 1200);
            } else {
                $('#sbs-addon-msg').text(resp.data || 'Failed to add').css('color','#c00');
                $('#sbs-addon-confirm').prop('disabled', false).text('Add');
            }
        });
    });

    // Close modal
    $('#sbs-addon-cancel').on('click', function() {
        $('#sbs-copy-addon-modal').hide();
    });
    $(document).on('click', '#sbs-copy-addon-modal', function(e) {
        if ($(e.target).is('#sbs-copy-addon-modal')) $('#sbs-copy-addon-modal').hide();
    });


    // -- Option row drag-sort ------------------------------------------------
    function initOptionSortable($tbody) {
        $tbody.sortable({
            handle: '.sbs-option-drag-handle',
            axis: 'y',
            items: 'tr',
            placeholder: 'ui-state-highlight',
            tolerance: 'pointer',
            stop: function(e, ui) {
                var serviceId = $tbody.data('service-id');
                var order = [];
                $tbody.find('tr[data-option-id]').each(function(i) {
                    order.push(parseInt($(this).data('option-id')));
                });
                $.post(ajaxurl, {
                    action: 'yatoon_reorder_options',
                    nonce:      '<?php echo esc_html( wp_create_nonce("yatoon_option") ); ?>',
                    service_id: serviceId,
                    order:      JSON.stringify(order),
                }, function(resp) {
                    if (!resp.success) alert('Failed to save order: ' + (resp.data || ''));
                });
            }
        });
    }

    // Init all visible option sortables
    $('.sbs-options-sortable').each(function() { initOptionSortable($(this)); });

    // Also init when options are shown (toggle)
    $(document).on('click', '.sbs-toggle-options', function() {
        var serviceId = $(this).data('service-id');
        setTimeout(function() {
            var $tbody = $('.sbs-options-sortable[data-service-id="' + serviceId + '"]');
            if ($tbody.length && !$tbody.hasClass('ui-sortable')) {
                initOptionSortable($tbody);
            }
        }, 100);
    });

});
</script>
