<template>
    <Head title="Import Contacts" />

    <AppLayout>
        <!-- Page header -->
        <div class="import-page-hdr">
            <div>
                <h2 style="font-size:20px;font-weight:700;color:#111827;margin:0 0 4px">Import Contacts</h2>
                <p style="font-size:13px;color:#6b7280;margin:0">Upload a CSV file to add contacts in bulk.</p>
            </div>
            <Link href="/contacts" class="btn btn-outline">
                <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="M15.75 19.5L8.25 12l7.5-7.5"/></svg>
                Back to Contacts
            </Link>
        </div>

        <!-- Wizard step indicator -->
        <div class="wizard-steps">
            <div v-for="(s, i) in steps" :key="s.key" class="wizard-step"
                :class="{ 'is-done': step > i + 1, 'is-active': step === i + 1 }">
                <div class="wizard-dot">
                    <svg v-if="step > i + 1" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="3" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"/></svg>
                    <span v-else>{{ i + 1 }}</span>
                </div>
                <span class="wizard-label">{{ s.label }}</span>
                <div v-if="i < steps.length - 1" class="wizard-line" :class="{ 'is-done': step > i + 1 }"></div>
            </div>
        </div>

        <!-- Two-column layout -->
        <div class="import-layout">

            <!-- Main column -->
            <div class="import-main">

                <!-- ── Step 1: Upload ── -->
                <div v-if="step === 1" class="import-card">
                    <div class="import-card-hdr">
                        <h3>Upload file</h3>
                        <p>CSV format. First row must be the column headers.</p>
                    </div>

                    <!-- Drop zone -->
                    <div
                        class="drop-zone"
                        :class="{ 'is-dragging': dragging, 'is-loaded': !!fileName }"
                        @dragover.prevent="dragging = true"
                        @dragleave="dragging = false"
                        @drop.prevent="onDrop"
                        @click="$refs.fileInput.click()"
                    >
                        <input ref="fileInput" type="file" accept=".csv,text/csv" style="display:none" @change="onFileSelect">

                        <template v-if="!fileName">
                            <div class="drop-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><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>
                            </div>
                            <p class="drop-main">Click to upload or drag &amp; drop</p>
                            <p class="drop-sub">CSV files only · max 10,000 rows</p>
                        </template>

                        <template v-else>
                            <div class="file-loaded">
                                <div class="file-icon">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"/></svg>
                                </div>
                                <div>
                                    <p class="file-name">{{ fileName }}</p>
                                    <p class="file-meta">{{ totalRows.toLocaleString() }} rows · {{ headers.length }} columns detected</p>
                                </div>
                                <button class="btn btn-ghost btn-sm" @click.stop="resetFile">Change</button>
                            </div>
                        </template>
                    </div>

                    <!-- Error -->
                    <p v-if="parseError" class="parse-error">{{ parseError }}</p>

                    <!-- Download template -->
                    <div class="template-row">
                        <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 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 002.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 00-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75 2.25 2.25 0 00-.1-.664m-5.8 0A2.251 2.251 0 0113.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25z"/></svg>
                        <a href="#" @click.prevent="downloadTemplate" class="template-link">Download CSV template</a>
                        <span style="color:#9ca3af">- shows all supported columns</span>
                    </div>

                    <div class="import-card-ftr">
                        <span></span>
                        <button class="btn btn-primary" :disabled="!fileName" @click="step = 2">
                            Continue to column mapping →
                        </button>
                    </div>
                </div>

                <!-- ── Step 2: Column mapping ── -->
                <div v-if="step === 2" class="import-card">
                    <div class="import-card-hdr">
                        <h3>Map columns</h3>
                        <p>Match each column in your file to a CRMfic contact field.</p>
                    </div>

                    <table class="map-table">
                        <thead>
                            <tr>
                                <th>Your column</th>
                                <th>Sample data</th>
                                <th>Maps to</th>
                                <th style="width:90px"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(header, idx) in headers" :key="idx">
                                <td><code class="col-code">{{ header }}</code></td>
                                <td class="sample-cell">{{ previewRows[0]?.[idx] ?? '-' }}</td>
                                <td>
                                    <select class="form-select" style="font-size:12px;padding:6px 10px" v-model="mapping[idx]">
                                        <option v-for="f in contactFields" :key="f.value" :value="f.value">{{ f.label }}</option>
                                    </select>
                                </td>
                                <td>
                                    <span v-if="mapping[idx] === 'email'" class="map-required">✓ Required</span>
                                    <span v-else-if="mapping[idx] === '__skip__'" class="map-skip">Skip</span>
                                </td>
                            </tr>
                        </tbody>
                    </table>

                    <p v-if="!emailMapped" class="map-error">
                        <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="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"/></svg>
                        You must map at least one column to "Email address".
                    </p>

                    <div class="import-card-ftr">
                        <button class="btn btn-outline" @click="step = 1">← Back</button>
                        <button class="btn btn-primary" :disabled="!emailMapped" @click="step = 3">
                            Continue to options →
                        </button>
                    </div>
                </div>

                <!-- ── Step 3: Options ── -->
                <div v-if="step === 3" class="import-card">
                    <div class="import-card-hdr">
                        <h3>Import options</h3>
                        <p>Configure list assignment and how to handle duplicates.</p>
                    </div>

                    <!-- Assign to lists -->
                    <div class="options-section">
                        <label class="form-label">Assign all imported contacts to lists <span style="color:#9ca3af;font-weight:400">(optional)</span></label>
                        <div class="list-select-area">
                            <div v-if="selectedListIds.length" class="multi-chips">
                                <span v-for="id in selectedListIds" :key="id" class="chip-sel">
                                    {{ listTitle(id) }}
                                    <button type="button" class="chip-rm" @click="selectedListIds = selectedListIds.filter(x => x !== id)">&times;</button>
                                </span>
                            </div>
                            <select class="form-select" @change="addList($event.target.value); $event.target.value = ''">
                                <option value="">Add to list…</option>
                                <option v-for="l in availableLists" :key="l.id" :value="l.id">{{ l.title }}</option>
                            </select>
                        </div>
                    </div>

                    <!-- Duplicate handling -->
                    <div class="options-section">
                        <label class="form-label">When a contact with the same email already exists</label>
                        <div class="radio-group">
                            <label class="radio-opt" :class="{ 'is-selected': duplicateHandling === 'skip' }">
                                <input type="radio" v-model="duplicateHandling" value="skip">
                                <div>
                                    <span class="radio-title">Skip duplicate</span>
                                    <span class="radio-desc">Keep the existing contact unchanged, skip the row.</span>
                                </div>
                            </label>
                            <label class="radio-opt" :class="{ 'is-selected': duplicateHandling === 'update' }">
                                <input type="radio" v-model="duplicateHandling" value="update">
                                <div>
                                    <span class="radio-title">Update existing</span>
                                    <span class="radio-desc">Overwrite existing contact fields with the imported data.</span>
                                </div>
                            </label>
                        </div>
                    </div>

                    <div class="import-card-ftr">
                        <button class="btn btn-outline" @click="step = 2">← Back</button>
                        <button class="btn btn-primary" @click="startImport">
                            <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="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3"/></svg>
                            Start Import ({{ dataRows.length.toLocaleString() }} rows)
                        </button>
                    </div>
                </div>

                <!-- ── Step 4: Progress / Results ── -->
                <div v-if="step === 4" class="import-card">

                    <!-- Importing spinner -->
                    <div v-if="importing" class="import-progress">
                        <div class="progress-spinner"></div>
                        <p class="progress-title">Importing contacts…</p>
                        <p class="progress-sub">Processing {{ dataRows.length.toLocaleString() }} rows. Please wait.</p>
                        <div class="progress-bar-wrap">
                            <div class="progress-bar-fill" :style="{ width: progressPct + '%' }"></div>
                        </div>
                    </div>

                    <!-- Results -->
                    <template v-else-if="results">
                        <div class="import-card-hdr">
                            <h3>Import complete</h3>
                            <p>Here's a summary of what happened.</p>
                        </div>

                        <div class="results-grid">
                            <div class="result-stat result-stat--green">
                                <span class="result-num">{{ results.imported.toLocaleString() }}</span>
                                <span class="result-label">Imported</span>
                            </div>
                            <div class="result-stat result-stat--blue">
                                <span class="result-num">{{ results.updated.toLocaleString() }}</span>
                                <span class="result-label">Updated</span>
                            </div>
                            <div class="result-stat result-stat--yellow">
                                <span class="result-num">{{ results.skipped.toLocaleString() }}</span>
                                <span class="result-label">Skipped</span>
                            </div>
                            <div class="result-stat result-stat--red">
                                <span class="result-num">{{ results.errors.length.toLocaleString() }}</span>
                                <span class="result-label">Errors</span>
                            </div>
                        </div>

                        <!-- Error rows -->
                        <div v-if="results.errors.length" class="error-list">
                            <p class="error-list-hdr">
                                <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="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"/></svg>
                                Rows with errors (showing first {{ Math.min(results.errors.length, 10) }})
                            </p>
                            <table class="error-table">
                                <thead>
                                    <tr><th>Row</th><th>Email</th><th>Reason</th></tr>
                                </thead>
                                <tbody>
                                    <tr v-for="err in results.errors.slice(0, 10)" :key="err.row">
                                        <td>{{ err.row }}</td>
                                        <td>{{ err.email }}</td>
                                        <td>{{ err.reason }}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        <div class="import-card-ftr">
                            <button class="btn btn-outline" @click="resetAll">Import another file</button>
                            <Link href="/contacts" class="btn btn-primary">View Contacts →</Link>
                        </div>
                    </template>

                    <!-- Error state -->
                    <div v-else-if="importError" class="import-error-state">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126z"/></svg>
                        <p>{{ importError }}</p>
                        <button class="btn btn-outline btn-sm" @click="step = 3">Try again</button>
                    </div>

                </div>

            </div>
            <!-- /import-main -->

            <!-- Sidebar summary -->
            <div class="import-sidebar">
                <div class="import-card" style="padding:0">
                    <div class="import-card-hdr" style="border-bottom:1px solid #f3f4f6">
                        <h3>File summary</h3>
                    </div>
                    <div class="summary-rows">
                        <div class="summary-row">
                            <span>Total rows</span>
                            <strong>{{ totalRows > 0 ? totalRows.toLocaleString() : '-' }}</strong>
                        </div>
                        <div class="summary-row">
                            <span>Columns</span>
                            <strong>{{ headers.length > 0 ? headers.length : '-' }}</strong>
                        </div>
                        <div class="summary-row">
                            <span>Email column</span>
                            <strong :class="emailMapped ? 'text-green' : 'text-gray'">
                                {{ emailMapped ? '✓ Mapped' : step >= 2 ? '✗ Not mapped' : '-' }}
                            </strong>
                        </div>
                        <div class="summary-row">
                            <span>Duplicate mode</span>
                            <strong>{{ duplicateHandling === 'skip' ? 'Skip' : 'Update' }}</strong>
                        </div>
                        <div class="summary-row" style="border-bottom:none">
                            <span>Assigned lists</span>
                            <strong>{{ selectedListIds.length > 0 ? selectedListIds.length : 'None' }}</strong>
                        </div>
                    </div>
                </div>

                <!-- Preview card (step 2+) -->
                <div v-if="step >= 2 && previewRows.length" class="import-card" style="padding:0;margin-top:16px">
                    <div class="import-card-hdr" style="border-bottom:1px solid #f3f4f6">
                        <h3>Preview (first 3 rows)</h3>
                    </div>
                    <div style="overflow-x:auto">
                        <table class="preview-table">
                            <thead>
                                <tr>
                                    <th v-for="(h, i) in headers" :key="i">{{ h }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="(row, ri) in previewRows" :key="ri">
                                    <td v-for="(cell, ci) in row" :key="ci">{{ cell || '-' }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

        </div>
    </AppLayout>
</template>

<script setup>
import { ref, computed } from 'vue';
import { Head, Link } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';

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

// Wizard state
const step = ref(1);

const steps = [
    { key: 'upload', label: 'Upload file' },
    { key: 'map',    label: 'Map columns' },
    { key: 'opts',   label: 'Options' },
    { key: 'import', label: 'Import' },
];

// Step 1: file
const fileInput      = ref(null);
const dragging       = ref(false);
const fileName       = ref('');
const parseError     = ref('');
const headers        = ref([]);
const dataRows       = ref([]);
const previewRows    = computed(() => dataRows.value.slice(0, 3));
const totalRows      = computed(() => dataRows.value.length);

// Step 2: mapping
const mapping = ref({});

const contactFields = [
    { value: '__skip__',        label: '- Skip -' },
    { value: 'email',           label: 'Email address' },
    { value: 'first_name',      label: 'First name' },
    { value: 'last_name',       label: 'Last name' },
    { value: 'prefix',          label: 'Prefix' },
    { value: 'phone',           label: 'Phone' },
    { value: 'date_of_birth',   label: 'Date of birth' },
    { value: 'status',          label: 'Status' },
    { value: 'source',          label: 'Source' },
    { 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 / Postal code' },
    { value: 'country',         label: 'Country' },
];

// Auto-detect field names
const AUTO_MAP = {
    'email': 'email', 'email address': 'email', 'e-mail': 'email', 'emailaddress': 'email',
    'first_name': 'first_name', 'first name': 'first_name', 'firstname': 'first_name', 'given name': 'first_name',
    'last_name': 'last_name', 'last name': 'last_name', 'lastname': 'last_name', 'surname': 'last_name', 'family name': 'last_name',
    'prefix': 'prefix', 'salutation': 'prefix', 'title': 'prefix',
    'phone': 'phone', 'telephone': 'phone', 'mobile': 'phone', 'phone_number': 'phone', 'phonenumber': 'phone',
    'dob': 'date_of_birth', 'date_of_birth': 'date_of_birth', 'birthday': 'date_of_birth', 'birth date': 'date_of_birth', 'dateofbirth': 'date_of_birth',
    'status': 'status',
    'source': 'source',
    'address': 'address_line_1', 'address1': 'address_line_1', 'address_line_1': 'address_line_1', 'address line 1': 'address_line_1', 'street': 'address_line_1',
    'address2': 'address_line_2', 'address_line_2': 'address_line_2', 'address line 2': 'address_line_2',
    'city': 'city', 'town': 'city',
    'state': 'state', 'region': 'state', 'province': 'state',
    'zip': 'postal_code', 'postal_code': 'postal_code', 'postcode': 'postal_code', 'zip_code': 'postal_code', 'zipcode': 'postal_code',
    'country': 'country',
};

const emailMapped = computed(() => Object.values(mapping.value).includes('email'));

// Step 3: options
const selectedListIds  = ref([]);
const duplicateHandling = ref('skip');

const availableLists = computed(() =>
    props.allLists.filter(l => !selectedListIds.value.includes(l.id))
);

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

function addList(id) {
    const num = Number(id);
    if (id && !selectedListIds.value.includes(num)) selectedListIds.value.push(num);
}

// Step 4: import
const importing   = ref(false);
const progressPct = ref(0);
const results     = ref(null);
const importError = ref('');

// ── File parsing ──

function onDrop(e) {
    dragging.value = false;
    const file = e.dataTransfer.files[0];
    if (file) loadFile(file);
}

function onFileSelect(e) {
    const file = e.target.files[0];
    if (file) loadFile(file);
    e.target.value = '';
}

function loadFile(file) {
    parseError.value = '';
    if (!file.name.toLowerCase().endsWith('.csv')) {
        parseError.value = 'Only CSV files are supported.';
        return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
        try {
            const parsed = parseCSV(e.target.result);
            if (parsed.length < 2) {
                parseError.value = 'The file appears to be empty or has no data rows.';
                return;
            }
            headers.value  = parsed[0];
            dataRows.value = parsed.slice(1).filter(r => r.some(c => c));

            // Auto-map columns
            const m = {};
            headers.value.forEach((h, i) => {
                const key = h.toLowerCase().trim();
                m[i] = AUTO_MAP[key] ?? '__skip__';
            });
            mapping.value = m;

            fileName.value = file.name;
        } catch (err) {
            parseError.value = 'Failed to parse CSV: ' + err.message;
        }
    };
    reader.readAsText(file, 'UTF-8');
}

function parseCSV(text) {
    // Remove BOM
    const clean = text.replace(/^﻿/, '');
    const lines = clean.split(/\r?\n/);
    const rows  = [];

    for (const line of lines) {
        if (!line.trim()) continue;
        const row = [];
        let cur = '';
        let inQ = false;

        for (let i = 0; i < line.length; i++) {
            const ch = line[i];
            if (ch === '"') {
                if (inQ && line[i + 1] === '"') { cur += '"'; i++; }
                else inQ = !inQ;
            } else if (ch === ',' && !inQ) {
                row.push(cur.trim());
                cur = '';
            } else {
                cur += ch;
            }
        }
        row.push(cur.trim());
        rows.push(row);
    }

    return rows;
}

function resetFile() {
    fileName.value = '';
    headers.value  = [];
    dataRows.value = [];
    mapping.value  = {};
    parseError.value = '';
}

function resetAll() {
    step.value = 1;
    resetFile();
    selectedListIds.value   = [];
    duplicateHandling.value = 'skip';
    results.value     = null;
    importError.value = '';
    progressPct.value = 0;
}

// ── Template download ──

function downloadTemplate() {
    const headers_row = 'email,first_name,last_name,prefix,phone,date_of_birth,status,source,address_line_1,address_line_2,city,state,postal_code,country';
    const example     = 'alice@example.com,Alice,Johnson,Ms.,+1-555-0101,1990-06-15,subscribed,website,123 Main St,,New York,NY,10001,US';
    const blob = new Blob([headers_row + '\n' + example], { type: 'text/csv;charset=utf-8;' });
    const url  = URL.createObjectURL(blob);
    const a    = document.createElement('a');
    a.href     = url;
    a.download = 'crmfic_contacts_template.csv';
    a.click();
    URL.revokeObjectURL(url);
}

// ── Import submission ──

async function startImport() {
    step.value        = 4;
    importing.value   = true;
    importError.value = '';
    results.value     = null;
    progressPct.value = 10;

    // Animate progress bar while waiting
    const ticker = setInterval(() => {
        if (progressPct.value < 85) progressPct.value += 3;
    }, 300);

    try {
        const payload = {
            rows:               dataRows.value,
            mapping:            mapping.value,
            list_ids:           selectedListIds.value,
            duplicate_handling: duplicateHandling.value,
        };

        const res = await window.axios.post(route('contacts.import.store'), payload);

        clearInterval(ticker);
        progressPct.value = 100;
        await delay(300);

        results.value   = res.data.results;
        importing.value = false;
    } catch (err) {
        clearInterval(ticker);
        importing.value = false;

        const msg = err.response?.data?.message
            || err.response?.data?.errors?.rows?.[0]
            || 'Import failed. Please try again.';
        importError.value = msg;
    }
}

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
</script>

<style scoped>
/* Layout */
.import-page-hdr { display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;flex-wrap:wrap;gap:12px; }
.import-layout   { display:grid;grid-template-columns:1fr 300px;gap:20px;align-items:start; }
@media(max-width:900px){ .import-layout{ grid-template-columns:1fr; } }
.import-main    { min-width:0; }
.import-sidebar { min-width:0; }

/* Wizard steps */
.wizard-steps {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
    gap: 0;
}

.wizard-step {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-shrink: 0;
}

.wizard-dot {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    background: var(--border-color);
    color: var(--text-muted);
    font-size: 12px;
    font-weight: 700;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    transition: background .2s, color .2s;
}

.wizard-dot svg { width: 13px; height: 13px; }

.wizard-step.is-active .wizard-dot  { background: var(--active-text); color: #fff; }
.wizard-step.is-done   .wizard-dot  { background: var(--success); color: #fff; }

.wizard-label {
    font-size: 13px;
    font-weight: 500;
    color: var(--text-secondary);
    white-space: nowrap;
}

.wizard-step.is-active .wizard-label { color: var(--text-primary); }
.wizard-step.is-done   .wizard-label { color: var(--text-secondary); }

.wizard-line {
    flex: 1;
    height: 2px;
    background: var(--border-color);
    margin: 0 8px;
    min-width: 20px;
    transition: background .2s;
}

.wizard-line.is-done { background: var(--success); }

@media (max-width: 600px) {
    .wizard-label {
        display: none;
    }
}

/* Card */
.import-card {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 0;
}

.import-card-hdr { margin-bottom: 16px; }
.import-card-hdr h3 { font-size: 15px; font-weight: 700; color: var(--text-primary); margin: 0 0 4px; }
.import-card-hdr p  { font-size: 13px; color: var(--text-secondary); margin: 0; }

.import-card-ftr {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20px;
    padding-top: 16px;
    border-top: 1px solid var(--border-color);
    gap: 8px;
}

/* Drop zone */
.drop-zone {
    border: 2px dashed var(--border-color);
    border-radius: 10px;
    padding: 40px 20px;
    text-align: center;
    cursor: pointer;
    transition: border-color .15s, background .15s;
    margin-bottom: 14px;
}

.drop-zone:hover, .drop-zone.is-dragging {
    border-color: var(--active-text);
    background: var(--active-bg);
}

.drop-zone.is-loaded {
    border-style: solid;
    border-color: var(--success-border);
    background: var(--success-light);
    padding: 16px 20px;
}

.drop-icon {
    width: 48px;
    height: 48px;
    background: var(--bg-hover);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 12px;
}

.drop-icon svg { width: 22px; height: 22px; color: var(--text-secondary); }

.drop-main { font-size: 14px; font-weight: 600; color: var(--text-primary); margin: 0 0 4px; }
.drop-sub  { font-size: 12px; color: var(--text-muted); margin: 0; }

.file-loaded {
    display: flex;
    align-items: center;
    gap: 12px;
    text-align: left;
}

.file-icon {
    width: 40px;
    height: 40px;
    background: var(--success-light);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.file-icon svg { width: 20px; height: 20px; color: var(--success); }
.file-name  { font-size: 13px; font-weight: 600; color: var(--text-primary); margin: 0 0 2px; }
.file-meta  { font-size: 12px; color: var(--text-secondary); margin: 0; }

.parse-error {
    font-size: 12px;
    color: var(--danger);
    margin: 0 0 12px;
    display: flex;
    align-items: center;
    gap: 6px;
}

.template-row {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: var(--text-secondary);
}

.template-row svg { width: 14px; height: 14px; flex-shrink: 0; }
.template-link { color: var(--active-text); text-decoration: none; }
.template-link:hover { text-decoration: underline; }

/* Column mapping table */
.map-table { width: 100%; border-collapse: collapse; font-size: 13px; }
.map-table th { padding: 10px 12px; text-align: left; color: var(--text-primary); font-weight: 600; border-bottom: 1px solid var(--border-color); background: var(--bg-hover); font-size: 12px; }
.map-table td { padding: 10px 12px; border-bottom: 1px solid var(--border-color); }

.col-code { background: var(--bg-hover-strong); padding: 2px 6px; border-radius: 4px; font-size: 11px; font-family: monospace; color: var(--text-primary); }
.sample-cell { color: var(--text-secondary); font-size: 12px; max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.map-required { font-size: 12px; color: var(--success); font-weight: 500; }
.map-skip     { font-size: 12px; color: var(--text-muted); }

.map-error {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: var(--danger);
    background: var(--danger-light);
    border: 1px solid var(--danger-border);
    border-radius: 6px;
    padding: 8px 12px;
    margin-top: 12px;
}

.map-error svg { width: 14px; height: 14px; flex-shrink: 0; }

/* Options */
.options-section { margin-bottom: 20px; }
.list-select-area { margin-top: 6px; }
.multi-chips { display:flex;flex-wrap:wrap;gap:4px;margin-bottom:8px; }
.chip-sel { display:inline-flex;align-items:center;gap:4px;font-size:12px;background:var(--active-bg);color:var(--active-text);border-radius:4px;padding:2px 7px; }
.chip-rm  { background:none;border:none;cursor:pointer;color:inherit;padding:0;font-size:14px;line-height:1; }

.radio-group { display: flex; flex-direction: column; gap: 8px; margin-top: 8px; }

.radio-opt {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    padding: 14px 16px;
    cursor: pointer;
    transition: border-color .15s, background .15s;
}

.radio-opt input { margin-top: 2px; accent-color: var(--active-text); flex-shrink: 0; }
.radio-opt.is-selected { border-color: var(--active-text); background: var(--active-bg); }

.radio-title { display: block; font-size: 13px; font-weight: 600; color: var(--text-primary); margin-bottom: 2px; }
.radio-desc  { font-size: 12px; color: var(--text-secondary); }

/* Progress */
.import-progress {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 48px 20px;
    text-align: center;
}

.progress-spinner {
    width: 48px;
    height: 48px;
    border: 4px solid var(--border-color);
    border-top-color: var(--active-text);
    border-radius: 50%;
    animation: spin .7s linear infinite;
    margin-bottom: 20px;
}

@keyframes spin { to { transform: rotate(360deg); } }

.progress-title { font-size: 16px; font-weight: 700; color: var(--text-primary); margin: 0 0 6px; }
.progress-sub   { font-size: 13px; color: var(--text-secondary); margin: 0 0 20px; }

.progress-bar-wrap {
    width: 100%;
    max-width: 320px;
    height: 6px;
    background: var(--border-color);
    border-radius: 99px;
    overflow: hidden;
}

.progress-bar-fill {
    height: 100%;
    background: linear-gradient(90deg, var(--active-text), var(--success));
    border-radius: 99px;
    transition: width .3s ease;
}

/* Results */
.results-grid {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    gap: 12px;
    margin-bottom: 20px;
}

@media(max-width:600px){ .results-grid{ grid-template-columns:1fr 1fr; } }

.result-stat {
    border-radius: 8px;
    padding: 16px;
    text-align: center;
    border: 1px solid;
}

.result-stat--green  { background: var(--success-light); border-color: var(--success-border); }
.result-stat--blue   { background: var(--active-bg); border-color: var(--border-color); }
.result-stat--yellow { background: var(--warning-light); border-color: var(--warning-border); }
.result-stat--red    { background: var(--danger-light); border-color: var(--danger-border); }

.result-num   { display: block; font-size: 28px; font-weight: 800; line-height: 1; margin-bottom: 4px; }
.result-label { font-size: 12px; color: var(--text-secondary); }

.result-stat--green  .result-num { color: var(--success); }
.result-stat--blue   .result-num { color: var(--active-text); }
.result-stat--yellow .result-num { color: var(--warning); }
.result-stat--red    .result-num { color: var(--danger); }

/* Error table */
.error-list { background: var(--danger-light); border: 1px solid var(--danger-border); border-radius: 8px; overflow: hidden; }
.error-list-hdr { display:flex;align-items:center;gap:6px;font-size:12px;font-weight:600;color:var(--danger);padding:10px 14px;margin:0;border-bottom:1px solid var(--danger-border); }
.error-list-hdr svg { width: 14px; height: 14px; }

.error-table { width: 100%; border-collapse: collapse; font-size: 12px; }
.error-table th { padding: 8px 14px; text-align: left; color: var(--text-primary); font-weight: 600; background: var(--danger-light); border-bottom: 1px solid var(--danger-border); }
.error-table td { padding: 8px 14px; color: var(--text-secondary); border-bottom: 1px solid var(--danger-border); }
.error-table tr:last-child td { border-bottom: none; }

.import-error-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40px 20px;
    text-align: center;
    gap: 12px;
}

.import-error-state svg { width: 40px; height: 40px; color: var(--danger); }
.import-error-state p   { font-size: 14px; color: var(--text-primary); margin: 0; }

/* Sidebar */
.summary-rows { }
.summary-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 20px;
    border-bottom: 1px solid var(--border-color);
    font-size: 13px;
}

.summary-row span  { color: var(--text-secondary); }
.summary-row strong { color: var(--text-primary); }
.text-green { color: var(--success) !important; }
.text-gray  { color: var(--text-muted) !important; }

.preview-table { width: 100%; border-collapse: collapse; font-size: 11px; }
.preview-table th { padding: 8px 12px; text-align: left; color: var(--text-primary); border-bottom: 1px solid var(--border-color); background: var(--bg-hover); white-space: nowrap; }
.preview-table td { padding: 8px 12px; color: var(--text-secondary); border-bottom: 1px solid var(--border-color); max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
</style>
