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

                <div class="modal-header">
                    <div>
                        <h3 class="modal-title">Add New Contact</h3>
                        <p class="modal-subtitle">Add a subscriber to your audience.</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>

                <div class="modal-body" style="max-height:72vh;overflow-y:auto;display:flex;flex-direction:column;gap:16px;overflow-x:visible">

                    <!-- Basic Info heading -->
                    <p class="section-label">Basic Info</p>

                    <!-- Prefix / First / Last -->
                    <div class="fg3" style="overflow:visible">
                        <div class="field" style="overflow:visible">
                            <label class="form-label">Prefix</label>
                            <CwSelect v-model="form.prefix" :options="prefixOptions" placeholder="Select" />
                        </div>
                        <div class="field">
                            <label class="form-label">First Name</label>
                            <input type="text" class="form-input" v-model="form.first_name" placeholder="First name">
                        </div>
                        <div class="field">
                            <label class="form-label">Last Name</label>
                            <input type="text" class="form-input" v-model="form.last_name" placeholder="Last name">
                        </div>
                    </div>

                    <!-- Email / Phone / Date of Birth in 3 Columns -->
                    <div class="fg2" style="overflow:visible">
                        <!-- Email -->
                        <div class="field">
                            <label class="form-label"><span class="req">*</span> Email</label>
                            <input type="email" class="form-input" :class="{ 'is-invalid': errors.email || pageErrors.email }" v-model="form.email" placeholder="email@example.com">
                            <span v-if="errors.email || pageErrors.email" class="field-error">{{ errors.email || pageErrors.email }}</span>
                        </div>

                        <!-- Phone -->
                        <div class="field">
                            <label class="form-label">Phone</label>
                            <input type="tel" class="form-input" v-model="form.phone" placeholder="+1 (555) 000-0000">
                        </div>

                        <!-- DOB -->
                        <div class="field" style="overflow:visible">
                            <label class="form-label">Date of Birth</label>
                            <CwDateTimePicker v-model="form.date_of_birth" mode="date" placeholder="Select Birth Date" :disable-past="false" />
                        </div>
                    </div>

                    <!-- Address toggle -->
                    <label class="addr-toggle">
                        <input type="checkbox" v-model="showAddress"> Add Address Info
                    </label>

                    <template v-if="showAddress">
                        <div class="fg2">
                            <div class="field">
                                <label class="form-label">Address Line 1</label>
                                <input type="text" class="form-input" v-model="form.address_line_1" placeholder="Street address">
                            </div>
                            <div class="field">
                                <label class="form-label">Address Line 2</label>
                                <input type="text" class="form-input" v-model="form.address_line_2" placeholder="Apt, suite, etc.">
                            </div>
                        </div>
                        <div class="fg4">
                            <div class="field">
                                <label class="form-label">City</label>
                                <input type="text" class="form-input" v-model="form.city">
                            </div>
                            <div class="field">
                                <label class="form-label">State</label>
                                <input type="text" class="form-input" v-model="form.state">
                            </div>
                            <div class="field">
                                <label class="form-label">ZIP</label>
                                <input type="text" class="form-input" v-model="form.postal_code">
                            </div>
                            <div class="field">
                                <label class="form-label">Country</label>
                                <input type="text" class="form-input" v-model="form.country">
                            </div>
                        </div>
                    </template>

                    <!-- Identifiers heading -->
                    <p class="section-label" style="margin-top:4px">Identifiers</p>

                    <div class="fg3" style="overflow:visible">
                        <!-- Lists multi-select -->
                        <div class="field" style="overflow:visible">
                            <label class="form-label">Lists</label>
                            <CwSelect v-model="selectedListTemp" :options="listOptions" placeholder="Add list…" placement="top" @change="val => { if (val) { addList(val); selectedListTemp = ''; } }" />
                            <div class="multi-chips" v-if="form.list_ids.length" style="margin-top:6px;margin-bottom:0">
                                <span v-for="id in form.list_ids" :key="id" class="chip-sel">
                                    {{ listTitle(id) }}
                                    <button type="button" class="chip-rm" @click="removeList(id)">&times;</button>
                                </span>
                            </div>
                        </div>

                        <!-- Tags multi-select -->
                        <div class="field" style="overflow:visible">
                            <label class="form-label">Tags</label>
                            <CwSelect v-model="selectedTagTemp" :options="tagOptions" placeholder="Add tag…" placement="top" @change="val => { if (val) { addTag(val); selectedTagTemp = ''; } }" />
                            <div class="multi-chips" v-if="form.tag_ids.length" style="margin-top:6px;margin-bottom:0">
                                <span v-for="id in form.tag_ids" :key="id" class="chip-sel chip-sel--tag">
                                    {{ tagTitle(id) }}
                                    <button type="button" class="chip-rm" @click="removeTag(id)">&times;</button>
                                </span>
                            </div>
                        </div>

                        <!-- Status -->
                        <div class="field" style="overflow:visible">
                            <label class="form-label">Status <span class="req">*</span></label>
                            <CwSelect v-model="form.status" :options="statusOptions" placeholder="Select Status" placement="top" />
                        </div>
                    </div>
                </div>

                <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">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:14px;height:14px"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/></svg>
                        Create Contact
                    </button>
                </div>

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

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

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

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

const showAddress = ref(false);

const form = reactive({
    prefix: '', first_name: '', last_name: '',
    email: '', phone: '', date_of_birth: '',
    address_line_1: '', address_line_2: '',
    city: '', state: '', postal_code: '', country: '',
    status: 'subscribed',
    list_ids: [],
    tag_ids: [],
});

const errors = reactive({ email: '' });
const pageErrors = computed(() => usePage().props.errors || {});

const prefixOptions = [
    { value: '', label: 'Select' },
    { value: 'Mr.', label: 'Mr.' },
    { value: 'Mrs.', label: 'Mrs.' },
    { value: 'Ms.', label: 'Ms.' },
    { value: 'Dr.', label: 'Dr.' },
    { value: 'Prof.', label: 'Prof.' },
];

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

const selectedListTemp = ref('');
const listOptions = computed(() => {
    return [
        { value: '', label: 'Add list…' },
        ...availableLists.value.map(l => ({ value: l.id, label: l.title }))
    ];
});

const selectedTagTemp = ref('');
const tagOptions = computed(() => {
    return [
        { value: '', label: 'Add tag…' },
        ...availableTags.value.map(t => ({ value: t.id, label: t.title }))
    ];
});

watch(() => props.open, (v) => {
    if (v) {
        Object.assign(form, {
            prefix: '', first_name: '', last_name: '',
            email: '', phone: '', date_of_birth: '',
            address_line_1: '', address_line_2: '',
            city: '', state: '', postal_code: '', country: '',
            status: 'subscribed', list_ids: [], tag_ids: [],
        });
        errors.email = '';
        showAddress.value = false;
        selectedListTemp.value = '';
        selectedTagTemp.value = '';
    }
});

const availableLists = computed(() => props.allLists.filter(l => !form.list_ids.includes(l.id)));
const availableTags  = computed(() => props.allTags.filter(t => !form.tag_ids.includes(t.id)));

function listTitle(id) { return props.allLists.find(l => l.id == id)?.title || id; }
function tagTitle(id)  { return props.allTags.find(t => t.id == id)?.title  || id; }

function addList(id)  { if (id && !form.list_ids.includes(Number(id))) form.list_ids.push(Number(id)); }
function removeList(id) { form.list_ids = form.list_ids.filter(x => x !== id); }
function addTag(id)   { if (id && !form.tag_ids.includes(Number(id))) form.tag_ids.push(Number(id)); }
function removeTag(id)  { form.tag_ids = form.tag_ids.filter(x => x !== id); }

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

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

<style scoped>
.section-label { font-size:12px;font-weight:600;color:#4285F4;text-transform:uppercase;letter-spacing:.06em;padding-bottom:8px;margin:0; }
.field { display:flex;flex-direction:column;gap:6px; }
.fg2 { display:grid;grid-template-columns:1fr 1fr;gap:12px; }
.fg3 { display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px; }
.fg4 { display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:12px; }
@media(max-width:600px){ .fg3,.fg4{ grid-template-columns:1fr; } }
.req { color:#ef4444;font-weight:700; }
.field-error { font-size:12px;color:#ef4444; }
.form-input.is-invalid { border-color:#ef4444; }
.addr-toggle { display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;color:var(--text-secondary); }
.addr-toggle input { width:15px;height:15px;accent-color:#4285F4; }
.multi-chips { display:flex;flex-wrap:wrap;gap:4px;margin-bottom:6px; }
.chip-sel { display:inline-flex;align-items:center;gap:4px;font-size:12px;background:#e8f0fe;color:#1a56db;border-radius:4px;padding:2px 6px; }
.chip-sel--tag { background:#fef3c7;color:#92400e; }
.chip-rm { background:none;border:none;cursor:pointer;color:inherit;padding:0;font-size:14px;line-height:1; }
</style>
