<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL,WordPress.NamingConventions.PrefixAllGlobals -- Template variables and plugin-owned tables are intentionally local to this partial.
/**
 * Newsletter Tab Content
 *
 * Manage newsletter campaigns with complete campaign creation system
 */

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

// Handle campaign creation/editing
if (isset($_POST['submit_newsletter_campaign'])) {
    // Verify nonce before processing form data
    if (!isset($_POST['campaign_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['campaign_nonce'])), 'save_newsletter_campaign')) {
        return;
    }

    // Process campaign data
    $instant_popup_builder_campaign_data = [
        'name' => isset($_POST['campaign_name']) ? sanitize_text_field(wp_unslash($_POST['campaign_name'])) : '',
        'campaign_associations' => isset($_POST['campaign_associations']) ? array_map('intval', $_POST['campaign_associations']) : [],
        'sender_name' => isset($_POST['sender_name']) ? sanitize_text_field(wp_unslash($_POST['sender_name'])) : '',
        'sender_email' => isset($_POST['sender_email']) ? sanitize_email(wp_unslash($_POST['sender_email'])) : '',
        'subject_line' => isset($_POST['subject_line']) ? sanitize_text_field(wp_unslash($_POST['subject_line'])) : '',
        'template_id' => isset($_POST['template_id']) ? intval($_POST['template_id']) : 0,
        'template_content' => isset($_POST['template_content']) ? sanitize_textarea_field(wp_unslash($_POST['template_content'])) : '',
        'status' => isset($_POST['campaign_status']) ? sanitize_text_field(wp_unslash($_POST['campaign_status'])) : '',
        'created_at' => current_time('mysql'),
        'updated_at' => current_time('mysql')
    ];

        // Validate required fields
        $instant_popup_builder_errors = [];
        if (empty($instant_popup_builder_campaign_data['name'])) {
            $instant_popup_builder_errors[] = 'Campaign name is required.';
        }
        if (empty($instant_popup_builder_campaign_data['campaign_associations'])) {
            $instant_popup_builder_errors[] = 'At least one campaign association is required.';
        }
        if (empty($instant_popup_builder_campaign_data['sender_name'])) {
            $instant_popup_builder_errors[] = 'Sender name is required.';
        }
        if (empty($instant_popup_builder_campaign_data['sender_email']) || !is_email($instant_popup_builder_campaign_data['sender_email'])) {
            $instant_popup_builder_errors[] = 'Valid sender email is required.';
        }
        if (empty($instant_popup_builder_campaign_data['subject_line'])) {
            $instant_popup_builder_errors[] = 'Subject line is required.';
        }

        if (!empty($instant_popup_builder_errors)) {
            $error_message = implode('<br>', is_array($instant_popup_builder_errors) ? $instant_popup_builder_errors : []);
            $error_message = is_string($error_message) ? $error_message : '';
            echo '<div class="notice notice-error"><p>' . wp_kses_post($error_message) . '</p></div>';
        } else {
            // Save campaign to database
            global $wpdb;
            $instant_popup_builder_campaigns_table = $wpdb->prefix . 'instant_popup_newsletter_campaigns';

            $instant_popup_builder_campaign_id = isset($_POST['campaign_id']) ? intval($_POST['campaign_id']) : 0;

            if ($instant_popup_builder_campaign_id > 0) {
                // Update existing campaign
                $instant_popup_builder_result = $wpdb->update(
                    $instant_popup_builder_campaigns_table,
                    [
                        'name' => $instant_popup_builder_campaign_data['name'],
                        'campaign_associations' => json_encode($instant_popup_builder_campaign_data['campaign_associations']),
                        'sender_name' => $instant_popup_builder_campaign_data['sender_name'],
                        'sender_email' => $instant_popup_builder_campaign_data['sender_email'],
                        'subject_line' => $instant_popup_builder_campaign_data['subject_line'],
                        'template_id' => $instant_popup_builder_campaign_data['template_id'],
                        'template_content' => $instant_popup_builder_campaign_data['template_content'],
                        'status' => $instant_popup_builder_campaign_data['status'],
                        'updated_at' => $instant_popup_builder_campaign_data['updated_at']
                    ],
                    ['id' => $instant_popup_builder_campaign_id],
                    ['%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s'],
                    ['%d']
                );

                if ($instant_popup_builder_result !== false) {
                    echo '<div class="notice notice-success"><p>Campaign "' . esc_html($instant_popup_builder_campaign_data['name']) . '" updated successfully!</p></div>';
                } else {
                    echo '<div class="notice notice-error"><p>Failed to update campaign. Please try again.</p></div>';
                }
            } else {
                // Create new campaign
                $instant_popup_builder_result = $wpdb->insert(
                    $instant_popup_builder_campaigns_table,
                    [
                        'name' => $instant_popup_builder_campaign_data['name'],
                        'campaign_associations' => json_encode($instant_popup_builder_campaign_data['campaign_associations']),
                        'sender_name' => $instant_popup_builder_campaign_data['sender_name'],
                        'sender_email' => $instant_popup_builder_campaign_data['sender_email'],
                        'subject_line' => $instant_popup_builder_campaign_data['subject_line'],
                        'template_id' => $instant_popup_builder_campaign_data['template_id'],
                        'template_content' => $instant_popup_builder_campaign_data['template_content'],
                        'status' => $instant_popup_builder_campaign_data['status'],
                        'created_by' => get_current_user_id(),
                        'created_at' => $instant_popup_builder_campaign_data['created_at'],
                        'updated_at' => $instant_popup_builder_campaign_data['updated_at']
                    ],
                    ['%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%d', '%s', '%s']
                );

                if ($instant_popup_builder_result) {
                    echo '<div class="notice notice-success"><p>Campaign "' . esc_html($instant_popup_builder_campaign_data['name']) . '" created successfully!</p></div>';
                } else {
                    $instant_popup_builder_db_error = $wpdb->last_error;
                    echo '<div class="notice notice-error"><p>Failed to create campaign. Database error: ' . esc_html($instant_popup_builder_db_error) . '</p></div>';
                }
            }
        }
}

// Handle campaign deletion
if (isset($_GET['delete_campaign']) && isset($_GET['nc_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nc_nonce'])), 'delete_newsletter_campaign')) {
    $instant_popup_builder_delete_id = intval($_GET['delete_campaign']);
    global $wpdb;
    $instant_popup_builder_campaigns_table = $wpdb->prefix . 'instant_popup_newsletter_campaigns';

    $instant_popup_builder_result = $wpdb->delete($instant_popup_builder_campaigns_table, ['id' => $instant_popup_builder_delete_id], ['%d']);

    if ($instant_popup_builder_result) {
        echo '<div class="notice notice-success"><p>Campaign deleted successfully!</p></div>';
    } else {
        echo '<div class="notice notice-error"><p>Failed to delete campaign.</p></div>';
    }
}

// Fetch existing newsletter campaigns
global $wpdb;
$instant_popup_builder_campaigns_table = $wpdb->prefix . 'instant_popup_newsletter_campaigns';

// Handle edit campaign parameter
$instant_popup_builder_editing_campaign = null;
$instant_popup_builder_edit_campaign_id = isset($_GET['edit_campaign']) ? intval($_GET['edit_campaign']) : 0;

if ($instant_popup_builder_edit_campaign_id > 0) {
    $instant_popup_builder_escaped_campaigns_table = esc_sql($instant_popup_builder_campaigns_table);
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $instant_popup_builder_editing_campaign = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM `{$instant_popup_builder_escaped_campaigns_table}` WHERE id = %d",
        $instant_popup_builder_edit_campaign_id
    ), ARRAY_A);

    if (!$instant_popup_builder_editing_campaign) {
        echo '<div class="notice notice-error"><p>Campaign not found.</p></div>';
        $instant_popup_builder_edit_campaign_id = 0;
    }
}

$instant_popup_builder_escaped_campaigns_table = esc_sql($instant_popup_builder_campaigns_table);
$instant_popup_builder_escaped_users_table = esc_sql($wpdb->users);
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$instant_popup_builder_newsletter_campaigns = $wpdb->get_results("
    SELECT nc.*, u.display_name as created_by_name
    FROM `{$instant_popup_builder_escaped_campaigns_table}` nc
    LEFT JOIN `{$instant_popup_builder_escaped_users_table}` u ON nc.created_by = u.ID
    WHERE nc.status != 'deleted'
    ORDER BY nc.created_at DESC
", ARRAY_A);

// Fetch available subscription campaigns for associations (same as subscriber system)
$instant_popup_builder_table_popup = $wpdb->prefix . 'instant_popup_builder';
$instant_popup_builder_escaped_table_popup = esc_sql($instant_popup_builder_table_popup);
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$instant_popup_builder_campaigns = $wpdb->get_results($wpdb->prepare("SELECT id, title FROM `{$instant_popup_builder_escaped_table_popup}` WHERE type = %s", 'subscription'));

// Ensure templates table exists and fetch available email templates (same as Templates tab)
$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.name ASC
", 'active');
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query is prepared immediately above with a fixed placeholder.
$instant_popup_builder_templates = $wpdb->get_results($instant_popup_builder_templates_query, ARRAY_A);
?>

<div class="newsletter-tab-content">
    <!-- Newsletter Campaigns Section -->
    <div class="newsletter-section">
        <div class="section-header">
            <div class="section-title">
                <h3>Newsletter Campaigns</h3>
                <p>Create and manage newsletter campaigns with advanced template editing and popup associations.</p>
            </div>
            <div class="section-actions">
                <button type="button" class="hover-button button button-primary" id="create-new-campaign">
                   <span> <span class="dashicons dashicons-plus-alt" style="margin-top: 6px;"></span>
                    Create Campaign </span>
                </button>
            </div>
        </div>

        <div class="campaigns-table-container">
            <table class="wp-list-table widefat fixed striped campaigns-table">
                <thead>
                    <tr>
                        <th scope="col" class="column-id">ID</th>
                        <th scope="col" class="column-name">Campaign Name</th>
                        <th scope="col" class="column-associations">Campaign Associations</th>
                        <th scope="col" class="column-subject">Subject Line</th>
                        <th scope="col" class="column-status">Status</th>
                        <th scope="col" class="column-subscribers">Subscribers</th>
                        <th scope="col" class="column-created">Created</th>
                        <th scope="col" class="column-actions">Actions</th>
                    </tr>
                </thead>
                <tbody>

                    <tr>
                        <td colspan="8" class="no-campaigns">
                            <div class="no-campaigns-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>

</div>

<!-- Create/Edit Campaign Modal -->
<div id="create-campaign-modal" class="campaign-modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modal-title">Create New Campaign</h3>
            <button type="button" class="close-modal">&times;</button>
        </div>
        <div class="modal-body">
            <form method="post" action="" class="campaign-form" id="campaign-form">
                <?php wp_nonce_field('save_newsletter_campaign', 'campaign_nonce'); ?>
                <input type="hidden" id="campaign_id" name="campaign_id" value="">

                <div class="form-sections">
                    <!-- Basic Information Section -->
                    <div class="form-section">
                        <div class="section-header">
                            <h4><span class="dashicons dashicons-admin-generic"></span> Basic Information</h4>
                            <p>Set up the basic details for your newsletter campaign</p>
                        </div>

                        <div class="form-grid">
                            <div class="form-group">
                                <label for="campaign_name">Campaign Name <span class="required">*</span></label>
                                <input type="text" id="campaign_name" name="campaign_name"
                                       placeholder="Enter campaign name" required class="form-input">
                                <div class="field-help">Choose a descriptive name for your campaign</div>
                            </div>

                            <div class="form-group">
                                <label for="campaign_status">Status</label>
                                <select id="campaign_status" name="campaign_status" class="form-select">
                                    <option value="draft">Draft</option>
                                    <option value="active">Active</option>
                                    <option value="paused">Paused</option>
                                    <option value="scheduled">Scheduled</option>
                                </select>
                                <div class="field-help">Set the campaign status</div>
                            </div>
                        </div>
                    </div>

                    <!-- Campaign Associations Section -->
                    <div class="form-section">
                        <div class="section-header">
                            <h4><span class="dashicons dashicons-admin-links"></span> Campaign Associations</h4>
                            <p>Select which subscription campaigns this newsletter will be associated with</p>
                        </div>

                        <div class="form-group full-width">
                            <label for="campaign_associations">Associated Campaigns <span class="required">*</span></label>
                            <select id="campaign_associations" name="campaign_associations[]" multiple required class="ipb_form_select" style="height: 120px;">
                                <?php
                                if (!empty($instant_popup_builder_campaigns)) {
                                    foreach ($instant_popup_builder_campaigns as $instant_popup_builder_campaign) {
                                        echo '<option value="' . esc_attr($instant_popup_builder_campaign->id ?? '') . '">';
                                        echo esc_html($instant_popup_builder_campaign->title ?? '') . ' (ID: ' . esc_html($instant_popup_builder_campaign->id ?? '') . ')';
                                        echo '</option>';
                                    }
                                } else {
                                    echo '<option value="" disabled>No subscription campaigns found. Please create a subscription popup first.</option>';
                                }
                                ?>
                            </select>
                            <div class="field-help">
                                Select one or more subscription campaigns to associate with this newsletter.
                                <?php if (!empty($instant_popup_builder_campaigns)): ?>
                                    <strong>Found <?php echo count($instant_popup_builder_campaigns); ?> subscription campaign(s) available:</strong>
                                    <ul style="margin-top: 5px; padding-left: 20px;">
                                        <?php foreach (array_slice($instant_popup_builder_campaigns, 0, 3) as $instant_popup_builder_campaign): ?>
                                            <li><?php echo esc_html($instant_popup_builder_campaign->title ?? ''); ?> (ID: <?php echo esc_html($instant_popup_builder_campaign->id ?? ''); ?>)</li>
                                        <?php endforeach; ?>
                                        <?php if (count($instant_popup_builder_campaigns) > 3): ?>
                                            <li><em>... and <?php echo count($instant_popup_builder_campaigns) - 3; ?> more</em></li>
                                        <?php endif; ?>
                                    </ul>
                                <?php else: ?>
                                    <strong style="color: #d63638;">No subscription campaigns found!</strong> You need to create at least one subscription popup first.
                                <?php endif; ?>
                            </div>
                            <div class="campaigns-actions">
                                <a href="<?php echo esc_url(admin_url('admin.php?page=instant-popup-builder')); ?>" target="_blank" class="button">
                                    <span class="dashicons dashicons-plus-alt"></span> Create New Popup
                                </a>
                                <?php if (empty($instant_popup_builder_campaigns)): ?>
                                    <p class="field-help error-text">
                                        <strong>No subscription campaigns found!</strong> You need to create at least one subscription popup before creating newsletter campaigns.
                                    </p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Sender Details Section -->
                    <div class="form-section">
                        <div class="section-header">
                            <h4><span class="dashicons dashicons-email-alt"></span> Sender Details</h4>
                            <p>Configure who the email appears to be from</p>
                        </div>

                        <div class="form-grid">
                            <div class="form-group">
                                <label for="sender_name">Sender Name <span class="required">*</span></label>
                                <input type="text" id="sender_name" name="sender_name"
                                       placeholder="Your Name or Company" required class="form-input">
                                <div class="field-help">Name that appears in the "From" field</div>
                            </div>

                            <div class="form-group">
                                <label for="sender_email">Sender Email <span class="required">*</span></label>
                                <input type="email" id="sender_email" name="sender_email"
                                       placeholder="noreply@yourdomain.com" required class="form-input">
                                <div class="field-help">Email address that appears in the "From" field</div>
                            </div>
                        </div>
                    </div>

                    <!-- Email Content Section -->
                    <div class="form-section">
                        <div class="section-header">
                            <h4><span class="dashicons dashicons-edit"></span> Email Content</h4>
                            <p>Configure the subject line and email template</p>
                        </div>

                        <div class="form-group full-width">
                            <label for="subject_line">Subject Line <span class="required">*</span></label>
                            <input type="text" id="subject_line" name="subject_line"
                                   placeholder="Enter compelling subject line" required class="form-input">
                            <div class="field-help">Keep it concise and engaging to improve open rates</div>
                        </div>

                        <div class="form-group full-width">
                            <label for="template_id">Email Template</label>
                            <select id="template_id" name="template_id" class="form-select">
                                <option value="0">Select a template (optional)</option>
                                <?php foreach ($instant_popup_builder_templates as $instant_popup_builder_template): ?>
                                    <option value="<?php echo esc_attr($instant_popup_builder_template['id']); ?>"
                                            data-content="<?php echo esc_attr($instant_popup_builder_template['content']); ?>">
                                        <?php echo esc_html($instant_popup_builder_template['name']); ?>
                                        (<?php echo esc_html(ucfirst($instant_popup_builder_template['category'])); ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="field-help">Choose a base template to start with (optional)</div>
                        </div>

                        <div class="form-group full-width">
                            <label for="template_content">Email Content</label>
                            <div class="editor-container">
                                <div class="editor-toolbar">
                                    <button type="button" class="editor-btn" data-command="bold" title="Bold">
                                        <strong>B</strong>
                                    </button>
                                    <button type="button" class="editor-btn" data-command="italic" title="Italic">
                                        <em>I</em>
                                    </button>
                                    <button type="button" class="editor-btn" data-command="underline" title="Underline">
                                        <u>U</u>
                                    </button>
                                    <button type="button" class="editor-btn" data-command="createLink" title="Link">
                                        🔗
                                    </button>
                                    <button type="button" class="editor-btn" data-command="insertUnorderedList" title="Bullet List">
                                        • List
                                    </button>
                                    <button type="button" class="editor-btn" data-command="insertOrderedList" title="Numbered List">
                                        1. List
                                    </button>
                                    <button type="button" class="editor-btn" data-command="justifyLeft" title="Align Left">
                                        ⬅
                                    </button>
                                    <button type="button" class="editor-btn" data-command="justifyCenter" title="Center">
                                        ⬌
                                    </button>
                                    <button type="button" class="editor-btn" data-command="justifyRight" title="Align Right">
                                        ➡
                                    </button>
                                </div>
                                <div id="template_content_editor" class="template-editor" contenteditable="true">
                                    <p>Start writing your newsletter content here...</p>
                                    <p>You can use the toolbar above to format your text, add links, and create lists.</p>
                                    <p><strong>Tip:</strong> Use engaging content to keep your subscribers interested!</p>
                                </div>
                                <textarea id="template_content" name="template_content" style="display: none;"></textarea>
                            </div>
                            <div class="field-help">
                                Create your email content using the rich text editor.
                                Changes made here are saved specifically for this campaign and won't affect the original template.
                            </div>
                        </div>
                    </div>

                    <!-- Scheduling Section -->
                    <div class="form-section">
                        <div class="section-header">
                            <h4><span class="dashicons dashicons-calendar-alt"></span> Campaign Scheduling</h4>
                            <p>Choose when to send this campaign</p>
                        </div>

                        <div class="form-group full-width">
                            <label class="scheduling-options">
                                <input type="radio" name="send_type" value="now" checked>
                                <span class="radio-label">
                                    <strong>Send Immediately</strong>
                                    <small>Campaign will be sent as soon as it's created</small>
                                </span>
                            </label>

                            <label class="scheduling-options">
                                <input type="radio" name="send_type" value="draft">
                                <span class="radio-label">
                                    <strong>Save as Draft</strong>
                                    <small>Save campaign without sending, send manually later</small>
                                </span>
                            </label>

                            <label class="scheduling-options">
                                <input type="radio" name="send_type" value="scheduled">
                                <span class="radio-label">
                                    <strong>Schedule for Later</strong>
                                    <small>Choose a specific date and time to send</small>
                                </span>
                            </label>
                        </div>

                        <div id="scheduling-details" class="form-group full-width" style="display: none;">
                            <div class="form-grid">
                                <div class="form-group">
                                    <label for="scheduled_date">Send Date <span class="required">*</span></label>
                                    <input type="date" id="scheduled_date" name="scheduled_date"
                                           min="<?php echo esc_attr(gmdate('Y-m-d')); ?>" class="form-input">
                                    <div class="field-help">Date when the campaign should be sent</div>
                                </div>

                                <div class="form-group">
                                    <label for="scheduled_time">Send Time <span class="required">*</span></label>
                                    <input type="time" id="scheduled_time" name="scheduled_time"
                                           value="09:00" class="form-input">
                                    <div class="field-help">Time when the campaign should be sent</div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="timezone_info">Timezone Information</label>
                                <div class="timezone-display">
                                    <span class="dashicons dashicons-clock"></span>
                                    <span id="timezone-text">
                                        <?php
                                        $instant_popup_builder_timezone = get_option('timezone_string') ?: 'UTC';
                                        $instant_popup_builder_current_time = new DateTime('now', new DateTimeZone($instant_popup_builder_timezone));
                                        echo esc_html('Current time: ' . $instant_popup_builder_current_time->format('Y-m-d H:i:s') . ' (' . $instant_popup_builder_timezone . ')');
                                        ?>
                                    </span>
                                </div>
                                <div class="field-help">
                                    Scheduled time will be based on your WordPress timezone setting.
                                    <a href="<?php echo esc_url(admin_url('options-general.php')); ?>" target="_blank">Change timezone</a>
                                </div>
                            </div>

                            <div class="scheduling-preview" id="scheduling-preview" style="display: none;">
                                <div class="preview-box">
                                    <span class="dashicons dashicons-info"></span>
                                    <div class="preview-content">
                                        <strong>Campaign will be sent:</strong>
                                        <div id="preview-datetime"></div>
                                        <div id="preview-relative"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" name="submit_newsletter_campaign" class="button button-primary">
                        <span class="dashicons dashicons-yes"></span>
                        <span class="button-text">Create Campaign</span>
                    </button>
                    <button type="button" class="button cancel-modal">
                        <span class="dashicons dashicons-no"></span>
                        Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

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

.newsletter-section {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
}

.newsletter-section h3 {
    margin-top: 0;
    margin-bottom: 15px;
    font-size: 16px;
    font-weight: 600;
    color: #23282d;
    border-bottom: 1px solid #e1e1e1;
    padding-bottom: 10px;
}

/* Enhanced table columns */
.column-id { width: 50px; }
.column-name { width: 200px; }
.column-associations { width: 150px; }
.column-subject { width: 180px; }
.column-status { width: 80px; }
.column-subscribers { width: 100px; }
.column-created { width: 100px; }
.column-actions { width: 140px; }

/* Campaign meta information */
.campaign-meta {
    font-size: 12px;
    color: #666;
    margin-top: 4px;
}

.sender-info {
    font-style: italic;
}

.campaign-stats {
    font-size: 11px;
    color: #666;
    margin-top: 2px;
}

.subject-preview {
    display: block;
    max-width: 180px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.no-associations {
    color: #d63638;
    font-style: italic;
    font-size: 12px;
}

.last-sent {
    font-size: 11px;
    color: #666;
    margin-top: 2px;
}

/* Section Header */
.section-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
}

.section-title h3 {
    margin: 0 0 5px 0;
    border: none;
    padding: 0;
}

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

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

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

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

/* Campaigns Table */
.campaigns-table-container {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    margin-bottom: 20px;
}

.campaigns-table {
    border: none;
    border-radius: 4px;
}

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

.campaigns-table td {
    vertical-align: middle;
}

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

.status-active {
    background: #e8f5e8;
    color: #388e3c;
}

.status-draft {
    background: #fff3e0;
    color: #f57c00;
}

.status-scheduled {
    background: #e3f2fd;
    color: #1976d2;
}

.status-paused {
    background: #fce4ec;
    color: #c2185b;
}

/* Campaign Actions */
.campaign-actions {
    display: flex;
    gap: 5px;
}

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

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

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

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

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

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

/* Form Elements */
.large-text {
    width: 100%;
    max-width: 500px;
}

.regular-text {
    width: 300px;
}

/* Responsive Design */
@media (max-width: 768px) {
    .newsletter-section {
        padding: 15px;
    }

    .section-header {
        flex-direction: column;
        gap: 15px;
        align-items: stretch;
    }

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

    .campaigns-table-container {
        overflow-x: auto;
    }

    .campaigns-table {
        min-width: 700px;
    }

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



    .large-text,
    .regular-text {
        width: 100%;
        max-width: 100%;
    }
}

/* Campaign Modal Styles */
.campaign-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    z-index: 9999;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(2px);
}

.campaign-modal .modal-content {
    background: #fff;
    border-radius: 8px;
    max-width: 900px;
    width: 95%;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.campaign-modal .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 25px;
    border-bottom: 1px solid #e1e1e1;
    background: linear-gradient(135deg, #f8f9fa, #e9ecef);
}

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

.campaign-modal .close-modal {
    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;
}

.campaign-modal .close-modal:hover {
    background: rgba(220, 53, 69, 0.1);
    color: #dc3545;
}

.campaign-modal .modal-body {
    padding: 25px;
}

/* Form Sections */
.form-sections {
    display: flex;
    flex-direction: column;
    gap: 25px;
}

.form-section {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 20px;
    transition: all 0.3s ease;
}

.form-section:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-section .section-header {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 2px solid #e9ecef;
}

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

.form-section .section-header .dashicons {
    color: #2271b1;
    font-size: 18px;
}

.form-section .section-header p {
    margin: 0;
    color: #666;
    font-size: 14px;
}

/* Form Grid */
.form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.form-group.full-width {
    grid-column: 1 / -1;
}

.form-group label {
    font-weight: 600;
    color: #23282d;
    font-size: 14px;
}

.form-group .required {
    color: #d63638;
    margin-left: 2px;
}

.form-input,
.form-select {
    padding: 12px;
    border: 1px solid #8c8f94;
    border-radius: 6px;
    font-size: 14px;
    transition: all 0.3s ease;
    background: #fff;
}

.form-input:focus,
.form-select:focus {
    border-color: #2271b1;
    box-shadow: 0 0 0 2px rgba(34, 113, 177, 0.1);
    outline: none;
}

.field-help {
    font-size: 12px;
    color: #666;
    font-style: italic;
    line-height: 1.4;
}

.field-help.error-text {
    color: #d63638;
    font-weight: 500;
}

/* Campaign Select2 Styling */
.ipb-campaign-select2 {
    width: 100% !important;
}

.campaigns-actions {
    display: flex;
    gap: 10px;
    margin-top: 12px;
    align-items: center;
}

.campaigns-actions .button {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    font-size: 12px;
    padding: 6px 12px;
}

.campaigns-actions .dashicons {
    font-size: 14px;
    width: 14px;
    height: 14px;
}

/* Rich Text Editor */
.editor-container {
    border: 1px solid #8c8f94;
    border-radius: 6px;
    background: #fff;
    overflow: hidden;
}

.editor-toolbar {
    display: flex;
    gap: 2px;
    padding: 8px;
    background: #f8f9fa;
    border-bottom: 1px solid #e9ecef;
    flex-wrap: wrap;
}

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

.editor-btn:hover {
    background: #f0f0f1;
    border-color: #8c8f94;
}

.editor-btn:active,
.editor-btn.active {
    background: #2271b1;
    color: #fff;
    border-color: #2271b1;
}

.template-editor {
    min-height: 300px;
    padding: 15px;
    font-family: Arial, sans-serif;
    font-size: 14px;
    line-height: 1.6;
    color: #23282d;
    outline: none;
    overflow-y: auto;
    max-height: 400px;
}

.template-editor:focus {
    background: #fafafa;
}

.template-editor p {
    margin: 0 0 12px 0;
}

.template-editor p:last-child {
    margin-bottom: 0;
}

/* Scheduling Section Styles */
.scheduling-options {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 15px;
    border: 2px solid #e1e1e1;
    border-radius: 8px;
    margin-bottom: 15px;
    cursor: pointer;
    transition: all 0.3s ease;
    background: #fafafa;
}

.scheduling-options:hover {
    border-color: #2271b1;
    background: #f0f6fc;
}

.scheduling-options input[type="radio"] {
    margin: 0;
    margin-top: 2px;
}

.scheduling-options input[type="radio"]:checked + .radio-label {
    color: #2271b1;
}

.scheduling-options.selected {
    border-color: #2271b1;
    background: #f0f6fc;
    box-shadow: 0 0 0 1px #2271b1;
}

.radio-label {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.radio-label strong {
    font-size: 14px;
    font-weight: 600;
    color: #23282d;
}

.radio-label small {
    font-size: 12px;
    color: #666;
    line-height: 1.4;
}

.timezone-display {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 15px;
    background: #f8f9fa;
    border: 1px solid #e1e1e1;
    border-radius: 6px;
    font-family: monospace;
    font-size: 13px;
    color: #23282d;
}

.timezone-display .dashicons {
    color: #2271b1;
    font-size: 16px;
}

.scheduling-preview {
    margin-top: 15px;
}

.preview-box {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    padding: 15px;
    background: linear-gradient(135deg, #e8f4f8, #f0f8ff);
    border: 1px solid #2271b1;
    border-radius: 8px;
    color: #1e5a8a;
}

.preview-box .dashicons {
    color: #2271b1;
    font-size: 18px;
    margin-top: 2px;
}

.preview-content {
    flex: 1;
}

.preview-content strong {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
}

.preview-content div {
    font-size: 13px;
    margin-bottom: 4px;
}

#preview-datetime {
    font-weight: 600;
    font-size: 14px;
}

#preview-relative {
    color: #666;
    font-style: italic;
}

/* Form Actions */
.form-actions {
    display: flex;
    gap: 15px;
    justify-content: flex-end;
    padding-top: 25px;
    border-top: 1px solid #e1e1e1;
    margin-top: 25px;
}

.form-actions .button {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 20px;
    font-size: 14px;
    font-weight: 500;
    border-radius: 6px;
    transition: all 0.3s ease;
}

.form-actions .button-primary {
    background: linear-gradient(135deg, #2271b1, #1e5a8a);
    border: none;
    color: #fff;
    box-shadow: 0 2px 4px rgba(34, 113, 177, 0.3);
}

.form-actions .button-primary:hover {
    background: linear-gradient(135deg, #1e5a8a, #2271b1);
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(34, 113, 177, 0.4);
}

.form-actions .button:not(.button-primary) {
    background: #f6f7f7;
    border: 1px solid #dcdcde;
    color: #3c434a;
}

.form-actions .button:not(.button-primary):hover {
    background: #f0f0f1;
    border-color: #8c8f94;
}

/* Modal Responsive Design */
@media (max-width: 768px) {
    .campaign-modal .modal-content {
        width: 95%;
        margin: 10px;
        max-height: 95vh;
    }

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

    .form-grid {
        grid-template-columns: 1fr;
        gap: 15px;
    }

    .form-actions {
        flex-direction: column;
    }

    .form-actions .button {
        justify-content: center;
    }

    .editor-toolbar {
        gap: 1px;
    }

    .editor-btn {
        padding: 4px 6px;
        font-size: 11px;
        min-width: 26px;
    }
}

/* Send Campaign Modal Styles */
.send-campaign-info {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 25px;
    border-left: 4px solid #2271b1;
}

.send-campaign-info h3 {
    margin: 0 0 10px 0;
    color: #23282d;
    font-size: 18px;
}

.send-campaign-info p {
    margin: 0;
    color: #666;
}

.send-options {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.send-option {
    background: #fff;
    border: 2px solid #e9ecef;
    border-radius: 8px;
    padding: 20px;
    transition: all 0.3s ease;
}

.send-option:hover {
    border-color: #2271b1;
    box-shadow: 0 2px 8px rgba(34, 113, 177, 0.1);
}

.send-option h4 {
    margin: 0 0 10px 0;
    color: #23282d;
    font-size: 16px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 8px;
}

.send-option h4 .dashicons {
    color: #2271b1;
    font-size: 18px;
}

.send-option p {
    margin: 0 0 15px 0;
    color: #666;
    line-height: 1.5;
}

.test-email-form,
.send-all-form {
    display: flex;
    gap: 12px;
    align-items: center;
}

.test-email-form input[type="email"] {
    flex: 1;
    min-width: 250px;
}

.modal-footer {
    padding: 20px 25px;
    border-top: 1px solid #e1e1e1;
    display: flex;
    justify-content: flex-end;
}

.close-send-modal {
    position: absolute;
    top: 15px;
    right: 20px;
    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;
}

.close-send-modal:hover {
    background: rgba(220, 53, 69, 0.1);
    color: #dc3545;
}

/* Send Modal Responsive */
@media (max-width: 768px) {
    .test-email-form,
    .send-all-form {
        flex-direction: column;
        align-items: stretch;
    }

    .test-email-form input[type="email"] {
        min-width: auto;
        margin-bottom: 10px;
    }
}
</style>

<!-- Send Campaign Modal -->
<div id="send-campaign-modal" class="campaign-modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h2>Send Campaign</h2>
            <span class="close-send-modal">&times;</span>
        </div>

        <div class="modal-body">
            <div class="send-campaign-info">
                <h3>Campaign: <span id="send-campaign-name"></span></h3>
                <p>Choose how you want to send this campaign:</p>
            </div>

            <div class="send-options">
                <div class="send-option">
                    <h4><span class="dashicons dashicons-email-alt"></span> Send Test Email</h4>
                    <p>Send a test email to verify everything looks correct before sending to all subscribers.</p>
                    <div class="test-email-form">
                        <input type="email" id="test-email-address" placeholder="Enter test email address" class="form-input" />
                        <button type="button" id="send-test-email" class="button button-secondary">
                            <span class="dashicons dashicons-email-alt"></span>
                            Send Test
                        </button>
                    </div>
                </div>

                <div class="send-option">
                    <h4><span class="dashicons dashicons-groups"></span> Send to All Subscribers</h4>
                    <p>Send this campaign to all active subscribers associated with the selected popups.</p>
                    <div class="send-all-form">
                        <button type="button" id="send-campaign-all" class="button button-primary">
                            <span class="dashicons dashicons-email-alt"></span>
                            Send Campaign
                        </button>
                    </div>
                </div>
            </div>

            <input type="hidden" id="send-campaign-id" value="" />
        </div>

        <div class="modal-footer">
            <button type="button" class="button cancel-send-modal">Cancel</button>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Simple multiselect functionality - no Select2 needed
    function initializeCampaignSelect() {
        // Add help text for multiselect
        $('#campaign_associations').after('<p class="description">Hold Ctrl (Cmd on Mac) to select multiple campaigns</p>');
    }

    // Scheduling functionality
    function initializeScheduling() {
        // Handle scheduling option changes
        $('input[name="send_type"]').on('change', function() {
            var selectedValue = $(this).val();
            var schedulingDetails = $('#scheduling-details');
            var schedulingPreview = $('#scheduling-preview');

            // Update visual selection
            $('.scheduling-options').removeClass('selected');
            $(this).closest('.scheduling-options').addClass('selected');

            if (selectedValue === 'scheduled') {
                schedulingDetails.slideDown(300);
                updateSchedulingPreview();
            } else {
                schedulingDetails.slideUp(300);
                schedulingPreview.hide();
            }

            // Update button text based on selection
            var buttonText = $('.button-text');
            switch(selectedValue) {
                case 'now':
                    buttonText.text('Create & Send Campaign');
                    break;
                case 'draft':
                    buttonText.text('Save as Draft');
                    break;
                case 'scheduled':
                    buttonText.text('Schedule Campaign');
                    break;
            }
        });

        // Handle date/time changes for preview
        $('#scheduled_date, #scheduled_time').on('change', function() {
            updateSchedulingPreview();
        });

        // Set initial state
        $('.scheduling-options').first().addClass('selected');
    }

    function updateSchedulingPreview() {
        var date = $('#scheduled_date').val();
        var time = $('#scheduled_time').val();
        var preview = $('#scheduling-preview');
        var previewDateTime = $('#preview-datetime');
        var previewRelative = $('#preview-relative');

        if (date && time) {
            // Create datetime object
            var scheduledDateTime = new Date(date + 'T' + time);
            var now = new Date();

            // Format the datetime
            var options = {
                weekday: 'long',
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            };
            var formattedDateTime = scheduledDateTime.toLocaleDateString('en-US', options);

            // Calculate relative time
            var timeDiff = scheduledDateTime.getTime() - now.getTime();
            var relativeText = '';

            if (timeDiff > 0) {
                var days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
                var hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                var minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));

                if (days > 0) {
                    relativeText = `in ${days} day${days > 1 ? 's' : ''} and ${hours} hour${hours > 1 ? 's' : ''}`;
                } else if (hours > 0) {
                    relativeText = `in ${hours} hour${hours > 1 ? 's' : ''} and ${minutes} minute${minutes > 1 ? 's' : ''}`;
                } else if (minutes > 0) {
                    relativeText = `in ${minutes} minute${minutes > 1 ? 's' : ''}`;
                } else {
                    relativeText = 'in less than a minute';
                }
            } else {
                relativeText = 'This time has already passed!';
                previewRelative.css('color', '#d63638');
            }

            previewDateTime.text(formattedDateTime);
            previewRelative.text(relativeText);
            preview.slideDown(300);
        } else {
            preview.slideUp(300);
        }
    }

    // Rich Text Editor functionality
    function initializeEditor() {
        var editor = document.getElementById('template_content_editor');
        var hiddenTextarea = document.getElementById('template_content');

        // Editor toolbar buttons
        $('.editor-btn').on('click', function(e) {
            e.preventDefault();
            var command = $(this).data('command');

            if (command === 'createLink') {
                var url = prompt('Enter the URL:');
                if (url) {
                    document.execCommand(command, false, url);
                }
            } else {
                document.execCommand(command, false, null);
            }

            // Update hidden textarea
            updateHiddenTextarea();

            // Update button active state
            updateToolbarState();
        });

        // Update hidden textarea when editor content changes
        $(editor).on('input', updateHiddenTextarea);

        function updateHiddenTextarea() {
            hiddenTextarea.value = editor.innerHTML;
        }

        function updateToolbarState() {
            $('.editor-btn').each(function() {
                var command = $(this).data('command');
                if (document.queryCommandState(command)) {
                    $(this).addClass('active');
                } else {
                    $(this).removeClass('active');
                }
            });
        }

        // Update toolbar state on selection change
        $(editor).on('mouseup keyup', updateToolbarState);
    }

    // Template selection handler
    $('#template_id').on('change', function() {
        var selectedOption = $(this).find('option:selected');
        var templateContent = selectedOption.data('content');

        if (templateContent) {
            $('#template_content_editor').html(templateContent);
            $('#template_content').val(templateContent);
        }
    });

    // Show create campaign modal
    $('#create-new-campaign, #create-first-campaign').on('click', function(e) {
        window.open('https://instantpopupbuilder.com/extensions/subscription-popup/', '_blank');
    });

    // Handle edit campaign links
    $('.edit-campaign-link').on('click', function(e) {
        e.preventDefault();
        var campaignId = $(this).data('id');
        openCampaignModal('edit', campaignId);
    });

    // Function to open campaign modal
    function openCampaignModal(mode, campaignId) {
        if (mode === 'create') {
            $('#modal-title').text('Create New Campaign');
            $('.button-text').text('Create & Send Campaign');
            $('#campaign_id').val('');
            $('#campaign-form')[0].reset();
            $('#campaign_associations').val([]);
            $('#template_content_editor').html('<p>Start writing your newsletter content here...</p><p>You can use the toolbar above to format your text, add links, and create lists.</p><p><strong>Tip:</strong> Use engaging content to keep your subscribers interested!</p>');
            $('#template_content').val('');

            // Reset scheduling options
            $('input[name="send_type"][value="now"]').prop('checked', true);
            $('.scheduling-options').removeClass('selected').first().addClass('selected');
            $('#scheduling-details').hide();
            $('#scheduling-preview').hide();
        } else if (mode === 'edit' && campaignId) {
            $('#modal-title').text('Edit Campaign');
            $('.button-text').text('Update Campaign');
            loadCampaignData(campaignId);
        }

        $('#create-campaign-modal').show();
    }

    // Function to load campaign data for editing
    function loadCampaignData(campaignId) {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'ipb_get_campaign',
                campaign_id: campaignId,
                nonce: '<?php echo esc_js(wp_create_nonce('ipb_get_campaign')); ?>'
            },
            success: function(response) {
                if (response.success && response.data) {
                    var campaign = response.data;

                    // Fill form fields
                    $('#campaign_id').val(campaign.id);
                    $('#campaign_name').val(campaign.name);
                    $('#campaign_status').val(campaign.status);
                    $('#sender_name').val(campaign.sender_name);
                    $('#sender_email').val(campaign.sender_email);
                    $('#subject_line').val(campaign.subject_line);
                    $('#template_id').val(campaign.template_id);

                    // Set campaign associations
                    if (campaign.campaign_associations) {
                        var associations = JSON.parse(campaign.campaign_associations);
                        $('#campaign_associations').val(associations);
                    }

                    // Set template content
                    if (campaign.template_content) {
                        $('#template_content_editor').html(campaign.template_content);
                        $('#template_content').val(campaign.template_content);
                    }

                    // Set scheduling if applicable
                    if (campaign.send_type === 'scheduled') {
                        $('input[name="send_type"][value="scheduled"]').prop('checked', true);
                        $('.scheduling-options').removeClass('selected').eq(1).addClass('selected');
                        $('#scheduling-details').show();
                        $('#scheduled_date').val(campaign.scheduled_date);
                        $('#scheduled_time').val(campaign.scheduled_time);
                    }
                } else {
                    alert('Failed to load campaign data: ' + (response.data || 'Unknown error'));
                }
            },
            error: function() {
                alert('Error loading campaign data. Please try again.');
            }
        });
    }

    // Close modal
    $('.close-modal, .cancel-modal').on('click', function(e) {
        e.preventDefault();
        $('#create-campaign-modal').hide();
    });

    // Close modal on outside click
    $(document).on('click', function(e) {
        if ($(e.target).is('#create-campaign-modal')) {
            $('#create-campaign-modal').hide();
        }
    });

    // Form validation
    $('.campaign-form').on('submit', function(e) {
        var name = $('#campaign_name').val();
        var associations = $('#campaign_associations').val();
        var senderName = $('#sender_name').val();
        var senderEmail = $('#sender_email').val();
        var subjectLine = $('#subject_line').val();
        var sendType = $('input[name="send_type"]:checked').val();

        if (!name || !associations || associations.length === 0 || !senderName || !senderEmail || !subjectLine) {
            e.preventDefault();
            alert('Please fill in all required fields and select at least one campaign association.');
            return false;
        }

        // Email validation
        var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(senderEmail)) {
            e.preventDefault();
            alert('Please enter a valid sender email address.');
            return false;
        }

        // Scheduling validation
        if (sendType === 'scheduled') {
            var scheduledDate = $('#scheduled_date').val();
            var scheduledTime = $('#scheduled_time').val();

            if (!scheduledDate || !scheduledTime) {
                e.preventDefault();
                alert('Please select both date and time for scheduled campaigns.');
                return false;
            }

            // Check if scheduled time is in the future
            var scheduledDateTime = new Date(scheduledDate + 'T' + scheduledTime);
            var now = new Date();

            if (scheduledDateTime <= now) {
                e.preventDefault();
                alert('Scheduled time must be in the future.');
                return false;
            }
        }

        // Update hidden textarea before submit
        $('#template_content').val($('#template_content_editor').html());
    });

    // Send Campaign buttons
    $('.send-campaign').on('click', function(e) {
        e.preventDefault();
        var campaignId = $(this).data('id');
        var campaignName = $(this).data('name');

        // Set modal data
        $('#send-campaign-id').val(campaignId);
        $('#send-campaign-name').text(campaignName);
        $('#send-campaign-modal').show();
    });

    // Close send modal
    $('.close-send-modal, .cancel-send-modal').on('click', function(e) {
        e.preventDefault();
        $('#send-campaign-modal').hide();
    });

    // Send test email
    $('#send-test-email').on('click', function(e) {
        e.preventDefault();
        var campaignId = $('#send-campaign-id').val();
        var testEmail = $('#test-email-address').val();

        if (!testEmail || !campaignId) {
            alert('Please enter a test email address.');
            return;
        }

        var button = $(this);
        var originalText = button.html();
        button.html('<span class="dashicons dashicons-update spin"></span> Sending...').prop('disabled', true);

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'ipb_send_campaign',
                campaign_id: campaignId,
                test_email: testEmail,
                is_test: 'true',
                nonce: '<?php echo esc_js(wp_create_nonce('ipb_send_campaign')); ?>'
            },
            success: function(response) {
                if (response.success) {
                    alert('Test email sent successfully to ' + testEmail);
                } else {
                    alert('Failed to send test email: ' + response.data);
                }
            },
            error: function() {
                alert('Error sending test email. Please try again.');
            },
            complete: function() {
                button.html(originalText).prop('disabled', false);
            }
        });
    });

    // Send campaign to all subscribers
    $('#send-campaign-all').on('click', function(e) {
        e.preventDefault();
        var campaignId = $('#send-campaign-id').val();
        var campaignName = $('#send-campaign-name').text();

        if (!confirm('Are you sure you want to send "' + campaignName + '" to all associated subscribers? This action cannot be undone.')) {
            return;
        }

        var button = $(this);
        var originalText = button.html();
        button.html('<span class="dashicons dashicons-update spin"></span> Sending...').prop('disabled', true);

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'ipb_send_campaign',
                campaign_id: campaignId,
                is_test: 'false',
                nonce: '<?php echo esc_js(wp_create_nonce('ipb_send_campaign')); ?>'
            },
            success: function(response) {
                if (response.success) {
                    alert('Campaign sent successfully! ' + response.data);
                    location.reload(); // Refresh to show updated stats
                } else {
                    alert('Failed to send campaign: ' + response.data);
                }
            },
            error: function() {
                alert('Error sending campaign. Please try again.');
            },
            complete: function() {
                button.html(originalText).prop('disabled', false);
            }
        });
    });

    // Initialize components
    initializeCampaignSelect();
    initializeEditor();
    initializeScheduling();

    // Check if we should open edit modal on page load
    <?php if ($instant_popup_builder_edit_campaign_id > 0 && $instant_popup_builder_editing_campaign): ?>
    $(document).ready(function() {
        // Auto-open edit modal with campaign data
        openCampaignModal('edit', <?php echo esc_js($instant_popup_builder_edit_campaign_id); ?>);

        // Pre-fill form with campaign data
        var campaign = <?php echo json_encode($instant_popup_builder_editing_campaign); ?>;
        $('#campaign_id').val(campaign.id);
        $('#campaign_name').val(campaign.name);
        $('#campaign_status').val(campaign.status);
        $('#sender_name').val(campaign.sender_name);
        $('#sender_email').val(campaign.sender_email);
        $('#subject_line').val(campaign.subject_line);
        $('#template_id').val(campaign.template_id);

        // Set campaign associations
        if (campaign.campaign_associations) {
            var associations = JSON.parse(campaign.campaign_associations);
            $('#campaign_associations').val(associations);
        }

        // Set template content
        if (campaign.template_content) {
            $('#template_content_editor').html(campaign.template_content);
            $('#template_content').val(campaign.template_content);
        }

        // Set scheduling if applicable
        if (campaign.send_type === 'scheduled') {
            $('input[name="send_type"][value="scheduled"]').prop('checked', true);
            $('.scheduling-options').removeClass('selected').eq(1).addClass('selected');
            $('#scheduling-details').show();
            $('#scheduled_date').val(campaign.scheduled_date);
            $('#scheduled_time').val(campaign.scheduled_time);
        }
    });
    <?php endif; ?>
});
</script>
