<template>
    <Head title="Settings" />

    <AppLayout>
        <div class="settings-shell">
            <!-- Left: section nav -->
            <aside class="settings-nav" :class="{ 'is-mobile-open': mobileNavOpen }">
                <!-- Mobile Section Toggle Button -->
                <button class="settings-mobile-toggle" @click="mobileNavOpen = !mobileNavOpen" type="button">
                    <div class="settings-mobile-toggle-left">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" v-html="currentTab.icon"></svg>
                        <span>{{ currentTab.label }}</span>
                    </div>
                    <div class="settings-mobile-toggle-right">
                        <span class="settings-mobile-toggle-badge">{{ mobileNavOpen ? 'Close Menu' : 'Change Section' }}</span>
                        <svg class="settings-mobile-toggle-chevron" :class="{ 'is-open': mobileNavOpen }" 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="M19.5 8.25l-7.5 7.5-7.5-7.5" />
                        </svg>
                    </div>
                </button>

                <div class="settings-nav-list" :class="{ 'is-open': mobileNavOpen }">
                    <button
                        v-for="tab in TABS"
                        :key="tab.id"
                        class="settings-nav-item"
                        :class="{ 'is-active': activeTab === tab.id }"
                        @click="activeTab = tab.id; mobileNavOpen = false"
                    >
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" v-html="tab.icon"></svg>
                        {{ tab.label }}
                    </button>

                    <div class="settings-nav-divider"></div>

                    <Link v-for="link in EXTERNAL_LINKS" :key="link.href" :href="link.href" class="settings-nav-item" @click="mobileNavOpen = false">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" v-html="link.icon"></svg>
                        {{ link.label }}
                        <svg class="settings-nav-item-external" 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="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25"/></svg>
                    </Link>
                </div>
            </aside>

            <!-- Right: active section panel -->
            <section class="settings-content">
                <div class="settings-panel-header">
                    <h2>{{ currentTab.label }}</h2>
                    <button v-if="currentTab.savable !== false" class="btn btn-primary" :disabled="saving" @click="saveSection(currentTab.id)">
                        {{ saving && savingTab === currentTab.id ? 'Saving…' : 'Save Settings' }}
                    </button>
                </div>

                <p v-if="saved === currentTab.id" class="settings-saved">Settings saved.</p>
                <p v-if="currentTab.notice" class="settings-notice">{{ currentTab.notice }}</p>

                <!-- Business Settings (custom: logo upload) -->
                <template v-if="currentTab.id === 'business'">
                    <p class="settings-subhead" style="text-transform:none;letter-spacing:normal;font-weight:400;color:var(--text-secondary)">
                        These aren't your sender identity (see Email Settings for that)  they're available as merge tags you can drop anywhere in a campaign's content, header, or footer: <code>{{ tag('business_name') }}</code>, <code>{{ tag('business_logo') }}</code>, <code>{{ tag('business_address') }}</code>.
                    </p>

                    <div class="settings-row">
                        <div class="settings-row-info">
                            <div class="settings-row-label">Business Name</div>
                            <div class="settings-row-desc">Available as <code>{{ tag('business_name') }}</code>.</div>
                        </div>
                        <div class="settings-row-control">
                            <input type="text" v-model="business.name" placeholder="e.g., MyBusiness Inc.">
                        </div>
                    </div>

                    <div class="settings-row">
                        <div class="settings-row-info">
                            <div class="settings-row-label">Logo</div>
                            <div class="settings-row-desc">PNG/JPEG, min 400×400px. Available as <code>{{ tag('business_logo') }}</code>  e.g. inside an HTML block's <code>&lt;img src="{{ tag('business_logo') }}"&gt;</code>.</div>
                        </div>
                        <div class="settings-row-control settings-logo-row">
                            <div class="settings-avatar">
                                <img v-if="business.logo" :src="business.logo" alt="Business logo">
                                <span v-else>{{ businessInitial }}</span>
                            </div>
                            <label class="btn btn-outline btn-sm settings-upload-btn">
                                Change
                                <input type="file" accept="image/*" class="settings-file-input" @change="uploadLogo">
                            </label>
                            <button class="btn btn-outline btn-sm" @click="libraryOpen = true">Library</button>
                            <button v-if="business.logo" class="btn btn-ghost btn-sm" @click="business.logo = null">Remove</button>
                        </div>
                    </div>

                    <div class="settings-row">
                        <div class="settings-row-info">
                            <div class="settings-row-label">Business Full Address</div>
                            <div class="settings-row-desc">Available as <code>{{ tag('business_address') }}</code>  most commercial-email laws (e.g. CAN-SPAM) require a physical postal address in the footer.</div>
                        </div>
                        <div class="settings-row-control">
                            <textarea v-model="business.address" rows="3" placeholder="street, city, state, zip, country"></textarea>
                        </div>
                    </div>
                </template>

                <!-- Email Settings (custom: from/reply-to defaults + footer content) -->
                <template v-else-if="currentTab.id === 'email'">
                    <div class="settings-subcard">
                        <div class="settings-subcard-header">Default From Settings</div>
                        <div class="settings-subcard-body">
                            <div class="settings-info-banner">
                                <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="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>
                                Configure the default sender information for your emails. This will be used when no specific sender is set.
                            </div>

                            <div class="settings-row">
                                <div class="settings-row-info">
                                    <div class="settings-row-label">From Name</div>
                                    <div class="settings-row-desc">This name shows as the sender in recipients' inbox.</div>
                                </div>
                                <div class="settings-row-control">
                                    <input type="text" v-model="emailSettings.from_name" placeholder="e.g., John Doe">
                                </div>
                            </div>

                            <div class="settings-row">
                                <div class="settings-row-info">
                                    <div class="settings-row-label">From Email Address</div>
                                    <div class="settings-row-desc">Use the email set in your domain/SMTP. Mismatches may cause delivery issues.</div>
                                </div>
                                <div class="settings-row-control">
                                    <input type="text" v-model="emailSettings.from_email" placeholder="name@domain.com">
                                </div>
                            </div>

                            <div class="settings-row">
                                <div class="settings-row-info">
                                    <div class="settings-row-label">Reply to Name</div>
                                    <div class="settings-row-desc">This name will appear as the sender in recipient inboxes</div>
                                </div>
                                <div class="settings-row-control">
                                    <input type="text" v-model="emailSettings.reply_to_name" placeholder="e.g., Support Team">
                                </div>
                            </div>

                            <div class="settings-row">
                                <div class="settings-row-info">
                                    <div class="settings-row-label">Reply to Email</div>
                                    <div class="settings-row-desc">This name will appear as the sender in recipient inboxes</div>
                                </div>
                                <div class="settings-row-control">
                                    <input type="text" v-model="emailSettings.reply_to_email" placeholder="e.g., support@yourdomain.com">
                                </div>
                            </div>

                            <div class="settings-row">
                                <div class="settings-row-info">
                                    <div class="settings-row-label">Maximum Emails Per Second: {{ emailSettings.rate_limit_per_second }}</div>
                                    <div class="settings-row-desc">Set the rate limit for sending emails to prevent server overload and comply with SMTP restrictions.</div>
                                </div>
                                <div class="settings-row-control">
                                    <div class="settings-stepper">
                                        <button type="button" @click="adjustRateLimit(-1)">−</button>
                                        <span>{{ emailSettings.rate_limit_per_second }}</span>
                                        <button type="button" @click="adjustRateLimit(1)">+</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="settings-subcard">
                        <div class="settings-subcard-header">Email Tracking</div>
                        <div class="settings-subcard-body">
                            <div class="settings-info-banner">
                                <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="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>
                                Open and click tracking use a pixel and link redirects to record when a contact opens an email or clicks a link. Some countries' privacy laws restrict or require consent for this  disable it here if you need to stop collecting this data.
                            </div>

                            <label class="settings-checkbox-label">
                                <input type="checkbox" v-model="emailSettings.tracking_enabled">
                                Enable email open &amp; click tracking
                            </label>
                            <p v-if="!emailSettings.tracking_enabled" class="settings-hint">
                                Tracking is off  new emails won't include an open pixel or click-tracking redirects, and opens/clicks won't be recorded even from an already-sent email that still has tracking embedded. Unsubscribe links are never affected by this setting.
                            </p>
                        </div>
                    </div>

                    <div class="settings-subcard">
                        <div class="settings-subcard-header">Email Footer Settings</div>
                        <div class="settings-subcard-body">
                            <p class="settings-subhead">Footer Content</p>

                            <div class="settings-field">
                                <label>Notice Text</label>
                                <textarea v-model="emailSettings.footer_notice" rows="3"></textarea>
                            </div>

                            <div class="settings-field">
                                <label>Copyright Text</label>
                                <input type="text" v-model="emailSettings.footer_copyright">
                            </div>

                            <label class="settings-checkbox-label">
                                <input type="checkbox" v-model="emailSettings.footer_show_unsubscribe">
                                Show Unsubscribe Link
                            </label>
                            <label class="settings-checkbox-label">
                                <input type="checkbox" v-model="emailSettings.footer_show_privacy">
                                Show Privacy Link
                            </label>

                            <div class="settings-field" v-if="emailSettings.footer_show_privacy">
                                <label>Privacy Policy URL</label>
                                <input type="text" v-model="emailSettings.footer_privacy_url" placeholder="https://...">
                            </div>

                            <div class="settings-row">
                                <div class="settings-row-info">
                                    <div class="settings-row-label">Redirect URL after unsubscribe</div>
                                    <div class="settings-row-desc">leave blank for inline message</div>
                                </div>
                                <div class="settings-row-control">
                                    <input type="text" v-model="emailSettings.unsubscribe_redirect_url" placeholder="URL after redirect">
                                </div>
                            </div>
                        </div>
                    </div>
                </template>

                <!-- Custom Contact Fields (custom: reference list + repeatable rows) -->
                <template v-else-if="currentTab.id === 'custom_fields'">
                    <p class="settings-subhead">Fields recognized automatically from imports and webhooks</p>
                    <div class="settings-chip-row">
                        <span v-for="f in builtinFields" :key="f" class="settings-chip">{{ f }}</span>
                    </div>

                    <p class="settings-subhead settings-subhead--spaced">Additional custom fields</p>
                    <div v-for="(field, i) in customFields" :key="i" class="settings-repeat-row">
                        <input type="text" v-model="field.label" placeholder="Field label (e.g. Company)">
                        <input type="text" v-model="field.key" placeholder="field_key">
                        <select v-model="field.type">
                            <option value="text">Text</option>
                            <option value="number">Number</option>
                            <option value="date">Date</option>
                            <option value="select">Dropdown</option>
                        </select>
                        <button class="btn btn-ghost btn-sm" @click="customFields.splice(i, 1)">Remove</button>
                    </div>
                    <button class="btn btn-outline btn-sm" @click="customFields.push({ label: '', key: '', type: 'text' })">+ Add Field</button>
                </template>

                <!-- Every other tab: generic schema-driven form -->
                <template v-else>
                    <div v-for="field in currentTab.fields" :key="field.key" class="settings-field">
                        <label v-if="field.type !== 'checkbox'">{{ field.label }}</label>

                        <input v-if="field.type === 'text'" type="text" v-model="formData[currentTab.id][field.key]" :placeholder="field.placeholder">

                        <textarea v-else-if="field.type === 'textarea'" v-model="formData[currentTab.id][field.key]" :placeholder="field.placeholder" rows="3"></textarea>

                        <select v-else-if="field.type === 'select'" v-model="formData[currentTab.id][field.key]">
                            <option v-for="opt in field.options" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
                        </select>

                        <label v-else-if="field.type === 'checkbox'" class="settings-checkbox-label">
                            <input type="checkbox" v-model="formData[currentTab.id][field.key]">
                            {{ field.label }}
                        </label>

                        <p v-if="field.hint" class="settings-hint">{{ field.hint }}</p>
                    </div>
                </template>
            </section>
        </div>

        <MediaLibraryModal
            :open="libraryOpen"
            type="image"
            collection="business-logo"
            @close="libraryOpen = false"
            @select="onLogoSelected"
        />
    </AppLayout>
</template>

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

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

const mobileNavOpen = ref(false);

const ICONS = {
    doc:   '<path stroke-linecap="round" stroke-linejoin="round" d="M3.75 21h16.5M4.5 3h15M5.25 3v18m13.5-18v18M9 6.75h1.5m-1.5 3h1.5m-1.5 3h1.5m3-6H15m-1.5 3H15m-1.5 3H15M9 21v-3.375c0-.621.504-1.125 1.125-1.125h3.75c.621 0 1.125.504 1.125 1.125V21"/>',
    mail:  '<path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75"/>',
    cog:   '<path stroke-linecap="round" stroke-linejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>',
    link:  '<path stroke-linecap="round" stroke-linejoin="round" d="M13.19 8.688a4.5 4.5 0 011.242 7.244l-4.5 4.5a4.5 4.5 0 01-6.364-6.364l1.757-1.757m13.35-.622l1.757-1.757a4.5 4.5 0 00-6.364-6.364l-4.5 4.5a4.5 4.5 0 001.242 7.244"/>',
    userCheck: '<path stroke-linecap="round" stroke-linejoin="round" d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"/>',
    lock:  '<path stroke-linecap="round" stroke-linejoin="round" d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"/>',
};

const TIMEZONES = [
    'UTC',
    'America/New_York', 'America/Chicago', 'America/Denver', 'America/Los_Angeles',
    'America/Anchorage', 'America/Sao_Paulo', 'America/Mexico_City', 'America/Bogota',
    'America/Toronto', 'America/Vancouver',
    'Europe/London', 'Europe/Lisbon', 'Europe/Berlin', 'Europe/Paris', 'Europe/Madrid',
    'Europe/Rome', 'Europe/Amsterdam', 'Europe/Athens', 'Europe/Istanbul', 'Europe/Moscow',
    'Africa/Cairo', 'Africa/Lagos', 'Africa/Johannesburg', 'Africa/Nairobi',
    'Asia/Dubai', 'Asia/Karachi', 'Asia/Kolkata', 'Asia/Dhaka', 'Asia/Kathmandu',
    'Asia/Yangon', 'Asia/Bangkok', 'Asia/Jakarta', 'Asia/Singapore', 'Asia/Kuala_Lumpur',
    'Asia/Manila', 'Asia/Shanghai', 'Asia/Hong_Kong', 'Asia/Taipei', 'Asia/Tokyo',
    'Asia/Seoul', 'Asia/Riyadh', 'Asia/Tehran', 'Asia/Jerusalem',
    'Australia/Perth', 'Australia/Adelaide', 'Australia/Sydney', 'Australia/Brisbane',
    'Pacific/Auckland', 'Pacific/Fiji',
].map((tz) => ({ value: tz, label: tz }));

const DATE_FORMATS = [
    { value: 'MMM D, YYYY', label: 'Jan 6, 2026' },
    { value: 'DD/MM/YYYY',  label: '06/01/2026' },
    { value: 'MM/DD/YYYY',  label: '01/06/2026' },
    { value: 'YYYY-MM-DD',  label: '2026-01-06' },
];

const TABS = [
    { id: 'business', label: 'Business Setup', icon: ICONS.doc, kind: 'custom' },
    { id: 'email', label: 'Email Settings', icon: ICONS.mail, kind: 'custom' },
    { id: 'general', label: 'General Settings', icon: ICONS.cog, kind: 'form', fields: [
        { key: 'timezone',    label: 'Timezone',    type: 'select', options: TIMEZONES, default: 'UTC' },
        { key: 'date_format', label: 'Date Format', type: 'select', options: DATE_FORMATS, default: 'MMM D, YYYY' },
    ] },
    { id: 'custom_fields', label: 'Custom Contact Fields', icon: ICONS.userCheck, kind: 'custom' },
    { id: 'license', label: 'License Management', icon: ICONS.lock, kind: 'form',
        notice: 'CRMfic is self-hosted and does not require a license to operate.',
        fields: [
            { key: 'license_key', label: 'License Key', type: 'text', placeholder: 'Not required - self-hosted installation' },
        ] },
];

const EXTERNAL_LINKS = [
    { label: 'Incoming Webhooks', href: '/webhooks', icon: ICONS.link },
    { label: 'SMTP/Email Service Settings', href: '/sending/smtp', icon: ICONS.mail },
];

const activeTab = ref('business');
const currentTab = computed(() => TABS.find((t) => t.id === activeTab.value));

const saving = ref(false);
const savingTab = ref(null);
const saved = ref(null);

// ── Business (custom) ──
const business = reactive({
    name: props.settings.business?.name ?? '',
    address: props.settings.business?.address ?? '',
    logo: props.settings.business?.logo ?? null,
});
const businessInitial = computed(() => (business.name.trim()[0] || 'B').toUpperCase());

// Renders literal "{{business_name}}" as text  writing that directly in a
// template interpolation would break Vue's own {{ }} parsing.
function tag(name) {
    return '{{' + name + '}}';
}

// ── Email Settings (custom: from/reply-to defaults + footer content) ──
const emailSettings = reactive({
    from_name:                props.settings.email?.from_name ?? '',
    from_email:                props.settings.email?.from_email ?? '',
    reply_to_name:             props.settings.email?.reply_to_name ?? '',
    reply_to_email:            props.settings.email?.reply_to_email ?? '',
    rate_limit_per_second:     props.settings.email?.rate_limit_per_second ?? 15,
    tracking_enabled:          props.settings.email?.tracking_enabled ?? true,
    footer_notice:             props.settings.email?.footer_notice ?? "You're receiving this email because you subscribed to our newsletter.",
    footer_copyright:          props.settings.email?.footer_copyright ?? `© ${new Date().getFullYear()} Your Company · All rights reserved`,
    footer_show_unsubscribe:   props.settings.email?.footer_show_unsubscribe ?? true,
    footer_show_privacy:       props.settings.email?.footer_show_privacy ?? true,
    footer_privacy_url:        props.settings.email?.footer_privacy_url ?? '',
    unsubscribe_redirect_url:  props.settings.email?.unsubscribe_redirect_url ?? '',
});
function adjustRateLimit(delta) {
    emailSettings.rate_limit_per_second = Math.min(100, Math.max(1, emailSettings.rate_limit_per_second + delta));
}

// ── Custom Contact Fields (custom, repeatable rows) ──
const builtinFields = props.builtinFields;
const customFields = reactive([...(props.settings.custom_fields ?? [])]);

// ── Generic schema-driven sections ──
const formData = reactive({});
TABS.filter((t) => t.kind === 'form').forEach((tab) => {
    const defaults = {};
    tab.fields.forEach((f) => { defaults[f.key] = f.type === 'checkbox' ? false : (f.default ?? ''); });
    formData[tab.id] = { ...defaults, ...(props.settings[tab.id] ?? {}) };
});

function sectionPayload(id) {
    if (id === 'business') return business;
    if (id === 'email') return emailSettings;
    if (id === 'custom_fields') return customFields;
    return formData[id];
}

async function saveSection(id) {
    saving.value = true;
    savingTab.value = id;
    saved.value = null;

    try {
        await axios.put('/settings', { section: id, data: sectionPayload(id) });
        saved.value = id;
        setTimeout(() => { if (saved.value === id) saved.value = null; }, 3000);
    } finally {
        saving.value = false;
        savingTab.value = null;
    }
}

async function uploadLogo(e) {
    const file = e.target.files?.[0];
    if (!file) return;

    const uploadData = new FormData();
    uploadData.append('logo', file);

    const { data } = await axios.post('/settings/logo', uploadData);
    business.logo = data.url;
    e.target.value = '';
}

const libraryOpen = ref(false);

function onLogoSelected(item) {
    business.logo = item.url;
    libraryOpen.value = false;
}
</script>

<style scoped>
.settings-shell {
    display: grid;
    grid-template-columns: 240px 1fr;
    gap: 20px;
}

.settings-mobile-toggle {
    display: none;
}
.settings-nav-list {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

@media (max-width: 900px) {
    .settings-shell {
        grid-template-columns: 1fr;
    }
    .settings-nav {
        position: static !important;
        flex-direction: column !important;
        overflow: visible !important;
        max-height: none !important;
        padding: 6px !important;
        border-radius: 10px;
        background: var(--bg-surface);
        border: 1px solid var(--border-color);
        margin-bottom: 16px;
    }
    .settings-mobile-toggle {
        display: flex !important;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        padding: 10px 14px;
        background: var(--bg-surface);
        border: none;
        border-radius: 8px;
        color: var(--text-primary);
        font-weight: 600;
        font-size: 14px;
        cursor: pointer;
        transition: background 0.15s;
        box-sizing: border-box;
    }
    .settings-mobile-toggle:hover {
        background: var(--bg-hover);
    }
    .settings-mobile-toggle-left {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    .settings-mobile-toggle-left svg {
        width: 18px;
        height: 18px;
        color: var(--info, #3b82f6);
        flex-shrink: 0;
    }
    .settings-mobile-toggle-right {
        display: flex;
        align-items: center;
        gap: 8px;
    }
    .settings-mobile-toggle-badge {
        font-size: 11px;
        font-weight: 600;
        color: var(--text-muted);
        background: var(--bg-hover);
        padding: 3px 8px;
        border-radius: 12px;
    }
    .settings-mobile-toggle-chevron {
        width: 16px;
        height: 16px;
        transition: transform 0.2s ease;
        flex-shrink: 0;
    }
    .settings-mobile-toggle-chevron.is-open {
        transform: rotate(180deg);
    }
    .settings-nav-list {
        display: none;
        flex-direction: column;
        gap: 4px;
        padding-top: 8px;
        margin-top: 6px;
        border-top: 1px solid var(--border-color);
    }
    .settings-nav-list.is-open {
        display: flex !important;
    }
    .settings-nav-item {
        width: 100% !important;
        white-space: normal !important;
        padding: 10px 12px;
        font-size: 14px;
        border-radius: 6px;
    }
    .settings-nav-divider {
        display: block !important;
        height: 1px;
        background: var(--border-color);
        margin: 6px 0;
    }
}

/* ── Left nav ── */
.settings-nav {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 8px;
    display: flex;
    flex-direction: column;
    gap: 2px;
    max-height: calc(100vh - 40px);
    overflow-y: auto;
    position: sticky;
    top: 20px;
}
.settings-nav-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 9px 12px;
    border: none;
    background: none;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 500;
    color: var(--text-secondary);
    text-decoration: none;
    cursor: pointer;
    text-align: left;
    width: 100%;
    box-sizing: border-box;
    transition: background 0.1s, color 0.1s;
}
.settings-nav-item svg { width: 16px; height: 16px; flex-shrink: 0; }
.settings-nav-item:hover { background: var(--bg-hover); color: var(--text-primary); text-decoration: none; }
.settings-nav-item.is-active { background: var(--active-bg); color: var(--active-text); font-weight: 600; }
.settings-nav-item-external { width: 12px !important; height: 12px !important; margin-left: auto; opacity: 0.6; }
.settings-nav-divider { height: 1px; background: var(--border-color); margin: 6px 4px; }

/* ── Right panel ── */
.settings-content {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 20px 24px 28px;
}
.settings-panel-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    margin-bottom: 18px;
}
.settings-panel-header h2 {
    font-size: 16px;
    font-weight: 700;
    color: var(--text-primary);
    margin: 0;
}

.settings-saved {
    font-size: 13px;
    color: var(--success);
    background: var(--success-light);
    border: 1px solid var(--success-border);
    border-radius: 6px;
    padding: 8px 12px;
    margin: 0 0 16px;
}
.settings-notice {
    font-size: 13px;
    color: var(--warning);
    background: var(--warning-light);
    border: 1px solid var(--warning-border);
    border-radius: 6px;
    padding: 8px 12px;
    margin: 0 0 16px;
}

.settings-field { margin-bottom: 20px; max-width: 520px; }
.settings-field label {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 13px;
    font-weight: 500;
    color: var(--text-primary);
    margin-bottom: 6px;
}
.settings-field input[type="text"],
.settings-field select,
.settings-field textarea {
    width: 100%;
    padding: 0 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    font-size: 13px;
    color: var(--text-primary);
    background: var(--bg-surface);
    box-sizing: border-box;
    font-family: inherit;
}
.settings-field input[type="text"],
.settings-field select { height: 38px; }
.settings-field textarea { padding: 10px 12px; resize: vertical; }
.settings-field input::placeholder,
.settings-field textarea::placeholder { color: var(--text-muted); }
.settings-field input:focus,
.settings-field select:focus,
.settings-field textarea:focus {
    outline: none;
    border-color: #93c5fd;
    box-shadow: 0 0 0 3px rgba(66, 133, 244, 0.15);
}
.settings-hint { font-size: 12px; color: var(--text-muted); margin: 6px 0 0; }

.settings-checkbox-label {
    display: flex !important;
    align-items: center;
    gap: 8px;
    cursor: pointer;
}
.settings-checkbox-label input[type="checkbox"] { width: 16px; height: 16px; cursor: pointer; }

.settings-subhead {
    font-size: 12px;
    font-weight: 600;
    color: var(--text-muted);
    text-transform: uppercase;
    letter-spacing: 0.05em;
    margin: 0 0 10px;
}
.settings-subhead--spaced { margin-top: 24px; }

.settings-chip-row { display: flex; flex-wrap: wrap; gap: 6px; }
.settings-chip {
    font-size: 12px;
    color: var(--text-secondary);
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    border-radius: 999px;
    padding: 4px 10px;
}

.settings-repeat-row {
    display: grid;
    grid-template-columns: 1fr 1fr 140px auto;
    gap: 8px;
    margin-bottom: 8px;
    max-width: 720px;
}
@media (max-width: 576px) {
    .settings-repeat-row {
        grid-template-columns: 1fr;
    }
}
.settings-repeat-row input,
.settings-repeat-row select {
    height: 36px;
    padding: 0 10px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    font-size: 13px;
    color: var(--text-primary);
    background: var(--bg-surface);
}

.settings-logo-row { display: flex; align-items: center; gap: 12px; max-width: none; }
.settings-upload-btn { position: relative; overflow: hidden; }
.settings-file-input { position: absolute; inset: 0; opacity: 0; cursor: pointer; }

/* ── Two-column settings row (label + description left, control right) ── */
.settings-row {
    display: grid;
    grid-template-columns: 260px 1fr;
    gap: 24px;
    padding: 20px 0;
    border-bottom: 1px solid var(--border-color);
    align-items: start;
}
@media (max-width: 768px) {
    .settings-row {
        grid-template-columns: 1fr;
        gap: 8px;
        padding: 16px 0;
    }
    .settings-row-control {
        max-width: 100%;
    }
}
.settings-row:first-child { padding-top: 0; }
.settings-row:last-child { border-bottom: none; padding-bottom: 0; }
.settings-row-label { font-size: 13px; font-weight: 600; color: var(--text-primary); margin-bottom: 4px; }
.settings-row-desc { font-size: 12px; color: var(--text-secondary); line-height: 1.5; }
.settings-row-control { max-width: 420px; width: 100%; }
.settings-row-control input[type="text"],
.settings-row-control textarea {
    width: 100%;
    padding: 0 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    font-size: 13px;
    color: var(--text-primary);
    background: var(--bg-surface);
    box-sizing: border-box;
    font-family: inherit;
}
.settings-row-control input[type="text"] { height: 38px; }
.settings-row-control textarea { padding: 10px 12px; resize: vertical; min-height: 76px; }
.settings-row-control input::placeholder,
.settings-row-control textarea::placeholder { color: var(--text-muted); }
.settings-row-control input:focus,
.settings-row-control textarea:focus {
    outline: none;
    border-color: #93c5fd;
    box-shadow: 0 0 0 3px rgba(66, 133, 244, 0.15);
}

.settings-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: var(--bg-hover);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 15px;
    font-weight: 600;
    color: var(--text-secondary);
    overflow: hidden;
    flex-shrink: 0;
}
.settings-avatar img { width: 100%; height: 100%; object-fit: cover; }

/* ── Email Settings sub-cards ── */
.settings-subcard {
    border: 1px solid var(--border-color);
    border-radius: 10px;
    margin-bottom: 24px;
    overflow: hidden;
}
.settings-subcard:last-child { margin-bottom: 0; }
.settings-subcard-header {
    padding: 14px 20px;
    font-size: 14px;
    font-weight: 700;
    color: var(--text-primary);
    border-bottom: 1px solid var(--border-color);
    background: var(--bg-hover);
}
.settings-subcard-body { padding: 20px; }
.settings-subcard-body .settings-field:last-child { margin-bottom: 0; }

.settings-info-banner {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    background: var(--bg-hover);
    border-radius: 8px;
    padding: 10px 14px;
    font-size: 12px;
    color: var(--text-secondary);
    line-height: 1.5;
    margin-bottom: 8px;
}
.settings-info-banner svg { width: 16px; height: 16px; flex-shrink: 0; margin-top: 1px; color: var(--text-muted); }

.settings-stepper {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    padding: 0 6px;
    height: 38px;
}
.settings-stepper button {
    width: 24px;
    height: 24px;
    border: none;
    background: var(--bg-hover);
    border-radius: 4px;
    font-size: 16px;
    line-height: 1;
    cursor: pointer;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    justify-content: center;
}
.settings-stepper button:hover { background: var(--active-bg); }
.settings-stepper span { min-width: 24px; text-align: center; font-size: 13px; font-weight: 600; color: var(--text-primary); }
</style>
