<template>
    <AppLayout>
        <!-- Page header -->
        <div class="page-header">
            <div class="page-header__left">
                <h1>Recurring Email</h1>
                <p>Schedule emails that send automatically on a repeating cadence - daily, weekly, or monthly.</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>
                    Create Recurring Email
                </button>
            </div>
        </div>

        <!-- Stats row -->
        <div class="re-stats-row">
            <div class="metric-card">
                <div class="metric-card-label">Total Recurring</div>
                <div class="metric-card-value">{{ stats.total }}</div>
                <div class="metric-card-sub">{{ stats.active }} active · {{ stats.paused }} paused · {{ stats.draft }} draft</div>
            </div>
            <div class="metric-card">
                <div class="metric-card-label">Sent This Month</div>
                <div class="metric-card-value">{{ stats.sentThisMonth.toLocaleString() }}</div>
                <div class="metric-card-sub">emails dispatched</div>
            </div>
            <div class="metric-card">
                <div class="metric-card-label">Avg. Open Rate</div>
                <div class="metric-card-value" style="color:#16a34a">{{ stats.avgOpenRate }}%</div>
                <div class="metric-card-sub">across all recurring</div>
            </div>
            <div class="metric-card">
                <div class="metric-card-label">Next Send</div>
                <div class="metric-card-value">{{ nextSendHeadline }}</div>
                <div class="metric-card-sub">{{ nextSendSub }}</div>
            </div>
        </div>

        <!-- Table -->
        <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 recurring emails…" @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 }} recurring email{{ 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"
                            style="width: 140px;"
                        />
                        <CwSelect
                            v-model="frequencyFilter"
                            :options="frequencyOptions"
                            @change="onSearch"
                            style="width: 150px;"
                        />
                    </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>Frequency</th>
                            <th>Recipients</th>
                            <th>Last Sent</th>
                            <th>Next Send</th>
                            <th>Sent</th>
                            <th>Open Rate</th>
                            <th>Status</th>
                            <th style="width:120px">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-if="campaigns.data.length === 0">
                            <td colspan="10" style="text-align:center;padding:48px 24px;color:#9ca3af">
                                No recurring emails yet. <button class="link-btn" @click="showCreate = true">Create your first one.</button>
                            </td>
                        </tr>
                        <tr v-for="c in campaigns.data" :key="c.id" :class="{ 'is-selected': selected.includes(c.id) }">
                            <td class="cell-checkbox"><input type="checkbox" class="table-checkbox" :value="c.id" v-model="selected"></td>
                            <td data-label="Name" class="cell-name cell-title">
                                <div class="automation-title-container">
                                    <Link :href="route('recurring.edit', c.id)" class="automation-title-link">
                                        {{ c.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="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                                    {{ scheduleSummary(c) }}
                                </div>
                            </td>
                            <td data-label="Frequency">
                                <span class="badge" :class="'badge--' + (c.frequency === 'daily' ? 'sending' : c.frequency === 'monthly' ? 'sent' : 'primary')" style="text-transform:capitalize">{{ c.frequency ?? '' }}</span>
                            </td>
                            <td data-label="Recipients" style="font-size:13px">{{ (c.recipients_count ?? 0).toLocaleString() }}</td>
                            <td data-label="Last Sent" style="font-size:12px;color:var(--text-secondary)">{{ c.last_sent_at ? formatDate(c.last_sent_at) : '' }}</td>
                            <td data-label="Next Send" style="font-size:12px;color:var(--text-primary);font-weight:500">{{ c.status === 'active' && c.next_run_at ? formatDateTime(c.next_run_at) : '' }}</td>
                            <td data-label="Sent" style="font-size:13px">{{ c.occurrences_sent ?? 0 }}</td>
                            <td data-label="Open Rate">
                                <div v-if="c.occurrences_sent > 0" class="rate-cell">
                                    <div class="rate-cell-value">{{ c.open_rate }}%</div>
                                    <div class="rate-cell-bar"><div class="rate-cell-bar-fill" :style="{ width: c.open_rate + '%' }"></div></div>
                                </div>
                                <span v-else></span>
                            </td>
                            <td data-label="Status"><span class="badge" :class="statusBadgeClass(c.status)">{{ statusLabel(c.status) }}</span></td>
                            <td class="cell-actions" data-label="">
                                <div style="display:flex;gap:6px">
                                    <!-- Edit -->
                                    <Link :href="route('recurring.edit', c.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>

                                    <!-- Pause / Resume -->
                                    <button v-if="c.status === 'active'" class="re-action-btn" title="Pause" @click="doSetStatus(c, 'paused')">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#f59e0b"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 5.25v13.5m-7.5-13.5v13.5"/></svg>
                                    </button>
                                    <button v-else-if="c.status === 'paused'" class="re-action-btn" title="Resume" @click="doSetStatus(c, 'active')">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#16a34a"><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>
                                    </button>
                                    
                                    <!-- Delete -->
                                    <button class="re-action-btn" title="Delete" @click="confirmDelete(c)">
                                        <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 {{ campaigns.from ?? 0 }}–{{ campaigns.to ?? 0 }} of {{ campaigns.total }}</span>
                <Pagination :paginator="campaigns" 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">Create Recurring Email</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> Campaign Title</label>
                    <input v-model="newTitle" type="text" class="form-input" placeholder="e.g. Weekly Newsletter Digest" style="font-size:15px;padding:12px 14px" ref="newTitleInputRef" @keydown.enter="createRecurring">
                </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="createRecurring" :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 Recurring Email</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="deleteCampaign" :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.length }} {{ selected.length === 1 ? 'Recurring Email' : 'Recurring Emails' }}</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 {{ selected.length === 1 ? 'item' : 'items' }}? 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 { Link, router } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';
import Pagination from '@/Components/Pagination.vue';
import CwSelect from '@/Components/CwSelect.vue';
import { useTenantTimezone } from '@/Composables/useTenantTimezone';

const { timezone, formatDate: formatDateTz, formatDateTime: formatDateTimeTz, formatTime: formatTimeTz } = useTenantTimezone();

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

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

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

const frequencyOptions = [
    { value: '', label: 'All frequencies' },
    { value: 'daily', label: 'Daily' },
    { value: 'weekly', label: 'Weekly' },
    { value: 'monthly', label: 'Monthly' }
];

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.campaigns.data.length > 0 &&
    props.campaigns.data.every(c => selected.value.includes(c.id))
);

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

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

function scheduleSummary(c) {
    const time = c.recurring_time ? formatTime(c.recurring_time) : '';
    if (c.frequency === 'daily') return `Every day · ${time}`;
    if (c.frequency === 'weekly') {
        const days = (c.recurring_days ?? []).map(d => DAY_LABELS[d]?.slice(0, 3)).join(' & ');
        return `Every ${days || ''} · ${time}`;
    }
    if (c.frequency === 'monthly') {
        const days = (c.recurring_days ?? []).join(', ');
        return `Day ${days || ''} of month · ${time}`;
    }
    return 'Not scheduled yet';
}

function formatTime(hhmm) {
    const [h, m] = hhmm.split(':').map(Number);
    const period = h >= 12 ? 'PM' : 'AM';
    const hour12 = ((h + 11) % 12) + 1;
    return `${hour12}:${String(m).padStart(2, '0')} ${period}`;
}

function statusLabel(status) {
    return { active: 'Active', paused: 'Paused', draft: 'Draft' }[status] ?? status;
}
function statusBadgeClass(status) {
    return { active: 'badge--sent', paused: 'badge--paused', draft: 'badge--draft' }[status] ?? 'badge--draft';
}

function formatDate(iso) {
    return formatDateTz(iso);
}
function formatDateTime(iso) {
    return formatDateTimeTz(iso);
}

// Calendar-day key in the tenant's timezone, not the browser's  otherwise
// "Today" could be wrong near midnight for a tenant in a different timezone.
function dayKey(iso) {
    return new Date(iso).toLocaleDateString('en-CA', { timeZone: timezone.value });
}

const nextSendHeadline = computed(() => {
    if (!props.stats.nextSend) return '';
    if (dayKey(props.stats.nextSend) === dayKey(new Date().toISOString())) return 'Today';
    return formatDate(props.stats.nextSend);
});
const nextSendSub = computed(() => {
    if (!props.stats.nextSend) return 'no active schedules';
    return formatTimeTz(props.stats.nextSend);
});

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

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

async function setStatus(campaign, status) {
    await window.axios.patch(route('recurring.update-status', campaign.id), { status });
    router.reload({ only: ['campaigns', 'stats'], preserveScroll: true });
}

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 doSetStatus(campaign, status) {
    openMenu.value = null;
    setStatus(campaign, status);
}

function doConfirmDelete(campaign) {
    openMenu.value = null;
    confirmDelete(campaign);
}

function confirmDelete(campaign) {
    deleteTarget.value = campaign;
}
function deleteCampaign() {
    const deletedId = deleteTarget.value.id;
    deleting.value = true;
    router.delete(route('recurring.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('recurring.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-stats-row {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 24px;
}
@media (max-width: 900px) {
    .re-stats-row { grid-template-columns: repeat(2, 1fr); }
}
@media (max-width: 576px) {
    .re-stats-row { grid-template-columns: 1fr; }
}

.re-selected-count { font-size: 13px; font-weight: 600; color: var(--text-primary); padding: 0 4px; }

/* ── Actions ── */
.cw-menu-wrap { position: relative; }
.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;
}
.cw-action-btn:hover { background: var(--bg-hover); border-color: var(--border-color); color: var(--text-primary); }

/* ── 3-dot dropdown ── */
.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;
        width: auto;
    }
}

@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>
