<template>
    <Head title="Sequences - CRMfic" />

    <AppLayout>
        <!-- Page header -->
        <div class="page-header">
            <div class="page-header__left">
                <h1>Sequences</h1>
                <p>Automated drip email series delivered on a time-based schedule.</p>
            </div>
            <div class="page-header__actions">
                <button class="btn btn-primary" @click="showCreate = true">
                    <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="M12 4.5v15m7.5-7.5h-15" />
                    </svg>
                    New sequence
                </button>
            </div>
        </div>

        <!-- Table wrap -->
        <div class="table-wrap">
            <div class="table-toolbar" :class="{ 'has-selection': selected.length > 0 }">
                <div v-if="selected.length === 0" class="table-toolbar-left">
                    <div class="table-search">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"/></svg>
                        <input v-model="search" type="search" placeholder="Search sequences…" @input="onSearch">
                    </div>
                </div>
                <div v-else class="table-toolbar-left">
                    <div class="selection-status">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" width="16" height="16" style="color: var(--active-text);"><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>
                        <span class="selection-count">{{ selected.length }} sequence{{ selected.length === 1 ? '' : 's' }} selected</span>
                    </div>
                </div>
                <div class="table-toolbar-right">
                    <template v-if="selected.length > 0">
                        <button class="btn btn-outline" style="color: var(--danger); border-color: var(--danger-border);" @click="showBulkDelete = true">Delete</button>
                        <button class="btn btn-outline" @click="selected = []">Cancel</button>
                    </template>
                    <template v-else>
                        <CwSelect
                            v-model="statusFilter"
                            :options="statusOptions"
                            @change="onSearch"
                            placeholder="All statuses"
                            style="width: 160px;"
                        />
                    </template>
                </div>
            </div>

            <div class="table-scroll">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th style="width:40px"><input type="checkbox" class="table-checkbox" :checked="allSelected" @change="toggleAll"></th>
                            <th>Name</th>
                            <th>Emails</th>
                            <th>Subscribers</th>
                            <th>Avg. Open</th>
                            <th>Avg. Click</th>
                            <th>Status</th>
                            <th>Created</th>
                            <th style="width:120px"></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-if="sequences.data.length === 0">
                            <td colspan="9" style="text-align:center;padding:48px 24px;color:#9ca3af">
                                No sequences yet. <button class="link-btn" @click="showCreate = true">Create your first one.</button>
                            </td>
                        </tr>
                        <tr v-for="s in sequences.data" :key="s.id" :class="{ 'is-selected': selected.includes(s.id) }">
                            <td class="cell-checkbox"><input type="checkbox" class="table-checkbox" :value="s.id" v-model="selected"></td>
                            <td data-label="Name" class="cell-name cell-title">
                                <div class="automation-title-container">
                                    <Link :href="route('sequences.edit', s.id)" class="automation-title-link">
                                        {{ s.title }}
                                    </Link>
                                </div>
                                <div class="automation-title-sub">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" 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>
                                    {{ s.emails_count }} steps · {{ startHeadline(s) }}
                                </div>
                            </td>
                            <td data-label="Emails">{{ s.emails_count }}</td>
                            <td data-label="Subscribers">{{ (s.subscribers ?? 0).toLocaleString() }}</td>
                            <td data-label="Avg. Open">
                                <div v-if="s.avg_open !== null" class="rate-cell">
                                    <span>{{ s.avg_open }}%</span>
                                    <div class="rate-bar">
                                        <div :style="{ width: s.avg_open + '%' }"></div>
                                    </div>
                                </div>
                                <span v-else>-</span>
                            </td>
                            <td data-label="Avg. Click">
                                <div v-if="s.avg_click !== null" class="rate-cell">
                                    <span>{{ s.avg_click }}%</span>
                                    <div class="rate-bar">
                                        <div :style="{ width: s.avg_click + '%' }"></div>
                                    </div>
                                </div>
                                <span v-else>-</span>
                            </td>
                            <td data-label="Status">
                                <span class="badge" :class="statusBadgeClass(s.status)">{{ statusLabel(s.status) }}</span>
                            </td>
                            <td data-label="Created">{{ s.created_at }}</td>
                            <td class="cell-actions" data-label="">
                                <div style="display:flex;gap:6px">
                                    <!-- Edit -->
                                    <Link :href="route('sequences.edit', s.id)" class="re-action-btn" title="Edit">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#2563eb"><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>
                                    </Link>
                                    
                                    <!-- Report -->
                                    <Link v-if="s.has_sent || s.status !== 'draft'" :href="route('sequences.show', s.id)" class="re-action-btn" title="View Report">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#0f766e">
                                            <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.125v5.25c0 .621-.504 1.125-1.125 1.125h-2.25A1.125 1.125 0 013 18.375v-5.25zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v9.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125v-9.75zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v14.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z" />
                                        </svg>
                                    </Link>
                                    <button v-else class="re-action-btn is-disabled" disabled title="No report available for draft sequence">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#9ca3af">
                                            <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.125v5.25c0 .621-.504 1.125-1.125 1.125h-2.25A1.125 1.125 0 013 18.375v-5.25zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v9.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125v-9.75zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v14.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z" />
                                        </svg>
                                    </button>
                                    
                                    <!-- Delete -->
                                    <button class="re-action-btn" title="Delete" @click="confirmDelete(s)">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#ef4444"><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>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

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

        <!-- Create modal -->
        <div v-if="showCreate" class="modal-overlay is-open" @click.self="showCreate = false">
            <div class="modal" style="width:520px;max-width:96vw">
                <div class="modal-header">
                    <h2 class="modal-title">New Sequence</h2>
                    <button class="modal-close" @click="showCreate = 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:24px">
                    <label class="form-label"><span style="color:#ef4444">*</span> Sequence Title</label>
                    <input v-model="newTitle" type="text" class="form-input" placeholder="e.g. Welcome Onboarding" style="font-size:15px;padding:12px 14px" ref="newTitleInputRef" @keydown.enter="createSequence">
                </div>
                <div class="modal-footer" style="justify-content:flex-end">
                    <button class="btn btn-outline" @click="showCreate = false">Cancel</button>
                    <button class="btn btn-primary" @click="createSequence" :disabled="creating || !newTitle.trim()">
                        <span v-if="creating">Creating…</span>
                        <span v-else>Create &amp; Configure</span>
                    </button>
                </div>
            </div>
        </div>

        <!-- Delete confirm modal -->
        <div v-if="deleteTarget" class="modal-overlay is-open" @click.self="deleteTarget = null">
            <div class="modal modal--sm">
                <div class="modal-header">
                    <h3 class="modal-title">Delete Sequence</h3>
                    <button class="modal-close" @click="deleteTarget = 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">
                    <p style="color:#6b7280;font-size:14px">Are you sure you want to delete <strong>{{ deleteTarget.title }}</strong>? This cannot be undone.</p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline" @click="deleteTarget = null">Cancel</button>
                    <button class="btn btn-danger" @click="deleteSequence" :disabled="deleting">
                        <span v-if="deleting">Deleting…</span>
                        <span v-else>Delete</span>
                    </button>
                </div>
            </div>
        </div>

        <!-- Bulk delete confirm modal -->
        <div v-if="showBulkDelete" class="modal-overlay is-open" @click.self="showBulkDelete = false">
            <div class="modal modal--sm">
                <div class="modal-header">
                    <h3 class="modal-title">Delete Selected</h3>
                    <button class="modal-close" @click="showBulkDelete = 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">
                    <p style="color:#6b7280;font-size:14px">Are you sure you want to delete the <strong>{{ selected.length }}</strong> selected sequences? This cannot be undone.</p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline" @click="showBulkDelete = false">Cancel</button>
                    <button class="btn btn-danger" @click="bulkDelete" :disabled="bulkDeleting">
                        <span v-if="bulkDeleting">Deleting…</span>
                        <span v-else>Delete</span>
                    </button>
                </div>
            </div>
        </div>
    </AppLayout>
</template>

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

const statusOptions = [
    { value: '', label: 'All statuses' },
    { value: 'active', label: 'Active' },
    { value: 'paused', label: 'Paused' },
    { value: 'draft', label: 'Draft' },
    { value: 'completed', label: 'Completed' },
];

const props = defineProps({
    sequences: Object,
    filters:   Object,
});

const search       = ref(props.filters?.search ?? '');
const statusFilter = ref(props.filters?.status ?? '');

const showCreate = ref(false);
const newTitle   = ref('');
const newTitleInputRef = ref(null);

watch(showCreate, (val) => {
    if (val) {
        nextTick(() => {
            newTitleInputRef.value?.focus();
        });
    }
});
const creating   = ref(false);

const deleteTarget = ref(null);
const deleting     = ref(false);

const selected       = ref([]);
const showBulkDelete = ref(false);
const bulkDeleting   = ref(false);

const allSelected = computed(() =>
    props.sequences.data.length > 0 &&
    props.sequences.data.every(s => selected.value.includes(s.id))
);

function toggleAll(e) {
    selected.value = e.target.checked ? props.sequences.data.map(s => s.id) : [];
}

function startHeadline(s) {
    return { draft: 'Not started', active: 'Running', paused: 'Paused', completed: 'Finished' }[s.status] ?? 'Not started';
}

const openMenu = ref(null);
function toggleMenu(id) {
    openMenu.value = openMenu.value === id ? null : id;
}
function closeMenu() { openMenu.value = null; }

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

function doDuplicate(s) {
    openMenu.value = null;
    router.post(route('sequences.duplicate', s.id));
}

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

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';
}

let searchTimer = null;
function onSearch() {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => {
        router.get(route('sequences.index'), {
            search: search.value, status: statusFilter.value,
        }, { preserveState: true, replace: true });
    }, 350);
}

function createSequence() {
    if (!newTitle.value.trim()) return;
    creating.value = true;
    router.post(route('sequences.store'), { title: newTitle.value.trim() }, {
        onFinish: () => { creating.value = false; },
    });
}

function confirmDelete(sequence) {
    deleteTarget.value = sequence;
}

function deleteSequence() {
    const deletedId = deleteTarget.value.id;
    deleting.value = true;
    router.delete(route('sequences.destroy', deletedId), {
        onSuccess: () => {
            deleteTarget.value = null;
            selected.value = selected.value.filter(id => id !== deletedId);
        },
        onFinish: () => { deleting.value = false; },
    });
}

function bulkDelete() {
    bulkDeleting.value = true;
    router.post(route('sequences.bulk-destroy'), { ids: selected.value }, {
        onSuccess: () => { showBulkDelete.value = false; selected.value = []; },
        onFinish:  () => { bulkDeleting.value = false; },
    });
}
</script>

<style scoped>
.link-btn { background: none; border: none; color: var(--info); cursor: pointer; font-size: inherit; padding: 0; }
.re-selected-count { font-size: 13px; font-weight: 600; color: var(--text-primary); padding: 0 4px; }
.table-toolbar { display: flex; justify-content: space-between; align-items: center; }
.table-toolbar-left, .table-toolbar-right { display: flex; gap: 8px; align-items: center; }

/* ── Actions ── */
.cw-action-btn {
    width: 30px; height: 30px;
    display: flex; align-items: center; justify-content: center;
    border: 1px solid transparent;
    background: transparent;
    border-radius: 6px;
    cursor: pointer;
    color: var(--text-secondary);
    text-decoration: none;
    transition: background 0.1s, border-color 0.1s, color 0.1s;
    margin-left: auto;
}
.cw-action-btn:hover { background: var(--bg-hover); border-color: var(--border-color); color: var(--text-primary); }

/* ── 3-dot dropdown ── */
.cw-menu-wrap { position: relative; }
.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;
    text-decoration: none;
    background: none;
    border: none;
    width: 100%;
    text-align: left;
    transition: background 0.1s;
}
.cw-dd-item:hover { background: var(--bg-hover); color: var(--text-primary); }
.cw-dd-item svg { flex-shrink: 0; color: var(--text-muted); }
.cw-dd-danger { color: var(--danger); }
.cw-dd-danger svg { color: var(--danger); }
.cw-dd-danger:hover { background: var(--danger-light); }

@media (max-width: 1024px) {
    /* Hide table head */
    .data-table thead {
        display: none;
    }
    
    /* Each row acts as a card */
    .data-table tbody tr {
        display: block;
        background: var(--bg-surface);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        padding: 16px;
        margin-bottom: 16px;
        position: relative;
    }
    
    /* Individual cell styles */
    .data-table tbody td {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border: none;
        padding: 8px 0;
        font-size: 13px;
        text-align: right;
    }
    
    /* Checkbox positioning */
    .data-table tbody td.cell-checkbox {
        position: absolute;
        top: 16px;
        left: 16px;
        padding: 0;
        z-index: 2;
    }
    
    /* Name styling in card */
    .data-table tbody td.cell-name {
        display: block;
        text-align: left;
        padding-left: 28px;
        margin-bottom: 12px;
        border-bottom: 1px solid var(--border-color);
        padding-bottom: 12px;
    }
    
    /* Actions column styling */
    .data-table tbody td.cell-actions {
        position: absolute;
        top: 10px;
        right: 12px;
        padding: 0;
        z-index: 2;
    }
    
    /* Add labels */
    .data-table tbody td[data-label]::before {
        content: attr(data-label);
        font-weight: 600;
        color: var(--text-muted);
        text-transform: uppercase;
        font-size: 10px;
        letter-spacing: 0.05em;
        margin-right: 8px;
    }
    
    /* Adjust rate cells on mobile */
    .rate-cell {
        justify-content: flex-end;
    }
}

@media (max-width: 576px) {
    .table-toolbar {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;
    }
    .table-toolbar-left, .table-toolbar-right {
        width: 100%;
        justify-content: space-between;
    }
    .table-search {
        width: 100%;
    }
    .table-search input {
        width: 100% !important;
    }
}
</style>
