<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">

                <!-- Header -->
                <div class="modal-header">
                    <div>
                        <h3 class="modal-title">{{ editing ? 'Edit List' : 'Add New List' }}</h3>
                        <p class="modal-subtitle">{{ editing ? 'Update list details.' : 'Organise and segment your contacts into groups.' }}</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">

                    <!-- Title + Slug -->
                    <div class="field-grid2">
                        <div class="field">
                            <label class="form-label"><span class="req">*</span> Title</label>
                            <input
                                type="text"
                                class="form-input"
                                :class="{ 'is-invalid': errors.title }"
                                v-model="form.title"
                                placeholder="e.g. Newsletter Subscribers"
                                @input="syncSlug"
                            >
                            <span v-if="errors.title" class="field-error">{{ errors.title }}</span>
                        </div>
                        <div class="field">
                            <label class="form-label"><span class="req">*</span> Slug <span class="hint">Auto-generated</span></label>
                            <input
                                type="text"
                                class="form-input"
                                :class="{ 'is-invalid': errors.slug }"
                                v-model="form.slug"
                                placeholder="e.g. newsletter-subscribers"
                                style="font-family:monospace;font-size:12px"
                            >
                            <span v-if="errors.slug" class="field-error">{{ errors.slug }}</span>
                        </div>
                    </div>

                    <!-- Description -->
                    <div class="field">
                        <label class="form-label">Description <span class="optional">(Optional)</span></label>
                        <input
                            type="text"
                            class="form-input"
                            v-model="form.description"
                            placeholder="A short note visible only to your team"
                        >
                    </div>

                    <!-- Color -->
                    <div class="field">
                        <label class="form-label">Color</label>
                        <div class="color-picker-row">
                            <div
                                v-for="c in swatches"
                                :key="c"
                                class="swatch"
                                :style="{ background: c, outline: form.color === c ? '3px solid #111827' : '2px solid transparent', outlineOffset: '2px' }"
                                @click="form.color = c"
                                :title="c"
                            ></div>
                            <!-- Custom hex input -->
                            <div class="swatch-custom">
                                <span class="color-preview" :style="{ background: form.color }"></span>
                                <input
                                    type="text"
                                    v-model="form.color"
                                    maxlength="7"
                                    class="hex-input"
                                    placeholder="#4285F4"
                                >
                            </div>
                        </div>
                    </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">
                        <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>
                        {{ editing ? 'Save Changes' : 'Create List' }}
                    </button>
                </div>

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

<script setup>
import { reactive, ref, watch } from 'vue';

const props = defineProps({
    open:    { type: Boolean, default: false },
    editing: { type: Object,  default: null  },
});

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

const swatches = [
    '#4285F4', '#1A73E8', '#34A853', '#FBBC05',
    '#EA4335', '#7c3aed', '#ec4899', '#f97316',
    '#16a34a', '#0891b2', '#6b7280', '#111827',
];

const form   = reactive({ title: '', slug: '', description: '', color: '#4285F4' });
const errors = reactive({ title: '', slug: '' });

watch(() => props.open, (open) => {
    if (open) {
        if (props.editing) {
            form.title       = props.editing.title       ?? '';
            form.slug        = props.editing.slug        ?? '';
            form.description = props.editing.description ?? '';
            form.color       = props.editing.color       ?? '#4285F4';
        } else {
            resetForm();
        }
        errors.title = '';
        errors.slug  = '';
    }
});

function syncSlug() {
    if (!props.editing) {
        form.slug = form.title
            .toLowerCase()
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-|-$/g, '');
    }
}

function validate() {
    errors.title = form.title.trim() ? '' : 'Title is required.';
    errors.slug  = form.slug.trim()  ? '' : 'Slug is required.';
    return !errors.title && !errors.slug;
}

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

function resetForm() {
    form.title       = '';
    form.slug        = '';
    form.description = '';
    form.color       = '#4285F4';
}
</script>

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

.field { display: flex; flex-direction: column; gap: 6px; }

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

.field-error { font-size: 12px; color: #ef4444; }

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

/* Color picker */
.color-picker-row {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
}

.swatch {
    width: 28px;
    height: 28px;
    border-radius: 6px;
    cursor: pointer;
    border: 1px solid rgba(0,0,0,.1);
    transition: transform .1s;
    flex-shrink: 0;
}
.swatch:hover { transform: scale(1.15); }

.swatch-custom {
    display: flex;
    align-items: center;
    gap: 6px;
    border: 1px solid var(--border-color, #e5e7eb);
    border-radius: 6px;
    padding: 4px 8px;
    background: var(--bg-surface, #fff);
    transition: border-color 0.15s ease, box-shadow 0.15s ease;
}
.swatch-custom:focus-within {
    border-color: var(--active-text, #2563eb);
    box-shadow: 0 0 0 3px var(--active-bg, rgba(37, 99, 235, 0.15));
}

.color-preview {
    width: 18px;
    height: 18px;
    border-radius: 4px;
    flex-shrink: 0;
    border: 1px solid rgba(0,0,0,.1);
}

.hex-input {
    border: none !important;
    outline: none !important;
    box-shadow: none !important;
    font-family: monospace;
    font-size: 12px;
    color: var(--text-primary, #374151);
    width: 72px;
    background: transparent;
    padding: 0;
}
.hex-input:focus {
    border: none !important;
    outline: none !important;
    box-shadow: none !important;
}
</style>
