<template>
    <Teleport to="body">
        <div class="modal-overlay" :class="{ 'is-open': open }" @click.self="$emit('close')">
            <div class="modal" style="width:640px;max-width:96vw">

                <!-- Header -->
                <div class="modal-header">
                    <div>
                        <h3 class="modal-title">{{ editing ? 'Edit Webhook' : 'Create Webhook' }}</h3>
                        <p class="modal-subtitle">{{ editing ? 'Update where this webhook sends contacts.' : 'Paste the URL into an external form or automation tool once created.' }}</p>
                    </div>
                    <button class="modal-close" @click="$emit('close')" aria-label="Close">
                        <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>

                <!-- Body -->
                <div class="modal-body" style="display:flex; flex-direction:column; gap:16px">

                    <div class="field">
                        <label class="form-label"><span class="req">*</span> Name</label>
                        <input
                            type="text"
                            class="form-input"
                            :class="{ 'is-invalid': errors.name }"
                            v-model="form.name"
                            placeholder="e.g. Website Contact Form"
                        >
                        <span v-if="errors.name" class="field-error">{{ errors.name }}</span>
                    </div>

                    <!-- Lists & Tags in 2 Columns using CwSelect multi-select -->
                    <div class="field-grid2">
                        <div class="field">
                            <label class="form-label">Add to Lists <span class="optional">(Optional)</span></label>
                            <CwSelect
                                v-model="form.list_ids"
                                :options="listOptions"
                                multiple
                                placeholder="Select lists..."
                            />
                        </div>
                        <div class="field">
                            <label class="form-label">Add Tags <span class="optional">(Optional)</span></label>
                            <CwSelect
                                v-model="form.tag_ids"
                                :options="tagOptions"
                                multiple
                                placeholder="Select tags..."
                            />
                        </div>
                    </div>

                    <div class="field-grid2">
                        <div class="field">
                            <label class="form-label">New contact status</label>
                            <CwSelect
                                v-model="form.default_status"
                                :options="statusOptions"
                                placeholder="Select status"
                            />
                        </div>
                        <div class="field">
                            <label class="form-label">If the email already exists</label>
                            <CwSelect
                                v-model="form.duplicate_handling"
                                :options="duplicateOptions"
                                placeholder="Select action"
                            />
                        </div>
                    </div>

                    <div class="field">
                        <label class="form-label">Success redirect URL <span class="optional">(Optional)</span></label>
                        <input type="url" class="form-input" v-model="form.success_redirect_url" placeholder="https://yoursite.com/thank-you">
                        <p class="field-hint">Only used for plain HTML form submissions (not JS/fetch) - sends the visitor's browser here after a successful submission.</p>
                    </div>

                    <div class="checkbox-group">
                        <label class="custom-checkbox-label">
                            <input type="checkbox" v-model="form.use_secret" class="sr-only">
                            <span class="custom-checkbox" :class="{ 'is-checked': form.use_secret }">
                                <svg v-if="form.use_secret" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="check-svg">
                                    <path fill-rule="evenodd" d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z" clip-rule="evenodd"/>
                                </svg>
                            </span>
                            <span class="label-text">Require a signed request (HMAC)</span>
                            <span class="info-tooltip-wrapper">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="info-icon">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M11.25 11.25l.041-.02a.75.75 0 011.063.852l-.708 2.836a.75.75 0 001.063.853l.041-.021M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9-3.75h.008v.008H12V8.25z" />
                                </svg>
                                <span class="tooltip-bubble">Adds a secret key. Requests must include an X-Webhook-Signature header (HMAC-SHA256 of the raw request body). Only enable this if the tool sending data can compute a signature.</span>
                            </span>
                        </label>

                        <label class="custom-checkbox-label">
                            <input type="checkbox" v-model="form.is_active" class="sr-only">
                            <span class="custom-checkbox" :class="{ 'is-checked': form.is_active }">
                                <svg v-if="form.is_active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="check-svg">
                                    <path fill-rule="evenodd" d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z" clip-rule="evenodd"/>
                                </svg>
                            </span>
                            <span class="label-text">Active</span>
                        </label>
                    </div>

                </div>

                <!-- Footer -->
                <div class="modal-footer" style="justify-content:flex-end;gap:10px">
                    <button class="btn btn-outline" @click="$emit('close')">Cancel</button>
                    <button class="btn btn-primary" @click="submit">
                        {{ editing ? 'Save Changes' : 'Create Webhook' }}
                    </button>
                </div>

            </div>
        </div>
    </Teleport>
</template>

<script setup>
import { reactive, watch, computed, ref } from 'vue';
import CwSelect from '@/Components/CwSelect.vue';

const props = defineProps({
    open:     { type: Boolean, default: false },
    editing:  { type: Object,  default: null  },
    allLists: { type: Array,   default: () => [] },
    allTags:  { type: Array,   default: () => [] },
});

const emit = defineEmits(['close', 'save']);

const listOptions = computed(() => (props.allLists || []).map(l => ({ value: l.id, label: l.title, color: l.color })));
const tagOptions = computed(() => (props.allTags || []).map(t => ({ value: t.id, label: t.title, color: t.color })));

const statusOptions = ref([
    { value: 'subscribed', label: 'Subscribed' },
    { value: 'unsubscribed', label: 'Unsubscribed' },
]);

const duplicateOptions = ref([
    { value: 'update', label: 'Update the existing contact' },
    { value: 'skip', label: 'Skip (leave it unchanged)' },
]);

const errors = reactive({ name: '' });

const form = reactive(emptyForm());

function emptyForm() {
    return {
        name:                  '',
        list_ids:              [],
        tag_ids:               [],
        default_status:        'subscribed',
        duplicate_handling:    'update',
        success_redirect_url:  '',
        use_secret:            false,
        is_active:             true,
    };
}

watch(() => props.open, (open) => {
    if (!open) return;

    if (props.editing) {
        Object.assign(form, {
            name:                 props.editing.name,
            list_ids:             [...(props.editing.list_ids ?? [])],
            tag_ids:              [...(props.editing.tag_ids ?? [])],
            default_status:       props.editing.default_status ?? 'subscribed',
            duplicate_handling:   props.editing.duplicate_handling ?? 'update',
            success_redirect_url: props.editing.success_redirect_url ?? '',
            use_secret:           !!props.editing.has_secret,
            is_active:            !!props.editing.is_active,
        });
    } else {
        Object.assign(form, emptyForm());
    }

    errors.name = '';
});

function validate() {
    errors.name = form.name.trim() ? '' : 'Name is required.';
    return !errors.name;
}

function submit() {
    if (!validate()) return;
    emit('save', { ...form });
}
</script>

<style scoped>
.field { display: flex; flex-direction: column; gap: 6px; }

.field-grid2 {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
}
@media (max-width: 500px) { .field-grid2 { grid-template-columns: 1fr; } }

.req      { color: #ef4444; font-weight: 700; }
.optional { font-size: 12px; font-weight: 400; color: #9ca3af; }

.field-error { font-size: 12px; color: #ef4444; }
.field-hint  { font-size: 12px; color: #9ca3af; margin: 0; }

.form-input.is-invalid { border-color: #ef4444; }

.check-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    max-height: 140px;
    overflow-y: auto;
    padding: 10px;
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
}

.check-chip {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    font-weight: 500;
    color: #374151;
    background: #f9fafb;
    border: 1px solid #e5e7eb;
    border-radius: 20px;
    padding: 4px 10px 4px 8px;
    cursor: pointer;
}

.color-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }

/* Custom Checkbox Group Styling */
.checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin-top: 4px;
}

.custom-checkbox-label {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    font-weight: 500;
    color: #374151;
    cursor: pointer;
    user-select: none;
    transition: color 0.15s ease;
}

.custom-checkbox-label:hover {
    color: #111827;
}

.sr-only {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    white-space: nowrap;
    border-width: 0;
}

.custom-checkbox {
    width: 18px;
    height: 18px;
    border: 1px solid var(--border-color);
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.15s ease;
    flex-shrink: 0;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.custom-checkbox-label:hover .custom-checkbox {
    border-color: #93c5fd;
}

.custom-checkbox.is-checked {
    background: #2563eb;
    border-color: #2563eb;
    color: #ffffff;
    box-shadow: 0 1px 3px rgba(37, 99, 235, 0.3);
}

.check-svg {
    width: 12px;
    height: 12px;
}

.label-text {
    line-height: 1.4;
    color: var(--text-secondary);
}

/* Info Icon & Tooltip */
.info-tooltip-wrapper {
    position: relative;
    display: inline-flex;
    align-items: center;
    margin-left: 2px;
}

.info-icon {
    width: 16px;
    height: 16px;
    color: #3b82f6;
    transition: color 0.15s ease, transform 0.15s ease;
    cursor: help;
}

.info-tooltip-wrapper:hover .info-icon {
    color: #1d4ed8;
    transform: scale(1.1);
}

.tooltip-bubble {
    visibility: hidden;
    opacity: 0;
    width: 270px;
    background-color: var();
    color: #f8fafc;
    text-align: left;
    border-radius: 8px;
    padding: 8px 12px;
    font-size: 11px;
    font-weight: 400;
    line-height: 1.4;
    position: absolute;
    z-index: 1100;
    bottom: 125%;
    left: 50%;
    transform: translateX(-50%) translateY(4px);
    transition: opacity 0.2s ease, transform 0.2s ease, visibility 0.2s ease;
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
    pointer-events: none;
}

.tooltip-bubble::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #1e293b transparent transparent transparent;
}

.info-tooltip-wrapper:hover .tooltip-bubble {
    visibility: visible;
    opacity: 1;
    transform: translateX(-50%) translateY(0);
}
</style>
