<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL -- Templates are stored in a plugin-owned custom table.
/**
 * Templates Tab Content
 *
 * Manage email templates and layouts
 */

if (!defined('ABSPATH')) exit; // Exit if accessed directly

// Handle form submissions
if (isset($_POST['submit_template_settings'])) {
    // Handle template settings form submission
    if (isset($_POST['template_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['template_nonce'])), 'save_template_settings')) {
        // Save template settings logic here
        echo '<div class="notice notice-success"><p>Template settings saved successfully!</p></div>';
    }
}

// Handle create/edit template submissions
if (isset($_POST['submit_template'])) {
    if (isset($_POST['template_create_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['template_create_nonce'])), 'create_template_action')) {
        // Handle template creation/editing logic here
        $instant_popup_builder_template_name = isset($_POST['template_name']) ? sanitize_text_field(wp_unslash($_POST['template_name'])) : '';
        $instant_popup_builder_template_description = isset($_POST['template_description']) ? sanitize_textarea_field(wp_unslash($_POST['template_description'])) : '';
        $instant_popup_builder_template_category = isset($_POST['template_category']) ? sanitize_text_field(wp_unslash($_POST['template_category'])) : '';
        $instant_popup_builder_template_content = isset($_POST['template_content']) ? sanitize_textarea_field(wp_unslash($_POST['template_content'])) : '';

        // Collect all template data
        $instant_popup_builder_template_data = [
            'template_width' => sanitize_text_field(wp_unslash($_POST['template_width'] ?? '')),
            'button_color' => sanitize_hex_color(wp_unslash($_POST['button_color'] ?? '')),
            'font_family' => sanitize_text_field(wp_unslash($_POST['font_family'] ?? '')),
            'font_size' => sanitize_text_field(wp_unslash($_POST['font_size'] ?? '')),
        ];

        global $wpdb;
        $instant_popup_builder_templates_table = $wpdb->prefix . 'instant_popup_templates';
        $instant_popup_builder_template_id = isset($_POST['template_id']) ? intval($_POST['template_id']) : 0;
        $instant_popup_builder_current_user_id = get_current_user_id();

        if ($instant_popup_builder_template_id > 0) {
            // Update existing template
            $instant_popup_builder_result = $wpdb->update(
                $instant_popup_builder_templates_table,
                [
                    'name' => $instant_popup_builder_template_name,
                    'description' => $instant_popup_builder_template_description,
                    'category' => $instant_popup_builder_template_category,
                    'content' => $instant_popup_builder_template_content,
                    'template_data' => json_encode($instant_popup_builder_template_data),
                    'updated_at' => current_time('mysql')
                ],
                ['id' => $instant_popup_builder_template_id],
                ['%s', '%s', '%s', '%s', '%s', '%s'],
                ['%d']
            );

            if ($instant_popup_builder_result !== false) {
                echo '<div class="notice notice-success"><p>Template "' . esc_html($instant_popup_builder_template_name) . '" updated successfully!</p></div>';
            } else {
                echo '<div class="notice notice-error"><p>Failed to update template. Please try again.</p></div>';
            }
        } else {
            // Create new template
            $instant_popup_builder_result = $wpdb->insert(
                $instant_popup_builder_templates_table,
                [
                    'name' => $instant_popup_builder_template_name,
                    'description' => $instant_popup_builder_template_description,
                    'category' => $instant_popup_builder_template_category,
                    'content' => $instant_popup_builder_template_content,
                    'template_data' => json_encode($instant_popup_builder_template_data),
                    'created_by' => $instant_popup_builder_current_user_id,
                    'status' => 'active'
                ],
                ['%s', '%s', '%s', '%s', '%s', '%d', '%s']
            );

            if ($instant_popup_builder_result) {
                echo '<div class="notice notice-success"><p>Template "' . esc_html($instant_popup_builder_template_name) . '" created successfully!</p></div>';
            } else {
                echo '<div class="notice notice-error"><p>Failed to create template. Please try again.</p></div>';
            }
        }
    }
}

// Ensure templates table exists
global $wpdb;
$instant_popup_builder_templates_table = $wpdb->prefix . 'instant_popup_templates';
$instant_popup_builder_escaped_templates_table = esc_sql($instant_popup_builder_templates_table);
$instant_popup_builder_escaped_users_table = esc_sql($wpdb->users);
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$instant_popup_builder_templates_query = $wpdb->prepare("
    SELECT t.*, u.display_name as created_by_name
    FROM `{$instant_popup_builder_escaped_templates_table}` t
    LEFT JOIN `{$instant_popup_builder_escaped_users_table}` u ON t.created_by = u.ID
    WHERE t.status = %s
    ORDER BY t.created_at DESC
", 'active');

// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query is prepared immediately above with a fixed placeholder.
$instant_popup_builder_templates_results = $wpdb->get_results($instant_popup_builder_templates_query, ARRAY_A);
$instant_popup_builder_templates = [];

if ($instant_popup_builder_templates_results) {
    foreach ($instant_popup_builder_templates_results as $instant_popup_builder_template) {
        $instant_popup_builder_templates[] = [
            'id' => $instant_popup_builder_template['id'],
            'name' => $instant_popup_builder_template['name'],
            'category' => ucfirst($instant_popup_builder_template['category']),
            'created_by' => $instant_popup_builder_template['created_by_name'] ?: 'Unknown',
            'date_created' => gmdate('Y-m-d', strtotime($instant_popup_builder_template['created_at']))
        ];
    }
}

// Available categories
$instant_popup_builder_categories = [
    'invoice' => 'Invoice',
    'email' => 'Email',
    'marketing' => 'Marketing',
    'newsletter' => 'Newsletter',
    'welcome' => 'Welcome',
    'promotional' => 'Promotional'
];
?>

<div class="templates-tab-content">
    <!-- Header with Create New Button -->
    <div class="templates-header">
        <div class="templates-title">
            <h3>Email Templates</h3>
            <p>Manage your email templates for subscription confirmations, newsletters, and automated responses.</p>
        </div>
        <div class="templates-actions">
            <button type="button" class="hover-button button button-primary" id="create-new-template">
                <span>
                <span class="dashicons dashicons-plus-alt" style="margin-top: 6px;"></span>
                Create New</span>
            </button>
        </div>
    </div>

    <!-- Templates Table -->
    <div class="templates-table-container">
        <table class="wp-list-table widefat fixed striped templates-table">
            <thead>
                <tr>
                    <th scope="col" class="column-id">ID</th>
                    <th scope="col" class="column-name">Template Name</th>
                    <th scope="col" class="column-category">Category</th>
                    <th scope="col" class="column-created-by">Created By</th>
                    <th scope="col" class="column-date">Date Created</th>
                    <th scope="col" class="column-actions">Actions</th>
                </tr>
            </thead>
            <tbody>

                    <tr>
                        <td colspan="6" class="no-templates">
                            <div class="no-templates-message">
                                <span class="dashicons dashicons-lock"></span>
                                <h4 style="margin: 15px 0 10px 32px;">Upgrade to Pro</h4>
                            </div>
                        </td>
                    </tr>
            </tbody>
        </table>
    </div>

</div>

<!-- Create/Edit Template Modal -->
<div id="template-modal" class="template-modal" style="display: none;">
    <div class="template-modal-backdrop"></div>
    <div class="template-modal-content">
        <div class="template-modal-header">
            <h2 id="template-modal-title">Create New Template</h2>
            <button type="button" class="template-modal-close">&times;</button>
        </div>

        <div class="template-modal-body">
            <form id="template-form" method="post" action="" enctype="multipart/form-data">
                <?php wp_nonce_field('create_template_action', 'template_create_nonce'); ?>
                <input type="hidden" id="template_id" name="template_id" value="">

                <div class="template-form-container">
                    <!-- Main Content Area -->
                    <div class="template-main-content">
                        <!-- Template Information Section -->
                        <div class="template-info-section">
                            <div class="template-header-row">
                                <div class="template-name-group">
                                    <label for="template_name">Template Name</label>
                                    <input type="text" id="template_name" name="template_name" class="form-control" required placeholder="Enter template name">
                                </div>

                                <div class="template-category-group">
                                    <label for="template_category">Category</label>
                                    <div class="category-management">
                                        <div class="category-select-wrapper">
                                            <select id="template_category" name="template_category" class="form-control">
                                                <?php foreach ($instant_popup_builder_categories as $instant_popup_builder_key => $instant_popup_builder_label): ?>
                                                    <option value="<?php echo esc_attr($instant_popup_builder_key); ?>"><?php echo esc_html($instant_popup_builder_label); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="category-actions">
                                            <button type="button" class="button button-small" id="add-category" title="Add New Category">
                                                <span class="dashicons dashicons-plus-alt"></span>
                                            </button>
                                            <button type="button" class="button button-small" id="edit-category" title="Edit Category">
                                                <span class="dashicons dashicons-edit"></span>
                                            </button>
                                            <button type="button" class="button button-small button-link-delete" id="delete-category" title="Delete Category">
                                                <span class="dashicons dashicons-trash"></span>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Category Management Modal -->
                        <div id="category-modal" class="category-modal" style="display: none;">
                            <div class="category-modal-backdrop"></div>
                            <div class="category-modal-content">
                                <div class="category-modal-header">
                                    <h3 id="category-modal-title">Add New Category</h3>
                                    <button type="button" class="category-modal-close">&times;</button>
                                </div>
                                <div class="category-modal-body">
                                    <form id="category-form">
                                        <input type="hidden" id="category_action" value="add">
                                        <input type="hidden" id="category_original_key" value="">

                                        <div class="form-group">
                                            <label for="category_name">Category Name</label>
                                            <input type="text" id="category_name" name="category_name" class="form-control" required placeholder="Enter category name">
                                        </div>

                                        <div class="form-group">
                                            <label for="category_key">Category Key</label>
                                            <input type="text" id="category_key" name="category_key" class="form-control" required placeholder="category_key" pattern="[a-z0-9_]+" title="Only lowercase letters, numbers, and underscores allowed">
                                            <p class="description">Used internally. Only lowercase letters, numbers, and underscores.</p>
                                        </div>
                                    </form>
                                </div>
                                <div class="category-modal-footer">
                                    <button type="button" class="button button-secondary" id="cancel-category">Cancel</button>
                                    <button type="button" class="button button-primary" id="save-category">Save Category</button>
                                </div>
                            </div>
                        </div>
                        <div class="content-builder-section">
                            <div class="builder-header">
                                <label>Content Builder</label>
                                <div class="builder-controls">
                                    <button type="button" class="button button-secondary" id="live-preview-btn" title="Toggle Live Preview">
                                        <span class="dashicons dashicons-visibility"></span>
                                        Live Preview
                                    </button>
                                    <button type="button" class="button button-secondary" id="insert-template-tag-btn" title="Insert Template Tag">
                                        <span class="dashicons dashicons-tag"></span>
                                        Insert Template Tag
                                    </button>
                                    <div class="editor-mode-toggle">
                                        <button type="button" class="mode-btn active" data-mode="visual" title="Visual Editor">
                                            <span class="dashicons dashicons-visibility"></span>
                                            Visual
                                        </button>
                                        <button type="button" class="mode-btn" data-mode="html" title="HTML Editor">
                                            <span class="dashicons dashicons-editor-code"></span>
                                            HTML
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- Template Tags Modal -->
                            <div id="template-tags-modal" class="template-tags-modal" style="display: none;">
                                <div class="template-tags-modal-backdrop"></div>
                                <div class="template-tags-modal-content">
                                    <div class="template-tags-modal-header">
                                        <h3>Insert Template Tag</h3>
                                        <button type="button" class="template-tags-modal-close">&times;</button>
                                    </div>
                                    <div class="template-tags-modal-body">
                                        <div class="tags-search">
                                            <input type="text" id="tags-search-input" placeholder="Search tags..." class="form-control">
                                        </div>
                                        <div class="tags-list">
                                            <div class="tag-group">
                                                <h4>Subscriber Information</h4>
                                                <div class="tag-items">
                                                    <div class="tag-item" data-tag="{subscriber_name}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{subscriber_name}</span>
                                                            <span class="tag-description">Subscriber's name</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                    <div class="tag-item" data-tag="{subscriber_email}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{subscriber_email}</span>
                                                            <span class="tag-description">Subscriber's email address</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                    <div class="tag-item" data-tag="{subscription_date}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{subscription_date}</span>
                                                            <span class="tag-description">Date of subscription</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="tag-group">
                                                <h4>Campaign & Content</h4>
                                                <div class="tag-items">
                                                    <div class="tag-item" data-tag="{campaign_name}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{campaign_name}</span>
                                                            <span class="tag-description">Campaign name</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                    <div class="tag-item" data-tag="{popup_title}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{popup_title}</span>
                                                            <span class="tag-description">Popup title</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                    <div class="tag-item" data-tag="{coupon_code}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{coupon_code}</span>
                                                            <span class="tag-description">Coupon code</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="tag-group">
                                                <h4>Site Information</h4>
                                                <div class="tag-items">
                                                    <div class="tag-item" data-tag="{site_name}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{site_name}</span>
                                                            <span class="tag-description">Site name</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                    <div class="tag-item" data-tag="{site_url}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{site_url}</span>
                                                            <span class="tag-description">Site URL</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="tag-group">
                                                <h4>Action Links</h4>
                                                <div class="tag-items">
                                                    <div class="tag-item" data-tag="{unsubscribe_link}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{unsubscribe_link}</span>
                                                            <span class="tag-description">Unsubscribe link</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                    <div class="tag-item" data-tag="{verification_link}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{verification_link}</span>
                                                            <span class="tag-description">Email verification link</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="tag-group">
                                                <h4>Custom Fields</h4>
                                                <div class="tag-items">
                                                    <div class="tag-item" data-tag="{custom_field_1}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{custom_field_1}</span>
                                                            <span class="tag-description">Custom field 1</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                    <div class="tag-item" data-tag="{custom_field_2}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{custom_field_2}</span>
                                                            <span class="tag-description">Custom field 2</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                    <div class="tag-item" data-tag="{custom_field_3}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{custom_field_3}</span>
                                                            <span class="tag-description">Custom field 3</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                    <div class="tag-item" data-tag="{custom_field_4}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{custom_field_4}</span>
                                                            <span class="tag-description">Custom field 4</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                    <div class="tag-item" data-tag="{custom_field_5}">
                                                        <div class="tag-info">
                                                            <span class="tag-name">{custom_field_5}</span>
                                                            <span class="tag-description">Custom field 5</span>
                                                        </div>
                                                        <button type="button" class="button button-small insert-tag-btn">Insert</button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="tags-usage-info">
                                            <p><strong>Tip:</strong> You can add fallback values using the format <code>{tag_name|fallback_value}</code></p>
                                            <p><strong>Example:</strong> <code>{subscriber_name|Valued Customer}</code></p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Visual Editor -->
                            <div class="visual-editor-container" id="visual-editor-container">
                                <div class="visual-editor-toolbar">
                                    <div class="toolbar-group">
                                        <select class="editor-control" id="font-family">
                                            <option value="Arial, sans-serif">Arial</option>
                                            <option value="Georgia, serif">Georgia</option>
                                            <option value="'Times New Roman', serif">Times New Roman</option>
                                            <option value="Verdana, sans-serif">Verdana</option>
                                            <option value="Helvetica, sans-serif">Helvetica</option>
                                            <option value="'Courier New', monospace">Courier New</option>
                                        </select>
                                        <select class="editor-control" id="font-size">
                                            <option value="12px">12px</option>
                                            <option value="14px" selected>14px</option>
                                            <option value="16px">16px</option>
                                            <option value="18px">18px</option>
                                            <option value="20px">20px</option>
                                            <option value="24px">24px</option>
                                            <option value="28px">28px</option>
                                            <option value="32px">32px</option>
                                        </select>
                                    </div>

                                    <div class="toolbar-group">
                                        <button type="button" class="editor-btn" data-action="bold" title="Bold">
                                            <span class="dashicons dashicons-editor-bold"></span>
                                        </button>
                                        <button type="button" class="editor-btn" data-action="italic" title="Italic">
                                            <span class="dashicons dashicons-editor-italic"></span>
                                        </button>
                                        <button type="button" class="editor-btn" data-action="underline" title="Underline">
                                            <span class="dashicons dashicons-editor-underline"></span>
                                        </button>
                                        <button type="button" class="editor-btn" data-action="strikethrough" title="Strikethrough">
                                            <span class="dashicons dashicons-editor-strikethrough"></span>
                                        </button>
                                    </div>

                                    <div class="toolbar-group">
                                        <input type="color" class="color-picker" id="text-color" title="Text Color" value="#000000">
                                        <input type="color" class="color-picker" id="bg-color" title="Background Color" value="#ffffff">
                                    </div>

                                    <div class="toolbar-group">
                                        <button type="button" class="editor-btn" data-action="justifyLeft" title="Align Left">
                                            <span class="dashicons dashicons-editor-alignleft"></span>
                                        </button>
                                        <button type="button" class="editor-btn" data-action="justifyCenter" title="Align Center">
                                            <span class="dashicons dashicons-editor-aligncenter"></span>
                                        </button>
                                        <button type="button" class="editor-btn" data-action="justifyRight" title="Align Right">
                                            <span class="dashicons dashicons-editor-alignright"></span>
                                        </button>
                                        <button type="button" class="editor-btn" data-action="justifyFull" title="Justify">
                                            <span class="dashicons dashicons-editor-justify"></span>
                                        </button>
                                    </div>

                                    <div class="toolbar-group">
                                        <button type="button" class="editor-btn" data-action="insertUnorderedList" title="Bullet List">
                                            <span class="dashicons dashicons-editor-ul"></span>
                                        </button>
                                        <button type="button" class="editor-btn" data-action="insertOrderedList" title="Numbered List">
                                            <span class="dashicons dashicons-editor-ol"></span>
                                        </button>
                                        <button type="button" class="editor-btn" data-action="indent" title="Indent">
                                            <span class="dashicons dashicons-editor-indent"></span>
                                        </button>
                                        <button type="button" class="editor-btn" data-action="outdent" title="Outdent">
                                            <span class="dashicons dashicons-editor-outdent"></span>
                                        </button>
                                    </div>

                                    <div class="toolbar-group">
                                        <button type="button" class="editor-btn" data-action="createLink" title="Insert Link">
                                            <span class="dashicons dashicons-admin-links"></span>
                                        </button>
                                        <button type="button" class="editor-btn" data-action="unlink" title="Remove Link">
                                            <span class="dashicons dashicons-editor-unlink"></span>
                                        </button>
                                        <button type="button" class="editor-btn" id="insert-image-btn" title="Insert Image">
                                            <span class="dashicons dashicons-format-image"></span>
                                        </button>
                                    </div>

                                    <div class="toolbar-group">
                                        <button type="button" class="editor-btn" data-action="removeFormat" title="Clear Formatting">
                                            <span class="dashicons dashicons-editor-removeformatting"></span>
                                        </button>
                                        <button type="button" class="editor-btn" data-action="undo" title="Undo">
                                            <span class="dashicons dashicons-undo"></span>
                                        </button>
                                        <button type="button" class="editor-btn" data-action="redo" title="Redo">
                                            <span class="dashicons dashicons-redo"></span>
                                        </button>
                                    </div>
                                </div>

                                <div class="visual-editor-content">
                                    <div id="visual-editor" contenteditable="true" class="editor-content" placeholder="Start typing your content here..."></div>
                                </div>
                            </div>

                            <!-- HTML Editor -->
                            <div class="html-editor-container" id="html-editor-container" style="display: none;">
                                <div class="html-editor-toolbar">
                                    <span class="toolbar-label">HTML Editor</span>
                                    <div class="html-actions">
                                        <button type="button" class="button button-small" id="format-html-btn" title="Format HTML">
                                            <span class="dashicons dashicons-editor-code"></span>
                                            Format
                                        </button>
                                        <button type="button" class="button button-small" id="validate-html-btn" title="Validate HTML">
                                            <span class="dashicons dashicons-yes-alt"></span>
                                            Validate
                                        </button>
                                    </div>
                                </div>
                                <div class="html-editor-content">
                                    <textarea id="html-editor" name="template_content" class="form-control html-textarea" rows="12" placeholder="Enter your HTML content here..."></textarea>
                                </div>
                            </div>

                            <!-- Live Preview -->
                            <div class="live-preview-section" id="live-preview-section" style="display: none;">
                                <div class="preview-header">
                                    <h4>
                                        <span class="dashicons dashicons-visibility"></span>
                                        Live Preview
                                    </h4>
                                    <button type="button" class="button button-small" id="refresh-preview-btn" title="Refresh Preview">
                                        <span class="dashicons dashicons-update"></span>
                                        Refresh
                                    </button>
                                </div>
                                <div class="preview-content">
                                    <div id="content-preview" class="preview-area"></div>
                                </div>
                            </div>
                        </div>









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

        <div class="template-modal-footer">
            <button type="button" class="button button-secondary" id="cancel-template">Cancel</button>
            <button type="button" class="button button-primary" id="save-template">Save</button>
        </div>
    </div>
</div>

<style>
/* Templates Tab Styles */
.templates-tab-content {
    max-width: 100%;
}

.templates-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 25px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e1e1e1;
}

.templates-title h3 {
    margin: 0 0 5px 0;
    font-size: 18px;
    font-weight: 600;
}

.templates-title p {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.templates-actions {
    flex-shrink: 0;
}

#create-new-template {
    display: flex;
    align-items: center;
    gap: 5px;
}

#create-new-template .dashicons {
    font-size: 16px;
    width: 16px;
    height: 16px;
}

/* Templates Table */
.templates-table-container {
    margin-bottom: 30px;
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    overflow: hidden;
}

.templates-table {
    border: none;
    border-radius: 4px;
    width: 100%;
    table-layout: fixed;
}

.templates-table th {
    background: #f8f9fa;
    font-weight: 600;
    color: #23282d;
    border-bottom: 1px solid #e1e1e1;
}

.templates-table td {
    vertical-align: middle;
    word-wrap: break-word;
    overflow: hidden;
}

.templates-table .column-name {
    text-overflow: ellipsis;
    white-space: nowrap;
}

.templates-table .column-created-by,
.templates-table .column-date {
    text-overflow: ellipsis;
    white-space: nowrap;
}

.column-id {
    width: 50px;
}

.column-name {
    width: 30%;
}

.column-category {
    width: 15%;
}

.column-created-by {
    width: 15%;
}

.column-date {
    width: 15%;
}

.column-actions {
    width: 25%;
}

/* Category Badges */
.category-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.category-marketing {
    background: #e3f2fd;
    color: #1976d2;
}

.category-voice {
    background: #f3e5f5;
    color: #7b1fa2;
}

.category-newsletter {
    background: #e8f5e8;
    color: #388e3c;
}

.category-invoice {
    background: #fff3e0;
    color: #f57c00;
}

.category-email {
    background: #e8eaf6;
    color: #3f51b5;
}

.category-welcome {
    background: #fce4ec;
    color: #e91e63;
}

.category-promotional {
    background: #e0f2f1;
    color: #00796b;
}

/* Template Actions */
.template-actions {
    display: flex;
    gap: 5px;
}

.template-actions .button {
    font-size: 12px;
    padding: 4px 8px;
    line-height: 1.4;
}

/* No Templates Message */
.no-templates {
    text-align: center;
    padding: 40px 20px;
}

.no-templates-message {
    color: #666;
}

.no-templates-message .dashicons {
    font-size: 48px;
    color: #ccc;
    margin-bottom: 15px;
}

.no-templates-message h4 {
    margin: 0 0 10px 0;
    font-size: 16px;
    color: #555;
}

.no-templates-message p {
    margin: 0;
    font-size: 14px;
}

/* Settings Section */
.templates-settings-section {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
}

.templates-settings-section h3 {
    margin-top: 0;
    margin-bottom: 15px;
    font-size: 16px;
    font-weight: 600;
    color: #23282d;
}

/* Template Modal Styles */
.template-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100000;
    display: flex;
    align-items: center;
    justify-content: center;
}

.template-modal-backdrop {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    z-index: 1;
}

.template-modal-content {
    position: relative;
    background: #fff;
    border-radius: 8px;
    width: 90%;
    max-width: 1200px;
    max-height: 90vh;
    overflow: hidden;
    z-index: 2;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.template-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 25px;
    border-bottom: 1px solid #e1e1e1;
    background: #f8f9fa;
}

.template-modal-header h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #23282d;
}

.template-modal-close {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #666;
    padding: 0;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.2s ease;
}

.template-modal-close:hover {
    background: #e1e1e1;
    color: #333;
}

.template-modal-body {
    padding: 0;
    max-height: calc(90vh - 140px);
    overflow-y: auto;
}

.template-form-container {
    min-height: 500px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: 500;
    color: #23282d;
    font-size: 14px;
}

.form-control {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    transition: border-color 0.2s ease;
}

.form-control:focus {
    outline: none;
    border-color: #0073aa;
    box-shadow: 0 0 0 1px #0073aa;
}

/* Category Dropdown */
.category-dropdown {
    position: relative;
}

.category-options {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: #fff;
    border: 1px solid #ddd;
    border-top: none;
    border-radius: 0 0 4px 4px;
    z-index: 10;
    max-height: 200px;
    overflow-y: auto;
}

.category-option {
    padding: 10px 12px;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: background-color 0.2s ease;
}

.category-option:hover {
    background: #f8f9fa;
}

.category-icon {
    display: flex;
    gap: 5px;
}

.category-icon i {
    font-size: 12px;
    cursor: pointer;
    padding: 2px;
    border-radius: 2px;
    transition: background-color 0.2s ease;
}

.category-icon i:hover {
    background: #e1e1e1;
}

/* Main Content Area */
.template-main-content {
    padding: 25px;
    width: 100%;
}

/* Template Information Section */
.template-info-section {
    background: #f8f9fa;
    border: 1px solid #e1e1e1;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 25px;
}

/* Template Header Row */
.template-header-row {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
}

.template-name-group {
    flex: 2;
}

.template-category-group {
    flex: 1;
    min-width: 200px;
}

.template-description-group {
    flex: 3;
}

.template-name-group label,
.template-description-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: 500;
    color: #23282d;
    font-size: 14px;
}

/* Template Category Section */
.template-category-section {
    margin-bottom: 0;
}

.template-category-section > label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #23282d;
    font-size: 14px;
}

.category-management {
    display: flex;
    align-items: center;
    gap: 10px;
}

.category-select-wrapper {
    flex: 1;
    max-width: 300px;
}

.category-actions {
    display: flex;
    gap: 5px;
}

.category-actions .button {
    padding: 6px 8px;
    min-height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.category-actions .dashicons {
    font-size: 16px;
    width: 16px;
    height: 16px;
}

/* Category Modal Styles */
.category-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100001;
    display: flex;
    align-items: center;
    justify-content: center;
}

.category-modal-backdrop {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    z-index: 1;
}

.category-modal-content {
    position: relative;
    background: #fff;
    border-radius: 6px;
    width: 90%;
    max-width: 500px;
    z-index: 2;
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
}

.category-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    border-bottom: 1px solid #e1e1e1;
    background: #f8f9fa;
    border-radius: 6px 6px 0 0;
}

.category-modal-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #23282d;
}

.category-modal-close {
    background: none;
    border: none;
    font-size: 20px;
    cursor: pointer;
    color: #666;
    padding: 0;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.2s ease;
}

.category-modal-close:hover {
    background: #e1e1e1;
    color: #333;
}

.category-modal-body {
    padding: 20px;
}

.category-modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 15px 20px;
    border-top: 1px solid #e1e1e1;
    background: #f8f9fa;
    border-radius: 0 0 6px 6px;
}

/* Content Builder */
.content-builder-section {
    margin-bottom: 25px;
}

.builder-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e1e1e1;
}

.builder-header label {
    margin: 0;
    font-weight: 600;
    color: #23282d;
    font-size: 16px;
}

.builder-controls {
    display: flex;
    align-items: center;
    gap: 15px;
}

#live-preview-btn,
#insert-template-tag-btn {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    font-weight: 500;
    transition: all 0.2s ease;
}

#live-preview-btn .dashicons,
#insert-template-tag-btn .dashicons {
    font-size: 14px;
    width: 14px;
    height: 14px;
}

#live-preview-btn.button-primary {
    background: #0073aa;
    border-color: #0073aa;
    color: #fff;
}

#live-preview-btn.button-primary:hover {
    background: #005a87;
    border-color: #005a87;
}

.editor-mode-toggle {
    display: flex;
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
}

.mode-btn {
    background: #f8f9fa;
    border: none;
    padding: 8px 15px;
    cursor: pointer;
    font-size: 13px;
    font-weight: 500;
    color: #666;
    display: flex;
    align-items: center;
    gap: 5px;
    transition: all 0.2s ease;
    border-right: 1px solid #ddd;
}

.mode-btn:last-child {
    border-right: none;
}

.mode-btn:hover {
    background: #e9ecef;
    color: #333;
}

.mode-btn.active {
    background: #0073aa;
    color: #fff;
}

.mode-btn .dashicons {
    font-size: 14px;
    width: 14px;
    height: 14px;
}

/* Template Tags Modal */
.template-tags-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100002;
    display: flex;
    align-items: center;
    justify-content: center;
}

.template-tags-modal-backdrop {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    z-index: 1;
}

.template-tags-modal-content {
    position: relative;
    background: #fff;
    border-radius: 6px;
    width: 90%;
    max-width: 700px;
    max-height: 80vh;
    z-index: 2;
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
    display: flex;
    flex-direction: column;
}

.template-tags-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    border-bottom: 1px solid #e1e1e1;
    background: #f8f9fa;
    border-radius: 6px 6px 0 0;
    flex-shrink: 0;
}

.template-tags-modal-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #23282d;
}

.template-tags-modal-close {
    background: none;
    border: none;
    font-size: 20px;
    cursor: pointer;
    color: #666;
    padding: 0;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.2s ease;
}

.template-tags-modal-close:hover {
    background: #e1e1e1;
    color: #333;
}

.template-tags-modal-body {
    padding: 20px;
    overflow-y: auto;
    flex: 1;
}

.tags-search {
    margin-bottom: 20px;
}

.tags-search input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

.tags-list {
    max-height: 400px;
    overflow-y: auto;
}

.tag-group {
    margin-bottom: 25px;
}

.tag-group:last-child {
    margin-bottom: 0;
}

.tag-group h4 {
    margin: 0 0 12px 0;
    font-size: 14px;
    font-weight: 600;
    color: #23282d;
    padding-bottom: 6px;
    border-bottom: 1px solid #e1e1e1;
}

.tag-items {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.tag-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 12px;
    border: 1px solid #e1e1e1;
    border-radius: 4px;
    background: #fafafa;
    transition: all 0.2s ease;
}

.tag-item:hover {
    background: #f0f0f0;
    border-color: #ccc;
}

.tag-info {
    flex: 1;
}

.tag-name {
    display: block;
    font-family: 'Courier New', monospace;
    font-size: 13px;
    font-weight: 600;
    color: #0073aa;
    margin-bottom: 2px;
}

.tag-description {
    display: block;
    font-size: 12px;
    color: #666;
}

.insert-tag-btn {
    font-size: 12px;
    padding: 4px 12px;
    line-height: 1.4;
    flex-shrink: 0;
}

.tags-usage-info {
    margin-top: 20px;
    padding: 15px;
    background: #f8f9fa;
    border: 1px solid #e1e1e1;
    border-radius: 4px;
}

.tags-usage-info p {
    margin: 0 0 8px 0;
    font-size: 13px;
    line-height: 1.5;
}

.tags-usage-info p:last-child {
    margin-bottom: 0;
}

.tags-usage-info code {
    background: #fff;
    padding: 2px 4px;
    border-radius: 2px;
    font-size: 12px;
    border: 1px solid #ddd;
}

/* Visual Editor */
.visual-editor-container {
    border: 1px solid #e1e1e1;
    border-radius: 4px;
    background: #fff;
    margin-bottom: 20px;
}

.visual-editor-toolbar {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 10px;
    padding: 10px 15px;
    background: #f8f9fa;
    border-bottom: 1px solid #e1e1e1;
}

.toolbar-group {
    display: flex;
    align-items: center;
    gap: 5px;
    border-right: 1px solid #ddd;
    padding-right: 10px;
}

.toolbar-group:last-child {
    border-right: none;
    padding-right: 0;
}

.editor-control {
    padding: 4px 8px;
    border: 1px solid #ddd;
    border-radius: 3px;
    font-size: 12px;
    background: #fff;
}

.editor-btn {
    background: #fff;
    border: 1px solid #ddd;
    padding: 6px 8px;
    border-radius: 3px;
    cursor: pointer;
    font-size: 12px;
    min-width: 28px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
}

.editor-btn:hover {
    background: #f0f0f0;
    border-color: #999;
}

.editor-btn.active {
    background: #0073aa;
    color: #fff;
    border-color: #0073aa;
}

.editor-btn .dashicons {
    font-size: 14px;
    width: 14px;
    height: 14px;
}

.color-picker {
    width: 28px;
    height: 28px;
    border: 1px solid #ddd;
    border-radius: 3px;
    cursor: pointer;
    padding: 0;
}

.visual-editor-content {
    padding: 15px;
}

.editor-content {
    min-height: 200px;
    border: 1px solid #e1e1e1;
    border-radius: 4px;
    padding: 15px;
    font-family: Arial, sans-serif;
    font-size: 14px;
    line-height: 1.6;
    outline: none;
    background: #fff;
}

.editor-content:empty:before {
    content: attr(placeholder);
    color: #999;
    font-style: italic;
}

.editor-content:focus {
    border-color: #0073aa;
    box-shadow: 0 0 0 1px #0073aa;
}

/* HTML Editor */
.html-editor-container {
    border: 1px solid #e1e1e1;
    border-radius: 4px;
    background: #fff;
    margin-bottom: 20px;
}

.html-editor-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
    background: #2c3e50;
    color: #fff;
    border-bottom: 1px solid #e1e1e1;
}

.toolbar-label {
    font-weight: 600;
    font-size: 13px;
}

.html-actions {
    display: flex;
    gap: 8px;
}

.html-editor-content {
    padding: 0;
}

.html-textarea {
    border: none;
    border-radius: 0;
    resize: vertical;
    font-family: 'Courier New', monospace;
    font-size: 13px;
    line-height: 1.5;
    background: #f8f9fa;
    color: #333;
    padding: 15px;
}

.html-textarea:focus {
    outline: none;
    box-shadow: none;
    background: #fff;
}

/* Live Preview */
.live-preview-section {
    border: 1px solid #e1e1e1;
    border-radius: 4px;
    background: #fff;
}

.preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 15px;
    background: #f8f9fa;
    border-bottom: 1px solid #e1e1e1;
}

.preview-header h4 {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
    color: #23282d;
    display: flex;
    align-items: center;
    gap: 8px;
}

.preview-header .dashicons {
    font-size: 16px;
    width: 16px;
    height: 16px;
}

.preview-content {
    padding: 15px;
}

.preview-area {
    min-height: 150px;
    border: 1px dashed #ddd;
    border-radius: 4px;
    padding: 15px;
    background: #fafafa;
    font-family: Arial, sans-serif;
    font-size: 14px;
    line-height: 1.6;
}

.preview-area:empty:before {
    content: 'Preview will appear here...';
    color: #999;
    font-style: italic;
}

.text-block-container {
    border: 1px solid #e1e1e1;
    border-radius: 4px;
    background: #fff;
}

.text-block-header {
    background: #f8f9fa;
    padding: 10px 15px;
    border-bottom: 1px solid #e1e1e1;
    font-weight: 500;
    color: #23282d;
}

.text-editor-toolbar {
    display: flex;
    align-items: center;
    gap: 5px;
    padding: 10px 15px;
    border-bottom: 1px solid #e1e1e1;
    background: #fafafa;
    flex-wrap: wrap;
}

.font-style {
    padding: 4px 8px;
    border: 1px solid #ddd;
    border-radius: 3px;
    font-size: 12px;
    margin-right: 10px;
}

.editor-btn {
    background: #fff;
    border: 1px solid #ddd;
    padding: 4px 8px;
    border-radius: 3px;
    cursor: pointer;
    font-size: 12px;
    min-width: 28px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
}

.editor-btn:hover {
    background: #f0f0f0;
    border-color: #999;
}

.editor-btn.active {
    background: #0073aa;
    color: #fff;
    border-color: #0073aa;
}

.text-editor-content {
    padding: 15px;
}

.text-editor-content textarea {
    border: none;
    resize: vertical;
    font-family: inherit;
}

.text-editor-content textarea:focus {
    outline: none;
    box-shadow: none;
}

/* Image Upload */
.image-upload-container {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 15px;
    border: 2px dashed #ddd;
    border-radius: 4px;
    background: #fafafa;
}

.image-upload-btn {
    background: #0073aa;
    color: #fff;
    border: none;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.image-upload-btn:hover {
    background: #005a87;
}

.image-upload-btn .dashicons {
    font-size: 18px;
}

.image-upload-text {
    color: #666;
    font-size: 14px;
}

/* Width Presets */
.width-presets {
    margin-bottom: 25px;
}

.width-presets > label {
    display: block;
    margin-bottom: 10px;
    font-weight: 600;
    color: #23282d;
    font-size: 16px;
}

.width-buttons {
    display: flex;
    gap: 5px;
    margin-bottom: 15px;
    flex-wrap: wrap;
}

.width-btn {
    background: #f0f0f0;
    border: 1px solid #ddd;
    padding: 8px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    font-weight: 500;
    transition: all 0.2s ease;
    min-width: 50px;
}

.width-btn:hover {
    background: #e0e0e0;
    border-color: #999;
}

.width-btn.active {
    background: #0073aa;
    color: #fff;
    border-color: #0073aa;
}

.custom-width label {
    display: block;
    margin-bottom: 5px;
    font-weight: 500;
    color: #23282d;
    font-size: 14px;
}

/* Color Picker */
.color-picker-container {
    display: flex;
    align-items: center;
    gap: 15px;
}

.color-toggle {
    position: relative;
}

.toggle-switch {
    display: inline-block;
    width: 40px;
    height: 20px;
    background: #ccc;
    border-radius: 20px;
    position: relative;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.toggle-switch::after {
    content: '';
    position: absolute;
    top: 2px;
    left: 2px;
    width: 16px;
    height: 16px;
    background: #fff;
    border-radius: 50%;
    transition: transform 0.2s ease;
}

input[type="checkbox"]:checked + .toggle-switch {
    background: #0073aa;
}

input[type="checkbox"]:checked + .toggle-switch::after {
    transform: translateX(20px);
}

input[type="checkbox"] {
    display: none;
}

.color-picker {
    width: 50px;
    height: 35px;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
}

/* Background Image */
.bg-image-container {
    display: flex;
    align-items: center;
    gap: 15px;
}

.bg-image-toggle {
    position: relative;
}

.bg-image-controls {
    display: flex;
    align-items: center;
    gap: 10px;
}

.bg-image-text {
    color: #666;
    font-size: 14px;
}

/* Modal Footer */
.template-modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 20px 25px;
    border-top: 1px solid #e1e1e1;
    background: #f8f9fa;
}

/* Responsive Design */

@media (max-width: 768px) {
    .templates-header {
        flex-direction: column;
        gap: 15px;
        align-items: stretch;
    }

    .templates-actions {
        align-self: flex-start;
    }

    .templates-table-container {
        overflow-x: hidden;
    }

    .templates-table {
        width: 100%;
        table-layout: fixed;
    }

    .template-actions {
        flex-direction: column;
        gap: 3px;
    }

    .templates-table .column-name,
    .templates-table .column-created-by,
    .templates-table .column-date {
        white-space: normal;
        font-size: 12px;
    }

    .templates-table .column-id {
        width: 40px;
    }

    .templates-table .column-actions {
        width: 30%;
    }

    .template-modal-content {
        width: 95%;
        max-height: 95vh;
    }

    .template-main-content {
        padding: 15px;
    }

    .width-buttons {
        gap: 3px;
    }

    .width-btn {
        padding: 6px 8px;
        font-size: 11px;
        min-width: 40px;
    }

    .text-editor-toolbar {
        gap: 3px;
        padding: 8px 10px;
    }

    .editor-btn {
        min-width: 24px;
        height: 24px;
        font-size: 11px;
    }
}

/* Responsive Design */
@media (max-width: 768px) {
    /* Template Header Responsive */
    .template-header-row {
        flex-direction: column;
        gap: 15px;
    }

    .template-name-group,
    .template-description-group {
        flex: 1;
    }

    .category-management {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .category-select-wrapper {
        width: 100%;
        max-width: none;
    }

    .category-actions {
        align-self: flex-end;
    }

    .category-modal-content {
        width: 95%;
        margin: 10px;
    }

    .category-modal-header,
    .category-modal-body,
    .category-modal-footer {
        padding: 15px;
    }
}

@media (max-width: 480px) {
    .template-header-row {
        gap: 12px;
    }

    .category-actions {
        width: 100%;
        justify-content: center;
    }

    .category-modal-footer {
        flex-direction: column;
        gap: 8px;
    }

    .category-modal-footer .button {
        width: 100%;
        justify-content: center;
    }

    /* Content Builder Responsive */
    .builder-header {
        flex-direction: column;
        gap: 10px;
        align-items: flex-start;
    }

    .builder-controls {
        width: 100%;
        justify-content: space-between;
    }

    .visual-editor-toolbar {
        gap: 5px;
        padding: 8px 10px;
    }

    .toolbar-group {
        gap: 3px;
        padding-right: 8px;
    }

    .template-tags-modal-content {
        width: 95%;
        max-height: 85vh;
    }

    .template-tags-modal-body {
        padding: 15px;
    }

    .tag-item {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }

    .insert-tag-btn {
        align-self: flex-end;
    }

    .preview-header {
        flex-direction: column;
        gap: 8px;
        align-items: flex-start;
    }
}
</style>

<script>
jQuery(document).ready(function($) {
    // Template Modal Management
    var templateModal = $('#template-modal');
    var isEditMode = false;
    var currentTemplateId = null;

    // Create New Template button
    $('#create-new-template').on('click', function() {
        ///openTemplateModal('create');
        window.open('https://instantpopupbuilder.com/extensions/subscription-popup/', '_blank');
    });

    // Edit Template buttons
    $('.edit-template').on('click', function(e) {
        e.preventDefault();
        var templateId = $(this).data('id');
        openTemplateModal('edit', templateId);
    });

    // Delete Template buttons
    $('.delete-template').on('click', function(e) {
        e.preventDefault();
        var templateId = $(this).data('id');
        if (confirm('Are you sure you want to delete this template? This action cannot be undone.')) {
            deleteTemplate(templateId);
        }
    });

    // Duplicate Template buttons
    $('.duplicate-template').on('click', function(e) {
        e.preventDefault();
        var templateId = $(this).data('id');
        duplicateTemplate(templateId);
    });

    // Open Template Modal
    function openTemplateModal(mode, templateId) {
        isEditMode = (mode === 'edit');
        currentTemplateId = templateId || null;

        // Update modal title
        $('#template-modal-title').text(isEditMode ? 'Edit Template' : 'Create New Template');

        // Reset form
        resetTemplateForm();

        // Load template data if editing, otherwise load default template
        if (isEditMode && templateId) {
            loadTemplateData(templateId);
        } else {
            // Load default template for new templates
            setTimeout(function() {
                loadDefaultTemplate();
                updatePreview();
            }, 100);
        }

        // Show modal
        templateModal.fadeIn(300);
        $('body').addClass('modal-open');
    }

    // Close Template Modal
    function closeTemplateModal() {
        templateModal.fadeOut(300);
        $('body').removeClass('modal-open');
        resetTemplateForm();
        isEditMode = false;
        currentTemplateId = null;
    }

    // Reset Template Form
    function resetTemplateForm() {
        $('#template-form')[0].reset();
        $('#template_id').val('');
        $('.width-btn').removeClass('active');
        $('.width-btn[data-width="100"]').addClass('active');
        $('#template_width').val('100%');
        $('.editor-btn').removeClass('active');

        // Clear editor content
        visualEditor.html('');
        htmlEditor.val('');
    }

    // Load Template Data (for edit mode)
    function loadTemplateData(templateId) {
        // Send AJAX request to load template data
        $.ajax({
            url: ajaxurl || window.location.href,
            type: 'POST',
            data: {
                action: 'load_template_data',
                template_id: templateId,
                nonce: '<?php echo esc_js(wp_create_nonce("load_template_nonce")); ?>'
            },
            success: function(response) {
                if (response.success && response.data) {
                    var template = response.data;

                    // Fill form fields
                    $('#template_id').val(template.id);
                    $('#template_name').val(template.name);
                    $('#template_description').val(template.description || '');
                    $('#template_category').val(template.category);

                    // Set content in editors
                    if (template.content) {
                        visualEditor.html(template.content);
                        htmlEditor.val(template.content);
                        updatePreview();
                    }

                    // Set template data if available
                    if (template.template_data) {
                        var templateData = JSON.parse(template.template_data);

                        // Fill additional fields from template data
                        if (templateData.template_width) $('#template_width').val(templateData.template_width);
                        if (templateData.button_color) $('#button_color').val(templateData.button_color);
                        if (templateData.font_family) $('#font_family').val(templateData.font_family);
                        if (templateData.font_size) $('#font_size').val(templateData.font_size);
                    }
                } else {
                    showNotice('Failed to load template data.', 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('Load template error:', error);
                showNotice('Error loading template data.', 'error');
            }
        });
    }

    // Delete Template
    function deleteTemplate(templateId) {
        // Send AJAX request to delete template
        $.ajax({
            url: ajaxurl || window.location.href,
            type: 'POST',
            data: {
                action: 'delete_template_data',
                template_id: templateId,
                nonce: '<?php echo esc_js(wp_create_nonce("delete_template_nonce")); ?>'
            },
            success: function(response) {
                if (response.success) {
                    showNotice('Template deleted successfully!', 'success');

                    // Remove the row from table
                    $('tr').has('[data-id="' + templateId + '"]').fadeOut(300, function() {
                        $(this).remove();
                    });
                } else {
                    showNotice('Failed to delete template. Please try again.', 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('Delete template error:', error);
                showNotice('Error deleting template. Please try again.', 'error');
            }
        });
    }

    // Duplicate Template
    function duplicateTemplate(templateId) {
        console.log('Duplicating template ID:', templateId);

        // Send AJAX request to duplicate template
        $.ajax({
            url: ajaxurl || window.location.href,
            type: 'POST',
            data: {
                action: 'ipb_duplicate_template',
                template_id: templateId,
                nonce: '<?php echo esc_js(wp_create_nonce("ipb_template_action")); ?>'
            },
            success: function(response) {
                console.log('Duplicate response:', response);
                if (response.success) {
                    showNotice('Template duplicated successfully!', 'success');

                    // Reload the page to show the new template
                    setTimeout(function() {
                        location.reload();
                    }, 1000);
                } else {
                    showNotice('Failed to duplicate template: ' + (response.data || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('Duplicate template error:', error);
                console.error('Response:', xhr.responseText);
                showNotice('Error duplicating template. Please try again.', 'error');
            }
        });
    }

    // Show Notice
    function showNotice(message, type) {
        var noticeClass = type === 'success' ? 'notice-success' : 'notice-error';
        var notice = $('<div class="notice ' + noticeClass + ' is-dismissible"><p>' + message + '</p></div>');
        $('.templates-tab-content').prepend(notice);

        setTimeout(function() {
            notice.fadeOut(300, function() {
                $(this).remove();
            });
        }, 3000);
    }

    // Modal Event Handlers
    $('.template-modal-close, #cancel-template').on('click', function() {
        closeTemplateModal();
    });

    $('.template-modal-backdrop').on('click', function() {
        closeTemplateModal();
    });

    // Prevent modal close when clicking inside modal content
    $('.template-modal-content').on('click', function(e) {
        e.stopPropagation();
    });

    // Category Management
    var categoryModal = $('#category-modal');
    var categories = <?php echo json_encode($instant_popup_builder_categories); ?>;

    // Add Category
    $('#add-category').on('click', function() {
        openCategoryModal('add');
    });

    // Edit Category
    $('#edit-category').on('click', function() {
        var selectedKey = $('#template_category').val();
        if (selectedKey && categories[selectedKey]) {
            openCategoryModal('edit', selectedKey, categories[selectedKey]);
        } else {
            showNotice('Please select a category to edit.', 'error');
        }
    });

    // Delete Category
    $('#delete-category').on('click', function() {
        var selectedKey = $('#template_category').val();
        if (selectedKey && categories[selectedKey]) {
            if (confirm('Are you sure you want to delete the "' + categories[selectedKey] + '" category? This action cannot be undone.')) {
                deleteCategory(selectedKey);
            }
        } else {
            showNotice('Please select a category to delete.', 'error');
        }
    });

    // Open Category Modal
    function openCategoryModal(mode, key, name) {
        var isEdit = (mode === 'edit');

        // Update modal title
        $('#category-modal-title').text(isEdit ? 'Edit Category' : 'Add New Category');

        // Set form values
        $('#category_action').val(mode);
        $('#category_original_key').val(key || '');
        $('#category_name').val(name || '');
        $('#category_key').val(key || '');

        // Auto-generate key from name for new categories
        if (!isEdit) {
            $('#category_name').on('input', function() {
                var name = $(this).val();
                var key = name.toLowerCase().replace(/[^a-z0-9]/g, '_').replace(/_+/g, '_').replace(/^_|_$/g, '');
                $('#category_key').val(key);
            });
        } else {
            $('#category_name').off('input');
            $('#category_key').prop('readonly', true);
        }

        // Show modal
        categoryModal.fadeIn(300);
        $('body').addClass('modal-open');
        $('#category_name').focus();
    }

    // Close Category Modal
    function closeCategoryModal() {
        categoryModal.fadeOut(300);
        $('body').removeClass('modal-open');
        $('#category-form')[0].reset();
        $('#category_key').prop('readonly', false);
        $('#category_name').off('input');
    }

    // Save Category
    $('#save-category').on('click', function() {
        var action = $('#category_action').val();
        var originalKey = $('#category_original_key').val();
        var name = $('#category_name').val().trim();
        var key = $('#category_key').val().trim();

        // Validation
        if (!name) {
            showNotice('Category name is required.', 'error');
            $('#category_name').focus();
            return;
        }

        if (!key) {
            showNotice('Category key is required.', 'error');
            $('#category_key').focus();
            return;
        }

        if (!/^[a-z0-9_]+$/.test(key)) {
            showNotice('Category key can only contain lowercase letters, numbers, and underscores.', 'error');
            $('#category_key').focus();
            return;
        }

        // Check for duplicate keys (except when editing the same category)
        if (action === 'add' || (action === 'edit' && key !== originalKey)) {
            if (categories[key]) {
                showNotice('A category with this key already exists.', 'error');
                $('#category_key').focus();
                return;
            }
        }

        // Save category
        if (action === 'add') {
            addCategory(key, name);
        } else {
            editCategory(originalKey, key, name);
        }
    });

    // Add Category Function
    function addCategory(key, name) {
        // Update categories object
        categories[key] = name;

        // Add to select dropdown
        var option = $('<option value="' + key + '">' + name + '</option>');
        $('#template_category').append(option);
        $('#template_category').val(key);

        // Close modal
        closeCategoryModal();

        // Show success message
        showNotice('Category "' + name + '" added successfully!', 'success');

        // In a real implementation, you would send an AJAX request to save to database
        saveCategoryToDatabase('add', key, name);
    }

    // Edit Category Function
    function editCategory(originalKey, newKey, newName) {
        // Update categories object
        if (originalKey !== newKey) {
            delete categories[originalKey];
        }
        categories[newKey] = newName;

        // Update select dropdown
        var selectedValue = $('#template_category').val();
        var option = $('#template_category option[value="' + originalKey + '"]');

        if (originalKey !== newKey) {
            option.attr('value', newKey);
        }
        option.text(newName);

        // Keep selection if it was the edited category
        if (selectedValue === originalKey) {
            $('#template_category').val(newKey);
        }

        // Close modal
        closeCategoryModal();

        // Show success message
        showNotice('Category "' + newName + '" updated successfully!', 'success');

        // In a real implementation, you would send an AJAX request to save to database
        saveCategoryToDatabase('edit', newKey, newName, originalKey);
    }

    // Delete Category Function
    function deleteCategory(key) {
        var name = categories[key];

        // Remove from categories object
        delete categories[key];

        // Remove from select dropdown
        $('#template_category option[value="' + key + '"]').remove();

        // Select first available option
        $('#template_category').prop('selectedIndex', 0);

        // Show success message
        showNotice('Category "' + name + '" deleted successfully!', 'success');

        // In a real implementation, you would send an AJAX request to delete from database
        saveCategoryToDatabase('delete', key, name);
    }

    // Save Category to Database (placeholder function)
    function saveCategoryToDatabase(action, key, name, originalKey) {
        // In a real implementation, this would send an AJAX request
        // to save the category changes to the database
        console.log('Saving category to database:', {
            action: action,
            key: key,
            name: name,
            originalKey: originalKey
        });

        // Example AJAX call (uncomment and modify for real implementation):
        /*
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'save_template_category',
                category_action: action,
                category_key: key,
                category_name: name,
                original_key: originalKey,
                nonce: '<?php echo esc_js(wp_create_nonce("template_category_nonce")); ?>'
            },
            success: function(response) {
                if (response.success) {
                    console.log('Category saved successfully');
                } else {
                    showNotice('Error saving category: ' + response.data, 'error');
                }
            },
            error: function() {
                showNotice('Error saving category. Please try again.', 'error');
            }
        });
        */
    }

    // Category Modal Event Handlers
    $('.category-modal-close, #cancel-category').on('click', function() {
        closeCategoryModal();
    });

    $('.category-modal-backdrop').on('click', function() {
        closeCategoryModal();
    });

    // Prevent modal close when clicking inside modal content
    $('.category-modal-content').on('click', function(e) {
        e.stopPropagation();
    });

    // Handle Enter key in category form
    $('#category-form input').on('keypress', function(e) {
        if (e.which === 13) {
            e.preventDefault();
            $('#save-category').click();
        }
    });

    // Content Builder Functionality
    var currentEditorMode = 'visual';
    var visualEditor = $('#visual-editor');
    var htmlEditor = $('#html-editor');
    var previewArea = $('#content-preview');

    // Template Tags for replacement
    var templateTags = {
        '{subscriber_name}': 'John Doe',
        '{subscriber_email}': 'john@example.com',
        '{subscription_date}': new Date().toLocaleDateString(),
        '{campaign_name}': 'Summer Campaign 2024',
        '{popup_title}': 'Newsletter Signup',
        '{coupon_code}': 'SAVE20',
        '{site_name}': '<?php echo esc_js(get_bloginfo("name")); ?>',
        '{site_url}': '<?php echo esc_js(home_url()); ?>',
        '{unsubscribe_link}': '<a href="#unsubscribe">Unsubscribe</a>',
        '{verification_link}': '<a href="#verify">Verify Email</a>',
        '{custom_field_1}': 'Custom Value 1',
        '{custom_field_2}': 'Custom Value 2',
        '{custom_field_3}': 'Custom Value 3',
        '{custom_field_4}': 'Custom Value 4',
        '{custom_field_5}': 'Custom Value 5'
    };

    // Editor Mode Toggle
    $('.mode-btn').on('click', function() {
        var mode = $(this).data('mode');
        switchEditorMode(mode);
    });

    function switchEditorMode(mode) {
        $('.mode-btn').removeClass('active');
        $('.mode-btn[data-mode="' + mode + '"]').addClass('active');

        if (mode === 'visual') {
            // Switch to visual editor
            if (currentEditorMode === 'html') {
                // Convert HTML to visual
                visualEditor.html(htmlEditor.val());
            }
            $('#visual-editor-container').show();
            $('#html-editor-container').hide();
        } else {
            // Switch to HTML editor
            if (currentEditorMode === 'visual') {
                // Convert visual to HTML
                htmlEditor.val(visualEditor.html());
            }
            $('#visual-editor-container').hide();
            $('#html-editor-container').show();
        }

        currentEditorMode = mode;
        updatePreview();
    }

    // Template Tags Modal
    var templateTagsModal = $('#template-tags-modal');
    var lastCursorPosition = null;

    // Live Preview Toggle
    $('#live-preview-btn').on('click', function() {
        var $button = $(this);
        var $previewSection = $('#live-preview-section');
        var $icon = $button.find('.dashicons');

        if ($previewSection.is(':visible')) {
            // Hide preview
            $previewSection.slideUp(300);
            $button.removeClass('button-primary').addClass('button-secondary');
            $icon.removeClass('dashicons-hidden').addClass('dashicons-visibility');
            $button.find('span:not(.dashicons)').text(' Live Preview');
            $button.attr('title', 'Show Live Preview');
        } else {
            // Show preview
            $previewSection.slideDown(300);
            $button.removeClass('button-secondary').addClass('button-primary');
            $icon.removeClass('dashicons-visibility').addClass('dashicons-hidden');
            $button.find('span:not(.dashicons)').text(' Hide Preview');
            $button.attr('title', 'Hide Live Preview');

            // Update preview when showing
            updatePreview();
        }
    });

    // Open Template Tags Modal
    $('#insert-template-tag-btn').on('click', function() {
        // Ensure editor is focused before storing position
        if (currentEditorMode === 'visual') {
            visualEditor.focus();
        } else {
            htmlEditor.focus();
        }

        // Small delay to ensure focus is set
        setTimeout(function() {
            // Store current cursor position
            storeCursorPosition();

            // Show modal
            templateTagsModal.fadeIn(300);
            $('body').addClass('modal-open');

            // Focus search input
            $('#tags-search-input').focus();

            // Add direct click handlers to all insert buttons as fallback
            $('.insert-tag-btn').off('click.direct').on('click.direct', function(e) {
                e.preventDefault();
                e.stopPropagation();

                var $tagItem = $(this).closest('.tag-item');
                var tag = $tagItem.data('tag');

                if (!tag) {
                    console.error('No tag found for insertion');
                    return;
                }

                insertTagAtStoredPosition(tag);
                closeTemplateTagsModal();
            });

        }, 50);
    });

    // Close Template Tags Modal
    function closeTemplateTagsModal() {
        templateTagsModal.fadeOut(300);
        $('body').removeClass('modal-open');
        $('#tags-search-input').val('');
        filterTags('');

        // Restore focus to editor
        if (currentEditorMode === 'visual') {
            visualEditor.focus();
        } else {
            htmlEditor.focus();
        }
    }

    // Modal close events
    $('.template-tags-modal-close').on('click', closeTemplateTagsModal);
    $('.template-tags-modal-backdrop').on('click', closeTemplateTagsModal);

    // Prevent modal close when clicking inside modal content (but allow button clicks)
    $('.template-tags-modal-content').on('click', function(e) {
        // Only stop propagation if not clicking on a button
        if (!$(e.target).is('.insert-tag-btn, .template-tags-modal-close')) {
            e.stopPropagation();
        }
    });

    // Template Tag Insertion (using event delegation)
    $(document).on('click', '.insert-tag-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();

        var $tagItem = $(this).closest('.tag-item');
        var tag = $tagItem.data('tag');

        if (!tag) {
            console.error('No tag found for insertion');
            return;
        }

        insertTagAtStoredPosition(tag);
        closeTemplateTagsModal();
    });


    // Tags Search Functionality
    $('#tags-search-input').on('input', function() {
        var searchTerm = $(this).val().toLowerCase();
        filterTags(searchTerm);
    });

    function filterTags(searchTerm) {
        $('.tag-item').each(function() {
            var $item = $(this);
            var tagName = $item.find('.tag-name').text().toLowerCase();
            var tagDescription = $item.find('.tag-description').text().toLowerCase();

            if (tagName.includes(searchTerm) || tagDescription.includes(searchTerm)) {
                $item.show();
            } else {
                $item.hide();
            }
        });

        // Hide/show groups based on visible items
        $('.tag-group').each(function() {
            var $group = $(this);
            var hasVisibleItems = $group.find('.tag-item:visible').length > 0;
            $group.toggle(hasVisibleItems);
        });
    }

    // Store cursor position for later insertion
    function storeCursorPosition() {
        try {
            if (currentEditorMode === 'visual') {
                // Ensure visual editor is focused
                visualEditor.focus();

                var selection = window.getSelection();
                if (selection.rangeCount > 0) {
                    var range = selection.getRangeAt(0);
                    // Check if the range is within the visual editor
                    var editorElement = visualEditor[0];
                    if (editorElement.contains(range.startContainer) || editorElement.contains(range.endContainer)) {
                        lastCursorPosition = {
                            type: 'visual',
                            range: range.cloneRange()
                        };
                    } else {
                        // Range is outside editor, store null to append at end
                        lastCursorPosition = {
                            type: 'visual',
                            range: null
                        };
                    }
                } else {
                    // No selection, position at end
                    lastCursorPosition = {
                        type: 'visual',
                        range: null
                    };
                }
            } else {
                var element = htmlEditor[0];
                lastCursorPosition = {
                    type: 'html',
                    start: element.selectionStart || 0,
                    end: element.selectionEnd || 0
                };
            }
        } catch (e) {
            // Error storing position, will fallback to end insertion
            lastCursorPosition = null;
        }
    }

    // Insert tag at stored position
    function insertTagAtStoredPosition(tag) {
        if (!lastCursorPosition) {
            // Fallback: insert at end of content
            if (currentEditorMode === 'visual') {
                insertTagIntoVisualEditor(tag);
            } else {
                var currentContent = htmlEditor.val();
                htmlEditor.val(currentContent + tag);
                htmlEditor.focus();
            }
            updatePreview();
            return;
        }

        if (lastCursorPosition.type === 'visual') {
            if (lastCursorPosition.range) {
                try {
                    // Restore selection and insert
                    var selection = window.getSelection();
                    selection.removeAllRanges();
                    selection.addRange(lastCursorPosition.range);
                    insertTagIntoVisualEditor(tag);
                } catch (e) {
                    // Fallback if range is invalid
                    insertTagIntoVisualEditor(tag);
                }
            } else {
                // No stored range, insert at end
                insertTagIntoVisualEditor(tag);
            }
        } else {
            // Insert at stored position in HTML editor
            var element = htmlEditor[0];
            var start = lastCursorPosition.start || 0;
            var end = lastCursorPosition.end || 0;

            var value = element.value;
            element.value = value.substring(0, start) + tag + value.substring(end);
            element.selectionStart = element.selectionEnd = start + tag.length;
            htmlEditor.focus();
        }

        updatePreview();
        lastCursorPosition = null;
    }

    // Helper function to insert tag into visual editor
    function insertTagIntoVisualEditor(tag) {
        try {
            // Focus the visual editor first
            visualEditor.focus();

            // Get the editor element
            var editorElement = visualEditor[0];

            // Ensure the editor has focus
            if (document.activeElement !== editorElement) {
                editorElement.focus();
            }

            var selection = window.getSelection();

            // If there's a stored range, try to use it
            if (lastCursorPosition && lastCursorPosition.range) {
                try {
                    selection.removeAllRanges();
                    selection.addRange(lastCursorPosition.range);
                } catch (e) {
                    // Range is invalid, continue with current selection
                }
            }

            if (selection.rangeCount > 0) {
                // Insert at current selection/cursor position
                var range = selection.getRangeAt(0);
                range.deleteContents();
                var textNode = document.createTextNode(tag);
                range.insertNode(textNode);

                // Move cursor after inserted text
                range.setStartAfter(textNode);
                range.setEndAfter(textNode);
                selection.removeAllRanges();
                selection.addRange(range);
            } else {
                // No selection, append to the end
                var range = document.createRange();

                if (editorElement.childNodes.length > 0) {
                    // Position at end of last node
                    var lastNode = editorElement.lastChild;
                    if (lastNode.nodeType === Node.TEXT_NODE) {
                        range.setStart(lastNode, lastNode.textContent.length);
                    } else {
                        range.setStartAfter(lastNode);
                    }
                } else {
                    // Empty editor, position at start
                    range.setStart(editorElement, 0);
                }

                range.collapse(true);
                var textNode = document.createTextNode(tag);
                range.insertNode(textNode);

                // Set cursor after the inserted text
                range.setStartAfter(textNode);
                range.setEndAfter(textNode);
                selection.removeAllRanges();
                selection.addRange(range);
            }

            // Trigger input event to update the editor state
            var event = new Event('input', { bubbles: true });
            editorElement.dispatchEvent(event);
        } catch (e) {
            // Ultimate fallback - use document.execCommand
            try {
                visualEditor.focus();
                document.execCommand('insertText', false, tag);
            } catch (e2) {
                // Last resort - append to HTML content
                var currentContent = visualEditor.html();
                visualEditor.html(currentContent + tag);
            }
        }

        visualEditor.focus();
    }

    // Handle Escape key to close modal
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && templateTagsModal.is(':visible')) {
            closeTemplateTagsModal();
        }
    });

    function insertTag(tag) {
        if (currentEditorMode === 'visual') {
            // Insert into visual editor
            insertAtCursor(visualEditor[0], tag);
            visualEditor.focus();
        } else {
            // Insert into HTML editor
            insertAtCursor(htmlEditor[0], tag);
            htmlEditor.focus();
        }
        updatePreview();
    }

    // Visual Editor Toolbar Functions
    $('.editor-btn').on('click', function() {
        var action = $(this).data('action');
        if (action && currentEditorMode === 'visual') {
            executeCommand(action, $(this));
        }
    });

    // Font family and size changes
    $('#font-family').on('change', function() {
        if (currentEditorMode === 'visual') {
            document.execCommand('fontName', false, $(this).val());
            visualEditor.focus();
            updatePreview();
        }
    });

    $('#font-size').on('change', function() {
        if (currentEditorMode === 'visual') {
            var selection = window.getSelection();
            if (selection.rangeCount > 0) {
                var range = selection.getRangeAt(0);
                var span = document.createElement('span');
                span.style.fontSize = $(this).val();
                try {
                    range.surroundContents(span);
                } catch (e) {
                    span.appendChild(range.extractContents());
                    range.insertNode(span);
                }
            }
            visualEditor.focus();
            updatePreview();
        }
    });

    // Color pickers
    $('#text-color').on('change', function() {
        if (currentEditorMode === 'visual') {
            document.execCommand('foreColor', false, $(this).val());
            visualEditor.focus();
            updatePreview();
        }
    });

    $('#bg-color').on('change', function() {
        if (currentEditorMode === 'visual') {
            document.execCommand('hiliteColor', false, $(this).val());
            visualEditor.focus();
            updatePreview();
        }
    });

    // Insert Image
    $('#insert-image-btn').on('click', function() {
        var imageUrl = prompt('Enter image URL:');
        if (imageUrl) {
            if (currentEditorMode === 'visual') {
                document.execCommand('insertImage', false, imageUrl);
                visualEditor.focus();
            } else {
                insertAtCursor(htmlEditor[0], '<img src="' + imageUrl + '" alt="Image">');
                htmlEditor.focus();
            }
            updatePreview();
        }
    });

    // Execute editor commands
    function executeCommand(command, button) {
        document.execCommand(command, false, null);

        // Toggle active state for certain commands
        var toggleCommands = ['bold', 'italic', 'underline', 'strikethrough'];
        if (toggleCommands.includes(command)) {
            button.toggleClass('active');
        }

        visualEditor.focus();
        updatePreview();
    }

    // HTML Editor Functions
    $('#format-html-btn').on('click', function() {
        var html = htmlEditor.val();
        var formatted = formatHTML(html);
        htmlEditor.val(formatted);
        updatePreview();
    });

    $('#validate-html-btn').on('click', function() {
        var html = htmlEditor.val();
        var isValid = validateHTML(html);
        if (isValid) {
            showNotice('HTML is valid!', 'success');
        } else {
            showNotice('HTML contains errors. Please check your markup.', 'error');
        }
    });

    // Content change handlers
    visualEditor.on('input keyup paste', function() {
        updatePreview();
    });

    // Ensure visual editor maintains focus when clicked
    visualEditor.on('click', function() {
        $(this).focus();
    });

    htmlEditor.on('input keyup paste', function() {
        updatePreview();
    });

    // Preview Functions
    $('#refresh-preview-btn').on('click', function() {
        updatePreview();
    });

    function updatePreview() {
        // Only update preview if it's visible
        if (!$('#live-preview-section').is(':visible')) {
            return;
        }

        var content = '';

        if (currentEditorMode === 'visual') {
            content = visualEditor.html();
        } else {
            content = htmlEditor.val();
        }

        // Replace template tags with sample data
        var previewContent = content;
        for (var tag in templateTags) {
            var regex = new RegExp(escapeRegExp(tag) + '(\\|([^}]*))?', 'g');
            previewContent = previewContent.replace(regex, function(match, fallbackPart, fallback) {
                return templateTags[tag] || fallback || tag;
            });
        }

        previewArea.html(previewContent);
    }

    // Utility Functions
    function insertAtCursor(element, text) {
        if (element.setRangeText) {
            // Modern browsers
            var start = element.selectionStart;
            var end = element.selectionEnd;
            element.setRangeText(text);
            element.selectionStart = element.selectionEnd = start + text.length;
        } else if (document.selection) {
            // IE
            element.focus();
            var sel = document.selection.createRange();
            sel.text = text;
        } else if (element.contentEditable === 'true') {
            // Contenteditable elements
            var selection = window.getSelection();
            if (selection.rangeCount > 0) {
                var range = selection.getRangeAt(0);
                range.deleteContents();
                range.insertNode(document.createTextNode(text));
                range.collapse(false);
                selection.removeAllRanges();
                selection.addRange(range);
            } else {
                element.appendChild(document.createTextNode(text));
            }
        }
    }

    function formatHTML(html) {
        // Simple HTML formatting
        html = html.replace(/></g, '>\n<');
        var formatted = '';
        var indent = 0;
        var lines = html.split('\n');

        for (var i = 0; i < lines.length; i++) {
            var line = lines[i].trim();
            if (line.length === 0) continue;

            if (line.match(/^<\/\w/)) {
                indent--;
            }

            formatted += '  '.repeat(Math.max(0, indent)) + line + '\n';

            if (line.match(/^<\w[^>]*[^\/]>.*$/) && !line.match(/^<(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)/)) {
                indent++;
            }
        }

        return formatted.trim();
    }

    function validateHTML(html) {
        // Simple HTML validation
        var openTags = [];
        var tagRegex = /<\/?([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>/g;
        var match;

        while ((match = tagRegex.exec(html)) !== null) {
            var tag = match[1].toLowerCase();
            var isClosing = match[0].startsWith('</');
            var isSelfClosing = match[0].endsWith('/>') ||
                ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr'].includes(tag);

            if (isClosing) {
                if (openTags.length === 0 || openTags.pop() !== tag) {
                    return false;
                }
            } else if (!isSelfClosing) {
                openTags.push(tag);
            }
        }

        return openTags.length === 0;
    }

    function escapeRegExp(string) {
        return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }

    // Load default template content for new templates
    function loadDefaultTemplate() {
        // Only load default content if this is a new template (not editing)
        if (isEditMode || $('#template_id').val()) {
            return;
        }

        // Start with empty content for new templates
        var defaultContent = '';

        // Set empty content in both editors
        visualEditor.html(defaultContent);
        htmlEditor.val(defaultContent);

        // Set helpful placeholders for form fields
        $('#template_name').attr('placeholder', 'e.g., Monthly Newsletter Template');
    }

    // Initialize editor with default template
    loadDefaultTemplate();
    updatePreview();


    // Width Preset Buttons
    $('.width-btn').on('click', function() {
        var width = $(this).data('width');

        $('.width-btn').removeClass('active');
        $(this).addClass('active');

        $('#template_width').val(width + '%');
    });

    // Custom Width Input
    $('#template_width').on('input', function() {
        $('.width-btn').removeClass('active');
    });

    // Text Editor Toolbar
    $('.editor-btn').on('click', function() {
        var action = $(this).data('action');
        var textarea = $('#template_content')[0];

        $(this).toggleClass('active');

        // Focus textarea
        textarea.focus();

        // Handle different editor actions
        switch(action) {
            case 'bold':
                wrapSelectedText(textarea, '<strong>', '</strong>');
                break;
            case 'italic':
                wrapSelectedText(textarea, '<em>', '</em>');
                break;
            case 'underline':
                wrapSelectedText(textarea, '<u>', '</u>');
                break;
            case 'strikethrough':
                wrapSelectedText(textarea, '<s>', '</s>');
                break;
            case 'link':
                var url = prompt('Enter URL:');
                if (url) {
                    wrapSelectedText(textarea, '<a href="' + url + '">', '</a>');
                }
                break;
            case 'image':
                var imgUrl = prompt('Enter image URL:');
                if (imgUrl) {
                    insertAtCursor(textarea, '<img src="' + imgUrl + '" alt="Image">');
                }
                break;
            case 'align-left':
                wrapSelectedText(textarea, '<div style="text-align: left;">', '</div>');
                break;
            case 'align-center':
                wrapSelectedText(textarea, '<div style="text-align: center;">', '</div>');
                break;
            case 'align-right':
                wrapSelectedText(textarea, '<div style="text-align: right;">', '</div>');
                break;
            case 'list':
                wrapSelectedText(textarea, '<ul><li>', '</li></ul>');
                break;
        }
    });

    // Helper function to wrap selected text
    function wrapSelectedText(textarea, startTag, endTag) {
        var start = textarea.selectionStart;
        var end = textarea.selectionEnd;
        var selectedText = textarea.value.substring(start, end);
        var replacement = startTag + selectedText + endTag;

        textarea.value = textarea.value.substring(0, start) + replacement + textarea.value.substring(end);

        // Set cursor position after the inserted text
        var newPos = start + replacement.length;
        textarea.setSelectionRange(newPos, newPos);
    }

    // Helper function to insert text at cursor (removed duplicate - using the comprehensive version above)

    // File Upload Handlers
    $('#template_image').on('change', function() {
        var fileName = $(this).val().split('\\').pop();
        $('.image-upload-text').text(fileName || 'No File Chosen');
    });

    $('#background_image_file').on('change', function() {
        var fileName = $(this).val().split('\\').pop();
        $('.bg-image-text').text(fileName || 'No File Chosen');
    });

    // Toggle Switches
    $('#bg_color_toggle').on('change', function() {
        $('#background_color').prop('disabled', !$(this).is(':checked'));
    });

    $('#bg_image_toggle').on('change', function() {
        $('.bg-image-controls').toggle($(this).is(':checked'));
    });

    // Category Dropdown (Enhanced)
    $('#template_category').on('focus', function() {
        $('.category-options').show();
    });

    $(document).on('click', function(e) {
        if (!$(e.target).closest('.category-dropdown').length) {
            $('.category-options').hide();
        }
    });

    $('.category-option').on('click', function() {
        var value = $(this).data('value');
        var text = $(this).text().trim();

        $('#template_category').val(value);
        $('.category-options').hide();
    });

    // Save Template
    $('#save-template').on('click', function() {
        saveTemplate();
    });

    // Save Template Function
    function saveTemplate() {
        // Validate required fields
        var templateName = $('#template_name').val().trim();
        if (!templateName) {
            alert('Please enter a template name.');
            $('#template_name').focus();
            return;
        }

        // Show loading state
        $('#save-template').prop('disabled', true).text('Saving...');

        // Get content from active editor
        var templateContent = '';
        if (currentEditorMode === 'visual') {
            templateContent = visualEditor.html();
        } else {
            templateContent = htmlEditor.val();
        }

        // Add template content to form
        if (!$('#template-form input[name="template_content"]').length) {
            $('#template-form').append('<input type="hidden" name="template_content" id="template_content_hidden">');
        }
        $('#template_content_hidden').val(templateContent);

        // Prepare form data
        var formData = new FormData($('#template-form')[0]);
        formData.append('submit_template', '1');

        // Send AJAX request
        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                // Check if response contains success message
                if (response.indexOf('saved successfully') !== -1 || response.indexOf('created successfully') !== -1 || response.indexOf('updated successfully') !== -1) {
                    showNotice('Template "' + templateName + '" saved successfully!', 'success');
                    closeTemplateModal();

                    // Reload the page to show updated templates
                    setTimeout(function() {
                        window.location.reload();
                    }, 1000);
                } else if (response.indexOf('Failed to') !== -1) {
                    showNotice('Failed to save template. Please try again.', 'error');
                } else {
                    showNotice('Template saved successfully!', 'success');
                    closeTemplateModal();

                    // Reload the page to show updated templates
                    setTimeout(function() {
                        window.location.reload();
                    }, 1000);
                }
            },
            error: function(xhr, status, error) {
                console.error('Save error:', error);
                showNotice('Error saving template. Please try again.', 'error');
            },
            complete: function() {
                // Reset button state
                $('#save-template').prop('disabled', false).text('Save');
            }
        });
    }

    // Bind Template Actions (for dynamically added rows)
    function bindTemplateActions() {
        $('.edit-template').off('click').on('click', function(e) {
            e.preventDefault();
            var templateId = $(this).data('id');
            openTemplateModal('edit', templateId);
        });

        $('.delete-template').off('click').on('click', function(e) {
            e.preventDefault();
            var templateId = $(this).data('id');
            if (confirm('Are you sure you want to delete this template? This action cannot be undone.')) {
                deleteTemplate(templateId);
            }
        });
    }

    // Keyboard shortcuts
    $(document).on('keydown', function(e) {
        // ESC key to close modal
        if (e.keyCode === 27 && templateModal.is(':visible')) {
            closeTemplateModal();
        }

        // Ctrl+S to save (when modal is open)
        if (e.ctrlKey && e.keyCode === 83 && templateModal.is(':visible')) {
            e.preventDefault();
            saveTemplate();
        }
    });

    // Prevent body scroll when modal is open
    $('body').on('modal-open', function() {
        $('body').css('overflow', 'hidden');
    });

    $('body').on('modal-close', function() {
        $('body').css('overflow', 'auto');
    });

    // Initialize tooltips (if needed)
    $('.editor-btn').each(function() {
        var action = $(this).data('action');
        var tooltip = getTooltipText(action);
        if (tooltip) {
            $(this).attr('title', tooltip);
        }
    });

    // Get tooltip text for editor buttons
    function getTooltipText(action) {
        var tooltips = {
            'bold': 'Bold (Ctrl+B)',
            'italic': 'Italic (Ctrl+I)',
            'underline': 'Underline (Ctrl+U)',
            'strikethrough': 'Strikethrough',
            'link': 'Insert Link',
            'image': 'Insert Image',
            'align-left': 'Align Left',
            'align-center': 'Align Center',
            'align-right': 'Align Right',
            'list': 'Insert List'
        };

        return tooltips[action] || '';
    }
});
</script>
