<template>
    <Head :title="campaign.title || 'Edit Recurring Campaign'" />
    <AppLayout>
        <!-- Header -->
        <div class="re-header">
            <Link :href="route('recurring.index')" class="re-back">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="16" height="16">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"/>
                </svg>
                Recurring Campaigns
            </Link>

            <div class="re-title-row">
                <div class="re-title-left">
                    <span class="re-crumb-sep">›</span>
                    <h1 class="re-title">{{ campaign.title }}</h1>
                </div>
                <div class="re-title-actions">
                    <span v-if="savedAt" class="re-saved-indicator">Saved</span>
                    <button class="btn btn-outline btn-sm" @click="showTestModal = true">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="14" height="14">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5"/>
                        </svg>
                        Send a test email
                    </button>
                    <button class="btn btn-primary btn-sm" @click="saveAll" :disabled="savingAll">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="14" height="14">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3"/>
                        </svg>
                        {{ savingAll ? 'Saving…' : 'Save' }}
                    </button>
                </div>
            </div>
        </div>

        <!-- Tabs -->
        <div class="re-tabs-wrap">
            <div class="re-tabs">
                <button class="re-tab" :class="{ 'is-active': activeTab === 'configuration' }" @click="activeTab = 'configuration'">Email Configuration</button>
                <button class="re-tab" :class="{ 'is-active': activeTab === 'settings' }" @click="activeTab = 'settings'">Settings</button>
                <button class="re-tab" :class="{ 'is-active': activeTab === 'history' }" @click="activeTab = 'history'">Email History</button>
            </div>
        </div>

        <!-- Tab: Email Configuration -->
        <div v-if="activeTab === 'configuration'" class="re-content re-content--wide">
            <div class="rw-content-card">
                <h3>
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75"/></svg>
                    Email Details
                </h3>
                <div class="re-grid-2" style="margin-bottom:16px">
                    <div class="form-group" style="margin-bottom:0">
                        <label class="form-label">Email Subject</label>
                        <input v-model="composeForm.email_subject" type="text" class="form-input" placeholder="Email Subject" @input="queueComposeSave">
                    </div>
                    <div class="form-group" style="margin-bottom:0">
                        <label class="form-label">Email Pre-Header</label>
                        <input v-model="composeForm.email_pre_header" type="text" class="form-input" placeholder="Email Pre-Header" @input="queueComposeSave">
                    </div>
                </div>
                <label style="display:flex;align-items:center;gap:10px;cursor:pointer;font-size:13px;color:var(--text-primary);margin-bottom:12px">
                    <input type="checkbox" v-model="composeForm.utm_status" style="accent-color:var(--info);width:14px;height:14px" @change="queueComposeSave">
                    Add UTM Parameters For URLs
                </label>
                <div v-if="composeForm.utm_status" class="re-grid-5">
                    <div class="form-group" style="margin-bottom:0">
                        <label class="form-label">Campaign Source (required)</label>
                        <input v-model="composeForm.utm_source" type="text" class="form-input" placeholder="e.g. google, newsletter" @input="queueComposeSave">
                    </div>
                    <div class="form-group" style="margin-bottom:0">
                        <label class="form-label">Campaign Medium</label>
                        <input v-model="composeForm.utm_medium" type="text" class="form-input" placeholder="e.g. cpc, banner, email" @input="queueComposeSave">
                    </div>
                    <div class="form-group" style="margin-bottom:0">
                        <label class="form-label">Campaign Name</label>
                        <input v-model="composeForm.utm_campaign" type="text" class="form-input" placeholder="e.g. spring_sale" @input="queueComposeSave">
                    </div>
                    <div class="form-group" style="margin-bottom:0">
                        <label class="form-label">Campaign Term</label>
                        <input v-model="composeForm.utm_term" type="text" class="form-input" placeholder="Paid keywords" @input="queueComposeSave">
                    </div>
                    <div class="form-group" style="margin-bottom:0">
                        <label class="form-label">Campaign Content</label>
                        <input v-model="composeForm.utm_content" type="text" class="form-input" placeholder="Differentiate ads" @input="queueComposeSave">
                    </div>
                </div>
            </div>

            <div class="rw-content-card">
                <h3>
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"/></svg>
                    Sender Identity
                </h3>
                <div class="re-grid-2">
                    <div class="form-group" style="margin-bottom:0">
                        <label class="form-label">SMTP Profile</label>
                        <select v-model.number="composeForm.smtp_config_id" class="form-select" @change="queueComposeSave">
                            <option :value="null" disabled>Select an SMTP profile</option>
                            <option v-for="p in smtpProfiles" :key="p.id" :value="p.id">
                                {{ p.from_name || p.from_email }} - {{ p.name }}<template v-if="p.is_default"> (Default)</template>
                            </option>
                        </select>
                    </div>
                    <div class="form-group" style="margin-bottom:0">
                        <label class="form-label">Reply-to email (optional)</label>
                        <input v-model="composeForm.reply_to_email" type="email" class="form-input" placeholder="Leave blank to receive replies at the sender address" @input="queueComposeSave">
                    </div>
                </div>
            </div>

            <div class="re-builder-wrap">
                <EmailEditor
                    v-model="blocks"
                    :campaign-id="campaign.id"
                    :global-settings="globalSettings"
                />
            </div>
        </div>

        <!-- Tab: Settings -->
        <div v-if="activeTab === 'settings'" class="re-content">
            <div class="rw-content-card">
                <h3>
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5"/></svg>
                    Scheduling Settings
                </h3>

                <div class="re-status-row">
                    <label class="switch">
                        <input type="checkbox" :checked="status === 'active'" @change="toggleActive">
                        <span class="switch-slider"></span>
                    </label>
                    <span class="re-status-label">Campaign is {{ status === 'active' ? 'Active' : status === 'paused' ? 'Paused' : 'Draft' }}</span>
                    <span class="re-status-hint">{{ status === 'active' ? 'Sending on schedule.' : 'Turn on to start sending on the schedule below.' }}</span>
                </div>

                <div class="form-group">
                    <label class="form-label">Title of the Recurring Campaign</label>
                    <input v-model="scheduleForm.title" type="text" class="form-input" placeholder="eg: Weekly Post Updated" @input="queueScheduleSave">
                </div>

                <label class="form-label" style="margin-bottom:8px;display:block">How often you want to send this email?</label>
                <div class="freq-pills">
                    <div class="freq-pill" :class="{ 'is-active': scheduleForm.frequency === 'daily' }" @click="setFrequency('daily')">Daily</div>
                    <div class="freq-pill" :class="{ 'is-active': scheduleForm.frequency === 'weekly' }" @click="setFrequency('weekly')">Weekly</div>
                    <div class="freq-pill" :class="{ 'is-active': scheduleForm.frequency === 'monthly' }" @click="setFrequency('monthly')">Monthly</div>
                </div>

                <div class="re-grid-2" style="margin-bottom:20px">
                    <div class="form-group" style="margin-bottom:0" v-if="scheduleForm.frequency === 'weekly'">
                        <label class="form-label">Select which day you want to send email?</label>
                        <CwSelect v-model="scheduleForm.day" :options="weekdayOptions" @change="queueScheduleSave" />
                    </div>
                    <div class="form-group" style="margin-bottom:0" v-else-if="scheduleForm.frequency === 'monthly'">
                        <label class="form-label">Select which day of the month?</label>
                        <CwSelect v-model="scheduleForm.day" :options="monthlyDayOptions" @change="queueScheduleSave" />
                    </div>
                    <div class="form-group" style="margin-bottom:0" v-else></div>

                    <div class="form-group" style="margin-bottom:0">
                        <label class="form-label">Which time you would like to schedule</label>
                        <CwDateTimePicker v-model="recurringTimeVal" placeholder="Select Time" mode="time" />
                        <div style="font-size:11px;color:#9ca3af;margin-top:6px">
                            Selected: {{ formatTime(scheduleForm.recurring_time) }} · Current time in your timezone: {{ formattedServerNow }}
                        </div>
                    </div>
                </div>

                <label style="display:flex;align-items:flex-start;gap:10px;cursor:pointer;font-size:13px;color:var(--text-primary)">
                    <input type="checkbox" v-model="scheduleForm.auto_send" style="accent-color:var(--info);width:14px;height:14px;margin-top:2px" @change="queueScheduleSave">
                    <span>Send Emails automatically to the selected day and time (if you disable this, emails will be on draft state and you can trigger emails after review)</span>
                </label>
            </div>

            <div class="rw-content-card">
                <h3>
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 12h16.5m-16.5 3.75h16.5M3.75 19.5h16.5M5.625 4.5h12.75a1.875 1.875 0 010 3.75H5.625a1.875 1.875 0 010-3.75z"/></svg>
                    Duration
                </h3>
                <div class="date-grid" style="margin-bottom:20px">
                    <div class="form-group" style="margin-bottom:0">
                        <label class="form-label">Start Date</label>
                        <CwDateTimePicker v-model="startDateVal" placeholder="Select Start Date" mode="date" />
                    </div>
                    <div class="form-group" style="margin-bottom:0">
                        <label class="form-label">End Date <span style="font-size:11px;color:#9ca3af;font-weight:400">(optional)</span></label>
                        <CwDateTimePicker v-model="endDateVal" placeholder="Select End Date" mode="date" />
                    </div>
                </div>
                <label class="form-label" style="margin-bottom:10px;display:block">When to stop</label>
                <div class="end-opts">
                    <label class="end-opt" style="cursor:pointer">
                        <input type="radio" value="never" v-model="scheduleForm.end_type" @change="queueScheduleSave">
                        <span style="font-weight:500">Never - keep sending indefinitely</span>
                    </label>
                    <div class="end-opt" style="display:flex;align-items:center;flex-wrap:wrap;gap:12px">
                        <label style="display:flex;align-items:center;gap:10px;cursor:pointer">
                            <input type="radio" value="date" v-model="scheduleForm.end_type" @change="queueScheduleSave">
                            <span style="font-weight:500">On a specific end date</span>
                        </label>
                        <div style="flex:1;max-width:280px">
                            <CwDateTimePicker v-model="endDateVal" placeholder="Select End Date" mode="date" />
                        </div>
                    </div>
                    <div class="end-opt" style="display:flex;align-items:center;flex-wrap:wrap;gap:12px">
                        <label style="display:flex;align-items:center;gap:10px;cursor:pointer">
                            <input type="radio" value="count" v-model="scheduleForm.end_type" @change="queueScheduleSave">
                            <span style="font-weight:500">After</span>
                        </label>
                        <div style="display:flex;align-items:center;gap:8px">
                            <input type="number" class="form-input" style="width:80px;height:40px" min="1" v-model.number="scheduleForm.end_count" :disabled="scheduleForm.end_type !== 'count'" @change="queueScheduleSave">
                            <span style="font-weight:500;font-size:13px;color:#374151">occurrences</span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="cw-recipients-tabs">
                <div class="cw-recipients-tab" :class="{ 'is-active': recipientsMode === 'list_tag' }" @click="recipientsMode = 'list_tag'">By List &amp; Tag</div>
                <div class="cw-recipients-tab" :class="{ 'is-active': recipientsMode === 'advanced_filter' }" @click="recipientsMode = 'advanced_filter'">By Advanced Filter</div>
            </div>

            <div v-if="recipientsMode === 'advanced_filter'" class="rw-recip-card">
                <div class="rw-recip-card-header">
                    <h4>Advanced Filter</h4>
                </div>
                <AdvancedFilterBuilder
                    ref="filterBuilderRef"
                    v-model="filterTree"
                    :menu="filterFieldMenu"
                    :lists="lists"
                    :tags="tags"
                    :campaigns="campaigns"
                    :automations="automations"
                    @apply="saveRecipients"
                />
                <div style="text-align:center;padding:12px 0 4px">
                    <span class="recipient-count-badge">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:14px;height:14px"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"/></svg>
                        <span class="recipient-count-badge-num">{{ recipientCount }}</span> contacts found based on your selection
                    </span>
                </div>
            </div>

            <template v-if="recipientsMode === 'list_tag'">
            <div class="rw-recip-card">
                <div class="rw-recip-card-header">
                    <h4>Included Contacts</h4>
                    <button class="btn btn-sm" @click="addRow('included')">+ Add row</button>
                </div>
                <table class="rw-recip-table">
                    <tr v-for="(row, i) in recipientsForm.included" :key="'inc-' + i">
                        <td>
                            <CwSelect v-model="row.list_id" :options="listOptions" @change="queueRecipientsSave" />
                        </td>
                        <td>
                            <CwSelect v-model="row.tag_id" :options="tagOptions" @change="queueRecipientsSave" />
                        </td>
                        <td style="text-align:center">
                            <button class="re-row-remove" @click="removeRow('included', i)">−</button>
                        </td>
                    </tr>
                </table>
                <div style="text-align:center;padding:12px 0 4px">
                    <span class="recipient-count-badge">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:14px;height:14px"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"/></svg>
                        <span class="recipient-count-badge-num">{{ recipientCount }}</span> contacts found based on your selection
                    </span>
                </div>
            </div>

            <div class="rw-recip-card">
                <div class="rw-recip-card-header">
                    <h4>Excluded Contacts</h4>
                    <button class="btn btn-sm" @click="addRow('excluded')">+ Add row</button>
                </div>
                <table class="rw-recip-table">
                    <tr v-if="recipientsForm.excluded.length === 0">
                        <td colspan="3" style="text-align:center;color:#9ca3af;font-size:12px;padding:20px">No exclusions added. Click "+ Add row" to exclude contacts.</td>
                    </tr>
                    <tr v-for="(row, i) in recipientsForm.excluded" :key="'exc-' + i">
                        <td>
                            <CwSelect v-model="row.list_id" :options="exclusionListOptions" @change="queueRecipientsSave" />
                        </td>
                        <td>
                            <CwSelect v-model="row.tag_id" :options="exclusionTagOptions" @change="queueRecipientsSave" />
                        </td>
                        <td style="text-align:center">
                            <button class="re-row-remove" @click="removeRow('excluded', i)">−</button>
                        </td>
                    </tr>
                </table>
            </div>
            </template>
        </div>

        <!-- Tab: Email History -->
        <div v-if="activeTab === 'history'" class="re-content re-content--wide">
            <div class="re-history-wrap">
                <!-- Empty state -->
                <div v-if="occurrences.data.length === 0" class="re-history-empty">
                    All your email history from this recurring campaign will be shown here.
                </div>

                <template v-else>
                    <!-- Column header -->
                    <div class="re-history-col-header">
                        <div class="re-hcol-name">Date &amp; Time</div>
                        <div class="re-hcol-stat">Recipients</div>
                        <div class="re-hcol-stat">Sent</div>
                        <div class="re-hcol-stat">Failed</div>
                        <div class="re-hcol-stat">Bounced</div>
                        <div class="re-hcol-stat">Opens</div>
                        <div class="re-hcol-stat">Clicks</div>
                        <div class="re-hcol-status">Status</div>
                        <div class="re-hcol-actions"></div>
                    </div>

                    <!-- Rows -->
                    <div v-for="o in occurrences.data" :key="o.id" class="re-history-row">
                        <div class="re-hcol-name">
                            <div class="re-history-title">{{ o.title }}</div>
                            <div class="re-history-date">{{ formatDateTime(o.created_at) }}</div>
                        </div>
                        <div class="re-hcol-stat">{{ o.recipients_count }}</div>
                        <div class="re-hcol-stat">{{ o.emails_sent }}</div>
                        <div class="re-hcol-stat">{{ o.emails_failed }}</div>
                        <div class="re-hcol-stat">{{ o.emails_bounced }}</div>
                        <div class="re-hcol-stat">{{ o.unique_opens }}</div>
                        <div class="re-hcol-stat">{{ o.unique_clicks }}</div>
                        <div class="re-hcol-status">
                            <span class="badge" :class="occurrenceBadgeClass(o.status)">{{ occurrenceStatusLabel(o.status) }}</span>
                        </div>
                        <div class="re-hcol-actions">
                            <button v-if="o.status === 'draft'" class="btn btn-sm btn-primary" :disabled="sendingOccurrenceId === o.id" @click="sendOccurrenceNow(o)">
                                {{ sendingOccurrenceId === o.id ? 'Sending…' : 'Send Now' }}
                            </button>
                            <div class="re-menu-wrap" @click.stop>
                                <button class="re-menu-btn" @click="toggleHistoryMenu(o.id)" title="More">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="16" height="16"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6.75a.75.75 0 110-1.5.75.75 0 010 1.5zM12 12.75a.75.75 0 110-1.5.75.75 0 010 1.5zM12 18.75a.75.75 0 110-1.5.75.75 0 010 1.5z"/></svg>
                                </button>
                                <div v-if="openHistoryMenu === o.id" class="re-dropdown">
                                    <button class="re-dd-item" @click="openPreview(o)">Preview Email</button>
                                    <Link :href="route('recurring.occurrence.show', [campaign.id, o.id])" class="re-dd-item">View Report</Link>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="re-history-footer">
                        <span class="table-footer-info">Showing {{ occurrences.from ?? 0 }}–{{ occurrences.to ?? 0 }} of {{ occurrences.total }}</span>
                        <Pagination :paginator="occurrences" preserve-state />
                    </div>
                </template>
            </div>
        </div>

        <!-- Preview email modal -->
        <div v-if="showPreviewModal" class="modal-overlay is-open" @click.self="closePreview">
            <div class="modal modal--lg">
                <div class="modal-header">
                    <h2 class="modal-title">Email Preview</h2>
                    <button class="modal-close" @click="closePreview">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
                    </button>
                </div>
                <div class="modal-body" style="padding:20px">
                    <div v-if="previewLoading" style="text-align:center;padding:48px;color:#9ca3af">Loading…</div>
                    <template v-else-if="previewData">
                        <div class="re-preview-meta">
                            <div>
                                <div class="re-preview-label">Subject</div>
                                <div class="re-preview-value">{{ previewData.subject }}</div>
                            </div>
                            <div>
                                <div class="re-preview-label">Total Recipients</div>
                                <div class="re-preview-value">{{ previewData.recipients_count }}</div>
                            </div>
                            <div>
                                <div class="re-preview-label">Scheduled on</div>
                                <div class="re-preview-value">{{ formatDateTime(previewData.created_at) }}</div>
                            </div>
                        </div>
                        <div style="display:flex;justify-content:center;margin-bottom:14px">
                            <div style="display:inline-flex;background:#f3f4f6;border-radius:8px;padding:2px">
                                <button class="re-device-btn" :class="{ 'is-active': previewDevice === 'desktop' }" @click="previewDevice = 'desktop'">Desktop</button>
                                <button class="re-device-btn" :class="{ 'is-active': previewDevice === 'mobile' }" @click="previewDevice = 'mobile'">Mobile</button>
                            </div>
                        </div>
                        <div class="re-preview-frame" :class="{ 'is-mobile': previewDevice === 'mobile' }">
                            <div v-html="previewData.html"></div>
                        </div>
                    </template>
                </div>
            </div>
        </div>

        <!-- Send test email modal -->
        <div v-if="showTestModal" class="modal-overlay is-open" @click.self="closeTestModal">
            <div class="modal" style="width:480px;max-width:96vw">
                <div class="modal-header">
                    <h2 class="modal-title">Send a Test Email</h2>
                    <button class="modal-close" @click="closeTestModal">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
                    </button>
                </div>
                <div class="modal-body" style="padding:24px">
                    <label class="form-label">Send to email address</label>
                    <input v-model="testEmail" type="email" class="form-input" placeholder="you@example.com" @keydown.enter="sendTest">
                    <p v-if="testError" style="color:#dc2626;font-size:12px;margin-top:8px">{{ testError }}</p>
                    <p v-if="testSuccess" style="color:#16a34a;font-size:12px;margin-top:8px">Test email sent!</p>
                </div>
                <div class="modal-footer" style="justify-content:flex-end">
                    <button class="btn btn-outline" @click="closeTestModal">Cancel</button>
                    <button class="btn btn-primary" @click="sendTest" :disabled="sendingTest || !testEmail">
                        <span v-if="sendingTest">Sending…</span>
                        <span v-else>Send Test</span>
                    </button>
                </div>
            </div>
        </div>
    </AppLayout>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue';
import { Link, router, Head, usePage } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';
import Pagination from '@/Components/Pagination.vue';
import EmailEditor from '@/Components/EmailEditor/EmailEditor.vue';
import CwDateTimePicker from '@/Components/CwDateTimePicker.vue';
import CwSelect from '@/Components/CwSelect.vue';
import AdvancedFilterBuilder from '@/Components/AdvancedFilterBuilder.vue';
import { formatInTimeZone } from '@/utils/timezone';

const props = defineProps({
    campaign:        Object,
    lists:           Array,
    tags:            Array,
    occurrences:     Object,
    smtpProfiles:    { type: Array, default: () => [] },
    serverNow:       String,
    campaigns:       { type: Array, default: () => [] },
    automations:     { type: Array, default: () => [] },
    filterFieldMenu: { type: Array, default: () => [] }, 
    globalSettings: { type: Object, default: () => ({}) },
});

const activeTab = ref('configuration');
const status    = ref(props.campaign.status);
const savedAt   = ref(null);
const savingAll = ref(false);

const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

function formatTime(hhmm) {
    const [h, m] = hhmm.split(':').map(Number);
    const period = h >= 12 ? 'PM' : 'AM';
    const hour12 = ((h + 11) % 12) + 1;
    return `${hour12}:${String(m).padStart(2, '0')} ${period}`;
}
function ordinal(n) {
    const s = ['th', 'st', 'nd', 'rd'];
    const v = n % 100;
    return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
// Recurring send times are interpreted in the tenant's configured timezone
// (Settings > General Settings), not the browser's local timezone.
const tenantTimezone = computed(() => usePage().props.tenantTimezone || 'UTC');
function formatDate(iso) {
    return formatInTimeZone(iso, tenantTimezone.value, { hour: undefined, minute: undefined, hour12: undefined });
}
function formatDateTime(iso) {
    return formatInTimeZone(iso, tenantTimezone.value);
}
const formattedServerNow = computed(() => formatDateTime(props.serverNow));

function flashSaved() {
    savedAt.value = new Date();
    setTimeout(() => { savedAt.value = null; }, 2500);
}

// ── Email Configuration form ──────────────────────────────────────
const composeForm = reactive({
    email_subject:     props.campaign.email_subject ?? '',
    email_pre_header:  props.campaign.email_pre_header ?? '',
    utm_status:        !!props.campaign.utm_status,
    utm_source:        props.campaign.utm_source ?? '',
    utm_medium:        props.campaign.utm_medium ?? '',
    utm_campaign:      props.campaign.utm_campaign ?? '',
    utm_term:          props.campaign.utm_term ?? '',
    utm_content:       props.campaign.utm_content ?? '',
    reply_to_email:    props.campaign.settings?.reply_to_email ?? props.globalSettings?.email?.reply_to_email ?? '',
    smtp_config_id:    props.campaign.settings?.smtp_config_id
        ?? props.smtpProfiles.find(p => p.is_default)?.id
        ?? null,
});

const blocks = ref(props.campaign.settings?.blocks ?? []);

let composeTimer = null;
function queueComposeSave() {
    clearTimeout(composeTimer);
    composeTimer = setTimeout(saveCompose, 500);
}
async function saveCompose() {
    // reply_to_email/smtp_config_id live in campaign.settings (JSON), not as
    // direct campaign columns, so they're sent nested rather than top-level.
    const { reply_to_email, smtp_config_id, ...campaignFields } = composeForm;
    await window.axios.patch(route('recurring.update', props.campaign.id), {
        ...campaignFields,
        settings: { reply_to_email, smtp_config_id },
    });
    flashSaved();
}

let blocksTimer = null;
watch(blocks, () => {
    clearTimeout(blocksTimer);
    blocksTimer = setTimeout(saveBlocks, 800);
}, { deep: true });
async function saveBlocks() {
    await window.axios.patch(route('recurring.update', props.campaign.id), {
        settings: { blocks: blocks.value },
    });
    flashSaved();
}

// ── Scheduling Settings form ──────────────────────────────────────
const initialDays = props.campaign.recurring_days ?? [];
const scheduleForm = reactive({
    title:            props.campaign.title,
    frequency:        props.campaign.frequency ?? 'weekly',
    day:              initialDays.length ? initialDays[0] : 1,
    recurring_time:   props.campaign.recurring_time ?? '09:00',
    auto_send:        props.campaign.auto_send ?? true,
    start_date:       props.campaign.start_date ?? new Date().toISOString().slice(0, 10),
    end_type:         props.campaign.end_type ?? 'never',
    end_date_field:   props.campaign.end_date ?? '',
    end_count:        props.campaign.end_count ?? 12,
});

const startDateVal = computed({
    get: () => {
        if (!scheduleForm.start_date) return '';
        return `${scheduleForm.start_date}T00:00`;
    },
    set: (val) => {
        if (!val) {
            scheduleForm.start_date = '';
        } else {
            scheduleForm.start_date = val.split('T')[0];
        }
        queueScheduleSave();
    }
});

const endDateVal = computed({
    get: () => {
        if (!scheduleForm.end_date_field) return '';
        return `${scheduleForm.end_date_field}T00:00`;
    },
    set: (val) => {
        if (!val) {
            scheduleForm.end_date_field = '';
        } else {
            scheduleForm.end_date_field = val.split('T')[0];
            scheduleForm.end_type = 'date';
        }
        queueScheduleSave();
    }
});

const recurringTimeVal = computed({
    get: () => {
        const date = scheduleForm.start_date || new Date().toISOString().slice(0, 10);
        const time = scheduleForm.recurring_time || '09:00';
        return `${date}T${time}`;
    },
    set: (val) => {
        if (val) {
            const [date, time] = val.split('T');
            if (time) {
                scheduleForm.recurring_time = time;
            }
        }
        queueScheduleSave();
    }
});

const weekdayOptions = computed(() => {
    return WEEKDAYS.map((d, idx) => ({ value: idx, label: `Every ${d}` }));
});

const monthlyDayOptions = computed(() => {
    return Array.from({ length: 31 }, (_, i) => ({
        value: i + 1,
        label: `${ordinal(i + 1)} of the month`
    }));
});

const listOptions = computed(() => {
    return [
        { value: null, label: 'All Lists' },
        ...props.lists.map(l => ({ value: l.id, label: l.title }))
    ];
});

const tagOptions = computed(() => {
    return [
        { value: null, label: 'All contacts on selected list segment' },
        ...props.tags.map(t => ({ value: t.id, label: t.title }))
    ];
});

const exclusionListOptions = computed(() => {
    return [
        { value: null, label: 'Choose a List' },
        ...props.lists.map(l => ({ value: l.id, label: l.title }))
    ];
});

const exclusionTagOptions = computed(() => {
    return [
        { value: null, label: 'Select Tag First' },
        ...props.tags.map(t => ({ value: t.id, label: t.title }))
    ];
});

function setFrequency(freq) {
    scheduleForm.frequency = freq;
    queueScheduleSave();
}

function onEndDateChange() {
    scheduleForm.end_type = 'date';
    queueScheduleSave();
}

let scheduleTimer = null;
function queueScheduleSave() {
    clearTimeout(scheduleTimer);
    scheduleTimer = setTimeout(saveSchedule, 500);
}
async function saveSchedule() {
    const recurringDays = scheduleForm.frequency === 'daily' ? [] : [scheduleForm.day];

    await window.axios.patch(route('recurring.update', props.campaign.id), {
        title:               scheduleForm.title,
        frequency:           scheduleForm.frequency,
        recurring_days:      recurringDays,
        recurring_time:      scheduleForm.recurring_time,
        auto_send:           scheduleForm.auto_send,
        start_date:          scheduleForm.start_date,
        end_type:            scheduleForm.end_type,
        end_date:            scheduleForm.end_type === 'date' ? scheduleForm.end_date_field : null,
        end_count:           scheduleForm.end_type === 'count' ? scheduleForm.end_count : null,
    });
    flashSaved();
}

// ── Recipients form ────────────────────────────────────────────────
const recipientsForm = reactive({
    included: props.campaign.recipients_config?.included?.length
        ? props.campaign.recipients_config.included
        : [{ list_id: null, tag_id: null }],
    excluded: props.campaign.recipients_config?.excluded ?? [],
});
const recipientCount = ref(props.campaign.recipients_count ?? 0);

// By List & Tag vs By Advanced Filter are mutually exclusive - only the
// active mode's shape gets saved to recipients_config (see buildRecipientsConfig).
const recipientsMode   = ref(props.campaign.recipients_config?.mode ?? 'list_tag');
const filterTree       = reactive(props.campaign.recipients_config?.filter ?? { groups: [{ conditions: [{ field: null, operator: null, value: null }] }] });
const filterBuilderRef = ref(null);

function buildRecipientsConfig() {
    if (recipientsMode.value === 'advanced_filter') {
        return { mode: 'advanced_filter', filter: filterTree };
    }
    return {
        mode: 'list_tag',
        included: recipientsForm.included,
        excluded: recipientsForm.excluded.filter(r => r.list_id),
    };
}

watch(recipientsMode, () => queueRecipientsSave());

function addRow(kind) {
    recipientsForm[kind].push({ list_id: null, tag_id: null });
}
function removeRow(kind, index) {
    recipientsForm[kind].splice(index, 1);
    queueRecipientsSave();
}

let recipientsTimer = null;
function queueRecipientsSave() {
    clearTimeout(recipientsTimer);
    recipientsTimer = setTimeout(saveRecipients, 500);
}
async function saveRecipients() {
    await window.axios.patch(route('recurring.update', props.campaign.id), {
        recipients_config: buildRecipientsConfig(),
    });
    await refreshRecipientCount();
    flashSaved();
}
async function saveAll() {
    savingAll.value = true;
    clearTimeout(composeTimer);
    clearTimeout(blocksTimer);
    clearTimeout(scheduleTimer);
    clearTimeout(recipientsTimer);
    try {
        await Promise.all([saveCompose(), saveBlocks(), saveSchedule(), saveRecipients()]);
    } finally {
        savingAll.value = false;
    }
}

async function refreshRecipientCount() {
    // Avoid firing count-recipients against a filter the user is still
    // mid-way through building - a half-picked field/operator/value is
    // expected, not an error, so just skip the request until it's complete.
    if (recipientsMode.value === 'advanced_filter' && !filterBuilderRef.value?.isValid) {
        return;
    }

    try {
        const { data } = await window.axios.post(route('recurring.count-recipients'), buildRecipientsConfig());
        recipientCount.value = data.count;
    } catch {
        // silently ignore network/validation errors during count
    }
}
refreshRecipientCount();

// ── Status toggle ──────────────────────────────────────────────────
async function toggleActive() {
    const next = status.value === 'active' ? 'draft' : 'active';
    status.value = next;
    try {
        // Flush any pending debounced field saves (time/frequency/timezone/etc.)
        // first, so activation always computes next_run_at from what's on screen
        // right now rather than racing a stale, not-yet-saved database row.
        await saveAll();
        await window.axios.patch(route('recurring.update-status', props.campaign.id), {
            status: next,
        });
        flashSaved();
    } catch (e) {
        status.value = next === 'active' ? 'draft' : 'active'; // revert on failure
    }
}

// ── Send test email ────────────────────────────────────────────────
const showTestModal = ref(false);
const testEmail      = ref('');
const sendingTest     = ref(false);
const testError       = ref('');
const testSuccess     = ref(false);

function closeTestModal() {
    showTestModal.value = false;
    testError.value   = '';
    testSuccess.value = false;
}

async function sendTest() {
    if (!testEmail.value) return;
    sendingTest.value = true;
    testError.value   = '';
    testSuccess.value = false;
    try {
        await window.axios.post(route('recurring.send-test', props.campaign.id), {
            email: testEmail.value,
            smtp_config_id: composeForm.smtp_config_id,
        });
        testSuccess.value = true;
    } catch (e) {
        testError.value = e.response?.data?.message ?? 'Failed to send test email.';
    } finally {
        sendingTest.value = false;
    }
}

// ── Email History: each row is a materialized occurrence campaign ──
const sendingOccurrenceId = ref(null);
async function sendOccurrenceNow(occurrence) {
    sendingOccurrenceId.value = occurrence.id;
    try {
        await window.axios.post(route('campaigns.broadcast', occurrence.id), { send_mode: 'now' });
        router.reload({ only: ['occurrences'], preserveScroll: true });
    } finally {
        sendingOccurrenceId.value = null;
    }
}
function occurrenceStatusLabel(status) {
    return { draft: 'Pending Review', queued: 'Queued', scheduled: 'Scheduled', sending: 'Sending', sent: 'Sent' }[status] ?? status;
}
function occurrenceBadgeClass(status) {
    return { draft: 'badge--draft', queued: 'badge--sending', scheduled: 'badge--scheduled', sending: 'badge--sending', sent: 'badge--sent' }[status] ?? 'badge--draft';
}

// 3-dot menu per history row
const openHistoryMenu = ref(null);
function toggleHistoryMenu(id) {
    openHistoryMenu.value = openHistoryMenu.value === id ? null : id;
}
function closeHistoryMenu() {
    openHistoryMenu.value = null;
}
onMounted(() => document.addEventListener('click', closeHistoryMenu));
onUnmounted(() => document.removeEventListener('click', closeHistoryMenu));

// Preview Email modal - fetches the rendered HTML + metadata for one occurrence
const showPreviewModal = ref(false);
const previewData       = ref(null);
const previewLoading    = ref(false);
const previewDevice     = ref('desktop');

async function openPreview(occurrence) {
    openHistoryMenu.value = null;
    showPreviewModal.value = true;
    previewData.value = null;
    previewLoading.value = true;
    try {
        const { data } = await window.axios.get(route('campaigns.preview', occurrence.id));
        previewData.value = data;
    } finally {
        previewLoading.value = false;
    }
}
function closePreview() {
    showPreviewModal.value = false;
    previewData.value = null;
}
</script>

<style scoped>
.re-header { margin-bottom: 4px; }
.re-back {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    font-weight: 500;
    color: var(--text-secondary);
    text-decoration: none;
    margin-bottom: 10px;
}
.re-back:hover { color: var(--text-primary); }

.re-title-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 16px; flex-wrap: wrap; }
.re-title-left { display: flex; align-items: center; gap: 8px; }
.re-crumb-sep { display: none; }
.re-title { font-size: 20px; font-weight: 700; color: var(--text-primary); }
.re-title-actions { display: flex; align-items: center; gap: 12px; }
.re-saved-indicator { font-size: 12px; color: var(--success); font-weight: 500; }
.re-status-label { font-size: 13px; font-weight: 500; color: var(--text-primary); }
.re-status-row {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 12px 14px;
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    margin-bottom: 20px;
}
.re-status-hint { font-size: 12px; color: var(--text-muted); margin-left: auto; }

.re-tabs-wrap { border-bottom: 1px solid var(--border-color); margin-bottom: 24px; }
.re-tabs { display: flex; gap: 4px; }
.re-tab {
    padding: 10px 16px;
    font-size: 13px;
    font-weight: 500;
    color: var(--text-secondary);
    background: none;
    border: none;
    border-bottom: 2px solid transparent;
    cursor: pointer;
    margin-bottom: -1px;
}
.re-tab:hover { color: var(--text-primary); }
.re-tab.is-active { color: var(--info); border-bottom-color: var(--info); font-weight: 600; }

.re-content { max-width: 900px; margin: auto;}
.re-content--wide { max-width: none; }

.re-builder-wrap {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    overflow: hidden;
    height: 720px;
    max-width: 100%;
    display: flex;
    flex-direction: column;
}

.re-row-remove {
    background: var(--danger-light);
    color: var(--danger);
    border: none;
    border-radius: 4px;
    width: 26px;
    height: 26px;
    cursor: pointer;
    font-size: 16px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

/* Toggle switch */
.switch { position: relative; display: inline-block; width: 38px; height: 22px; flex-shrink: 0; }
.switch input { display: none; }
.switch-slider {
    position: absolute;
    inset: 0;
    background: var(--border-color);
    border-radius: 999px;
    cursor: pointer;
    transition: background 0.15s;
}
.switch-slider::before {
    content: '';
    position: absolute;
    left: 3px;
    top: 3px;
    width: 16px;
    height: 16px;
    background: #fff;
    border-radius: 50%;
    transition: transform 0.15s;
}
.switch input:checked + .switch-slider { background: var(--success); }
.switch input:checked + .switch-slider::before { transform: translateX(16px); }

/* Email History row menu */
.re-menu-wrap { position: relative; }
.re-menu-btn {
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid transparent;
    background: transparent;
    border-radius: 6px;
    cursor: pointer;
    color: var(--text-secondary);
}
.re-menu-btn:hover { background: var(--bg-hover); border-color: var(--border-color); color: var(--text-primary); }
.re-dropdown {
    position: absolute;
    right: 0;
    top: calc(100% + 4px);
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    box-shadow: 0 8px 24px rgba(0,0,0,0.12);
    min-width: 160px;
    z-index: 100;
    overflow: hidden;
    padding: 4px 0;
}
.re-dd-item {
    display: block;
    width: 100%;
    padding: 9px 14px;
    font-size: 13px;
    color: var(--text-primary);
    cursor: pointer;
    text-decoration: none;
    background: none;
    border: none;
    text-align: left;
}
.re-dd-item:hover { background: var(--bg-hover); color: var(--text-primary); }

/* Preview Email modal */
.re-preview-meta {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 16px;
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--border-color);
}
.re-preview-label { font-size: 11px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; letter-spacing: .04em; margin-bottom: 4px; }
.re-preview-value { font-size: 13px; color: var(--text-primary); font-weight: 500; word-break: break-word; }
.re-device-btn {
    border: none;
    background: transparent;
    cursor: pointer;
    padding: 6px 14px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 500;
    color: var(--text-secondary);
}
.re-device-btn.is-active { background: var(--bg-surface); color: var(--text-primary); box-shadow: 0 1px 2px rgba(0,0,0,0.08); }
.re-preview-frame {
    border: 1px solid var(--border-color);
    border-radius: 8px;
    background: var(--bg-page);
    padding: 24px;
    max-height: 60vh;
    overflow-y: auto;
    display: flex;
    justify-content: center;
}
.re-preview-frame > div { width: 100%; max-width: 600px; background: var(--bg-surface); }
.re-preview-frame.is-mobile > div { max-width: 375px; }

/* Email History  grid row list (matches Campaigns list pattern), NOT a table.
   overflow: visible is required here, or the row's action dropdown gets
   clipped by the wrapper  that was the previous bug. */
.re-history-wrap {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    overflow: visible;
}
.re-history-empty {
    text-align: center;
    padding: 64px 24px;
    color: var(--text-primary);
    font-weight: 600;
    font-size: 14px;
}
.re-history-col-header,
.re-history-row {
    display: grid;
    grid-template-columns: 1fr 90px 70px 70px 80px 70px 70px 110px 170px;
    align-items: center;
    gap: 8px;
}
.re-history-col-header {
    padding: 0 20px;
    background: var(--bg-hover);
    border-bottom: 1px solid var(--border-color);
    height: 36px;
    border-radius: 10px 10px 0 0;
}
.re-history-col-header > div {
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.04em;
    color: var(--text-muted);
}
.re-history-row {
    padding: 14px 20px;
    border-bottom: 1px solid var(--border-color);
    transition: background 0.12s;
    position: relative;
}
.re-history-row:last-child { border-bottom: none; }
.re-history-row:hover { background: var(--bg-hover); }

.re-history-title { font-size: 14px; font-weight: 600; color: var(--text-primary); line-height: 1.3; }
.re-history-date { font-size: 12px; color: var(--text-muted); margin-top: 2px; }

.re-hcol-stat { text-align: center; font-size: 13px; color: var(--text-primary); }
.re-hcol-status { text-align: center; }
.re-hcol-actions { display: flex; align-items: center; justify-content: flex-end; gap: 8px; }

.re-history-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 20px;
    border-top: 1px solid var(--border-color);
    gap: 12px;
    flex-wrap: wrap;
}

/* ── Custom responsive grids ── */
.re-grid-2 {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
}
.re-grid-5 {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 16px;
}

@media (max-width: 1024px) {
    .re-history-col-header {
        display: none;
    }
    .re-history-row {
        display: block;
        padding: 16px;
        position: relative;
    }
    .re-history-row > div {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 6px 0;
        font-size: 13px;
        text-align: right;
    }
    .re-history-row .re-hcol-name {
        display: block;
        text-align: left;
        padding-bottom: 12px;
        border-bottom: 1px solid var(--border-color);
        margin-bottom: 8px;
    }
    .re-history-row .re-hcol-actions {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        border-top: 1px solid var(--border-color);
        margin-top: 8px;
        padding-top: 10px;
    }
    .re-history-row .re-hcol-stat::before {
        font-weight: 600;
        color: var(--text-muted);
        text-transform: uppercase;
        font-size: 10px;
        letter-spacing: 0.05em;
        margin-right: 8px;
    }
    .re-history-row .re-hcol-stat:nth-child(2)::before { content: "Recipients"; }
    .re-history-row .re-hcol-stat:nth-child(3)::before { content: "Sent"; }
    .re-history-row .re-hcol-stat:nth-child(4)::before { content: "Failed"; }
    .re-history-row .re-hcol-stat:nth-child(5)::before { content: "Bounced"; }
    .re-history-row .re-hcol-stat:nth-child(6)::before { content: "Opens"; }
    .re-history-row .re-hcol-stat:nth-child(7)::before { content: "Clicks"; }
    .re-history-row .re-hcol-status::before {
        content: "Status";
        font-weight: 600;
        color: var(--text-muted);
        text-transform: uppercase;
        font-size: 10px;
        letter-spacing: 0.05em;
        margin-right: 8px;
    }
}

@media (max-width: 768px) {
    .re-grid-2 {
        grid-template-columns: 1fr;
    }
    .re-grid-5 {
        grid-template-columns: 1fr;
    }
    .re-preview-meta {
        grid-template-columns: 1fr;
        gap: 12px;
    }
}
</style>
