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

                <div class="modal-header">
                    <div>
                        <h3 class="modal-title">Export Contacts</h3>
                        <p class="modal-subtitle">Choose which columns to include in the CSV download.</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">
                    <p style="font-size:13px;color:#6b7280;margin:0 0 14px">Select the columns you want to export.</p>

                    <!-- Check all -->
                    <label class="check-all-row">
                        <input type="checkbox" :checked="allSelected" :indeterminate.prop="someSelected && !allSelected" @change="toggleAll">
                        <span style="font-weight:600;color:#111827">Select All</span>
                    </label>

                    <!-- Column grid -->
                    <div class="col-grid">
                        <label v-for="col in columns" :key="col.value" class="col-check">
                            <input type="checkbox" v-model="selected" :value="col.value">
                            <span>{{ col.label }}</span>
                        </label>
                    </div>

                    <!-- Scope note -->
                    <div v-if="hasActiveFilters" class="export-scope-note">
                        <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="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>
                        Active filters will be applied to the export.
                    </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" :disabled="selected.length === 0 || exporting" @click="doExport">
                        <span v-if="exporting" class="spin-icon">
                            <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="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99"/></svg>
                        </span>
                        <svg v-else 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="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>
                        {{ exporting ? 'Exporting…' : `Export ${selected.length} column${selected.length !== 1 ? 's' : ''}` }}
                    </button>
                </div>

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

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

const props = defineProps({
    open:            { type: Boolean, default: false },
    activeFilters:   { type: Object,  default: () => ({}) },
    exportRoute:     { type: String,  required: true },
});

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

const exporting = ref(false);

const columns = [
    { value: 'email',          label: 'Email' },
    { value: 'first_name',     label: 'First Name' },
    { value: 'last_name',      label: 'Last Name' },
    { value: 'prefix',         label: 'Prefix' },
    { value: 'phone',          label: 'Phone' },
    { value: 'status',         label: 'Status' },
    { value: 'contact_type',   label: 'Contact Type' },
    { value: 'source',         label: 'Source' },
    { value: 'date_of_birth',  label: 'Date of Birth' },
    { value: 'lists',          label: 'Lists' },
    { value: 'tags',           label: 'Tags' },
    { value: 'address_line_1', label: 'Address Line 1' },
    { value: 'address_line_2', label: 'Address Line 2' },
    { value: 'city',           label: 'City' },
    { value: 'state',          label: 'State' },
    { value: 'postal_code',    label: 'ZIP Code' },
    { value: 'country',        label: 'Country' },
    { value: 'ip',             label: 'IP Address' },
    { value: 'created_at',     label: 'Created At' },
    { value: 'last_activity',  label: 'Last Activity' },
];

const defaultSelected = ['email', 'first_name', 'last_name', 'status'];
const selected = ref([...defaultSelected]);

const allSelected  = computed(() => selected.value.length === columns.length);
const someSelected = computed(() => selected.value.length > 0);

const hasActiveFilters = computed(() =>
    Object.values(props.activeFilters).some(v => v)
);

watch(() => props.open, (v) => {
    if (v) { selected.value = [...defaultSelected]; exporting.value = false; }
});

function toggleAll() {
    selected.value = allSelected.value ? [] : columns.map(c => c.value);
}

async function doExport() {
    if (selected.value.length === 0 || exporting.value) return;
    exporting.value = true;

    try {
        const csrf = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
        const body = {
            columns: selected.value,
            ...Object.fromEntries(
                Object.entries(props.activeFilters).filter(([, v]) => v)
            ),
        };

        const res = await window.axios.post(props.exportRoute, body, {
            responseType: 'blob',
        });

        const url  = URL.createObjectURL(new Blob([res.data], { type: 'text/csv;charset=utf-8;' }));
        const link = document.createElement('a');
        link.href  = url;
        link.download = `contacts_${new Date().toISOString().slice(0, 10)}.csv`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);

        emit('close');
    } catch (err) {
        console.error('Export failed', err);
        alert('Export failed. Please try again.');
    } finally {
        exporting.value = false;
    }
}
</script>

<style scoped>
.check-all-row {
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    font-size: 13px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f3f4f6;
    margin-bottom: 12px;
}

.col-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 4px 16px;
}

.col-check {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    font-size: 13px;
    color: #374151;
    padding: 6px 0;
}

.col-check input[type="checkbox"] {
    width: 15px;
    height: 15px;
    accent-color: #4285F4;
    flex-shrink: 0;
}

.export-scope-note {
    display: flex;
    align-items: center;
    gap: 8px;
    background: #eff6ff;
    border: 1px solid #bfdbfe;
    border-radius: 6px;
    padding: 8px 12px;
    font-size: 12px;
    color: #1d4ed8;
    margin-top: 14px;
}

.export-scope-note svg { width: 14px; height: 14px; flex-shrink: 0; }

.spin-icon {
    display: inline-flex;
    animation: spin .7s linear infinite;
}

.spin-icon svg { width: 14px; height: 14px; }

@keyframes spin { to { transform: rotate(360deg); } }
</style>
