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

    <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">
                <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>
            <Link href="/webhooks" 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="M13.19 8.688a4.5 4.5 0 011.242 7.244l-4.5 4.5a4.5 4.5 0 01-6.364-6.364l1.757-1.757m13.35-.622l1.757-1.757a4.5 4.5 0 00-6.364-6.364l-4.5 4.5a4.5 4.5 0 001.242 7.244"/></svg>
                Webhooks
            </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>Webhooks</h1>
                <p>Give each external form or tool its own URL - submissions create or update a contact and attach it to whatever lists/tags you choose.</p>
            </div>
            <div class="page-header__actions">
                <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>
                    Create Webhook
                </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 webhooks..." @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 }} webhook{{ 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" @click="bulkToggleWebhookStatus(true)">Activate</button>
                    <button class="btn btn-outline" @click="bulkToggleWebhookStatus(false)">Pause</button>
                    <button class="btn btn-outline" style="color:#dc2626;border-color:#fecaca" @click="bulkDeleteWebhooks">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>Name</th>
                            <th>URL</th>
                            <th>Lists / Tags</th>
                            <th style="width:90px">Received</th>
                            <th style="width:150px">Last triggered</th>
                            <th style="width:80px">Status</th>
                            <th style="width:120px">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="item in webhooks.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">
                                <span class="tbl-title-link">{{ item.name }}</span>
                                <div style="font-size:11px;color:var(--text-muted);margin-top:1px">{{ item.logs_count }} log{{ item.logs_count === 1 ? '' : 's' }}</div>
                            </td>
                            <td data-label="URL">
                                <div class="url-row">
                                    <code class="url-code" :title="item.receive_url">{{ truncateUrl(item.receive_url) }}</code>
                                    <button class="copy-btn" :class="{ 'is-copied': copiedId === item.id }" @click="copyUrl(item)">
                                        {{ copiedId === item.id ? 'Copied!' : 'Copy' }}
                                    </button>
                                </div>
                                <div v-if="item.has_secret" style="font-size:11px;color:var(--text-muted);margin-top:3px">🔒 Signature required</div>
                            </td>
                            <td data-label="Lists / Tags">
                                <div style="display:flex; flex-direction:column; gap:6px;">
                                    <div v-if="item.lists && item.lists.length" class="chip-list">
                                        <span v-for="l in item.lists" :key="'l'+l.id" class="chip-list-item" :style="{ background: l.color + '22', color: l.color, border: '1px solid ' + l.color + '44' }">{{ l.title }}</span>
                                    </div>
                                    <div v-if="item.tags && item.tags.length" class="chip-tag-list">
                                        <span v-for="t in item.tags" :key="'t'+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-if="!item.lists.length && !item.tags.length" style="font-size:12px;color:var(--text-muted)">-</span>
                                </div>
                            </td>
                            <td data-label="Received" style="font-size:13px;color:var(--text-primary)">{{ item.total_received }}</td>
                            <td data-label="Last triggered" style="font-size:12px;color:var(--text-secondary)">{{ item.last_triggered_at ? formatDate(item.last_triggered_at) : 'Never' }}</td>
                            <td data-label="Status">
                                <span :class="['badge', item.is_active ? 'badge--success' : 'badge--gray']">
                                    {{ item.is_active ? 'Active' : 'Paused' }}
                                </span>
                            </td>
                            <td class="cell-actions">
                                <div style="display:flex;gap:6px">
                                    <button class="re-action-btn" title="View delivery logs" @click="openLogs(item)">
                                        <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="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                                    </button>
                                    <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="webhooks.data.length === 0">
                            <td colspan="7" style="text-align:center;padding:48px 0;color:#9ca3af;font-size:13px">No webhooks yet - create one to start receiving contacts from an external form.</td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="table-footer">
                <span class="table-footer-info">Total {{ webhooks.total }}</span>
                <Pagination :paginator="webhooks" />
            </div>
        </div>

        <!-- Documentation Banner -->
        <div class="docs-banner" @click="showDocsModal = true">
            <div class="docs-banner__left">
                <div class="docs-banner__icon">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="20" height="20"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6.042A8.967 8.967 0 006 3.75c-1.052 0-2.062.18-3 .512v14.25A8.987 8.987 0 016 18c2.305 0 4.408.867 6 2.292m0-14.25a8.966 8.966 0 016-2.292c1.052 0 2.062.18 3 .512v14.25A8.987 8.987 0 0018 18a8.967 8.967 0 00-6 2.292m0-14.25v14.25"/></svg>
                </div>
                <div>
                    <h4 class="docs-banner__title">Webhook documentation</h4>
                    <p class="docs-banner__desc">Learn how to connect forms, auto-detect field mappings, and verify signatures.</p>
                </div>
            </div>
            <button class="btn btn-outline" @click.stop="showDocsModal = true">
                View Documentation
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="14" height="14" style="margin-left: 4px;"><path stroke-linecap="round" stroke-linejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25"/></svg>
            </button>
        </div>

        <!-- Create / Edit Modal -->
        <WebhookModal
            :open="showModal"
            :editing="editingItem"
            :all-lists="allLists"
            :all-tags="allTags"
            @close="closeModal"
            @save="saveItem"
        />

        <!-- Delivery logs modal -->
        <WebhookLogsModal
            :open="showLogsModal"
            :webhook="logsTarget"
            @close="showLogsModal = false"
        />

        <!-- Detailed Documentation Modal -->
        <WebhookDocsModal
            :open="showDocsModal"
            @close="showDocsModal = false"
            @open-field-ref="showDocsModal = false; showFieldReference = true"
        />

        <!-- One-time secret reveal -->
        <Teleport to="body">
            <div class="modal-overlay" :class="{ 'is-open': !!revealSecret }" @click.self="revealSecret = null">
                <div class="modal" style="width:480px;max-width:96vw">
                    <div class="modal-header">
                        <h3 class="modal-title">Webhook secret</h3>
                        <button class="modal-close" @click="revealSecret = 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="font-size:13px;color:#6b7280;margin:0 0 12px">
                            Copy this now - it won't be shown again. Use it to compute an <code>X-Webhook-Signature</code> header
                            (<code>hash_hmac('sha256', rawRequestBody, secret)</code>) on requests you can sign (Zapier, Make.com, custom scripts).
                            Plain HTML forms can't compute this, so leave signing off for those.
                        </p>
                        <div class="url-row">
                            <code class="url-code" style="user-select:all">{{ revealSecret }}</code>
                            <button class="copy-btn" @click="copySecret">{{ secretCopied ? 'Copied!' : 'Copy' }}</button>
                        </div>
                    </div>
                    <div class="modal-footer" style="justify-content:flex-end">
                        <button class="btn btn-primary" @click="revealSecret = null">Done</button>
                    </div>
                </div>
            </div>
        </Teleport>

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

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

const { formatDateTime: formatDate } = useTenantTimezone();

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

const page = usePage();

const search        = ref('');
const showModal      = ref(false);
const editingItem    = ref(null);
const copiedId       = ref(null);
const showLogsModal  = ref(false);
const logsTarget     = ref(null);
const revealSecret   = ref(null);
const secretCopied   = ref(false);
const showFieldReference = ref(false);
const showDocsModal      = ref(false);

const selectedIds = ref([]);

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

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

function bulkToggleWebhookStatus(isActive) {
    router.post(route('webhooks.bulk-toggle-status'), { ids: selectedIds.value, is_active: isActive }, {
        onSuccess: () => { selectedIds.value = []; }
    });
}

async function bulkDeleteWebhooks() {
    if (!await confirm(`Delete ${selectedIds.value.length} webhooks? Any form still pointed at these URLs will stop working. This cannot be undone.`)) return;
    router.post(route('webhooks.bulk-destroy'), { ids: selectedIds.value }, {
        onSuccess: () => { selectedIds.value = []; }
    });
}

// Show the plaintext secret once, right after it's generated server-side.
watch(() => page.props.flash?.plainSecret, (secret) => {
    if (secret) {
        revealSecret.value = secret;
        secretCopied.value = false;
    }
}, { immediate: true });

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('webhooks.update', editingItem.value.id), data, { onSuccess: closeModal });
    } else {
        router.post(route('webhooks.store'), data, { onSuccess: closeModal });
    }
}

async function deleteItem(item) {
    if (!await confirm(`Delete "${item.name}"? Any form still pointed at this URL will stop working. This cannot be undone.`)) return;
    router.delete(route('webhooks.destroy', item.id), { preserveScroll: true });
}

function openLogs(item) {
    logsTarget.value    = item;
    showLogsModal.value = true;
}

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

async function copyUrl(item) {
    await navigator.clipboard.writeText(item.receive_url);
    copiedId.value = item.id;
    setTimeout(() => { if (copiedId.value === item.id) copiedId.value = null; }, 2000);
}

async function copySecret() {
    await navigator.clipboard.writeText(revealSecret.value);
    secretCopied.value = true;
}

function truncateUrl(url) {
    return url.length > 42 ? url.slice(0, 20) + '…' + url.slice(-18) : url;
}

</script>

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

.url-row {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.url-code {
    font-size: 11px;
    font-family: monospace;
    background: var(--bg-hover-strong);
    color: var(--text-primary);
    padding: 4px 8px;
    border-radius: 6px;
    white-space: nowrap;
}

.copy-btn {
    font-size: 11px;
    font-weight: 600;
    color: var(--active-text);
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 6px;
    padding: 3px 8px;
    cursor: pointer;
    flex-shrink: 0;
}
.copy-btn.is-copied { color: var(--success); border-color: var(--success-border); }

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

.badge-dot {
    font-size: 11px;
    font-weight: 600;
    padding: 2px 8px;
    border-radius: 20px;
}
.badge-dot--online { background: var(--success-light); color: var(--success); }
.badge-dot--idle   { background: var(--bg-hover-strong); color: var(--text-muted); }

.docs-banner {
    margin-top: 24px;
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 16px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    cursor: pointer;
    transition: border-color 0.15s ease, box-shadow 0.15s ease, background 0.15s ease;
    
}
.docs-banner:hover {
    border-color: var(--active-border, var(--border-color));
    background: var(--bg-hover);
    box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}

.docs-banner__left {
    display: flex;
    align-items: center;
    gap: 14px;
    min-width: 0;
}

.docs-banner__icon {
    width: 38px;
    height: 38px;
    border-radius: 10px;
    background: var(--active-bg, #eff6ff);
    color: var(--active-text, #2563eb);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.docs-banner__title {
    font-size: 14px;
    font-weight: 700;
    color: var(--text-primary);
    margin: 0 0 2px;
}

.docs-banner__desc {
    font-size: 12.5px;
    color: var(--text-secondary);
    margin: 0;
    line-height: 1.45;
}

.docs-banner .btn {
    flex-shrink: 0;
    white-space: nowrap;
}

@media (max-width: 640px) {
    .docs-banner {
        flex-direction: column;
        align-items: stretch;
        padding: 16px;
        gap: 14px;
    }
    .docs-banner__left {
        align-items: flex-start;
    }
    .docs-banner .btn {
        width: 100%;
        justify-content: center;
    }
}
</style>
