<template>
    <Head title="Lists" />

    <AppLayout>
        <!-- Audience tab bar -->
        <nav class="aud-tabs">
            <Link href="/contacts" class="aud-tab">
                <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="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"/></svg>
                Contacts
            </Link>
            <Link href="/lists" class="aud-tab is-active">
                <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="M8.25 6.75h12M8.25 12h12m-12 5.25h12M3.75 6.75h.007v.008H3.75V6.75zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zM3.75 12h.007v.008H3.75V12zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm-.375 5.25h.007v.008H3.75v-.008zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z"/></svg>
                Lists
            </Link>
            <Link href="/tags" class="aud-tab">
                <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="M9.568 3H5.25A2.25 2.25 0 003 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 005.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 009.568 3z"/><path stroke-linecap="round" stroke-linejoin="round" d="M6 6h.008v.008H6V6z"/></svg>
                Tags
            </Link>
        </nav>

        <!-- Flash message -->
        <div v-if="$page.props.flash?.success" class="flash-success">
            {{ $page.props.flash.success }}
        </div>

        <!-- Section header -->
        <div class="page-header">
            <div class="page-header__left">
                <h1>Lists</h1>
                <p>Categories for your contacts. Assign contacts to lists for better segmentation.</p>
            </div>
            <div class="page-header__actions">
                <button class="btn btn-primary" @click="openCreate">
                    <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 List
                </button>
            </div>
        </div>

        <!-- Table -->
        <div class="table-wrap">
            <div class="table-toolbar" :class="{ 'has-selection': selectedIds.length > 0 }">
                <div v-if="selectedIds.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 type="search" v-model="search" placeholder="Search lists..." @input="doSearch">
                    </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">{{ selectedIds.length }} list{{ selectedIds.length === 1 ? '' : 's' }} selected</span>
                    </div>
                </div>
                <div v-if="selectedIds.length > 0" class="table-toolbar-right" style="overflow: visible;">
                    <button class="btn btn-outline" style="color:#dc2626;border-color:#fecaca" @click="bulkDeleteLists">Delete</button>
                    <button class="btn btn-outline" @click="selectedIds = []">Cancel</button>
                </div>
            </div>
            <div class="table-scroll">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th style="width:40px"><input type="checkbox" class="table-checkbox" @change="toggleAll" :checked="allChecked"></th>
                            <th>Title</th>
                            <th style="width:100px">Color</th>
                            <th>Description</th>
                            <th style="width:160px">Created</th>
                            <th style="width:110px">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="item in lists.data" :key="item.id">
                            <td class="cell-checkbox"><input type="checkbox" class="table-checkbox" v-model="selectedIds" :value="item.id"></td>
                            <td class="cell-title">
                                <div style="display:flex;align-items:center;gap:8px">
                                    <span class="color-dot" :style="{ background: item.color }"></span>
                                    <span class="tbl-title-link">{{ item.title }}</span>
                                </div>
                                <div style="font-size:11px;color:var(--text-muted);margin-top:1px;padding-left:18px">{{ item.slug }}</div>
                            </td>
                            <td data-label="Color">
                                <div style="display:flex;align-items:center;gap:6px">
                                    <span class="color-swatch-sm" :style="{ background: item.color }"></span>
                                    <span style="font-size:12px;color:var(--text-secondary);font-family:monospace">{{ item.color }}</span>
                                </div>
                            </td>
                            <td data-label="Description" style="font-size:13px;color:var(--text-secondary);max-width:200px">
                                <span class="text-truncate">{{ item.description || '-' }}</span>
                            </td>
                            <td data-label="Created" style="font-size:12px;color:var(--text-secondary)">{{ formatDate(item.created_at) }}</td>
                            <td class="cell-actions">
                                <div style="display:flex;gap:6px">
                                    <button class="re-action-btn" title="Edit" @click="openEdit(item)">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#2563eb" style="width:18px;height:18px;"><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>
                                    </button>
                                    <button class="re-action-btn" title="Delete" @click="deleteItem(item)">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#ef4444" style="width:18px;height:18px;"><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>
                        <tr v-if="lists.data.length === 0">
                            <td colspan="6" style="text-align:center;padding:48px 0;color:#9ca3af;font-size:13px">No lists found.</td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Footer: total + pagination -->
            <div class="table-footer">
                <span class="table-footer-info">Total {{ lists.total }}</span>
                <Pagination :paginator="lists" />
            </div>
        </div>

        <!-- Create / Edit Modal -->
        <ListModal
            :open="showModal"
            :editing="editingItem"
            @close="closeModal"
            @save="saveItem"
        />
    </AppLayout>
</template>

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

const { formatDate: formatDateTz } = useTenantTimezone();

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

const search      = ref('');
const selectedIds = ref([]);
const showModal   = ref(false);
const editingItem = ref(null);

const allChecked = computed(() =>
    props.lists.data.length > 0 && selectedIds.value.length === props.lists.data.length
);

function toggleAll(e) {
    selectedIds.value = e.target.checked ? props.lists.data.map(l => l.id) : [];
}

function openCreate() {
    editingItem.value = null;
    showModal.value   = true;
}

function openEdit(item) {
    editingItem.value = { ...item };
    showModal.value   = true;
}

function closeModal() {
    showModal.value   = false;
    editingItem.value = null;
}

function saveItem(data) {
    if (editingItem.value) {
        router.put(route('lists.update', editingItem.value.id), data, {
            onSuccess: closeModal,
        });
    } else {
        router.post(route('lists.store'), data, {
            onSuccess: closeModal,
        });
    }
}

async function deleteItem(item) {
    if (!await confirm(`Delete "${item.title}"? This cannot be undone.`)) return;
    router.delete(route('lists.destroy', item.id), { preserveScroll: true });
}

async function bulkDeleteLists() {
    if (!await confirm(`Delete ${selectedIds.value.length} lists? This cannot be undone.`)) return;
    router.post(route('lists.bulk-destroy'), { ids: selectedIds.value }, {
        onSuccess: () => { selectedIds.value = []; }
    });
}

function doSearch() {
    router.get(route('lists.index'), { search: search.value }, { preserveState: true, replace: true });
}

function formatDate(iso) {
    if (!iso) return '-';
    return formatDateTz(iso);
}
</script>

<style scoped>
.color-dot      { width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; }
.color-swatch-sm { width: 16px; height: 16px; border-radius: 4px; flex-shrink: 0; border: 1px solid rgba(0,0,0,.1); }
.text-truncate  { display: block; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

.flash-success {
    background: #f0fdf4;
    border: 1px solid #bbf7d0;
    color: #15803d;
    border-radius: 8px;
    padding: 10px 14px;
    font-size: 13px;
    margin-bottom: 16px;
}
</style>
