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

    <AppLayout>
        <!-- Audience tab bar -->
        <nav class="aud-tabs">
            <Link href="/contacts" 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="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">
                <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 -->
        <div v-if="$page.props.flash?.success" class="flash-success">{{ $page.props.flash.success }}</div>

        <!-- Page header -->
        <div class="page-header">
            <div class="page-header__left">
                <h1>Contacts</h1>
                <p>Manage your subscribers and contacts.</p>
            </div>
            <div class="page-header__actions">
                <Link :href="route('contacts.import')" class="btn btn-outline">
                    <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="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3"/></svg>
                    Import
                </Link>
                <button class="btn btn-outline" @click="showExportModal = 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="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5"/></svg>
                    Export
                </button>
                <button class="btn btn-outline" title="Exact field names for webhook mapping" @click="showFieldReference = 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="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456z"/></svg>
                    Field Reference
                </button>
                <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>
                    Add Contact
                </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" @click.stop>
                    <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 contacts..." @input="doSearch">
                    </div>

                    <div class="filter-dropdown">
                        <button class="filter-btn" :class="{ 'is-active': activeFilters.list_id }" @click.stop="toggleDrop('list')">
                            Lists
                            <span v-if="activeFilters.list_id" class="filter-dot"></span>
                            <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="M19.5 8.25l-7.5 7.5-7.5-7.5"/></svg>
                        </button>
                        <div class="filter-menu" v-show="openDrop === 'list'" @click.stop>
                            <a class="filter-item" :class="{ 'is-selected': !activeFilters.list_id }" @click="setFilter('list_id', null)">All Lists</a>
                            <a v-for="l in allLists" :key="l.id" class="filter-item" :class="{ 'is-selected': activeFilters.list_id == l.id }" @click="setFilter('list_id', l.id)">
                                <span class="filter-dot-sm" :style="{ background: l.color }"></span>{{ l.title }}
                            </a>
                        </div>
                    </div>

                    <div class="filter-dropdown">
                        <button class="filter-btn" :class="{ 'is-active': activeFilters.tag_id }" @click.stop="toggleDrop('tag')">
                            Tags
                            <span v-if="activeFilters.tag_id" class="filter-dot"></span>
                            <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="M19.5 8.25l-7.5 7.5-7.5-7.5"/></svg>
                        </button>
                        <div class="filter-menu" v-show="openDrop === 'tag'" @click.stop>
                            <a class="filter-item" :class="{ 'is-selected': !activeFilters.tag_id }" @click="setFilter('tag_id', null)">All Tags</a>
                            <a v-for="t in allTags" :key="t.id" class="filter-item" :class="{ 'is-selected': activeFilters.tag_id == t.id }" @click="setFilter('tag_id', t.id)">
                                <span class="filter-dot-sm" :style="{ background: t.color }"></span>{{ t.title }}
                            </a>
                        </div>
                    </div>

                    <div class="filter-dropdown">
                        <button class="filter-btn" :class="{ 'is-active': activeFilters.status }" @click.stop="toggleDrop('status')">
                            Status
                            <span v-if="activeFilters.status" class="filter-dot"></span>
                            <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="M19.5 8.25l-7.5 7.5-7.5-7.5"/></svg>
                        </button>
                        <div class="filter-menu" v-show="openDrop === 'status'" @click.stop>
                            <a class="filter-item" :class="{ 'is-selected': !activeFilters.status }" @click="setFilter('status', null)">All</a>
                            <a v-for="s in statuses" :key="s.value" class="filter-item" :class="{ 'is-selected': activeFilters.status === s.value }" @click="setFilter('status', s.value)">{{ s.label }}</a>
                        </div>
                    </div>

                    <button v-if="hasFilters" class="filter-clear" @click="clearFilters">Clear filters</button>
                </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 }} contact{{ selectedIds.length === 1 ? '' : 's' }} selected</span>
                    </div>
                </div>

                <div v-if="selectedIds.length > 0" class="table-toolbar-right" style="overflow: visible;">
                    <div class="filter-dropdown">
                        <button class="filter-btn" @click.stop="toggleDrop('bulk_list')">
                            Add to List
                            <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="M19.5 8.25l-7.5 7.5-7.5-7.5"/></svg>
                        </button>
                        <div class="filter-menu" v-show="openDrop === 'bulk_list'" @click.stop>
                            <a class="filter-item" :class="{ 'is-selected': false }" v-for="l in allLists" :key="'bl'+l.id" @click="bulkAddLists(l.id)">
                                <span class="filter-dot-sm" :style="{ background: l.color }"></span>{{ l.title }}
                            </a>
                        </div>
                    </div>

                    <div class="filter-dropdown">
                        <button class="filter-btn" @click.stop="toggleDrop('bulk_tag')">
                            Add Tag
                            <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="M19.5 8.25l-7.5 7.5-7.5-7.5"/></svg>
                        </button>
                        <div class="filter-menu" v-show="openDrop === 'bulk_tag'" @click.stop>
                            <a class="filter-item" :class="{ 'is-selected': false }" v-for="t in allTags" :key="'bt'+t.id" @click="bulkAddTags(t.id)">
                                <span class="filter-dot-sm" :style="{ background: t.color }"></span>{{ t.title }}
                            </a>
                        </div>
                    </div>

                    <div class="filter-dropdown">
                        <button class="filter-btn" @click.stop="toggleDrop('bulk_status')">
                            Status
                            <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="M19.5 8.25l-7.5 7.5-7.5-7.5"/></svg>
                        </button>
                        <div class="filter-menu" v-show="openDrop === 'bulk_status'" @click.stop>
                            <a class="filter-item" :class="{ 'is-selected': false }" v-for="s in statuses" :key="'bs'+s.value" @click="bulkUpdateStatus(s.value)">{{ s.label }}</a>
                        </div>
                    </div>

                    <button class="btn btn-outline" style="color:#dc2626;border-color:#fecaca" @click="bulkDeleteContacts">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 style="width:36px"></th>
                            <th>Email</th>
                            <th>Name</th>
                            <th>Lists</th>
                            <th>Tags</th>
                            <th style="width:120px">Status</th>
                            <th style="width:90px">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="c in contacts.data" :key="c.id" style="cursor:pointer" @click="goToContact(c)">
                            <td class="cell-checkbox" @click.stop><input type="checkbox" class="table-checkbox" v-model="selectedIds" :value="c.id"></td>
                            <td class="cell-avatar">
                                <div class="contact-avatar" :style="{ background: avatarColor(c.email) }">{{ initials(c) }}</div>
                            </td>
                            <td data-label="Email" class="cell-email">{{ c.email }}</td>
                            <td data-label="Name">
                                {{ [c.first_name, c.last_name].filter(Boolean).join(' ') || '-' }}
                            </td>
                            <td data-label="Lists">
                                <div v-if="c.lists && c.lists.length" class="chip-list">
                                    <span v-for="l in c.lists" :key="l.id" class="chip-list-item" :style="{ background: l.color + '22', color: l.color, border: '1px solid ' + l.color + '44' }">{{ l.title }}</span>
                                </div>
                                <span v-else style="color:var(--text-muted);font-size:13px">-</span>
                            </td>
                            <td data-label="Tags">
                                <div v-if="c.tags && c.tags.length" class="chip-tag-list">
                                    <span v-for="t in c.tags" :key="t.id" class="chip-tag-item" :style="{ background: t.color ? t.color + '15' : '#fef3c7', color: t.color || '#d97706', border: '1px solid ' + (t.color ? t.color + '33' : '#fde68a') }">{{ t.title }}</span>
                                </div>
                                <span v-else style="color:var(--text-muted);font-size:13px">-</span>
                            </td>
                            <td data-label="Status"><span class="badge" :class="statusClass(c.status)">{{ c.status }}</span></td>
                            <td class="cell-actions" @click.stop>
                                <div style="display:flex;gap:6px">
                                    <Link :href="route('contacts.show', c.id)" class="re-action-btn" title="View">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#0f766e" style="width:18px;height:18px;"><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.964-7.178z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                                    </Link>
                                    <button class="re-action-btn" title="Delete" @click="deleteContact(c)">
                                        <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="contacts.data.length === 0">
                            <td colspan="8" style="text-align:center;padding:48px 0;color:#9ca3af;font-size:13px">No contacts found.</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="table-footer">
                <span class="table-footer-info">Total {{ contacts.total }}</span>
                <Pagination :paginator="contacts" />
            </div>
        </div>

        <ContactModal
            :open="showModal"
            :all-lists="allLists"
            :all-tags="allTags"
            @close="showModal = false"
            @save="createContact"
        />

        <ExportModal
            :open="showExportModal"
            :active-filters="activeFilters"
            :export-route="route('contacts.export')"
            @close="showExportModal = false"
        />

        <FieldReferenceModal
            :open="showFieldReference"
            :fields="fieldRegistry"
            @close="showFieldReference = false"
        />
    </AppLayout>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { Head, Link, router } from '@inertiajs/vue3';
import AppLayout           from '@/Layouts/AppLayout.vue';
import ContactModal        from '@/Components/ContactModal.vue';
import ExportModal         from '@/Components/ExportModal.vue';
import FieldReferenceModal from '@/Components/FieldReferenceModal.vue';
import Pagination          from '@/Components/Pagination.vue';

const props = defineProps({
    contacts:      Object,
    allLists:      Array,
    allTags:       Array,
    filters:       Object,
    fieldRegistry: { type: Object, default: () => ({}) },
});

const search          = ref(props.filters?.search || '');
const selectedIds     = ref([]);
const showModal       = ref(false);
const showExportModal = ref(false);
const showFieldReference = ref(false);
const openDrop        = ref(null);

const activeFilters = ref({
    search:  props.filters?.search  || null,
    list_id: props.filters?.list_id || null,
    tag_id:  props.filters?.tag_id  || null,
    status:  props.filters?.status  || null,
});

const statuses = [
    { value: 'subscribed',    label: 'Subscribed' },
    { value: 'unsubscribed',  label: 'Unsubscribed' },
    { value: 'bounced',       label: 'Bounced' },
    { value: 'spam_reported', label: 'Spam Reported' },
];

const hasFilters = computed(() => Object.values(activeFilters.value).some(v => v));

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

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

function applyFilters() {
    const params = {};
    Object.entries(activeFilters.value).forEach(([k, v]) => { if (v) params[k] = v; });
    router.get(route('contacts.index'), params, { preserveState: true, replace: true });
    openDrop.value = null;
}

function setFilter(key, value) {
    activeFilters.value[key] = value || null;
    applyFilters();
}

function clearFilters() {
    activeFilters.value = { search: null, list_id: null, tag_id: null, status: null };
    search.value = '';
    applyFilters();
}

function doSearch() {
    activeFilters.value.search = search.value || null;
    applyFilters();
}

function toggleDrop(name) {
    openDrop.value = openDrop.value === name ? null : name;
}

function closeDrops() { openDrop.value = null; }

onMounted(() => document.addEventListener('click', closeDrops));
onBeforeUnmount(() => document.removeEventListener('click', closeDrops));

function goToContact(c) {
    router.get(route('contacts.show', c.id));
}

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

function createContact(data) {
    router.post(route('contacts.store'), data, { onSuccess: () => { showModal.value = false; } });
}

async function deleteContact(c) {
    const name = [c.first_name, c.last_name].filter(Boolean).join(' ') || c.email;
    if (!await confirm(`Delete "${name}"? This cannot be undone.`)) return;
    router.delete(route('contacts.destroy', c.id), { preserveScroll: true });
}

function bulkAddLists(listId) {
    router.post(route('contacts.bulk-add-lists'), { ids: selectedIds.value, list_ids: [listId] }, {
        onSuccess: () => { selectedIds.value = []; openDrop.value = null; }
    });
}

function bulkAddTags(tagId) {
    router.post(route('contacts.bulk-add-tags'), { ids: selectedIds.value, tag_ids: [tagId] }, {
        onSuccess: () => { selectedIds.value = []; openDrop.value = null; }
    });
}

function bulkUpdateStatus(status) {
    router.post(route('contacts.bulk-update-status'), { ids: selectedIds.value, status: status }, {
        onSuccess: () => { selectedIds.value = []; openDrop.value = null; }
    });
}

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

const avatarColors = [
    '#7c3aed','#0891b2','#dc2626','#059669','#d97706',
    '#6366f1','#0f766e','#be185d','#9333ea','#475569',
    '#4285F4','#EA4335','#34A853','#FBBC05',
];

function avatarColor(email) {
    let h = 0;
    for (let i = 0; i < email.length; i++) h = email.charCodeAt(i) + ((h << 5) - h);
    return avatarColors[Math.abs(h) % avatarColors.length];
}

function initials(c) {
    const f = (c.first_name || '').charAt(0).toUpperCase();
    const l = (c.last_name  || '').charAt(0).toUpperCase();
    return (f + l) || (c.email || '').substring(0, 2).toUpperCase();
}

function statusClass(status) {
    return { subscribed: 'badge--subscribed', unsubscribed: 'badge--unsubscribed', bounced: 'badge--bounced', spam_reported: 'badge--bounced' }[status] || '';
}
</script>

<style scoped>
.filter-bar { display:flex;align-items:center;justify-content:space-between;background:#fff;border:1px solid var(--border-color);border-radius:8px;padding:10px 14px;margin-bottom:16px;flex-wrap:wrap;gap:8px; }
.filter-bar-left { display:flex;align-items:center;gap:8px;flex-wrap:wrap; }
.filter-dropdown { position:relative; }
.filter-btn { display:flex;align-items:center;gap:6px;padding:6px 12px;border:1px solid var(--border-color);border-radius:6px;font-size:12px;color:var(--text-primary);background:var(--bg-surface);cursor:pointer;white-space:nowrap;}
.filter-btn svg { width:14px;height:14px; }
.filter-btn.is-active { border-color:#4285F4;color:#4285F4; }
.filter-dot { width:6px;height:6px;border-radius:50%;background:#4285F4;display:inline-block; }
.filter-dot-sm { width:10px;height:10px;border-radius:50%;display:inline-block;flex-shrink:0; }
.filter-menu { position:absolute;top:calc(100% + 4px);left:0;background:var(--bg-surface);border:1px solid var(--border-color);border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,.08);z-index:50;min-width:180px;padding:4px 0; }
.filter-item { display:flex;align-items:center;gap:8px;padding:8px 14px;font-size:13px;color:var(--text-primary);cursor:pointer;white-space:nowrap; }
.filter-item:hover { background:var(--bg-hover); }
.filter-item.is-selected { color:#4285F4;font-weight:500; }
.filter-clear { font-size:12px;color:#6b7280;background:none;border:none;cursor:pointer;text-decoration:underline; }
.contact-avatar { width:28px;height:28px;border-radius:50%;color:#fff;font-size:11px;font-weight:600;display:flex;align-items:center;justify-content:center;flex-shrink:0; }
.chip-list,.chip-tag-list { display:flex;flex-wrap:wrap;gap:4px; }
.chip-list-item,
.chip-tag-item {
    font-size: 11px;
    font-weight: 600;
    padding: 2px 8px;
    border-radius: 6px;
    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>
