<template>
    <Head :title="sequence.title + ' - Sequence Builder'" />

    <div class="app-layout" :class="{ 'sidebar-collapsed': collapsed, 'mobile-open': mobileOpen }" id="app">
        <!-- Sidebar Navigation -->
        <AppSidebar :collapsed="collapsed" :mobileOpen="mobileOpen" @toggle-sidebar="toggleSidebar" />

        <!-- Main Wrapper -->
        <div class="main-wrapper" style="display:flex;flex-direction:column;height:100vh;overflow:hidden">
            <AppTopbar @toggle-sidebar="toggleSidebar" />
            <div style="display:flex;flex-direction:column;height:100%;overflow:hidden">

                <!-- Top Bar -->
                <div class="sb-topbar">
                    <div class="sb-topbar-header">
                        <Link href="/sequences" class="sb-topbar-back">
                            <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="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18" />
                            </svg>
                            Sequences
                        </Link>
                        <div class="sb-topbar-divider"></div>
                        <div class="sb-topbar-name">
                            <input type="text" v-model="form.title" @change="saveSequence" spellcheck="false">
                        </div>
                        <span class="sb-topbar-status" :class="statusBadgeClass(form.status)">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:10px;height:10px">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931z" />
                            </svg>
                            {{ statusLabel(form.status) }}
                        </span>
                    </div>

                    <div class="sb-topbar-actions">
                        <span v-if="saving" style="font-size:12px;color:#9ca3af">Saving…</span>
                        <button class="sb-btn" @click="resetSequence" title="Reset logs and re-enroll all matching contacts">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:13px;height:13px">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" />
                            </svg>
                            Reset &amp; Re-run
                        </button>
                        <button class="sb-btn" @click="togglePreview">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:13px;height:13px">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z" />
                                <path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                            </svg>
                            Preview
                        </button>
                        <button class="sb-btn" @click="saveSequence">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:13px;height:13px">
                                <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>
                            Save Draft
                        </button>
                        <button v-if="form.status === 'draft'" class="sb-btn sb-btn-success" @click="openStartModal">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:13px;height:13px">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.348a1.125 1.125 0 010 1.971l-11.54 6.347a1.125 1.125 0 01-1.667-.985V5.653z" />
                            </svg>
                            Start Sequence
                        </button>
                        <button v-else-if="form.status === 'paused'" class="sb-btn sb-btn-success" @click="setStatus('active')">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:13px;height:13px">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.348a1.125 1.125 0 010 1.971l-11.54 6.347a1.125 1.125 0 01-1.667-.985V5.653z" />
                            </svg>
                            Resume Sequence
                        </button>
                        <button v-else-if="form.status === 'active'" class="sb-btn" style="background:#f59e0b;color:#fff;border-color:#d97706" @click="setStatus('paused')">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:13px;height:13px">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 5.25v13.5m-7.5-13.5v13.5" />
                            </svg>
                            Pause Sequence
                        </button>
                    </div>
                </div>

                <div class="sb-layout">
                    <!-- Builder Canvas -->
                    <div class="sb-canvas">
                        <div class="sb-canvas-inner">
                            <!-- Start block -->
                            <div class="sb-trigger-block sb-trigger-block--clickable" :class="{ 'is-selected': rightPanelMode === 'sequence' }" @click="selectSequencePanel">
                                <div class="sb-trigger-block-label">
                                    <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 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z" />
                                    </svg>
                                    Sequence Start
                                </div>
                                <div class="sb-trigger-title">{{ recipientCount }} recipient(s) selected</div>
                                <div class="sb-trigger-desc">
                                    <span v-if="form.status === 'draft'">Click "Start Sequence" above to send Step 1 to your recipients.</span>
                                    <span v-else-if="form.send_mode === 'schedule' && form.scheduled_at">Starts {{ formattedScheduledAt }}.</span>
                                    <span v-else>Started immediately; contacts enter one after another.</span>
                                </div>
                            </div>

                            <!-- Steps container -->
                            <template v-for="(step, idx) in form.settings.steps" :key="step.id">
                                <SequenceStep
                                    :step="step"
                                    :index="idx"
                                    :step-label="`Step ${idx + 1}`"
                                    :is-selected="rightPanelMode === 'step' && selectedStepIdx === idx"
                                    :open-tooltip-node-id="openTooltipNodeId"
                                    :node-status="nodeStatus"
                                    :step-stats="props.stepStats"
                                    @select="handleSelect"
                                    @remove="handleRemove"
                                    @save="saveSequence"
                                    @open-delay="handleOpenDelay"
                                    @toggle-tooltip="(id) => openTooltipNodeId = (openTooltipNodeId === id ? null : id)"
                                />
                            </template>

                            <!-- Add step button -->
                            <div class="sb-connector">
                                <div class="sb-connector-line" style="height:16px"></div>
                            </div>
                            <div style="position:relative;width:100%;display:flex;justify-content:center">
                                <button class="sb-add-step" @click="addStep">
                                    <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="M12 4.5v15m7.5-7.5h-15" />
                                    </svg>
                                    Add Email
                                </button>
                            </div>

                            <!-- End of sequence marker -->
                            <div class="sb-connector">
                                <div class="sb-connector-line" style="height:20px"></div>
                            </div>
                            <div style="text-align:center;padding:12px 20px;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:10px;font-size:12px;font-weight:600;color:#16a34a;display:flex;align-items:center;justify-content:center;gap:6px;max-width:500px;width:100%;box-sizing:border-box">
                                <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="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                                End of Sequence · Contact completes enrollment
                            </div>
                            <div style="height:40px"></div>
                        </div>
                    </div>

                    <!-- Right Panel: Sequence settings, or the selected step's settings -->
                    <div class="sb-details" style="display:flex">
                        <div class="sb-details-header" style="display:flex; justify-content:space-between; align-items:center; width:100%;">
                            <h4>{{ rightPanelMode === 'sequence' ? 'Sequence Settings' : 'Step Details' }}</h4>
                            <div v-if="rightPanelMode === 'step'" style="display:flex; gap:10px; align-items:center;">
                                <button @click="deleteSelectedStep" title="Delete step" style="border:none; background:none; cursor:pointer; color:#ef4444; display:flex; align-items:center; justify-content:center; padding:4px; border-radius:4px;">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:16px;height:16px;">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
                                    </svg>
                                </button>
                                <button class="sb-details-close" @click="selectSequencePanel">
                                    <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="M6 18L18 6M6 6l12 12" />
                                    </svg>
                                </button>
                            </div>
                        </div>

                        <!-- Sequence-level settings -->
                        <div class="sb-details-body" v-if="rightPanelMode === 'sequence'">
                            <!-- Stats -->
                            <div class="sb-stat-row">
                                <div class="sb-stat">
                                    <div class="sb-stat-val">{{ stats.enrolled }}</div>
                                    <div class="sb-stat-label">Enrolled</div>
                                </div>
                                <div class="sb-stat">
                                    <div class="sb-stat-val">{{ stats.completed }}</div>
                                    <div class="sb-stat-label">Completed</div>
                                </div>
                                <div class="sb-stat">
                                    <div class="sb-stat-val">{{ stats.avgOpen }}%</div>
                                    <div class="sb-stat-label">Avg Open</div>
                                </div>
                            </div>

                            <div class="sb-details-section">
                                <div class="sb-details-section-title">Recipients</div>
                                <div class="sb-recipients-tabs">
                                    <div class="sb-recipients-tab" :class="{ 'is-active': form.recipients_config.mode !== 'advanced_filter' }" @click="setRecipientsMode('list_tag')">By List &amp; Tag</div>
                                    <div class="sb-recipients-tab" :class="{ 'is-active': form.recipients_config.mode === 'advanced_filter' }" @click="setRecipientsMode('advanced_filter')">Advanced Filter</div>
                                </div>

                                <template v-if="form.recipients_config.mode !== 'advanced_filter'">
                                    <div v-for="(row, idx) in form.recipients_config.included" :key="'inc-'+idx" class="sb-recipient-row">
                                        <CwSelect v-model="row.list_id" :options="listOptions" style="flex:1" @change="onRecipientsChange" />
                                        <CwSelect v-model="row.tag_id" :options="tagOptions" style="flex:1" @change="onRecipientsChange" />
                                        <button class="sb-recipient-act" @click="addIncluded" title="Add row">+</button>
                                        <button class="sb-recipient-act" @click="removeIncluded(idx)" :disabled="form.recipients_config.included.length === 1" title="Remove row">−</button>
                                    </div>

                                    <button class="sb-recipient-exclude-toggle" @click="showExcluded = !showExcluded">
                                        {{ showExcluded ? '− Hide' : '+ Add' }} exclusion rules
                                        <span v-if="form.recipients_config.excluded.length">({{ form.recipients_config.excluded.length }})</span>
                                    </button>
                                    <template v-if="showExcluded">
                                        <div v-for="(row, idx) in form.recipients_config.excluded" :key="'exc-'+idx" class="sb-recipient-row">
                                            <CwSelect v-model="row.list_id" :options="listOptions" style="flex:1" @change="onRecipientsChange" />
                                            <CwSelect v-model="row.tag_id" :options="tagOptions" style="flex:1" @change="onRecipientsChange" />
                                            <button class="sb-recipient-act" @click="removeExcluded(idx)" title="Remove row">−</button>
                                        </div>
                                        <button class="sb-recipient-act-add" @click="addExcluded">+ Add exclusion row</button>
                                    </template>
                                </template>
                                <template v-else>
                                    <AdvancedFilterBuilder
                                        v-model="form.recipients_config.filter"
                                        :menu="filterFieldMenu"
                                        :lists="lists"
                                        :tags="tags"
                                        :campaigns="campaigns"
                                        :automations="automations"
                                        @apply="onRecipientsChange"
                                    />
                                </template>

                                <div class="sb-recipient-count">
                                    <span v-if="loadingRecipientCount">Counting…</span>
                                    <span v-else>{{ recipientCount }} contact(s) will receive this sequence</span>
                                </div>
                                <button v-if="form.status !== 'draft'" class="sb-btn sb-btn--secondary" style="width:100%;justify-content:center;margin-top:4px" @click="enrollNewContacts" :disabled="enrollingNew">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:13px;height:13px">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M18 7.5v3m0 0v3m0-3h3m-3 0h-3m-2.25-4.125a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zM3 19.235v-.11a6.375 6.375 0 0112.75 0v.109A12.318 12.318 0 019.374 21c-2.331 0-4.512-.645-6.374-1.766z" />
                                    </svg>
                                    {{ enrollingNew ? 'Enrolling…' : 'Enroll New Matching Contacts' }}
                                </button>
                            </div>

                            <div class="sb-details-section">
                                <div class="sb-details-section-title">Sending Behavior</div>
                                <div class="sb-field" style="margin-bottom:10px">
                                    <label>SMTP Configuration</label>
                                    <CwSelect v-model="form.settings.smtp_config_id" :options="smtpSelectOptions" @change="saveSequence" />
                                    <div style="font-size:11px;color:#9ca3af;margin-top:4px">Used by every email step in this sequence.</div>
                                </div>
                                <div class="sb-field" style="margin-bottom:0">
                                    <label>Time Zone</label>
                                    <CwSelect v-model="form.settings.timezone" :options="timezoneOptions" @change="saveSequence" />
                                </div>
                            </div>

                            <div class="sb-details-section">
                                <div class="sb-details-section-title">Tags Applied on Completion</div>
                                <div class="sb-tag-list">
                                    <div class="sb-tag" v-for="(tag, idx) in form.settings.completion_tags" :key="idx">
                                        {{ tag }}
                                        <button @click="removeCompletionTag(idx)">&times;</button>
                                    </div>
                                </div>
                                <div style="display:flex;gap:6px">
                                    <input type="text" v-model="newCompletionTag" placeholder="Add tag…"
                                        style="flex:1;padding:5px 8px;border:1px solid #e5e7eb;border-radius:5px;font-size:12px;font-family:inherit;outline:none"
                                        @keydown.enter="addCompletionTag">
                                    <button @click="addCompletionTag"
                                        style="padding:5px 10px;border:1px solid #e5e7eb;border-radius:5px;font-size:12px;cursor:pointer;background:#fff">Add</button>
                                </div>
                            </div>

                            <div class="sb-details-section">
                                <div class="sb-details-section-title">Description</div>
                                <div class="sb-field" style="margin-bottom:0">
                                    <textarea v-model="form.settings.description" @change="saveSequence" placeholder="Internal notes about this sequence…"></textarea>
                                </div>
                            </div>

                            <!-- Diagnostic & Status Panel -->
                            <div class="sb-details-section" style="border-top:1px solid #e5e7eb;padding-top:16px">
                                <div class="sb-diagnostics-label">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-activity-icon"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>
                                    Diagnostics &amp; Live Status
                                </div>
                                <div class="sb-field" style="margin-top:10px;margin-bottom:0">
                                    <button class="sb-btn sb-btn--secondary" @click="showDiagnosticsModal = true" style="width: 100%; display: flex; align-items: center; justify-content: center; gap: 8px;">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>
                                        View Live Status ({{ pendingJobs.length }})
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Selected step's settings -->
                        <div class="sb-details-body" v-else-if="selectedStep !== null">
                            <div class="sb-details-section">
                                <div class="sb-details-section-title">Email</div>
                                <div class="sb-field" style="margin-bottom:10px">
                                    <label>Email Subject</label>
                                    <input type="text" v-model="selectedStep.subject" @change="saveSequence" placeholder="Enter email subject...">
                                </div>
                                <div class="sb-field" style="margin-bottom:0">
                                    <label>Email Pre-Header</label>
                                    <input type="text" v-model="selectedStep.pre_header" @change="saveSequence" placeholder="Preview text shown next to the subject">
                                </div>
                            </div>
                            <div class="sb-details-section">
                                <div class="sb-details-section-title">Sender</div>
                                <div class="sb-field" style="margin-bottom:10px">
                                    <label>From Name</label>
                                    <input type="text" v-model="selectedStep.from_name" @change="saveSequence">
                                </div>
                                <div class="sb-field" style="margin-bottom:0">
                                    <label>Reply-To Email</label>
                                    <input type="email" v-model="selectedStep.from_email" @change="saveSequence">
                                </div>
                            </div>
                            <div class="sb-details-section">
                                <div class="sb-details-section-title">Send Window</div>
                                <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:10px">
                                    <div class="sb-field" style="margin-bottom:0">
                                        <label>Sending Time Range</label>
                                        <div style="display:flex;gap:6px;align-items:center">
                                            <CwSelect
                                                v-model="selectedStep.send_hours_start"
                                                :options="hourOptions"
                                                @change="(val) => {
                                                    if (val === 'Any time') {
                                                        selectedStep.send_hours_end = 'Any time';
                                                    }
                                                    saveSequence();
                                                }"
                                                style="flex:1"
                                            />
                                            <template v-if="selectedStep.send_hours_start !== 'Any time'">
                                                <span style="font-size:12px;color:#9ca3af">to</span>
                                                <CwSelect v-model="selectedStep.send_hours_end" :options="hourOptions.filter(h => h.value !== 'Any time')" @change="saveSequence" style="flex:1" />
                                            </template>
                                        </div>
                                    </div>
                                    <div class="sb-field" style="margin-bottom:0">
                                        <label>Delay</label>
                                        <div style="display:flex;gap:6px">
                                            <input type="number" min="0" v-model.number="selectedStep.delay.amount" @change="saveSequence" style="width:64px">
                                            <CwSelect v-model="selectedStep.delay.unit" :options="delayUnitOptions" @change="saveSequence" style="flex:1" />
                                        </div>
                                    </div>
                                </div>
                                <label style="display:flex;align-items:center;gap:8px;font-size:12px;cursor:pointer;margin-bottom:8px">
                                    <input type="checkbox" :checked="!!(selectedStep.send_specific_days && selectedStep.send_specific_days.length)" @change="toggleSpecificDays(selectedStep, $event.target.checked)">
                                    Enable Specific Days Only
                                </label>
                                <div v-if="hasSpecificDays(selectedStep)" style="display:flex;gap:4px">
                                    <button v-for="d in weekDays" :key="d.value" type="button"
                                        class="sb-day-toggle" :class="{ 'is-active': selectedStep.send_specific_days.includes(d.value) }"
                                        @click="toggleDay(selectedStep, d.value)">
                                        {{ d.label }}
                                    </button>
                                </div>
                            </div>
                            <div class="sb-details-section">
                                <div class="sb-details-section-title">Tracking</div>
                                <div style="display:flex;flex-direction:column;gap:8px">
                                    <label style="display:flex;align-items:center;gap:8px;font-size:12px;cursor:pointer">
                                        <input type="checkbox" v-model="selectedStep.track_opens" @change="saveSequence"> Track email opens
                                    </label>
                                    <label style="display:flex;align-items:center;gap:8px;font-size:12px;cursor:pointer">
                                        <input type="checkbox" v-model="selectedStep.track_clicks" @change="saveSequence"> Track link clicks
                                    </label>
                                    <label style="display:flex;align-items:center;gap:8px;font-size:12px;cursor:pointer">
                                        <input type="checkbox" v-model="selectedStep.track_utm" @change="saveSequence"> Add UTM parameters
                                    </label>
                                    <div v-if="selectedStep.track_utm" style="margin-top:12px; display:flex; flex-direction:column; gap:10px; border-top:1px dashed #e5e7eb; padding-top:12px">
                                        <div class="sb-field" style="margin-bottom:0">
                                            <label>Campaign Source <span style="color:#ef4444">*</span></label>
                                            <input type="text" v-model="selectedStep.utm_source" @change="saveSequence" placeholder="e.g. google, newsletter">
                                        </div>
                                        <div class="sb-field" style="margin-bottom:0">
                                            <label>Campaign Medium <span style="color:#ef4444">*</span></label>
                                            <input type="text" v-model="selectedStep.utm_medium" @change="saveSequence" placeholder="e.g. cpc, email, banner">
                                        </div>
                                        <div class="sb-field" style="margin-bottom:0">
                                            <label>Campaign Name <span style="color:#ef4444">*</span></label>
                                            <input type="text" v-model="selectedStep.utm_campaign" @change="saveSequence" placeholder="e.g. spring_sale">
                                        </div>
                                        <div class="sb-field" style="margin-bottom:0">
                                            <label>Campaign Term</label>
                                            <input type="text" v-model="selectedStep.utm_term" @change="saveSequence" placeholder="Identify paid keywords">
                                        </div>
                                        <div class="sb-field" style="margin-bottom:0">
                                            <label>Campaign Content</label>
                                            <input type="text" v-model="selectedStep.utm_content" @change="saveSequence" placeholder="Differentiate ad creatives">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="sb-details-section">
                                <div class="sb-details-section-title">Performance</div>
                                <div v-if="selectedStepPerf && selectedStepPerf.sent > 0" style="display:flex;gap:14px;padding:8px 0">
                                    <div><div style="font-weight:700;font-size:15px">{{ selectedStepPerf.sent }}</div><div style="font-size:11px;color:#9ca3af">Sent</div></div>
                                    <div><div style="font-weight:700;font-size:15px">{{ Math.round((selectedStepPerf.opens / selectedStepPerf.sent) * 100) }}%</div><div style="font-size:11px;color:#9ca3af">Opened</div></div>
                                    <div><div style="font-weight:700;font-size:15px">{{ Math.round((selectedStepPerf.clicks / selectedStepPerf.sent) * 100) }}%</div><div style="font-size:11px;color:#9ca3af">Clicked</div></div>
                                </div>
                                <div v-else style="color:#9ca3af;font-size:12px;text-align:center;padding:12px 0">
                                    No data yet · start the sequence to begin tracking
                                </div>
                            </div>
                            <div class="sb-details-section" style="border-top:1px solid #e5e7eb;padding-top:16px">
                                <div class="sb-details-section-title">Email Content</div>
                                <div style="display:flex;flex-direction:column;gap:8px;width:100%">
                                    <button class="sb-step-btn sb-step-btn-primary" style="justify-content:center;padding:8px 12px;font-weight:600" @click.stop="editSelectedEmail">
                                        <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;margin-right:4px">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931z" />
                                        </svg>
                                        Edit Email Body
                                    </button>
                                    <button class="sb-step-btn" style="justify-content:center;padding:8px 12px;font-weight:600" @click.stop="sendSelectedTestEmail">
                                        Send Test Email
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

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

    <!-- Delay editor modal -->
    <div class="modal-overlay" :class="{ 'is-open': editingDelayIdx !== null }" @click.self="editingDelayIdx = null">
        <div class="modal" style="width:420px;max-width:96vw;overflow:visible" v-if="editingDelayIdx !== null">
            <div class="modal-header">
                <h2 class="modal-title">Edit Delay</h2>
                <button class="modal-close" @click="editingDelayIdx = null">
                    <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;overflow:visible">
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:14px">
                    <div class="form-group" style="margin-bottom:0">
                        <label class="form-label">Wait</label>
                        <input type="number" class="form-input" v-model.number="tempDelay.amount" min="0">
                    </div>
                    <div class="form-group" style="margin-bottom:0">
                        <label class="form-label">Unit</label>
                        <CwSelect v-model="tempDelay.unit" :options="delayUnitOptions" />
                    </div>
                </div>
            </div>
            <div class="modal-footer" style="justify-content:flex-end">
                <button class="btn btn-outline" @click="editingDelayIdx = null">Cancel</button>
                <button class="btn btn-primary" @click="saveDelay">Save Delay</button>
            </div>
        </div>
    </div>

    <!-- Start Sequence Modal -->
    <div class="modal-overlay" :class="{ 'is-open': showStartModal }" @click.self="showStartModal = false">
        <div class="modal" style="width:460px;max-width:96vw">
            <div class="modal-header">
                <h2 class="modal-title">Start Sequence</h2>
                <button class="modal-close" @click="showStartModal = false">
                    <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; display:flex; flex-direction:column; gap:14px;">
                <div style="font-size:13px;color:var(--text-secondary)">
                    {{ recipientCount }} contact(s) will be enrolled and receive Step 1 of this sequence.
                </div>
                <label class="cw-radio-item" style="display:flex;align-items:center;gap:8px">
                    <input type="radio" v-model="startSendMode" value="now" />
                    <span>Start right now</span>
                </label>
                <label class="cw-radio-item" style="display:flex;align-items:center;gap:8px">
                    <input type="radio" v-model="startSendMode" value="schedule" />
                    <span>Start at a specific date &amp; time</span>
                </label>
                <div v-if="startSendMode === 'schedule'" style="padding-left:2px">
                    <CwDateTimePicker v-model="startScheduledAt" placeholder="Choose date & time" align="left" />
                    <div style="font-size:11px;color:var(--text-muted);margin-top:6px">
                        Current time in your account timezone ({{ tenantTimezone }}): <code>{{ serverTime }}</code>
                    </div>
                </div>
                <div v-if="startError" style="color:#ef4444;font-size:12px">{{ startError }}</div>
            </div>
            <div class="modal-footer" style="justify-content:flex-end">
                <button class="btn btn-outline" @click="showStartModal = false">Cancel</button>
                <button class="btn btn-primary" :disabled="starting" @click="doStartSequence">
                    {{ starting ? 'Starting…' : (startSendMode === 'now' ? 'Start Now' : 'Schedule Start') }}
                </button>
            </div>
        </div>
    </div>

    <!-- Sequence Preview Modal -->
    <div class="modal-overlay" :class="{ 'is-open': showPreview }" @click.self="showPreview = false">
        <div class="modal" style="width:640px;max-width:96vw">
            <div class="modal-header">
                <h2 class="modal-title">Sequence Preview</h2>
                <button class="modal-close" @click="showPreview = false">
                    <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; display:flex; flex-direction:column; gap:16px;">
                <div>
                    <h3 style="font-weight:700; font-size:16px; margin-bottom:4px; color:var(--text-primary);">{{ form.title }}</h3>
                    <p style="color:var(--text-secondary);font-size:13px;margin:0">{{ form.settings.description || 'No description provided.' }}</p>
                </div>

                <!-- Tab Switcher -->
                <div style="display:flex; border-bottom:1px solid var(--border-color);">
                    <button @click="activePreviewTab = 'timeline'" :style="{ borderBottom: activePreviewTab === 'timeline' ? '2px solid #2563eb' : '2px solid transparent', color: activePreviewTab === 'timeline' ? '#2563eb' : 'var(--text-muted)' }" style="flex: 1; padding: 10px; font-weight: 700; background: transparent; border: none; cursor: pointer; text-align: center; font-size: 13px; outline: none;">
                        Timeline Flow
                    </button>
                    <button @click="activePreviewTab = 'email'" :style="{ borderBottom: activePreviewTab === 'email' ? '2px solid #2563eb' : '2px solid transparent', color: activePreviewTab === 'email' ? '#2563eb' : 'var(--text-muted)' }" style="flex: 1; padding: 10px; font-weight: 700; background: transparent; border: none; cursor: pointer; text-align: center; font-size: 13px; outline: none;">
                        Email Previews
                    </button>
                </div>

                <!-- Tab content: Timeline -->
                <div v-if="activePreviewTab === 'timeline'" style="border-left:2px solid var(--border-color);padding-left:16px;margin-left:8px; max-height:400px; overflow-y:auto;">
                    <div style="font-weight:600;font-size:11px;text-transform:uppercase;color:var(--text-muted);margin-bottom:12px">Steps Timeline</div>
                    <div v-for="(step, idx) in form.settings.steps" :key="step.id" style="margin-bottom:16px">
                        <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">
                            <span v-if="idx === 0 && step.delay.amount === 0">Send immediately</span>
                            <span v-else>Wait {{ step.delay.amount }} {{ step.delay.unit }}</span>
                        </div>
                        <div style="padding:10px;background:var(--bg-hover);border:1px solid var(--border-color);border-radius:6px;font-size:13px;color:var(--text-primary)">
                            <span style="font-weight:600;color:#2563eb">📧 Send Email:</span>
                            {{ step.subject }}
                        </div>
                    </div>
                    <div style="font-size:12px;font-weight:600;color:#16a34a">✓ End of Sequence</div>
                </div>

                <!-- Tab content: Email Previews -->
                <div v-else style="display:flex; flex-direction:column; gap:12px;">
                    <div v-if="form.settings.steps.length === 0" style="text-align:center; padding:40px; border:1px dashed var(--border-color); border-radius:8px; color:var(--text-muted); font-size:13px;">
                        No email steps found in this sequence.
                    </div>
                    <div v-else style="display:flex; flex-direction:column; gap:12px;">
                        <div>
                            <label style="display:block; font-size:12px; font-weight:700; color:var(--text-muted); margin-bottom:4px; text-transform:uppercase; letter-spacing:0.05em;">Select Email Step</label>
                            <select :value="selectedPreviewStepId" @change="fetchEmailPreview($event.target.value)" style="width:100%; padding:8px 12px; border:1px solid var(--border-color); border-radius:6px; background:var(--bg-surface); color:var(--text-primary); font-size:13px; font-family:inherit; outline:none;">
                                <option v-for="step in form.settings.steps" :key="step.id" :value="step.id">
                                    {{ step.subject || '(Untitled Email)' }}
                                </option>
                            </select>
                        </div>
                        <div style="position:relative; min-height:350px;">
                            <div v-if="loadingPreviewHtml" style="position:absolute; inset:0; display:flex; align-items:center; justify-content:center; background:rgba(var(--bg-surface-rgb), 0.7); z-index:10; border-radius:6px;">
                                <div style="display:flex; flex-direction:column; align-items:center; gap:8px;">
                                    <svg class="animate-spin" style="width:24px; height:24px; color:#2563eb" fill="none" viewBox="0 0 24 24">
                                        <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" style="opacity:0.25;"></circle>
                                        <path fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                    </svg>
                                    <span style="font-size:12px; color:var(--text-muted); font-weight:500;">Generating live email preview...</span>
                                </div>
                            </div>
                            <iframe v-if="emailPreviewHtml" :srcdoc="emailPreviewHtml" style="width:100%; height:380px; border:1px solid var(--border-color); border-radius:6px; background:white;"></iframe>
                            <div v-else-if="!loadingPreviewHtml" style="display:flex; align-items:center; justify-content:center; height:380px; border:1px dashed var(--border-color); border-radius:6px; color:var(--text-muted); font-size:13px;">
                                No preview content generated.
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer" style="justify-content:flex-end">
                <button class="btn btn-primary" @click="showPreview = false">Close</button>
            </div>
        </div>
    </div>

    <!-- Send Test Email Modal -->
    <div class="modal-overlay" :class="{ 'is-open': showTestMailModal }" @click.self="closeTestMailModal">
        <div class="modal" style="width:420px;max-width:96vw">
            <div class="modal-header">
                <h2 class="modal-title">Send Test Email</h2>
                <button class="modal-close" @click="closeTestMailModal">
                    <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 class="sb-field" style="margin-bottom:0">
                    <label>Recipient Email Address <span style="color:#ef4444">*</span></label>
                    <input type="email" v-model="testMailRecipient" placeholder="recipient@example.com" style="width:100%" @keyup.enter="doSendSelectedTestEmail">
                    <div v-if="testMailError" style="color:#ef4444;font-size:12px;margin-top:6px">{{ testMailError }}</div>
                    <div v-if="testMailSuccess" style="color:#16a34a;font-size:12px;margin-top:6px">{{ testMailSuccess }}</div>
                </div>
            </div>
            <div class="modal-footer" style="justify-content:flex-end">
                <button class="btn btn-outline" @click="closeTestMailModal">Cancel</button>
                <button class="btn btn-primary" :disabled="testMailSending" @click="doSendSelectedTestEmail">
                    {{ testMailSending ? 'Sending...' : 'Send Test' }}
                </button>
            </div>
        </div>
    </div>

    <!-- Fullscreen Email Builder Overlay -->
    <div v-if="editingEmailIdx !== null" class="modal-overlay is-open" style="z-index: 100000; padding: 0; background: var(--bg-surface);">
        <div style="width: 100vw; height: 100vh; display: flex; flex-direction: column; overflow: hidden; background: var(--bg-page);">
            <!-- Header bar inside editor -->
            <div class="sb-topbar" style="background: var(--bg-surface); border-bottom: 1px solid var(--border-color); z-index: 10;">
                <button class="sb-topbar-back" @click="closeEmailEditor">
                    <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="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18" />
                    </svg>
                    Back to Sequence Builder
                </button>
                <div class="sb-topbar-divider"></div>
                <div style="font-weight: 600; color: var(--text-primary); flex: 1;">
                    Editing Step: {{ getEditingStepSubject }}
                </div>
                <div class="sb-topbar-actions">
                    <button class="btn btn-primary" @click="closeEmailEditor">Save &amp; Return</button>
                </div>
            </div>
            <!-- Canvas -->
            <div style="flex: 1; overflow: hidden; position: relative;">
                <EmailEditor v-model="getEditingStepBlocks" :campaign-id="form.id" :global-settings="globalSettings" />
            </div>
        </div>
    </div>
    <!-- Diagnostics Modal -->
    <div class="sb-modal-overlay" :class="{ 'is-open': showDiagnosticsModal }" @click.self="showDiagnosticsModal = false">
        <div class="sb-modal-card" :class="{ 'is-open': showDiagnosticsModal }">
            <div class="sb-modal-header">
                <span class="modal-title">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>
                    Sequence Diagnostics &amp; Live Status
                </span>
                <button class="modal-close" @click="showDiagnosticsModal = false">&times;</button>
            </div>
            <div class="sb-modal-body">
                <!-- Queue Connection Banner -->
                <div class="sb-diag-card">
                    <div>
                        <div style="font-size:10px; text-transform:uppercase; font-weight:700; color:var(--text-muted); margin-bottom:2px">Queue Connection Status</div>
                        <div style="font-size:15px; font-weight:700; color:var(--text-primary); text-transform:uppercase">{{ queueConnection }}</div>
                    </div>
                    <span v-if="queueConnection === 'database'" class="sb-topbar-status badge--sending" style="font-size:10px; padding:4px 10px; border-radius:6px; font-weight:700">Active (needs worker)</span>
                    <span v-else class="sb-topbar-status badge--draft" style="font-size:10px; padding:4px 10px; border-radius:6px; font-weight:700">In-process (Sync)</span>
                </div>

                <!-- Sequence Steps Live Performance & Metrics -->
                <div style="font-size:11px; text-transform:uppercase; font-weight:700; color:var(--text-muted); margin-bottom:8px; letter-spacing:0.05em">Sequence Steps Performance</div>
                <div style="margin-bottom:20px;">
                    <div v-for="step in form.settings.steps" :key="step.id" class="sb-diag-step-row">
                        <div style="display:flex; flex-direction:column; gap:4px; flex: 1; min-width: 0;">
                            <div style="display:flex; align-items:center; gap:8px; min-width: 0;">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#3b82f6" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>
                                <span style="font-weight:600; font-size:13px; color:var(--text-primary); overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
                                    {{ step.subject }}
                                </span>
                            </div>
                        </div>
                        <div style="display:flex; gap:6px; align-items:center; flex-shrink: 0; margin-left: 12px;">
                            <span v-if="(nodeStatus[step.id]?.successCount || 0) > 0" class="sb-diag-badge-pill" style="color:#10b981; background:rgba(16,185,129,0.1)">
                                ✓ {{ nodeStatus[step.id].successCount }}
                            </span>
                            <span v-if="(nodeStatus[step.id]?.processingCount || 0) > 0" class="sb-diag-badge-pill" style="color:#3b82f6; background:rgba(59,130,246,0.1)">
                                ⏱ {{ nodeStatus[step.id].processingCount }}
                            </span>
                            <span v-if="(nodeStatus[step.id]?.errorCount || 0) > 0" class="sb-diag-badge-pill" style="color:#f43f5e; background:rgba(244,63,94,0.1)">
                                ⚠ {{ nodeStatus[step.id].errorCount }}
                            </span>
                            <span v-if="!(nodeStatus[step.id]?.successCount || nodeStatus[step.id]?.processingCount || nodeStatus[step.id]?.errorCount)" style="color:var(--text-muted); font-size:11px; font-style:italic">
                                No activity
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Pending Queue List -->
                <div style="font-size:11px; text-transform:uppercase; font-weight:700; color:var(--text-muted); margin-bottom:8px; letter-spacing:0.05em">Pending Live Queue ({{ pendingJobs.length }})</div>
                <div>
                    <div v-for="job in pendingJobs" :key="job.id" class="sb-diag-queue-card">
                        <div>
                            <div style="font-size:13px; font-weight:600; color:var(--text-primary)">{{ job.contact_email }}</div>
                            <div style="font-size:11px; color:var(--text-muted)">{{ job.step_desc || 'Sequence Step' }}</div>
                        </div>
                        <div style="font-size:12px; font-weight:700; color:#10b981">{{ job.run_time }}</div>
                    </div>
                    <div v-if="pendingJobs.length === 0" style="text-align:center; padding:24px; border: 1px dashed var(--border-color); border-radius:8px; color:var(--text-muted); font-size:13px;">
                        No pending steps in queue.
                    </div>
                </div>

                <!-- Failed Jobs List -->
                <div style="font-size:11px; text-transform:uppercase; font-weight:700; color:var(--text-muted); margin:20px 0 8px; letter-spacing:0.05em">Permanently Failed ({{ failedJobs.length }})</div>
                <div>
                    <div v-for="job in failedJobs" :key="job.id" class="sb-diag-queue-card" style="border-color:#fecaca;background:#fef2f2">
                        <div>
                            <div style="font-size:13px; font-weight:600; color:var(--text-primary)">{{ job.contact_email }}</div>
                            <div style="font-size:11px; color:var(--text-muted)">{{ job.step_desc }}</div>
                            <div style="font-size:11px; color:#dc2626; margin-top:2px">{{ job.exception }}</div>
                        </div>
                        <div style="font-size:11px; color:var(--text-muted); white-space:nowrap">{{ formatDateTime(job.failed_at) }}</div>
                    </div>
                    <div v-if="failedJobs.length === 0" style="text-align:center; padding:24px; border: 1px dashed var(--border-color); border-radius:8px; color:var(--text-muted); font-size:13px;">
                        No permanently failed steps.
                    </div>
                </div>
            </div>

        </div>
    </div>

    <!-- Mobile Sidebar Backdrop Overlay -->
    <Transition name="fade">
        <div v-if="mobileOpen" class="sidebar-backdrop" @click="mobileOpen = false"></div>
    </Transition>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
import { Head, Link, router, usePage } from '@inertiajs/vue3';
import SequenceStep from '@/Components/SequenceStep.vue';
import AppSidebar from '@/Components/AppSidebar.vue';
import AppTopbar from '@/Components/AppTopbar.vue';
import EmailEditor from '@/Components/EmailEditor/EmailEditor.vue';
import CwSelect from '@/Components/CwSelect.vue';
import CwDateTimePicker from '@/Components/CwDateTimePicker.vue';
import AdvancedFilterBuilder from '@/Components/AdvancedFilterBuilder.vue';
import { zonedTimeToUtcIso, formatInTimeZone, nowInTimeZone } from '@/utils/timezone';

const collapsed = ref(
    typeof window !== 'undefined' ? localStorage.getItem('sidebar-collapsed') === 'true' : false
);
const mobileOpen = ref(false);

const toggleSidebar = () => {
    if (typeof window !== 'undefined' && window.innerWidth <= 1024) {
        mobileOpen.value = !mobileOpen.value;
    } else {
        collapsed.value = !collapsed.value;
        if (typeof window !== 'undefined') {
            localStorage.setItem('sidebar-collapsed', collapsed.value ? 'true' : 'false');
        }
    }
};

const page = usePage();
watch(() => page.url, () => {
    mobileOpen.value = false;
});

const timezoneOptions = ref([
    { value: 'Contact\'s local time', label: 'Contact\'s local time' },
    { value: 'UTC', label: 'UTC' },
    { value: 'US/Eastern', label: 'US/Eastern' },
    { value: 'US/Pacific', label: 'US/Pacific' }
]);

let pollInterval = null;

onMounted(() => {
    try {
        const localTz = Intl.DateTimeFormat().resolvedOptions().timeZone;
        if (localTz && !timezoneOptions.value.some(o => o.value === localTz)) {
            timezoneOptions.value.push({ value: localTz, label: `Local: ${localTz}` });
        }
    } catch (e) {}

    fetchRecipientCount();

    pollInterval = setInterval(() => {
        if (form.value.status === 'active' && editingEmailIdx.value === null) {
            router.reload({
                only: ['sequence', 'pendingJobs', 'failedJobs', 'stats', 'stepStats'],
                preserveScroll: true,
                preserveState: true
            });
        }
    }, 3000);
});

onUnmounted(() => {
    if (pollInterval) {
        clearInterval(pollInterval);
    }
});

const weekDays = [
    { value: 0, label: 'Sun' },
    { value: 1, label: 'Mon' },
    { value: 2, label: 'Tue' },
    { value: 3, label: 'Wed' },
    { value: 4, label: 'Thu' },
    { value: 5, label: 'Fri' },
    { value: 6, label: 'Sat' },
];

const hourOptions = [
    { value: 'Any time', label: 'Any time (Send immediately)' },
    { value: '12:00 AM', label: '12:00 AM' },
    { value: '1:00 AM', label: '1:00 AM' },
    { value: '2:00 AM', label: '2:00 AM' },
    { value: '3:00 AM', label: '3:00 AM' },
    { value: '4:00 AM', label: '4:00 AM' },
    { value: '5:00 AM', label: '5:00 AM' },
    { value: '6:00 AM', label: '6:00 AM' },
    { value: '7:00 AM', label: '7:00 AM' },
    { value: '8:00 AM', label: '8:00 AM' },
    { value: '9:00 AM', label: '9:00 AM' },
    { value: '10:00 AM', label: '10:00 AM' },
    { value: '11:00 AM', label: '11:00 AM' },
    { value: '12:00 PM', label: '12:00 PM' },
    { value: '1:00 PM', label: '1:00 PM' },
    { value: '2:00 PM', label: '2:00 PM' },
    { value: '3:00 PM', label: '3:00 PM' },
    { value: '4:00 PM', label: '4:00 PM' },
    { value: '5:00 PM', label: '5:00 PM' },
    { value: '6:00 PM', label: '6:00 PM' },
    { value: '7:00 PM', label: '7:00 PM' },
    { value: '8:00 PM', label: '8:00 PM' },
    { value: '9:00 PM', label: '9:00 PM' },
    { value: '10:00 PM', label: '10:00 PM' },
    { value: '11:00 PM', label: '11:00 PM' }
];

const delayUnitOptions = [
    { value: 'minutes', label: 'minutes' },
    { value: 'hours', label: 'hours' },
    { value: 'days', label: 'days' },
    { value: 'weeks', label: 'weeks' }
];

const props = defineProps({
    sequence:      Object,
    lists:         Array,
    tags:          Array,
    smtpConfigs:   { type: Array, default: () => [] },
    defaultSender: Object,
    globalSettings: { type: Object, default: () => ({}) },
    stats:         { type: Object, default: () => ({ enrolled: 0, completed: 0, avgOpen: 0 }) },
    stepStats:     { type: Object, default: () => ({}) },
    pendingJobs:   { type: Array, default: () => [] },
    failedJobs:    { type: Array, default: () => [] },
    queueConnection: { type: String, default: 'sync' },
    filterFieldMenu: { type: Array, default: () => [] },
    campaigns:     { type: Array, default: () => [] },
    automations:   { type: Array, default: () => [] }
});

const filterFieldMenu = props.filterFieldMenu;
const campaigns = props.campaigns;
const automations = props.automations;

const smtpSelectOptions = computed(() => {
    return [
        { value: null, label: 'Default Sender Identity' },
        ...props.smtpConfigs.map(s => ({ value: s.id, label: `${s.name} (${s.from_email})` }))
    ];
});

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: 'Any Tag' },
        ...props.tags.map(t => ({ value: t.id, label: t.title }))
    ];
});

const form = ref({
    id:       props.sequence.id,
    title:    props.sequence.title,
    status:   props.sequence.status,
    send_mode: props.sequence.send_mode ?? null,
    scheduled_at: props.sequence.scheduled_at ?? null,
    recipients_config: props.sequence.recipients_config ? JSON.parse(JSON.stringify(props.sequence.recipients_config)) : {
        mode: 'list_tag',
        included: [{ list_id: null, tag_id: null }],
        excluded: []
    },
    settings: props.sequence.settings ? JSON.parse(JSON.stringify(props.sequence.settings)) : {
        timezone: 'Contact\'s local time',
        smtp_config_id: null,
        completion_tags: [],
        description: '',
        steps: []
    }
});
if (form.value.settings.smtp_config_id === undefined) {
    form.value.settings.smtp_config_id = null;
}

const stats = computed(() => props.stats);

const saving            = ref(false);
const showPreview       = ref(false);
const selectedStepIdx   = ref(null);
const rightPanelMode    = ref('sequence'); // 'sequence' | 'step'
const newCompletionTag  = ref('');
const editingDelayIdx   = ref(null);
const tempDelay         = ref({ amount: 1, unit: 'days' });
const editingEmailIdx   = ref(null);
const openTooltipNodeId = ref(null);

const showTestMailModal = ref(false);
const showDiagnosticsModal = ref(false);
const testMailRecipient = ref('test@example.com');
const testMailSending   = ref(false);
const testMailError     = ref('');
const testMailSuccess   = ref('');
const testMailTargetStep = ref(null);

const recipientCount = ref(0);
const loadingRecipientCount = ref(false);
const enrollingNew = ref(false);
const showExcluded = ref(false);

function enrollNewContacts() {
    enrollingNew.value = true;
    router.post(route('sequences.enroll-all', form.value.id), {}, {
        preserveScroll: true,
        onFinish: () => { enrollingNew.value = false; },
    });
}

async function fetchRecipientCount() {
    loadingRecipientCount.value = true;
    try {
        const res = await window.axios.post(route('campaigns.count-recipients'), form.value.recipients_config);
        recipientCount.value = res.data.count ?? 0;
    } catch (e) {
        // leave last known count on failure
    } finally {
        loadingRecipientCount.value = false;
    }
}

function onRecipientsChange() {
    fetchRecipientCount();
    saveSequence();
}

function setRecipientsMode(mode) {
    if (form.value.recipients_config.mode === mode) return;
    form.value.recipients_config.mode = mode;
    if (mode === 'advanced_filter' && !form.value.recipients_config.filter) {
        form.value.recipients_config.filter = { groups: [{ conditions: [{ field: null, operator: null, value: null }] }] };
    }
    onRecipientsChange();
}

function addIncluded() {
    form.value.recipients_config.included.push({ list_id: null, tag_id: null });
    onRecipientsChange();
}

function removeIncluded(idx) {
    if (form.value.recipients_config.included.length === 1) return;
    form.value.recipients_config.included.splice(idx, 1);
    onRecipientsChange();
}

function addExcluded() {
    form.value.recipients_config.excluded.push({ list_id: null, tag_id: null });
    onRecipientsChange();
}

function removeExcluded(idx) {
    form.value.recipients_config.excluded.splice(idx, 1);
    onRecipientsChange();
}

function handleSelect(idx) {
    selectedStepIdx.value = idx;
    rightPanelMode.value = 'step';
}

function selectSequencePanel() {
    rightPanelMode.value = 'sequence';
    selectedStepIdx.value = null;
}

function handleRemove(idx) {
    removeStep(idx);
}

function handleOpenDelay(idx) {
    const step = form.value.settings.steps[idx];
    tempDelay.value = { amount: step.delay.amount, unit: step.delay.unit };
    editingDelayIdx.value = idx;
}

function deleteSelectedStep() {
    if (selectedStepIdx.value !== null) {
        removeStep(selectedStepIdx.value);
    }
}

function editSelectedEmail() {
    if (selectedStepIdx.value === null) return;
    openEmailEditor(selectedStepIdx.value);
}

function sendSelectedTestEmail() {
    if (selectedStepIdx.value === null) return;
    const step = form.value.settings.steps[selectedStepIdx.value];
    if (!step) return;
    openTestMailModalForStep(step);
}

function openTestMailModalForStep(step) {
    testMailTargetStep.value = step;
    testMailError.value = '';
    testMailSuccess.value = '';
    showTestMailModal.value = true;
}

function closeTestMailModal() {
    showTestMailModal.value = false;
    testMailTargetStep.value = null;
}

async function doSendSelectedTestEmail() {
    const email = testMailRecipient.value.trim();
    if (!email) {
        testMailError.value = 'Please enter a recipient email address.';
        return;
    }
    if (!testMailTargetStep.value) return;

    testMailSending.value = true;
    testMailError.value = '';
    testMailSuccess.value = '';

    try {
        const response = await window.axios.post(route('sequences.send-test', form.value.id), {
            email: email,
            step_id: testMailTargetStep.value.id
        });
        if (response.data.success) {
            testMailSuccess.value = `Test email successfully sent to ${email}!`;
            setTimeout(() => {
                closeTestMailModal();
            }, 1500);
        } else {
            testMailError.value = response.data.message || 'Failed to send test email.';
        }
    } catch (err) {
        testMailError.value = err.response?.data?.message || 'Failed to send test email. Please check your mail settings.';
    } finally {
        testMailSending.value = false;
    }
}

const selectedStep = computed(() => {
    if (selectedStepIdx.value === null) return null;
    return form.value.settings.steps[selectedStepIdx.value] || null;
});

const selectedStepPerf = computed(() => {
    if (!selectedStep.value) return null;
    return props.stepStats?.[selectedStep.value.id] ?? null;
});

const nodeStatus = computed(() => {
    const events = props.sequence.node_events || [];
    const statusMap = {};

    events.forEach(e => {
        if (!e.node_id) return;
        if (!statusMap[e.node_id]) {
            statusMap[e.node_id] = {
                processingCount: 0,
                successCount: 0,
                errorCount: 0,
                logs: []
            };
        }

        statusMap[e.node_id].logs.push(e);

        if (e.event_type === 'node_processing') {
            statusMap[e.node_id].processingCount++;
        } else if (e.event_type === 'node_success' || e.event_type === 'enrolled' || e.event_type === 'sent') {
            statusMap[e.node_id].successCount++;
        } else if (e.event_type === 'node_error') {
            statusMap[e.node_id].errorCount++;
        }
    });

    return statusMap;
});

function addCompletionTag() {
    const val = newCompletionTag.value.trim();
    if (!val) return;
    if (!form.value.settings.completion_tags) {
        form.value.settings.completion_tags = [];
    }
    if (!form.value.settings.completion_tags.includes(val)) {
        form.value.settings.completion_tags.push(val);
    }
    newCompletionTag.value = '';
    saveSequence();
}

function removeCompletionTag(idx) {
    form.value.settings.completion_tags.splice(idx, 1);
    saveSequence();
}

function addStep() {
    const isFirstStep = form.value.settings.steps.length === 0;
    const newStep = {
        id: 'step_' + Math.random().toString(36).substr(2, 9),
        type: 'email',
        delay: isFirstStep ? { amount: 0, unit: 'hours' } : { amount: 1, unit: 'days' },
        subject: 'New email subject…',
        pre_header: '',
        from_name: props.defaultSender?.from_name || props.globalSettings?.email?.from_name || '',
        from_email: props.defaultSender?.from_email || props.globalSettings?.email?.from_email || '',
        send_days: 'any',
        send_specific_days: [],
        send_hours_start: 'Any time',
        send_hours_end: 'Any time',
        track_opens: true,
        track_clicks: true,
        track_utm: false,
        utm_source: '',
        utm_medium: 'email',
        utm_campaign: '',
        utm_term: '',
        utm_content: ''
    };

    form.value.settings.steps.push(newStep);
    selectedStepIdx.value = form.value.settings.steps.length - 1;
    saveSequence();
}

function removeStep(idx) {
    form.value.settings.steps.splice(idx, 1);
    if (selectedStepIdx.value === idx) {
        selectSequencePanel();
    } else if (selectedStepIdx.value > idx) {
        selectedStepIdx.value--;
    }
    saveSequence();
}

function hasSpecificDays(step) {
    return !!(step.send_specific_days && step.send_specific_days.length);
}

function toggleSpecificDays(step, enabled) {
    if (enabled) {
        if (!step.send_specific_days || !step.send_specific_days.length) {
            step.send_specific_days = [1, 2, 3, 4, 5];
        }
    } else {
        step.send_specific_days = [];
    }
    saveSequence();
}

function toggleDay(step, day) {
    if (!step.send_specific_days) step.send_specific_days = [];
    const idx = step.send_specific_days.indexOf(day);
    if (idx === -1) {
        step.send_specific_days.push(day);
    } else {
        step.send_specific_days.splice(idx, 1);
    }
    saveSequence();
}

function saveDelay() {
    if (editingDelayIdx.value !== null) {
        const step = form.value.settings.steps[editingDelayIdx.value];
        if (step) {
            step.delay.amount = tempDelay.value.amount;
            step.delay.unit = tempDelay.value.unit;
        }
        editingDelayIdx.value = null;
        saveSequence();
    }
}

const activePreviewTab = ref('timeline');
const selectedPreviewStepId = ref(null);
const emailPreviewHtml = ref('');
const loadingPreviewHtml = ref(false);

async function fetchEmailPreview(stepId) {
    if (!stepId) return;
    selectedPreviewStepId.value = stepId;
    loadingPreviewHtml.value = true;
    try {
        const res = await window.axios.post(route('sequences.preview-step', form.value.id), { step_id: stepId });
        emailPreviewHtml.value = res.data.html;
    } catch (e) {
        emailPreviewHtml.value = '<div style="color:red;padding:20px;">Failed to load preview.</div>';
    } finally {
        loadingPreviewHtml.value = false;
    }
}

function togglePreview() {
    showPreview.value = !showPreview.value;
    if (showPreview.value) {
        activePreviewTab.value = 'timeline';
        const firstEmail = form.value.settings.steps[0];
        if (firstEmail) {
            fetchEmailPreview(firstEmail.id);
        } else {
            selectedPreviewStepId.value = null;
            emailPreviewHtml.value = '';
        }
    }
}

function openEmailEditor(idx) {
    const step = form.value.settings.steps[idx];
    if (!step.blocks) {
        step.blocks = [];
    }
    editingEmailIdx.value = idx;
}

async function closeEmailEditor() {
    await saveSequence();
    editingEmailIdx.value = null;
}

const getEditingStepSubject = computed(() => {
    if (editingEmailIdx.value === null) return '';
    const step = form.value.settings.steps[editingEmailIdx.value];
    return step ? step.subject : '';
});

const getEditingStepBlocks = computed({
    get() {
        if (editingEmailIdx.value === null) return [];
        const step = form.value.settings.steps[editingEmailIdx.value];
        return step ? (step.blocks || []) : [];
    },
    set(val) {
        if (editingEmailIdx.value === null) return;
        const step = form.value.settings.steps[editingEmailIdx.value];
        if (step) {
            step.blocks = val;
        }
    }
});

async function saveSequence() {
    saving.value = true;
    try {
        await window.axios.put(route('sequences.update', form.value.id), {
            title:              form.value.title,
            status:             form.value.status,
            settings:           form.value.settings,
            recipients_config:  form.value.recipients_config
        });
    } catch (e) {
        console.error(e);
    } finally {
        saving.value = false;
    }
}

async function setStatus(status) {
    form.value.status = status;
    await saveSequence();
}

function resetSequence() {
    if (!confirm('Are you sure you want to reset execution logs and re-enroll all matching contacts?')) return;
    router.post(route('sequences.reset', form.value.id), {}, { preserveScroll: true });
}

// ── Start Sequence modal ──
const showStartModal  = ref(false);
const startSendMode   = ref('now');
const startScheduledAt = ref(null);
const starting         = ref(false);
const startError       = ref('');

const tenantTimezone = computed(() => usePage().props.tenantTimezone || 'UTC');
const serverTime = ref(nowInTimeZone(tenantTimezone.value));

const formattedScheduledAt = computed(() => {
    if (!form.value.scheduled_at) return '';
    return formatInTimeZone(form.value.scheduled_at, tenantTimezone.value);
});

function formatDateTime(iso) {
    if (!iso) return '';
    return formatInTimeZone(iso, tenantTimezone.value);
}

function openStartModal() {
    startSendMode.value = 'now';
    startScheduledAt.value = null;
    startError.value = '';
    showStartModal.value = true;
}

async function doStartSequence() {
    startError.value = '';
    if (startSendMode.value === 'schedule' && !startScheduledAt.value) {
        startError.value = 'Please choose a date and time to start the sequence.';
        return;
    }

    await saveSequence();

    starting.value = true;
    try {
        const toUtcIso = (v) => zonedTimeToUtcIso(v, tenantTimezone.value);
        const res = await window.axios.post(route('sequences.start', form.value.id), {
            send_mode:    startSendMode.value,
            scheduled_at: startSendMode.value === 'schedule' ? toUtcIso(startScheduledAt.value) : null,
        });
        form.value.status = 'active';
        form.value.send_mode = startSendMode.value;
        form.value.scheduled_at = startSendMode.value === 'schedule' ? toUtcIso(startScheduledAt.value) : null;
        showStartModal.value = false;
        router.reload({ only: ['sequence', 'pendingJobs', 'failedJobs', 'stats', 'stepStats'], preserveScroll: true });
    } catch (err) {
        startError.value = err.response?.data?.message || 'Failed to start the sequence.';
    } finally {
        starting.value = false;
    }
}

function statusLabel(status) {
    return { active: 'Active', paused: 'Paused', draft: 'Draft', completed: 'Completed' }[status] ?? status;
}
function statusBadgeClass(status) {
    return { active: 'badge--sending', paused: 'badge--paused', draft: 'badge--draft', completed: 'badge--sent' }[status] ?? 'badge--draft';
}
</script>

<style scoped>
/* Page Specific styling details if needed */
.sb-details {
    width: 340px;
    display: flex;
    flex-direction: column;
}
.sb-trigger-block--clickable {
    cursor: pointer;
    transition: box-shadow .15s, border-color .15s;
}
.sb-trigger-block--clickable:hover {
    box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.12);
}
.sb-trigger-block--clickable.is-selected {
    border-color: #2563eb;
    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15);
}
.sb-recipient-row {
    display: flex;
    gap: 6px;
    align-items: center;
    margin-bottom: 6px;
}
.sb-recipient-act {
    border: 1px solid #e5e7eb;
    background: #fff;
    border-radius: 5px;
    width: 26px;
    height: 26px;
    flex-shrink: 0;
    cursor: pointer;
    font-size: 14px;
    line-height: 1;
}
.sb-recipient-act:disabled {
    opacity: 0.4;
    cursor: not-allowed;
}
.sb-recipient-count {
    font-size: 11px;
    color: var(--text-muted, #9ca3af);
    margin: 4px 0 16px;
}
.sb-recipient-exclude-toggle {
    background: none;
    border: none;
    color: #2563eb;
    font-size: 11px;
    font-weight: 600;
    cursor: pointer;
    padding: 0;
    margin-top: 10px;
}
.sb-recipient-act-add {
    background: none;
    border: 1px dashed #e5e7eb;
    border-radius: 5px;
    color: #6b7280;
    font-size: 11px;
    cursor: pointer;
    padding: 5px 8px;
    width: 100%;
    margin-top: 4px;
}
.sb-recipients-tabs {
    display: flex;
    gap: 4px;
    margin-bottom: 10px;
    border-bottom: 1px solid #e5e7eb;
}
.sb-recipients-tab {
    padding: 6px 4px;
    font-size: 11px;
    font-weight: 600;
    color: #9ca3af;
    cursor: pointer;
    border-bottom: 2px solid transparent;
    margin-bottom: -1px;
}
.sb-recipients-tab.is-active {
    color: #2563eb;
    border-bottom-color: #2563eb;
}
.sb-day-toggle {
    flex: 1;
    padding: 5px 0;
    border: 1px solid #e5e7eb;
    background: #fff;
    border-radius: 5px;
    font-size: 11px;
    font-weight: 600;
    color: #6b7280;
    cursor: pointer;
}
.sb-day-toggle.is-active {
    background: #2563eb;
    border-color: #2563eb;
    color: #fff;
}
</style>
