<template>
    <Head :title="sequence.title" />
    <AppLayout>
        <!-- Back link + header -->
        <div class="cs-header">
            <Link :href="route('sequences.index')" class="cs-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>
                Sequences
            </Link>

            <div class="cs-title-row">
                <div class="cs-title-left">
                    <h1 class="cs-title">{{ sequence.title }}</h1>
                    <div class="cs-meta">
                        <span :class="['cs-badge', statusClass(sequence.status)]">{{ statusLabel(sequence.status) }}</span>
                        <span class="cs-meta-sep">·</span>
                        <span class="cs-meta-id">#{{ sequence.id }}</span>
                        <span class="cs-meta-sep">·</span>
                        <span class="cs-meta-date">{{ emailList.length }} email step(s)</span>
                    </div>
                </div>
                <div class="cs-title-actions">
                    <Link :href="route('sequences.edit', sequence.id)" class="btn btn-outline btn-sm">
                        <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="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
                    </Link>
                    <button class="btn btn-ghost btn-sm" @click="doDuplicate">Duplicate</button>
                </div>
            </div>
        </div>

        <!-- Default view: Email History (the only landing content - no aggregate/overview tab) -->
        <div v-if="!stepFilter" class="cs-content">
            <div class="cs-deliveries">
                <div class="cs-deliveries-head">
                    <h3>Email History</h3>
                    <span>{{ emailList.length }} step(s)</span>
                </div>
                <div class="cs-table-scroll">
                    <table class="cs-table">
                        <thead>
                            <tr>
                                <th>Step</th>
                                <th>Subject</th>
                                <th>Delay</th>
                                <th>Sending date</th>
                                <th>Status</th>
                                <th>Sent</th>
                                <th>Opens</th>
                                <th>Clicks</th>
                                <th>Open rate</th>
                                <th>Click rate</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="step in emailList" :key="step.id">
                                <td>Step {{ step.step_number }}</td>
                                <td>{{ step.subject }}</td>
                                <td>
                                    <span v-if="!step.delay || step.delay.amount === 0">Immediately</span>
                                    <span v-else>{{ step.delay.amount }} {{ step.delay.unit }}</span>
                                </td>
                                <td>
                                    <span v-if="step.first_sent_at" class="cs-send-date cs-send-date--sent">{{ formatDateTime(step.first_sent_at) }}</span>
                                    <span v-else-if="step.next_scheduled_at" class="cs-send-date cs-send-date--upcoming">{{ formatDateTime(step.next_scheduled_at) }}</span>
                                    <span v-else class="cs-send-date">Not scheduled</span>
                                </td>
                                <td>
                                    <span class="cs-delivery-status" :class="{ 'cs-delivery-status--pending': step.sent === 0 }">
                                        {{ step.sent > 0 ? 'Sent' : 'Pending' }}
                                    </span>
                                </td>
                                <td>{{ step.sent.toLocaleString() }}</td>
                                <td>{{ step.opens.toLocaleString() }}</td>
                                <td>{{ step.clicks.toLocaleString() }}</td>
                                <td>{{ step.open_rate }}%</td>
                                <td>{{ step.click_rate }}%</td>
                                <td>
                                    <div class="cw-menu-wrap" @click.stop>
                                        <button class="cw-action-btn cw-action-more" @click="toggleStepMenu(step.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="openStepMenu === step.id" class="cw-dropdown">
                                            <button class="cw-dd-item" @click="openPreview(step)">
                                                <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="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 Email
                                            </button>
                                            <button class="cw-dd-item" @click="openSendTest(step)">
                                                <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 Test Email
                                            </button>
                                            <Link :href="route('sequences.show', sequence.id) + '?step=' + step.id" class="cw-dd-item">
                                                <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 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 013 19.875v-6.75zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V8.625zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z"/></svg>
                                                View Report
                                            </Link>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Step-specific report: shown only after "View Report" on one email step -->
        <div v-else class="cs-content">
            <div class="cs-filter-banner">
                <span>Showing report for <strong>{{ stepFilter.subject }}</strong> only</span>
                <Link :href="route('sequences.show', sequence.id)" class="cs-filter-clear">← Back to Email History</Link>
            </div>

            <div class="cs-tabs-wrap">
                <div class="cs-tabs">
                    <button
                        v-for="tab in eventTabs"
                        :key="tab.id"
                        class="cs-tab"
                        :class="{ 'is-active': activeTab === tab.id }"
                        @click="activeTab = tab.id"
                    >{{ tab.label }}</button>
                </div>
            </div>

            <div v-if="currentEventTab.data && currentEventTab.data.total > 0" class="cs-deliveries">
                <div class="cs-deliveries-head">
                    <h3>{{ currentEventTab.title }}</h3>
                    <span>{{ currentEventTab.data.total }} {{ currentEventTab.summary }}</span>
                </div>
                <div class="cs-table-scroll">
                    <table class="cs-table">
                        <thead>
                            <tr>
                                <th>Email</th>
                                <th>Name</th>
                                <th>Step</th>
                                <th v-if="currentEventTab.showUrl">URL</th>
                                <th v-if="currentEventTab.showReason">Reason</th>
                                <th>Status</th>
                                <th>{{ currentEventTab.timeLabel }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="d in currentEventTab.data.data" :key="d.id">
                                <td>
                                    <button v-if="d.email" class="cs-contact-link" style="background:none;border:none;padding:0;cursor:pointer;font:inherit" @click="openEventDetail(d, currentEventTab)">{{ d.email }}</button>
                                    <span v-else>-</span>
                                </td>
                                <td>{{ d.name || '-' }}</td>
                                <td>
                                    <span v-if="d.step_number" class="cs-step-chip">Step {{ d.step_number }}</span>
                                    <span v-else>-</span>
                                </td>
                                <td v-if="currentEventTab.showUrl" class="cs-url-cell" :title="d.url">{{ d.url || '-' }}</td>
                                <td v-if="currentEventTab.showReason" class="cs-url-cell" :title="d.reason">{{ d.reason || '-' }}</td>
                                <td><span class="cs-delivery-status" :class="{ 'cs-delivery-status--danger': currentEventTab.id === 'bounced' }">{{ d.status ?? '-' }}</span></td>
                                <td>{{ formatDateTime(d.at) }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="cs-deliveries-footer">
                    <span class="cs-deliveries-range">{{ currentEventTab.data.from }}–{{ currentEventTab.data.to }} of {{ currentEventTab.data.total }}</span>
                    <Pagination :paginator="currentEventTab.data" :page-name="currentEventTab.pageName" preserve-state />
                </div>
            </div>
            <div v-else class="cs-placeholder">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" width="36" height="36"><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>
                <p>{{ currentEventTab.empty }}</p>
            </div>
        </div>

        <!-- Event detail popup -->
        <div class="modal-overlay" :class="{ 'is-open': showEventDetail }" @click.self="showEventDetail = false">
            <div class="modal" style="width:420px;max-width:96vw">
                <div class="modal-header">
                    <h2 class="modal-title">{{ eventDetail?.title }}</h2>
                    <button class="modal-close" @click="showEventDetail = 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" v-if="eventDetail">
                    <div class="cs-event-detail-row">
                        <span class="cs-event-detail-label">Contact</span>
                        <span class="cs-event-detail-val">{{ eventDetail.email }}<span v-if="eventDetail.name"> · {{ eventDetail.name }}</span></span>
                    </div>
                    <div class="cs-event-detail-row">
                        <span class="cs-event-detail-label">Step</span>
                        <span class="cs-event-detail-val">{{ eventDetail.stepLabel }}</span>
                    </div>
                    <div class="cs-event-detail-row">
                        <span class="cs-event-detail-label">{{ eventDetail.timeLabel }}</span>
                        <span class="cs-event-detail-val">{{ formatDateTime(eventDetail.at) }}</span>
                    </div>
                    <div class="cs-event-detail-row" v-if="eventDetail.url">
                        <span class="cs-event-detail-label">URL</span>
                        <span class="cs-event-detail-val cs-url-cell" style="max-width:none;white-space:normal;">{{ eventDetail.url }}</span>
                    </div>
                    <div class="cs-event-detail-row" v-if="eventDetail.reason">
                        <span class="cs-event-detail-label">Reason</span>
                        <span class="cs-event-detail-val">{{ eventDetail.reason }}</span>
                    </div>
                    <div class="cs-event-detail-row">
                        <span class="cs-event-detail-label">Status</span>
                        <span class="cs-event-detail-val">{{ eventDetail.status ?? '-' }}</span>
                    </div>
                </div>
                <div class="modal-footer" style="justify-content:space-between">
                    <Link v-if="eventDetail?.contact_id" :href="route('contacts.show', eventDetail.contact_id)" class="btn btn-outline btn-sm">View contact</Link>
                    <span v-else></span>
                    <button class="btn btn-primary" @click="showEventDetail = false">Close</button>
                </div>
            </div>
        </div>

        <!-- Preview Email modal -->
        <div class="modal-overlay" :class="{ 'is-open': showPreviewModal }" @click.self="showPreviewModal = false">
            <div class="modal" style="width:640px;max-width:96vw">
                <div class="modal-header">
                    <h2 class="modal-title">Preview: {{ previewTargetStep?.subject }}</h2>
                    <button class="modal-close" @click="showPreviewModal = 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">
                    <div v-if="loadingPreview" style="display:flex;align-items:center;justify-content:center;height:380px;color:#9ca3af;font-size:13px">
                        Generating live email preview...
                    </div>
                    <iframe v-else :srcdoc="previewHtml" style="width:100%; height:420px; border:1px solid var(--border-color); border-radius:6px; background:white;"></iframe>
                </div>
                <div class="modal-footer" style="justify-content:flex-end">
                    <button class="btn btn-primary" @click="showPreviewModal = false">Close</button>
                </div>
            </div>
        </div>

        <!-- Send Test Email modal -->
        <div class="modal-overlay" :class="{ 'is-open': showTestModal }" @click.self="closeSendTest">
            <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="closeSendTest">
                        <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">
                    <label class="form-label">Recipient Email Address <span style="color:#ef4444">*</span></label>
                    <input type="email" v-model="testEmail" placeholder="recipient@example.com" class="form-input" @keyup.enter="doSendTest">
                    <div v-if="testError" style="color:#ef4444;font-size:12px;margin-top:6px">{{ testError }}</div>
                    <div v-if="testSuccess" style="color:#16a34a;font-size:12px;margin-top:6px">{{ testSuccess }}</div>
                </div>
                <div class="modal-footer" style="justify-content:flex-end">
                    <button class="btn btn-outline" @click="closeSendTest">Cancel</button>
                    <button class="btn btn-primary" :disabled="testSending" @click="doSendTest">
                        {{ testSending ? 'Sending...' : 'Send Test' }}
                    </button>
                </div>
            </div>
        </div>
    </AppLayout>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { Link, router, Head } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';
import Pagination from '@/Components/Pagination.vue';
import { useTenantTimezone } from '@/Composables/useTenantTimezone';

const { formatDateTime: formatDateTimeTz } = useTenantTimezone();

const props = defineProps({
    sequence:      Object,
    emailList:     { type: Array, default: () => [] },
    stepFilter:    { type: Object, default: null },
    deliveries:    Object,
    opens:         Object,
    clicks:        Object,
    unsubscribes:  Object,
    bounces:       Object,
});

const sequence = props.sequence;
const stepFilter = props.stepFilter;
const emailList = props.emailList;

// ── Per-step actions menu ──
const openStepMenu = ref(null);
function toggleStepMenu(id) {
    openStepMenu.value = openStepMenu.value === id ? null : id;
}
function closeMenu() { openStepMenu.value = null; }

onMounted(() => {
    document.addEventListener('click', closeMenu);
});
onUnmounted(() => {
    document.removeEventListener('click', closeMenu);
});

// ── Event detail popup (clicking an email in a Deliverability/Opens/Clicks/... row) ──
const showEventDetail = ref(false);
const eventDetail      = ref(null);

function openEventDetail(row, tab) {
    eventDetail.value = {
        title:      tab.title,
        email:      row.email,
        name:       row.name,
        contact_id: row.contact_id,
        stepLabel:  row.step_number ? `Step ${row.step_number} · ${row.step_subject}` : 'Unknown step',
        status:     row.status,
        url:        row.url,
        reason:     row.reason,
        at:         row.at,
        timeLabel:  tab.timeLabel,
    };
    showEventDetail.value = true;
}

// ── Preview Email modal ──
const showPreviewModal  = ref(false);
const previewTargetStep = ref(null);
const previewHtml       = ref('');
const loadingPreview    = ref(false);

async function openPreview(step) {
    openStepMenu.value = null;
    previewTargetStep.value = step;
    showPreviewModal.value = true;
    loadingPreview.value = true;
    try {
        const res = await window.axios.post(route('sequences.preview-step', sequence.id), { step_id: step.id });
        previewHtml.value = res.data.html;
    } catch (e) {
        previewHtml.value = '<div style="color:red;padding:20px;">Failed to load preview.</div>';
    } finally {
        loadingPreview.value = false;
    }
}

// ── Send Test Email modal ──
const showTestModal  = ref(false);
const testTargetStep = ref(null);
const testEmail      = ref('test@example.com');
const testSending    = ref(false);
const testError      = ref('');
const testSuccess    = ref('');

function openSendTest(step) {
    openStepMenu.value = null;
    testTargetStep.value = step;
    testError.value = '';
    testSuccess.value = '';
    showTestModal.value = true;
}

function closeSendTest() {
    showTestModal.value = false;
    testTargetStep.value = null;
}

async function doSendTest() {
    const email = testEmail.value.trim();
    if (!email) {
        testError.value = 'Please enter a recipient email address.';
        return;
    }
    if (!testTargetStep.value) return;

    testSending.value = true;
    testError.value = '';
    testSuccess.value = '';

    try {
        const res = await window.axios.post(route('sequences.send-test', sequence.id), {
            email: email,
            step_id: testTargetStep.value.id,
        });
        if (res.data.success) {
            testSuccess.value = `Test email successfully sent to ${email}!`;
            setTimeout(closeSendTest, 1500);
        } else {
            testError.value = res.data.message || 'Failed to send test email.';
        }
    } catch (err) {
        testError.value = err.response?.data?.message || 'Failed to send test email. Please check your mail settings.';
    } finally {
        testSending.value = false;
    }
}

const activeTab = ref('deliverability');

const eventTabs = [
    { id: 'deliverability', label: 'Deliverability' },
    { id: 'opens',          label: 'Opens' },
    { id: 'clicks',         label: 'Clicks' },
    { id: 'unsubscribes',   label: 'Unsubscribes' },
    { id: 'bounced',        label: 'Bounced' },
];

const eventTabConfig = {
    deliverability: {
        title: 'Delivered emails',   summary: 'emails delivered',       timeLabel: 'Delivered at',
        pageName: 'deliveries_page', showUrl: false, showReason: false,
        empty: 'No emails delivered yet. Delivered contacts will be listed here once the sequence sends.',
    },
    opens: {
        title: 'Opens',              summary: 'contacts opened an email', timeLabel: 'Last opened at',
        pageName: 'opens_page',      showUrl: false, showReason: false,
        empty: 'No opens recorded yet. Contacts who open an email will be listed here.',
    },
    clicks: {
        title: 'Clicks',             summary: 'click events recorded',  timeLabel: 'Clicked at',
        pageName: 'clicks_page',     showUrl: true, showReason: false,
        empty: 'No clicks recorded yet. Contacts who click a link will be listed here.',
    },
    unsubscribes: {
        title: 'Unsubscribes',       summary: 'contacts unsubscribed',  timeLabel: 'Unsubscribed at',
        pageName: 'unsubscribes_page', showUrl: false, showReason: false,
        empty: 'No unsubscribes recorded. Contacts who opt out will be listed here.',
    },
    bounced: {
        title: 'Bounced emails',     summary: 'emails not delivered',   timeLabel: 'Bounced at',
        pageName: 'bounces_page',    showUrl: false, showReason: true,
        empty: 'No bounces recorded. Contacts whose email couldn\'t be delivered will be listed here with a reason.',
    },
};

const currentEventTab = computed(() => {
    const cfg = eventTabConfig[activeTab.value];
    if (!cfg) return null;
    const dataKey = activeTab.value === 'deliverability' ? 'deliveries' : activeTab.value === 'bounced' ? 'bounces' : activeTab.value;
    return { ...cfg, id: activeTab.value, data: props[dataKey] };
});


function statusLabel(s) {
    return { draft: 'Draft', active: 'Active', paused: 'Paused', completed: 'Completed' }[s] ?? s;
}
function statusClass(s) {
    return {
        draft: 'cs-badge--draft', active: 'cs-badge--sending',
        paused: 'cs-badge--paused', completed: 'cs-badge--sent',
    }[s] ?? 'cs-badge--draft';
}

function formatDateTime(iso) {
    if (!iso) return '';
    return formatDateTimeTz(iso);
}

function doDuplicate() {
    router.post(route('sequences.duplicate', sequence.id));
}
</script>

<style scoped>
/* ── Header ── */
.cs-header {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 20px 24px;
    margin-bottom: 20px;
}
.cs-back {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: var(--text-secondary);
    text-decoration: none;
    margin-bottom: 14px;
}
.cs-back:hover { color: var(--text-primary); }

.cs-title-row {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 16px;
}
.cs-title { font-size: 20px; font-weight: 700; color: var(--text-primary); margin: 0 0 6px; }
.cs-meta { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.cs-meta-sep { color: var(--border-color); }
.cs-meta-id { font-size: 12px; color: var(--text-muted); }
.cs-meta-date { font-size: 12px; color: var(--text-muted); }
.cs-title-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }

/* ── Badges ── */
.cs-badge { display: inline-block; font-size: 11px; font-weight: 600; padding: 2px 8px; border-radius: 10px; }
.cs-badge--draft   { background: var(--border-color); color: var(--text-secondary); }
.cs-badge--sending { background: var(--info-light); color: var(--info); }
.cs-badge--sent    { background: var(--success-light); color: var(--success); }
.cs-badge--paused  { background: var(--danger-light); color: var(--danger); }

/* ── Step filter banner ── */
.cs-filter-banner {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    background: var(--info-light);
    border: 1px solid var(--info-border);
    border-radius: 10px;
    padding: 10px 16px;
    margin-bottom: 16px;
    font-size: 13px;
    color: var(--info);
}
.cs-filter-clear { color: var(--info); font-weight: 600; text-decoration: none; white-space: nowrap; }
.cs-filter-clear:hover { text-decoration: underline; }

/* ── Tabs ── */
.cs-tabs-wrap {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    margin-bottom: 20px;
    overflow: hidden;
}
.cs-tabs {
    display: flex;
    border-bottom: none;
    padding: 0 8px;
    overflow-x: auto;
}
.cs-tab {
    padding: 14px 16px;
    font-size: 13px;
    font-weight: 500;
    color: var(--text-secondary);
    border: none;
    background: none;
    cursor: pointer;
    border-bottom: 2px solid transparent;
    margin-bottom: -1px;
    white-space: nowrap;
    transition: color 0.1s, border-color 0.1s;
}
.cs-tab:hover { color: var(--text-primary); }
.cs-tab.is-active { color: var(--info); border-bottom-color: var(--info); }

/* ── Content ── */
.cs-content { display: flex; flex-direction: column; gap: 20px; }

/* ── Deliveries / Emails table ── */
.cs-deliveries {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    overflow: hidden;
}
.cs-deliveries-head {
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    gap: 12px;
    padding: 16px 20px;
    border-bottom: 1px solid var(--border-color);
    flex-wrap: wrap;
}
.cs-deliveries-head h3 { font-size: 15px; font-weight: 600; color: var(--text-primary); margin: 0; }
.cs-deliveries-head span { font-size: 13px; color: var(--text-secondary); }
.cs-table { width: 100%; border-collapse: collapse; }
.cs-table th {
    text-align: left;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.04em;
    color: var(--text-muted);
    background: var(--bg-hover);
    padding: 10px 20px;
    border-bottom: 1px solid var(--border-color);
}
.cs-table td {
    font-size: 13px;
    color: var(--text-primary);
    padding: 12px 20px;
    border-bottom: 1px solid var(--border-color);
}
.cs-table tbody tr:hover { background: var(--bg-hover); }
.cs-table-scroll { overflow-x: auto; }
.cs-url-cell {
    max-width: 260px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: var(--text-secondary);
}
.cs-contact-link { color: var(--info); text-decoration: none; font-weight: 500; }
.cs-contact-link:hover { text-decoration: underline; }
.cs-step-chip {
    display: inline-block;
    font-size: 11px;
    font-weight: 600;
    color: var(--text-primary);
    background: var(--border-color);
    border-radius: 10px;
    padding: 2px 8px;
    white-space: nowrap;
}

/* ── Event detail popup ── */
.cs-event-detail-row {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 16px;
    padding: 10px 0;
    border-bottom: 1px solid var(--border-color);
    font-size: 13px;
}
.cs-event-detail-row:last-child { border-bottom: none; }
.cs-event-detail-label { color: var(--text-secondary); flex-shrink: 0; }
.cs-event-detail-val { color: var(--text-primary); font-weight: 500; text-align: right; }
.cs-delivery-status { font-size: 12px; color: var(--success); background: var(--success-light); border-radius: 10px; padding: 2px 8px; }
.cs-delivery-status--danger { color: var(--danger); background: var(--danger-light); }
.cs-delivery-status--pending { color: var(--warning); background: var(--warning-light); }
.cs-send-date { font-size: 12px; color: var(--text-muted); white-space: nowrap; }
.cs-send-date--sent { color: var(--success); font-weight: 500; }
.cs-send-date--upcoming { color: var(--info); font-weight: 500; }

/* ── Row actions dropdown ── */
.cw-menu-wrap { position: relative; display: inline-block; }
.cw-action-btn {
    width: 28px; height: 28px;
    display: flex; align-items: center; justify-content: center;
    border: 1px solid transparent;
    background: transparent;
    border-radius: 6px;
    cursor: pointer;
    color: var(--text-secondary);
    transition: background 0.1s, border-color 0.1s, color 0.1s;
}
.cw-action-btn:hover { background: var(--bg-hover); border-color: var(--border-color); color: var(--text-primary); }
.cw-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: 170px;
    z-index: 100;
    overflow: hidden;
    padding: 4px 0;
}
.cw-dd-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 9px 14px;
    font-size: 13px;
    color: var(--text-primary);
    cursor: pointer;
    background: none;
    border: none;
    width: 100%;
    text-align: left;
    transition: background 0.1s;
}
.cw-dd-item:hover { background: var(--bg-hover); }
.cw-dd-item svg { flex-shrink: 0; color: var(--text-muted); }
.cs-deliveries-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 12px 20px;
    flex-wrap: wrap;
}
.cs-deliveries-range { font-size: 12px; color: var(--text-secondary); }

.cs-placeholder {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 64px 24px;
    text-align: center;
    color: var(--text-muted);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    font-size: 14px;
}

@media (max-width: 768px) {
    .cs-title-row {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;
    }
    .cs-title-actions {
        justify-content: flex-start;
    }
}
@media (max-width: 576px) {
    .cs-deliveries-head {
        flex-direction: column;
        align-items: stretch;
        gap: 6px;
    }
}
</style>
