<template>
    <Head title="SMTP Configuration" />

    <AppLayout>
        <!-- Page header -->
        <div class="page-header">
            <div class="page-header__left">
                <h1>SMTP Configuration</h1>
                <p>Connect your email service providers for email delivery.</p>
            </div>
            <div class="page-header__actions">
                <button class="btn btn-primary" @click="openCreate">
                    <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 4.5v15m7.5-7.5h-15"/></svg>
                    Add connection
                </button>
            </div>
        </div>

        <!-- Flash -->
        <div v-if="$page.props.flash?.success" class="flash-success">
            {{ $page.props.flash.success }}
        </div>

        <!-- Info alert -->
        <div class="alert alert--info" style="margin-bottom:20px">
            <div class="alert-icon">
                <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>
            </div>
            <div class="alert-body">
                <div class="alert-title">Bring your own sending service</div>
                CRMfic does not provide a built-in sending relay. Connect your own provider - credentials are stored encrypted using AES-256-CBC.
                The <strong>From Name</strong> and <strong>From Email</strong> on your default connection are used as the sender identity for campaign emails.
            </div>
        </div>

        <!-- Empty state -->
        <div v-if="configs.length === 0" class="empty-state">
            <div class="empty-state-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="M5.25 14.25h13.5m-13.5 0a3 3 0 01-3-3m3 3a3 3 0 100 6h13.5a3 3 0 100-6m-16.5-3a3 3 0 013-3h13.5a3 3 0 013 3m-19.5 0a4.5 4.5 0 01.9-2.7L5.737 5.1a3.375 3.375 0 012.7-1.35h7.126c1.062 0 2.062.5 2.7 1.35l2.587 3.45a4.5 4.5 0 01.9 2.7m0 0a3 3 0 01-3 3m0 3h.008v.008h-.008v-.008zm0-6h.008v.008h-.008v-.008zm-3 6h.008v.008h-.008v-.008zm0-6h.008v.008h-.008v-.008z"/></svg>
            </div>
            <h3>Please configure your first email service provider connection</h3>
            <p>Pick a provider and connect it to start sending emails.</p>
            <button class="btn btn-primary" @click="openCreate">Configure provider</button>
        </div>

        <!-- Connection cards -->
        <div v-else class="smtp-list">
            <div v-for="config in configs" :key="config.id" class="smtp-card">
                <div class="smtp-card-header">
                    <div class="smtp-card-header-info">
                        <div class="smtp-card-title">
                            {{ config.name }}
                            <span class="smtp-provider-badge">{{ providerName(config.provider) }}</span>
                            <span v-if="config.is_default" class="smtp-default-badge">Default</span>
                        </div>
                        <div class="smtp-card-subtitle">{{ cardSubtitle(config) }}</div>
                    </div>
                    <div class="smtp-card-actions">
                        <span v-if="config.last_test_status === 'success'" class="badge-dot badge-dot--online">Connected</span>
                        <span v-else-if="config.last_test_status === 'failed'" class="badge-dot badge-dot--error">Error</span>
                        <span v-else class="badge-dot badge-dot--idle">Not tested</span>

                        <button class="btn btn-outline btn-sm" :disabled="checkingId === config.id" @click="checkConnection(config)">
                            <span v-if="checkingId === config.id" 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>
                            {{ checkingId === config.id ? 'Checking…' : 'Check connection' }}
                        </button>
                        <button class="btn btn-outline btn-sm" @click="openEdit(config)">Edit</button>

                        <div class="dropdown-wrap" :ref="el => cardMenuRef[config.id] = el">
                            <button class="btn btn-ghost btn-sm btn-icon" @click="toggleMenu(config.id)">
                                <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="M6.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM12.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM18.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0z"/></svg>
                            </button>
                            <div v-if="openMenuId === config.id" class="dropdown-menu dropdown-menu--right is-open">
                                <button class="dropdown-item" @click="openSendTest(config)">
                                    <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="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5"/></svg>
                                    Send test email
                                </button>
                                <button v-if="!config.is_default" class="dropdown-item" @click="setDefault(config)">
                                    <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.48 3.499a.562.562 0 011.04 0l2.125 5.111a.563.563 0 00.475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 00-.182.557l1.285 5.385a.562.562 0 01-.84.61l-4.725-2.885a.563.563 0 00-.586 0L6.982 20.54a.562.562 0 01-.84-.61l1.285-5.386a.562.562 0 00-.182-.557l-4.204-3.602a.563.563 0 01.321-.988l5.518-.442a.563.563 0 00.475-.345L11.48 3.5z"/></svg>
                                    Set as default
                                </button>
                                <button class="dropdown-item dropdown-item--danger" @click="confirmDelete(config)">
                                    <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="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"/></svg>
                                    Delete
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="smtp-card-body">
                    <div class="smtp-meta-grid">
                        <div v-for="m in cardMeta(config)" :key="m.label">
                            <div class="smtp-meta-label">{{ m.label }}</div>
                            <div class="smtp-meta-value">{{ m.value }}</div>
                        </div>
                    </div>
                    <div v-if="config.from_email" class="smtp-from-row">
                        <span class="smtp-meta-label">From:</span>
                        <span class="smtp-meta-value">{{ config.from_name ? `${config.from_name} <${config.from_email}>` : config.from_email }}</span>
                    </div>
                    <div v-if="config.last_tested_at" class="smtp-tested-row">
                        Last tested {{ formatDate(config.last_tested_at) }}
                    </div>

                    <!-- Inline check-connection result -->
                    <div v-if="cardResults[config.id]" class="smtp-test-result" :class="cardResults[config.id].success ? 'smtp-test-result--success' : 'smtp-test-result--error'">
                        <svg v-if="cardResults[config.id].success" 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="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                        <svg v-else 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>
                        {{ cardResults[config.id].message }}
                    </div>
                </div>
            </div>
        </div>

        <!-- Add/Edit Modal -->
        <Teleport to="body">
            <div class="modal-overlay" :class="{ 'is-open': showModal }" @click.self="closeModal">
                <div class="modal" style="width:760px;max-width:96vw">
                    <div class="modal-header">
                        <div>
                            <h3 class="modal-title">{{ editing ? 'Edit Connection' : 'Add Connection' }}</h3>
                            <p class="modal-subtitle">{{ modalStep === 'provider' ? 'Please configure your email service provider connection.' : providerName(form.provider) + ' connection settings.' }}</p>
                        </div>
                        <button class="modal-close" @click="closeModal" 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>

                    <!-- STEP 1: Provider grid -->
                    <div v-if="modalStep === 'provider'" class="modal-body">
                        <div class="prov-label">Connection Provider</div>
                        <div class="prov-grid">
                            <button
                                v-for="p in providers"
                                :key="p.slug"
                                type="button"
                                class="prov-tile"
                                :class="{ 'is-selected': form.provider === p.slug, 'is-disabled': !p.active }"
                                :disabled="!p.active"
                                :title="p.active ? p.name : p.name + ' - coming soon'"
                                @click="selectProvider(p)"
                            >
                                <span class="prov-logo" :style="{ background: p.color }">{{ p.tag }}</span>
                                <span class="prov-name">{{ p.name }}</span>
                                <span v-if="!p.active" class="prov-soon">Soon</span>
                            </button>
                        </div>
                    </div>

                    <!-- STEP 2: Connection form (Other SMTP) -->
                    <div v-else class="modal-body">
                        <!-- Current provider strip -->
                        <div class="prov-current">
                            <span class="prov-logo prov-logo--sm" :style="{ background: currentProvider.color }">{{ currentProvider.tag }}</span>
                            <span class="prov-current-name">{{ currentProvider.name }}</span>
                            <button v-if="!editing" type="button" class="prov-change-btn" @click="modalStep = 'provider'">Change provider</button>
                        </div>

                        <!-- ── Sender Settings ── -->
                        <div class="smtp-section">
                            <div class="smtp-section-title">Sender Settings</div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label class="form-label">From Email <span class="required">*</span></label>
                                    <input type="email" class="form-input" v-model="form.from_email" placeholder="From Email" :class="{ 'is-invalid': errors.from_email }">
                                    <span v-if="errors.from_email" class="form-error">{{ errors.from_email }}</span>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">From Name</label>
                                    <input type="text" class="form-input" v-model="form.from_name" placeholder="From Name">
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group" style="gap:8px;display:flex;flex-direction:column">
                                    <label class="form-check-label">
                                        <input type="checkbox" v-model="form.force_from_email" class="form-checkbox">
                                        Force From Email (Recommended: Enable)
                                        <span class="hint-i" title="If enabled, campaign emails always send from this address, ignoring any campaign-level From email.">ⓘ</span>
                                    </label>
                                    <label class="form-check-label">
                                        <input type="checkbox" v-model="form.return_path_match" class="form-checkbox">
                                        Set the return-path to match the From Email
                                        <span class="hint-i" title="Bounces are returned to the From Email address. Recommended for better deliverability.">ⓘ</span>
                                    </label>
                                </div>
                                <div class="form-group">
                                    <label class="form-check-label">
                                        <input type="checkbox" v-model="form.force_from_name" class="form-checkbox">
                                        Force Sender Name
                                        <span class="hint-i" title="If enabled, campaign emails always use this From name, ignoring any campaign-level sender name.">ⓘ</span>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <!-- ── PHP Mail warning ── -->
                        <div v-if="form.provider === 'phpmail'" class="smtp-region-note" style="color:#92400e;background:#fffbeb;border:1px solid #fde68a;margin-bottom:20px">
                            The Default option does not use SMTP or any Email Service Provider - it relies on your server's local mail agent (sendmail on Linux, or the SMTP/smtp_port settings in php.ini on Windows). This typically does not improve email deliverability and is not recommended for production sending.
                        </div>

                        <!-- ── Connection Settings (Other SMTP) ── -->
                        <div v-if="form.provider === 'smtp'" class="smtp-section">
                            <div class="smtp-section-title">Connection Settings</div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label class="form-label">SMTP Host <span class="required">*</span></label>
                                    <input type="text" class="form-input" v-model="form.host" placeholder="SMTP Host" :class="{ 'is-invalid': errors.host }">
                                    <span v-if="errors.host" class="form-error">{{ errors.host }}</span>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">SMTP Port <span class="required">*</span></label>
                                    <input type="number" class="form-input" v-model.number="form.port" placeholder="SMTP Port" :class="{ 'is-invalid': errors.port }">
                                    <span v-if="errors.port" class="form-error">{{ errors.port }}</span>
                                </div>
                            </div>

                            <!-- Encryption radios -->
                            <div class="smtp-inline-row">
                                <div class="smtp-inline-label">
                                    Encryption
                                    <span class="smtp-inline-hint">Select <strong>ssl</strong> on port <strong>465</strong>, or <strong>tls</strong> on port <strong>25</strong> or <strong>587</strong></span>
                                </div>
                                <div class="enc-options">
                                    <label class="enc-opt" :class="{ 'is-active': form.encryption === 'none' }">
                                        <input type="radio" value="none" v-model="form.encryption"> None
                                    </label>
                                    <label class="enc-opt" :class="{ 'is-active': form.encryption === 'ssl' }">
                                        <input type="radio" value="ssl" v-model="form.encryption"> SSL
                                    </label>
                                    <label class="enc-opt" :class="{ 'is-active': form.encryption === 'tls' }">
                                        <input type="radio" value="tls" v-model="form.encryption"> TLS
                                    </label>
                                </div>
                            </div>

                            <!-- Auto TLS -->
                            <div class="smtp-inline-row">
                                <div class="smtp-inline-label">Use Auto TLS</div>
                                <label class="switch">
                                    <input type="checkbox" v-model="form.auto_tls">
                                    <span class="switch-slider"></span>
                                </label>
                                <span class="smtp-inline-hint">By default, TLS encryption is used when the server supports it. Disable if it causes problems on your server.</span>
                            </div>

                            <!-- Authentication -->
                            <div class="smtp-inline-row">
                                <div class="smtp-inline-label">Authentication</div>
                                <label class="switch">
                                    <input type="checkbox" v-model="form.auth_enabled">
                                    <span class="switch-slider"></span>
                                </label>
                                <span class="smtp-inline-hint">Provide your SMTP server credentials (username and password). In most cases this is required.</span>
                            </div>

                            <div v-if="form.auth_enabled" class="form-row">
                                <div class="form-group">
                                    <label class="form-label">SMTP Username <span class="required">*</span></label>
                                    <input type="text" class="form-input" v-model="form.username" placeholder="Your SMTP Username" autocomplete="off" :class="{ 'is-invalid': errors.username }">
                                    <span v-if="errors.username" class="form-error">{{ errors.username }}</span>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">
                                        SMTP Password <span class="required">*</span>
                                        <span v-if="editing" class="form-label-hint">(leave blank to keep current)</span>
                                    </label>
                                    <div class="input-with-icon">
                                        <input
                                            :type="showPassword ? 'text' : 'password'"
                                            class="form-input"
                                            style="padding-right:38px"
                                            v-model="form.password"
                                            :placeholder="editing ? '••••••••••••' : 'Your SMTP Password'"
                                            autocomplete="new-password"
                                            :class="{ 'is-invalid': errors.password }"
                                        >
                                        <button type="button" class="input-icon input-icon--right input-icon--btn" @click="showPassword = !showPassword" tabindex="-1">
                                            <svg v-if="!showPassword" 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="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                                            <svg v-else 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="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88"/></svg>
                                        </button>
                                    </div>
                                    <p class="form-hint">Stored encrypted (AES-256-CBC) in the database.</p>
                                    <span v-if="errors.password" class="form-error">{{ errors.password }}</span>
                                </div>
                            </div>
                        </div>

                        <!-- ── API Credentials (Amazon SES) ── -->
                        <div v-else-if="form.provider === 'ses'" class="smtp-section">
                            <div class="smtp-section-title">API Credentials</div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label class="form-label">Access Key <span class="required">*</span></label>
                                    <input type="text" class="form-input" v-model="form.username" placeholder="AKIA…" autocomplete="off" :class="{ 'is-invalid': errors.username }">
                                    <p class="form-hint">Stored encrypted (AES-256-CBC) in the database.</p>
                                    <span v-if="errors.username" class="form-error">{{ errors.username }}</span>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">
                                        Secret Key <span class="required">*</span>
                                        <span v-if="editing" class="form-label-hint">(leave blank to keep current)</span>
                                    </label>
                                    <div class="input-with-icon">
                                        <input
                                            :type="showPassword ? 'text' : 'password'"
                                            class="form-input"
                                            style="padding-right:38px"
                                            v-model="form.password"
                                            :placeholder="editing ? '••••••••••••' : 'Your Secret Access Key'"
                                            autocomplete="new-password"
                                            :class="{ 'is-invalid': errors.password }"
                                        >
                                        <button type="button" class="input-icon input-icon--right input-icon--btn" @click="showPassword = !showPassword" tabindex="-1">
                                            <svg v-if="!showPassword" 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="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                                            <svg v-else 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="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88"/></svg>
                                        </button>
                                    </div>
                                    <p class="form-hint">Stored encrypted (AES-256-CBC) in the database.</p>
                                    <span v-if="errors.password" class="form-error">{{ errors.password }}</span>
                                </div>
                            </div>
                            <div class="form-group" style="max-width:360px">
                                <label class="form-label">Region <span class="form-label-hint">(Default: US East (N. Virginia) / us-east-1)</span></label>
                                <select class="form-select" v-model="form.region">
                                    <option v-for="r in sesRegions" :key="r.value" :value="r.value">{{ r.label }} - {{ r.value }}</option>
                                </select>
                                <p class="form-hint">Must match the region where your SES sending identity is verified.</p>
                                <span v-if="errors['settings.region']" class="form-error">{{ errors['settings.region'] }}</span>
                            </div>
                        </div>

                        <!-- ── Mailgun API Settings ── -->
                        <div v-else-if="form.provider === 'mailgun'" class="smtp-section">
                            <div class="smtp-section-title">Mailgun API Settings</div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label class="form-label">
                                        Private API Key <span class="required">*</span>
                                        <span v-if="editing" class="form-label-hint">(leave blank to keep current)</span>
                                    </label>
                                    <div class="input-with-icon">
                                        <input
                                            :type="showPassword ? 'text' : 'password'"
                                            class="form-input"
                                            style="padding-right:38px"
                                            v-model="form.password"
                                            :placeholder="editing ? '••••••••••••' : 'Your Mailgun Private API Key'"
                                            autocomplete="new-password"
                                            :class="{ 'is-invalid': errors.password }"
                                        >
                                        <button type="button" class="input-icon input-icon--right input-icon--btn" @click="showPassword = !showPassword" tabindex="-1">
                                            <svg v-if="!showPassword" 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="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                                            <svg v-else 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="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88"/></svg>
                                        </button>
                                    </div>
                                    <p class="form-hint">
                                        Stored encrypted (AES-256-CBC) in the database.
                                        Follow this link to get an API Key from Mailgun:
                                        <a href="https://app.mailgun.com/settings/api_security" target="_blank" rel="noopener" class="smtp-help-link" style="margin-top:0">Get a Private API Key</a>
                                    </p>
                                    <span v-if="errors.password" class="form-error">{{ errors.password }}</span>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Domain Name <span class="required">*</span></label>
                                    <input type="text" class="form-input" v-model="form.domain" placeholder="mg.yourdomain.com" autocomplete="off" :class="{ 'is-invalid': errors['settings.domain'] }">
                                    <p class="form-hint">
                                        Follow this link to get a Domain Name from Mailgun:
                                        <a href="https://app.mailgun.com/app/sending/domains" target="_blank" rel="noopener" class="smtp-help-link" style="margin-top:0">Get a Domain Name</a>
                                    </p>
                                    <span v-if="errors['settings.domain']" class="form-error">{{ errors['settings.domain'] }}</span>
                                </div>
                            </div>

                            <div class="smtp-inline-row">
                                <div class="smtp-inline-label">Select Region</div>
                                <div class="enc-options">
                                    <label class="enc-opt" :class="{ 'is-active': form.region === 'us' }">
                                        <input type="radio" value="us" v-model="form.region"> US
                                    </label>
                                    <label class="enc-opt" :class="{ 'is-active': form.region === 'eu' }">
                                        <input type="radio" value="eu" v-model="form.region"> EU
                                    </label>
                                </div>
                            </div>
                            <div class="smtp-region-note">
                                Define which endpoint you want to use for sending messages. If you are operating under EU laws, you may be required to use the EU region.
                            </div>
                        </div>

                        <!-- ── Postmark API Settings ── -->
                        <div v-else-if="form.provider === 'postmark'" class="smtp-section">
                            <div class="smtp-section-title">Postmark API Settings</div>
                            <div class="form-group">
                                <label class="form-label">
                                    API Key <span class="required">*</span>
                                    <span v-if="editing" class="form-label-hint">(leave blank to keep current)</span>
                                </label>
                                <div class="input-with-icon">
                                    <input
                                        :type="showPassword ? 'text' : 'password'"
                                        class="form-input"
                                        style="padding-right:38px"
                                        v-model="form.password"
                                        :placeholder="editing ? '••••••••••••' : 'Your Postmark Server API Token'"
                                        autocomplete="new-password"
                                        :class="{ 'is-invalid': errors.password }"
                                    >
                                    <button type="button" class="input-icon input-icon--right input-icon--btn" @click="showPassword = !showPassword" tabindex="-1">
                                        <svg v-if="!showPassword" 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="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                                        <svg v-else 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="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88"/></svg>
                                    </button>
                                </div>
                                <p class="form-hint">
                                    Stored encrypted (AES-256-CBC) in the database.
                                    Follow this link to get an API Key from Postmark (Your API key is in the API Tokens tab of your):
                                    <a href="https://account.postmarkapp.com/servers" target="_blank" rel="noopener" class="smtp-help-link" style="margin-top:0">Postmark Server</a>.
                                </p>
                                <span v-if="errors.password" class="form-error">{{ errors.password }}</span>
                            </div>

                            <div class="form-row">
                                <div class="form-group">
                                    <label class="form-label">Track Opens</label>
                                    <label class="form-check-label">
                                        <input type="checkbox" v-model="form.track_opens" class="form-checkbox">
                                        Enable email opens tracking on postmark (For HTML Emails only).
                                        <span class="hint-i" title="Adds an invisible tracking pixel to HTML emails so Postmark can record opens.">ⓘ</span>
                                    </label>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Track Links</label>
                                    <label class="form-check-label">
                                        <input type="checkbox" v-model="form.track_links" class="form-checkbox">
                                        Enable link tracking on postmark (For HTML Emails only).
                                        <span class="hint-i" title="Rewrites links in HTML emails so Postmark can record clicks.">ⓘ</span>
                                    </label>
                                </div>
                            </div>

                            <div class="form-group" style="max-width:360px">
                                <label class="form-label">Message Stream</label>
                                <input type="text" class="form-input" v-model="form.message_stream" placeholder="outbound">
                                <p class="form-hint">Must match a Message Stream configured on your Postmark server (default: outbound).</p>
                            </div>
                        </div>

                        <!-- ── ElasticEmail API Settings ── -->
                        <div v-else-if="form.provider === 'elastic'" class="smtp-section">
                            <div class="smtp-section-title">ElasticEmail API Settings</div>
                            <div class="form-group">
                                <label class="form-label">
                                    API Key <span class="required">*</span>
                                    <span v-if="editing" class="form-label-hint">(leave blank to keep current)</span>
                                </label>
                                <div class="input-with-icon">
                                    <input
                                        :type="showPassword ? 'text' : 'password'"
                                        class="form-input"
                                        style="padding-right:38px"
                                        v-model="form.password"
                                        :placeholder="editing ? '••••••••••••' : 'Your Elastic Email API Key'"
                                        autocomplete="new-password"
                                        :class="{ 'is-invalid': errors.password }"
                                    >
                                    <button type="button" class="input-icon input-icon--right input-icon--btn" @click="showPassword = !showPassword" tabindex="-1">
                                        <svg v-if="!showPassword" 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="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                                        <svg v-else 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="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88"/></svg>
                                    </button>
                                </div>
                                <p class="form-hint">
                                    Stored encrypted (AES-256-CBC) in the database.
                                    Follow this link to get an API Key from ElasticEmail:
                                    <a href="https://elasticemail.com/account#/settings/new/manage-api" target="_blank" rel="noopener" class="smtp-help-link" style="margin-top:0">Get API Key.</a>
                                </p>
                                <span v-if="errors.password" class="form-error">{{ errors.password }}</span>
                            </div>

                            <div class="smtp-inline-row">
                                <div class="smtp-inline-label">Email Type</div>
                                <div class="enc-options">
                                    <label class="enc-opt" :class="{ 'is-active': form.email_type === 'transactional' }">
                                        <input type="radio" value="transactional" v-model="form.email_type"> Transactional
                                    </label>
                                    <label class="enc-opt" :class="{ 'is-active': form.email_type === 'marketing' }">
                                        <input type="radio" value="marketing" v-model="form.email_type"> Marketing
                                    </label>
                                </div>
                            </div>
                        </div>

                        <!-- ── Gmail / Google Workspace API Settings ── -->
                        <div v-else-if="form.provider === 'gmail'" class="smtp-section">
                            <div class="smtp-section-title">Gmail / Google Workspace API Settings</div>
                            <p class="form-hint" style="margin-top:0">
                                Please <a href="https://developers.google.com/gmail/api/quickstart/php" target="_blank" rel="noopener" class="smtp-help-link" style="margin-top:0;display:inline">check the documentation</a> to create API keys on the Google Cloud Platform.
                            </p>

                            <div class="form-row">
                                <div class="form-group">
                                    <label class="form-label">Application Client ID <span class="required">*</span></label>
                                    <input type="text" class="form-input" v-model="form.username" placeholder="xxxxxxxxxxxx.apps.googleusercontent.com" autocomplete="off" :class="{ 'is-invalid': errors.username }">
                                    <span v-if="errors.username" class="form-error">{{ errors.username }}</span>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">
                                        Application Client Secret <span class="required">*</span>
                                        <span v-if="editing" class="form-label-hint">(leave blank to keep current)</span>
                                    </label>
                                    <div class="input-with-icon">
                                        <input
                                            :type="showPassword ? 'text' : 'password'"
                                            class="form-input"
                                            style="padding-right:38px"
                                            v-model="form.password"
                                            :placeholder="editing ? '••••••••••••' : 'Your Client Secret'"
                                            autocomplete="new-password"
                                            :class="{ 'is-invalid': errors.password }"
                                        >
                                        <button type="button" class="input-icon input-icon--right input-icon--btn" @click="showPassword = !showPassword" tabindex="-1">
                                            <svg v-if="!showPassword" 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="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                                            <svg v-else 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="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88"/></svg>
                                        </button>
                                    </div>
                                    <p class="form-hint">Stored encrypted (AES-256-CBC) in the database.</p>
                                    <span v-if="errors.password" class="form-error">{{ errors.password }}</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="form-label">Authorized Redirect URI</label>
                                <input type="text" class="form-input" :value="googleRedirectUri" readonly style="background:#f3f4f6;color:#6b7280">
                                <p class="form-hint">
                                    *** It is very important to put <strong>{{ googleRedirectUri }}</strong> in the <strong>Authorized Redirect URIs</strong> option in the Google Cloud project.
                                </p>
                            </div>

                            <div style="text-align:center;padding:20px 0 4px">
                                <template v-if="form.oauth.refresh_token">
                                    <p style="color:#059669;font-weight:600;margin:0 0 12px">✓ Connected to Google as {{ form.oauth.google_email }}</p>
                                    <button type="button" class="btn btn-outline" :disabled="googleAuthBusy" @click="authenticateWithGoogle">
                                        {{ googleAuthBusy ? 'Connecting…' : 'Re-authenticate with Google' }}
                                    </button>
                                </template>
                                <template v-else>
                                    <p style="font-weight:600;margin:0 0 12px">Please authenticate with Google to get an Access Token</p>
                                    <button type="button" class="btn btn-primary" :disabled="googleAuthBusy" @click="authenticateWithGoogle">
                                        {{ googleAuthBusy ? 'Waiting for Google…' : 'Authenticate with Google & Get Access Token' }}
                                    </button>
                                </template>
                                <p v-if="googleAuthError" class="form-error" style="margin-top:10px">{{ googleAuthError }}</p>
                                <p v-if="editing && editing.oauth_connected && !form.oauth.refresh_token" class="form-hint" style="margin-top:10px">
                                    Currently connected as {{ editing.google_email }} - re-authenticate above only if you need to reconnect or grant access again.
                                </p>
                            </div>
                        </div>

                        <!-- ── Outlook / Office365 API Settings ── -->
                        <div v-else-if="form.provider === 'outlook'" class="smtp-section">
                            <div class="smtp-section-title">Outlook / Office365 API Settings</div>
                            <p class="form-hint" style="margin-top:0">
                                Please <a href="https://learn.microsoft.com/en-us/graph/auth-register-app-v2" target="_blank" rel="noopener" class="smtp-help-link" style="margin-top:0;display:inline">check the documentation</a> first to create API keys at Microsoft.
                            </p>

                            <div class="form-row">
                                <div class="form-group">
                                    <label class="form-label">Application Client ID <span class="required">*</span></label>
                                    <input type="text" class="form-input" v-model="form.username" placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" autocomplete="off" :class="{ 'is-invalid': errors.username }">
                                    <span v-if="errors.username" class="form-error">{{ errors.username }}</span>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">
                                        Application Client Secret <span class="required">*</span>
                                        <span v-if="editing" class="form-label-hint">(leave blank to keep current)</span>
                                    </label>
                                    <div class="input-with-icon">
                                        <input
                                            :type="showPassword ? 'text' : 'password'"
                                            class="form-input"
                                            style="padding-right:38px"
                                            v-model="form.password"
                                            :placeholder="editing ? '••••••••••••' : 'Your Client Secret'"
                                            autocomplete="new-password"
                                            :class="{ 'is-invalid': errors.password }"
                                        >
                                        <button type="button" class="input-icon input-icon--right input-icon--btn" @click="showPassword = !showPassword" tabindex="-1">
                                            <svg v-if="!showPassword" 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="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                                            <svg v-else 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="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88"/></svg>
                                        </button>
                                    </div>
                                    <p class="form-hint">Stored encrypted (AES-256-CBC) in the database.</p>
                                    <span v-if="errors.password" class="form-error">{{ errors.password }}</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="form-label">App Callback URL (Use this URL in your App)</label>
                                <input type="text" class="form-input" :value="microsoftRedirectUri" readonly style="background:#f3f4f6;color:#6b7280">
                                <p class="form-hint">
                                    *** It is very important to add <strong>{{ microsoftRedirectUri }}</strong> as a <strong>Redirect URI</strong> on the Microsoft Entra app registration (platform type: Web).
                                </p>
                            </div>

                            <div style="text-align:center;padding:20px 0 4px">
                                <template v-if="form.oauth.refresh_token">
                                    <p style="color:#059669;font-weight:600;margin:0 0 12px">✓ Connected to Microsoft as {{ form.oauth.microsoft_email }}</p>
                                    <button type="button" class="btn btn-outline" :disabled="microsoftAuthBusy" @click="authenticateWithMicrosoft">
                                        {{ microsoftAuthBusy ? 'Connecting…' : 'Re-authenticate with Office365' }}
                                    </button>
                                </template>
                                <template v-else>
                                    <p style="font-weight:600;margin:0 0 12px">Please authenticate with Office365 to get an Access Token</p>
                                    <button type="button" class="btn btn-primary" :disabled="microsoftAuthBusy" @click="authenticateWithMicrosoft">
                                        {{ microsoftAuthBusy ? 'Waiting for Microsoft…' : 'Authenticate with Office365 & Get Access Token' }}
                                    </button>
                                </template>
                                <p v-if="microsoftAuthError" class="form-error" style="margin-top:10px">{{ microsoftAuthError }}</p>
                                <p v-if="editing && editing.oauth_connected && !form.oauth.refresh_token" class="form-hint" style="margin-top:10px">
                                    Currently connected as {{ editing.microsoft_email }} - re-authenticate above only if you need to reconnect or grant access again.
                                </p>
                            </div>
                        </div>

                        <!-- ── API Settings (single-key providers: SendGrid, Brevo, …) ── -->
                        <div v-else-if="apiKeyConfig" class="smtp-section">
                            <div class="smtp-section-title">{{ apiKeyConfig.section }}</div>
                            <div class="form-group">
                                <label class="form-label">
                                    API Key <span class="required">*</span>
                                    <span v-if="editing" class="form-label-hint">(leave blank to keep current)</span>
                                </label>
                                <div class="input-with-icon">
                                    <input
                                        :type="showPassword ? 'text' : 'password'"
                                        class="form-input"
                                        style="padding-right:38px"
                                        v-model="form.password"
                                        :placeholder="editing ? '••••••••••••' : apiKeyConfig.placeholder"
                                        autocomplete="new-password"
                                        :class="{ 'is-invalid': errors.password }"
                                    >
                                    <button type="button" class="input-icon input-icon--right input-icon--btn" @click="showPassword = !showPassword" tabindex="-1">
                                        <svg v-if="!showPassword" 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="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                                        <svg v-else 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="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88"/></svg>
                                    </button>
                                </div>
                                <p class="form-hint">
                                    Stored encrypted (AES-256-CBC) in the database.
                                    Follow this link to get an API Key from {{ currentProvider.name }}:
                                    <a :href="apiKeyConfig.keyUrl" target="_blank" rel="noopener" class="smtp-help-link" style="margin-top:0">{{ apiKeyConfig.keyLinkText }}</a>.
                                    {{ apiKeyConfig.note }}
                                </p>
                                <span v-if="errors.password" class="form-error">{{ errors.password }}</span>
                            </div>
                        </div>

                        <!-- ── Profile ── -->
                        <div class="smtp-section">
                            <div class="smtp-section-title">Profile</div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label class="form-label">Connection name <span class="required">*</span></label>
                                    <input type="text" class="form-input" v-model="form.name" placeholder="e.g. Marketing SMTP" :class="{ 'is-invalid': errors.name }">
                                    <span v-if="errors.name" class="form-error">{{ errors.name }}</span>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Max emails per hour</label>
                                    <input type="number" class="form-input" v-model.number="form.max_per_hour" min="1">
                                    <p class="form-hint">Prevents exceeding your provider's quota.</p>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="form-check-label">
                                    <input type="checkbox" v-model="form.is_default" class="form-checkbox">
                                    Set as default connection
                                </label>
                            </div>
                        </div>

                        <!-- Help: where do I get these values? -->
                        <div class="smtp-help">
                            <div class="smtp-help-title">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="16" height="16"><path stroke-linecap="round" stroke-linejoin="round" d="M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9 5.25h.008v.008H12v-.008z"/></svg>
                                {{ helpContent.title }}
                            </div>
                            <ol class="smtp-help-list">
                                <li v-for="(item, i) in helpContent.items" :key="i">{{ item }}</li>
                            </ol>
                            <a v-if="helpContent.link" :href="helpContent.link" target="_blank" rel="noopener" class="smtp-help-link">
                                {{ helpContent.linkText }}
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="12" height="12"><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>
                            </a>
                        </div>

                        <!-- Test result -->
                        <div v-if="testResult" class="smtp-test-result" :class="testResult.success ? 'smtp-test-result--success' : 'smtp-test-result--error'">
                            <svg v-if="testResult.success" 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="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                            <svg v-else 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>
                            {{ testResult.message }}
                        </div>
                    </div>

                    <div class="modal-footer" :style="modalStep === 'form' ? 'justify-content:space-between' : 'justify-content:flex-end'">
                        <button v-if="modalStep === 'form'" class="btn btn-outline" :disabled="testing" @click="testConnection">
                            <span v-if="testing" 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="1.8" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5"/></svg>
                            {{ testing ? 'Testing…' : 'Test connection' }}
                        </button>
                        <div style="display:flex;gap:10px">
                            <!-- <button class="btn btn-outline" @click="closeModal">Cancel</button> -->
                            <button v-if="modalStep === 'form'" class="btn btn-primary" :disabled="saving" @click="save">
                                <span v-if="saving" 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>
                                {{ saving ? 'Saving…' : 'Save Connection Settings' }}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </Teleport>

        <!-- Send test email modal -->
        <Teleport to="body">
            <div class="modal-overlay" :class="{ 'is-open': showTestModal }" @click.self="closeSendTest">
                <div class="modal" style="width:460px;max-width:96vw">
                    <div class="modal-header">
                        <div>
                            <h3 class="modal-title">Send Test Email</h3>
                            <p class="modal-subtitle" v-if="testTarget">via {{ testTarget.name }} ({{ testTarget.host }})</p>
                        </div>
                        <button class="modal-close" @click="closeSendTest">
                            <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">
                        <div class="form-group">
                            <label class="form-label">Send to</label>
                            <input type="email" class="form-input" v-model="testRecipient" placeholder="recipient@example.com" @keyup.enter="doSendTest">
                            <p class="form-hint">Leave blank to send to your own account email.</p>
                        </div>
                        <div v-if="testModalResult" class="smtp-test-result" :class="testModalResult.success ? 'smtp-test-result--success' : 'smtp-test-result--error'">
                            <svg v-if="testModalResult.success" 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="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                            <svg v-else 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>
                            {{ testModalResult.message }}
                        </div>
                    </div>
                    <div class="modal-footer" style="justify-content:flex-end;gap:10px">
                        <button class="btn btn-outline" @click="closeSendTest">Close</button>
                        <button class="btn btn-primary" :disabled="testSending" @click="doSendTest">
                            {{ testSending ? 'Sending…' : 'Send test email' }}
                        </button>
                    </div>
                </div>
            </div>
        </Teleport>

        <!-- Delete confirm modal -->
        <Teleport to="body">
            <div class="modal-overlay" :class="{ 'is-open': showDeleteModal }" @click.self="showDeleteModal = false">
                <div class="modal" style="width:440px;max-width:96vw">
                    <div class="modal-header">
                        <h3 class="modal-title">Delete Connection</h3>
                        <button class="modal-close" @click="showDeleteModal = false">
                            <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="color:#374151">Are you sure you want to delete <strong>{{ deletingConfig?.name }}</strong>? This action cannot be undone.</p>
                    </div>
                    <div class="modal-footer" style="justify-content:flex-end;gap:10px">
                        <button class="btn btn-outline" @click="showDeleteModal = false">Cancel</button>
                        <button class="btn btn-danger" @click="doDelete">Delete</button>
                    </div>
                </div>
            </div>
        </Teleport>
    </AppLayout>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue';
import { Head } from '@inertiajs/vue3';
import { router } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';
import { useTenantTimezone } from '@/Composables/useTenantTimezone';

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

// ── Providers ────────────────────────────────────────────────────
// Only "Other SMTP" is implemented so far; the rest are rolled out one by one.
const providers = [
    { slug: 'smtp',      name: 'Other SMTP',       tag: 'SMTP', color: '#2563eb', active: true  },
    { slug: 'ses',       name: 'Amazon SES',       tag: 'aws',  color: '#232f3e', active: true  },
    { slug: 'mailgun',   name: 'Mailgun',          tag: 'MG',   color: '#c02428', active: true  },
    { slug: 'sendgrid',  name: 'SendGrid',         tag: 'SG',   color: '#1a82e2', active: true  },
    { slug: 'brevo',     name: 'Brevo',            tag: 'Br',   color: '#0b996e', active: true  },
    { slug: 'sparkpost', name: 'SparkPost',        tag: 'SP',   color: '#fa6423', active: true  },
    { slug: 'netcore',   name: 'Netcore',          tag: 'NC',   color: '#143f93', active: true  },
    { slug: 'postmark',  name: 'Postmark',         tag: 'PM',   color: '#f4bb00', active: true  },
    { slug: 'elastic',   name: 'Elastic Email',    tag: 'EE',   color: '#2c3e94', active: true  },
    { slug: 'smtp2go',   name: 'SMTP2GO',          tag: '2GO',  color: '#10b3ae', active: true  },
    { slug: 'gmail',     name: 'Google Workspace', tag: 'G',    color: '#ea4335', active: true  },
    { slug: 'outlook',   name: 'Microsoft',        tag: 'MS',   color: '#0078d4', active: true  },
    { slug: 'tosend',    name: 'toSend',           tag: 'tS',   color: '#111827', active: true  },
    { slug: 'phpmail',   name: 'PHP Mail',         tag: 'php',  color: '#777bb3', active: true  },
];

function providerName(slug) {
    return providers.find(p => p.slug === slug)?.name ?? 'SMTP';
}
const currentProvider = computed(() => providers.find(p => p.slug === form.provider) ?? providers[0]);

// ── Single-API-key providers: form section config ────────────────
const API_KEY_FORMS = {
    sendgrid: {
        section:     'SendGrid API Settings',
        placeholder: 'SG.xxxxxxxxxxxxxxxx',
        keyUrl:      'https://app.sendgrid.com/settings/api_keys',
        keyLinkText: 'Create API Key',
        note:        'To send emails you will need only a Mail Send access level for this API key.',
    },
    brevo: {
        section:     'Brevo API Settings',
        placeholder: 'xkeysib-xxxxxxxxxxxx',
        keyUrl:      'https://app.brevo.com/settings/keys/api',
        keyLinkText: 'Get v3 API Key',
        note:        'Use a v3 API key - Brevo SMTP keys will not work with the API.',
    },
    sparkpost: {
        section:     'SparkPost API Settings',
        placeholder: 'Your SparkPost API Key',
        keyUrl:      'https://app.sparkpost.com/account/api-keys',
        keyLinkText: 'Get API Key',
        note:        'This key needs the "Transmissions: Read/Write" permission.',
    },
    netcore: {
        section:     'Pepipost API Settings',
        placeholder: 'Your Netcore (Pepipost) API Key',
        keyUrl:      'https://emaildocs.netcorecloud.com/docs/getting-started',
        keyLinkText: 'Get API Key',
        note:        'Uses the Netcore (Pepipost) v5 Email API.',
    },
    smtp2go: {
        section:     'SMTP2GO API Settings',
        placeholder: 'api-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXX',
        keyUrl:      'https://app.smtp2go.com/settings/api-keys/new/',
        keyLinkText: 'Create API Key',
        note:        'This key needs "Email Sending" permission.',
    },
    tosend: {
        section:     'ToSend API Settings',
        placeholder: 'tosend_xxxxxxx',
        keyUrl:      'https://dash.tosend.com/',
        keyLinkText: 'Get API Key',
        note:        'Get your API key from your toSend dashboard.',
    },
};
const apiKeyConfig = computed(() => API_KEY_FORMS[form.provider] ?? null);

// ── Amazon SES regions ───────────────────────────────────────────
const sesRegions = [
    { value: 'us-east-1',      label: 'US East (N. Virginia)' },
    { value: 'us-east-2',      label: 'US East (Ohio)' },
    { value: 'us-west-1',      label: 'US West (N. California)' },
    { value: 'us-west-2',      label: 'US West (Oregon)' },
    { value: 'af-south-1',     label: 'Africa (Cape Town)' },
    { value: 'ap-south-1',     label: 'Asia Pacific (Mumbai)' },
    { value: 'ap-northeast-1', label: 'Asia Pacific (Tokyo)' },
    { value: 'ap-northeast-2', label: 'Asia Pacific (Seoul)' },
    { value: 'ap-northeast-3', label: 'Asia Pacific (Osaka)' },
    { value: 'ap-southeast-1', label: 'Asia Pacific (Singapore)' },
    { value: 'ap-southeast-2', label: 'Asia Pacific (Sydney)' },
    { value: 'ca-central-1',   label: 'Canada (Central)' },
    { value: 'eu-central-1',   label: 'Europe (Frankfurt)' },
    { value: 'eu-west-1',      label: 'Europe (Ireland)' },
    { value: 'eu-west-2',      label: 'Europe (London)' },
    { value: 'eu-west-3',      label: 'Europe (Paris)' },
    { value: 'eu-north-1',     label: 'Europe (Stockholm)' },
    { value: 'eu-south-1',     label: 'Europe (Milan)' },
    { value: 'me-south-1',     label: 'Middle East (Bahrain)' },
    { value: 'sa-east-1',      label: 'South America (São Paulo)' },
];

// ── Help content ("where do I get these?") per provider ─────────
const helpContent = computed(() => {
    if (form.provider === 'brevo') {
        return {
            title: 'How to get your Brevo API key',
            items: [
                'Sign in to Brevo and click your account name (top right) → SMTP & API.',
                'Open the "API Keys" tab and click "Generate a new API key" (a v3 key). Copy it right away - it is shown only once.',
                'Verify your From address under Senders & IP → Senders, or authenticate your whole domain with DNS records (recommended for deliverability).',
                'Free accounts are limited to 300 emails per day - set the rate limit below accordingly.',
            ],
            link: 'https://developers.brevo.com/docs/getting-started',
            linkText: 'Read the Brevo documentation',
        };
    }
    if (form.provider === 'sendgrid') {
        return {
            title: 'How to get your SendGrid API key',
            items: [
                'Sign in to SendGrid and open Settings → API Keys, then click "Create API Key".',
                'Choose "Restricted Access" and enable only the Mail Send permission - that is all this connection needs.',
                'Copy the key immediately (SendGrid shows it only once) and paste it into the field above.',
                'Verify your From address under Settings → Sender Authentication - authenticate your domain (recommended) or verify a single sender. Unverified senders are rejected.',
            ],
            link: 'https://www.twilio.com/docs/sendgrid/for-developers/sending-email/getting-started-email-web',
            linkText: 'Read the SendGrid documentation',
        };
    }
    if (form.provider === 'mailgun') {
        return {
            title: 'How to get your Mailgun credentials',
            items: [
                'Sign in to your Mailgun account and open Settings → API Security to create or copy a Private API key.',
                'Your sending Domain Name is listed under Sending → Domains (e.g. mg.yourdomain.com). Add it there and verify it with the DNS records Mailgun provides.',
                'Pick the region that matches where your Mailgun domain was created - US or EU. Emails fail with a 404 error if the region does not match.',
                'New accounts can only send to authorized recipients until the account is upgraded - add test recipients under Sending → Authorized Recipients.',
            ],
            link: 'https://documentation.mailgun.com/docs/mailgun/user-manual/get-started/',
            linkText: 'Read the Mailgun documentation',
        };
    }
    if (form.provider === 'gmail') {
        return {
            title: 'How to connect Gmail / Google Workspace',
            items: [
                'In the Google Cloud Console, create (or select) a project, then enable the "Gmail API" under APIs & Services → Library.',
                'Under APIs & Services → Credentials, create an OAuth Client ID of type "Web application".',
                'Add the Authorized Redirect URI shown above to that OAuth Client - it must match exactly or Google will reject the authentication.',
                'Copy the Client ID and Client Secret into the fields above, then click "Authenticate with Google & Get Access Token" and grant access in the popup.',
                'While your OAuth consent screen is in "Testing" mode, only accounts you explicitly add as test users can authenticate - publish the app (or add test users) under OAuth consent screen settings.',
            ],
            link: 'https://developers.google.com/gmail/api/quickstart/php',
            linkText: 'Read the Gmail API documentation',
        };
    }
    if (form.provider === 'outlook') {
        return {
            title: 'How to connect Outlook / Office365',
            items: [
                'In the Microsoft Entra admin center (or Azure Portal), go to App registrations → New registration.',
                'Set the platform to "Web" and add the App Callback URL shown above as a Redirect URI - it must match exactly or Microsoft will reject the authentication.',
                'Under Certificates & secrets, create a new Client Secret and copy its value immediately - Microsoft shows it only once.',
                'Under API permissions, add Microsoft Graph delegated permissions "Mail.Send", "User.Read" and "offline_access" (offline_access is required for a refresh token).',
                'Copy the Application (client) ID and Client Secret into the fields above, then click "Authenticate with Office365 & Get Access Token" and sign in in the popup.',
                'While the app is unverified, only accounts within your own tenant (or accounts you add as test users) may be able to consent, depending on your Azure AD configuration.',
            ],
            link: 'https://learn.microsoft.com/en-us/graph/auth-register-app-v2',
            linkText: 'Read the Microsoft Graph authentication documentation',
        };
    }
    if (form.provider === 'phpmail') {
        return {
            title: 'About PHP Mail',
            items: [
                'No API key or SMTP credentials are needed - this uses your server\'s local mail agent directly.',
                'On Linux/macOS hosts this is the sendmail_path configured in php.ini. On Windows it uses the SMTP and smtp_port settings in php.ini.',
                'Deliverability is typically poor (no authentication, easily flagged as spam) - use a real SMTP or API provider connection above for anything user-facing.',
            ],
            link: null,
            linkText: null,
        };
    }
    if (form.provider === 'tosend') {
        return {
            title: 'How to get your toSend API key',
            items: [
                'Sign in to the toSend dashboard and open API Keys, then create a new key.',
                'Copy the key (it starts with "tosend_") and paste it into the field above - it is stored encrypted.',
                'Verify your sending domain under Domains before sending - unverified domains are rejected.',
            ],
            link: 'https://tosend.com/docs/api/introduction/',
            linkText: 'Read the toSend documentation',
        };
    }
    if (form.provider === 'smtp2go') {
        return {
            title: 'How to get your SMTP2GO API key',
            items: [
                'Sign in to SMTP2GO and open Settings → API Keys, then click "Add API Key".',
                'Grant it "Email Sending" permission - that is all this connection needs.',
                'Copy the key immediately (SMTP2GO shows it only once) and paste it into the field above.',
                'Verify your From domain or email address under Sender Domains / Verified Senders - unverified senders are rejected.',
            ],
            link: 'https://developers.smtp2go.com/docs/introduction-guide',
            linkText: 'Read the SMTP2GO documentation',
        };
    }
    if (form.provider === 'elastic') {
        return {
            title: 'How to get your Elastic Email API key',
            items: [
                'Sign in to Elastic Email and open Settings → API, then create a new API key.',
                'Copy the key and paste it into the field above - it is stored encrypted.',
                'Verify your From domain or email address under Settings → Domains - unverified senders may be rejected or throttled.',
                'Pick "Transactional" for one-to-one account emails (receipts, resets) or "Marketing" for bulk/promotional sends - this affects deliverability rules and compliance requirements on Elastic Email\'s side.',
            ],
            link: 'https://elasticemail.com/developers/api-documentation/rest-api',
            linkText: 'Read the Elastic Email documentation',
        };
    }
    if (form.provider === 'postmark') {
        return {
            title: 'How to get your Postmark Server API Token',
            items: [
                'Sign in to Postmark and open Servers, then select (or create) the server you want to send from.',
                'Open the "API Tokens" tab on that server and copy the Server API Token.',
                'Verify your From signature or authenticate your whole domain under Sender Signatures / Domains - unverified senders are rejected.',
                'The Message Stream must match one configured on this server - "outbound" is the default transactional stream.',
            ],
            link: 'https://postmarkapp.com/support/article/1002-what-are-message-streams',
            linkText: 'Read the Postmark documentation',
        };
    }
    if (form.provider === 'netcore') {
        return {
            title: 'How to get your Netcore (Pepipost) API key',
            items: [
                'Sign in to the Netcore Cloud dashboard and open Settings → API Keys, then create a new key.',
                'Copy the key and paste it into the field above - it is stored encrypted.',
                'Add and verify a Sending Domain under Domain Management before sending - unverified domains are rejected.',
                'New accounts may need sending credits provisioned before mail is delivered.',
            ],
            link: 'https://emaildocs.netcorecloud.com/docs/getting-started',
            linkText: 'Read the Netcore Email API documentation',
        };
    }
    if (form.provider === 'sparkpost') {
        return {
            title: 'How to get your SparkPost API key',
            items: [
                'Sign in to SparkPost and open Account → API Keys, then click "Create API Key".',
                'Grant the key "Transmissions: Read/Write" permission - that is all this connection needs.',
                'Copy the key immediately (SparkPost shows it only once) and paste it into the field above.',
                'Verify your From domain under Account → Sending Domains - unverified domains are rejected or heavily rate-limited.',
            ],
            link: 'https://support.sparkpost.com/getting-started',
            linkText: 'Read the SparkPost documentation',
        };
    }
    if (form.provider === 'ses') {
        return {
            title: 'How to get your Amazon SES credentials',
            items: [
                'Sign in to the AWS Console and open IAM → Users → Create user (programmatic access).',
                'Attach a policy that allows ses:SendEmail and ses:SendRawEmail (e.g. AmazonSESFullAccess).',
                'Copy the generated Access Key ID and Secret Access Key into the fields above.',
                'In the SES console, verify your From domain or email address - in the same region you select here.',
                'New SES accounts start in sandbox mode (you can only send to verified addresses). Request production access from the SES console to send to anyone.',
            ],
            link: 'https://docs.aws.amazon.com/ses/latest/dg/setting-up.html',
            linkText: 'Read the Amazon SES documentation',
        };
    }
    return {
        title: 'Where do I find these settings?',
        items: [
            'Your email provider’s dashboard lists the SMTP credentials. For example - SendGrid: Settings → API Keys (username is "apikey"); Mailgun: Sending → Domain settings → SMTP credentials; Postmark: Servers → Credentials.',
            'Common ports: 587 (TLS/STARTTLS), 465 (SSL), 25 (usually unencrypted and often blocked by hosts).',
            'The From Email should be an address on a domain you have verified with your provider - otherwise emails may be rejected or land in spam.',
        ],
        link: null,
        linkText: null,
    };
});

// ── Modal state ──────────────────────────────────────────────────
const showModal    = ref(false);
const modalStep    = ref('provider'); // 'provider' | 'form'
const editing      = ref(null);       // config object when editing, null when creating
const showPassword = ref(false);
const testing      = ref(false);
const saving       = ref(false);
const testResult   = ref(null);
const errors       = ref({});

// ── Gmail / Google Workspace OAuth2 (popup window flow) ───────────
const googleRedirectUri = route('smtp.google.callback');
const googleAuthBusy    = ref(false);
const googleAuthError   = ref(null);
let googleAuthWindow    = null;
let googleAuthPoll      = null;

function handleGoogleAuthMessage(event) {
    if (event.origin !== window.location.origin) return;
    if (!event.data || event.data.type !== 'google-oauth-result') return;

    window.removeEventListener('message', handleGoogleAuthMessage);
    clearInterval(googleAuthPoll);
    googleAuthBusy.value = false;

    if (event.data.success) {
        googleAuthError.value = null;
        form.oauth = {
            refresh_token: event.data.refreshToken,
            access_token:  event.data.accessToken,
            expires_at:    event.data.expiresAt,
            google_email:  event.data.googleEmail,
        };
    } else {
        googleAuthError.value = event.data.message || 'Authentication with Google failed.';
    }
}

async function authenticateWithGoogle() {
    if (googleAuthBusy.value) return;
    googleAuthError.value = null;

    if (!form.username || !form.password) {
        googleAuthError.value = 'Enter the Application Client ID and Client Secret first.';
        return;
    }

    googleAuthBusy.value = true;

    try {
        const res = await window.axios.post(route('smtp.google.start'), {
            client_id:     form.username,
            client_secret: form.password,
        });

        googleAuthWindow = window.open(res.data.url, 'google-oauth', 'width=520,height=650');

        if (!googleAuthWindow) {
            googleAuthBusy.value  = false;
            googleAuthError.value = 'Your browser blocked the Google sign-in popup - please allow popups for this site and try again.';
            return;
        }

        window.addEventListener('message', handleGoogleAuthMessage);

        clearInterval(googleAuthPoll);
        googleAuthPoll = setInterval(() => {
            if (googleAuthWindow && googleAuthWindow.closed) {
                clearInterval(googleAuthPoll);
                window.removeEventListener('message', handleGoogleAuthMessage);
                googleAuthBusy.value = false;
            }
        }, 500);
    } catch (err) {
        googleAuthBusy.value  = false;
        googleAuthError.value = err.response?.data?.message ?? 'Could not start Google authentication.';
    }
}

// ── Outlook / Office365 OAuth2 (popup window flow) ────────────────
const microsoftRedirectUri = route('smtp.microsoft.callback');
const microsoftAuthBusy    = ref(false);
const microsoftAuthError   = ref(null);
let microsoftAuthWindow    = null;
let microsoftAuthPoll      = null;

function handleMicrosoftAuthMessage(event) {
    if (event.origin !== window.location.origin) return;
    if (!event.data || event.data.type !== 'microsoft-oauth-result') return;

    window.removeEventListener('message', handleMicrosoftAuthMessage);
    clearInterval(microsoftAuthPoll);
    microsoftAuthBusy.value = false;

    if (event.data.success) {
        microsoftAuthError.value = null;
        form.oauth = {
            refresh_token:   event.data.refreshToken,
            access_token:    event.data.accessToken,
            expires_at:      event.data.expiresAt,
            microsoft_email: event.data.accountEmail,
        };
    } else {
        microsoftAuthError.value = event.data.message || 'Authentication with Microsoft failed.';
    }
}

async function authenticateWithMicrosoft() {
    if (microsoftAuthBusy.value) return;
    microsoftAuthError.value = null;

    if (!form.username || !form.password) {
        microsoftAuthError.value = 'Enter the Application Client ID and Client Secret first.';
        return;
    }

    microsoftAuthBusy.value = true;

    try {
        const res = await window.axios.post(route('smtp.microsoft.start'), {
            client_id:     form.username,
            client_secret: form.password,
        });

        microsoftAuthWindow = window.open(res.data.url, 'microsoft-oauth', 'width=520,height=650');

        if (!microsoftAuthWindow) {
            microsoftAuthBusy.value  = false;
            microsoftAuthError.value = 'Your browser blocked the Microsoft sign-in popup - please allow popups for this site and try again.';
            return;
        }

        window.addEventListener('message', handleMicrosoftAuthMessage);

        clearInterval(microsoftAuthPoll);
        microsoftAuthPoll = setInterval(() => {
            if (microsoftAuthWindow && microsoftAuthWindow.closed) {
                clearInterval(microsoftAuthPoll);
                window.removeEventListener('message', handleMicrosoftAuthMessage);
                microsoftAuthBusy.value = false;
            }
        }, 500);
    } catch (err) {
        microsoftAuthBusy.value  = false;
        microsoftAuthError.value = err.response?.data?.message ?? 'Could not start Microsoft authentication.';
    }
}

const emptyForm = () => ({
    provider:          'smtp',
    name:              '',
    host:              '',
    port:              587,
    encryption:        'tls',
    region:            'us-east-1',
    domain:            '',
    message_stream:    'outbound',
    track_opens:       false,
    track_links:       false,
    email_type:        'transactional',
    oauth:             { refresh_token: null, access_token: null, expires_at: null, google_email: null, microsoft_email: null },
    auto_tls:          true,
    auth_enabled:      true,
    username:          '',
    password:          '',
    from_email:        '',
    from_name:         '',
    force_from_email:  true,
    force_from_name:   false,
    return_path_match: true,
    max_per_hour:      500,
    is_default:        false,
});

const form = reactive(emptyForm());

function openCreate() {
    editing.value        = null;
    showPassword.value   = false;
    testResult.value     = null;
    errors.value         = {};
    googleAuthError.value    = null;
    microsoftAuthError.value = null;
    Object.assign(form, emptyForm());
    modalStep.value    = 'provider';
    showModal.value    = true;
}

function selectProvider(p) {
    if (!p.active) return;
    form.provider = p.slug;
    // Provider-appropriate region default
    if (p.slug === 'ses')     form.region = 'us-east-1';
    if (p.slug === 'mailgun') form.region = 'us';
    modalStep.value = 'form';
}

function openEdit(config) {
    editing.value        = config;
    showPassword.value   = false;
    testResult.value     = null;
    errors.value         = {};
    googleAuthError.value    = null;
    microsoftAuthError.value = null;
    Object.assign(form, {
        provider:          config.provider ?? 'smtp',
        name:              config.name,
        host:              config.host,
        port:              config.port,
        encryption:        config.encryption,
        region:            config.region ?? (config.provider === 'mailgun' ? 'us' : 'us-east-1'),
        domain:            config.domain ?? '',
        message_stream:    config.message_stream ?? 'outbound',
        track_opens:       config.track_opens ?? false,
        track_links:       (config.track_links ?? 'None') !== 'None',
        email_type:        (config.is_transactional ?? true) ? 'transactional' : 'marketing',
        oauth:             { refresh_token: null, access_token: null, expires_at: null, google_email: null, microsoft_email: null },
        auto_tls:          config.auto_tls ?? true,
        auth_enabled:      config.auth_enabled ?? true,
        username:          config.username ?? '',
        password:          '',  // never pre-fill password
        from_email:        config.from_email ?? '',
        from_name:         config.from_name  ?? '',
        force_from_email:  config.force_from_email ?? true,
        force_from_name:   config.force_from_name ?? false,
        return_path_match: config.return_path_match ?? true,
        max_per_hour:      config.max_per_hour ?? 500,
        is_default:        config.is_default,
    });
    modalStep.value = 'form';
    showModal.value = true;
}

function closeModal() {
    showModal.value  = false;
    testResult.value = null;
    errors.value     = {};
}

// ── Test connection (from the form) ──────────────────────────────
async function testConnection() {
    if (testing.value) return;
    testResult.value = null;
    testing.value    = true;

    try {
        const payload = {
            provider:   form.provider,
            username:   form.username,
            password:   form.password,
            from_email: form.from_email || null,
            from_name:  form.from_name  || null,
        };

        if (form.provider === 'ses') {
            payload.settings = { region: form.region };
        } else if (form.provider === 'mailgun') {
            payload.settings = { domain: form.domain, region: form.region };
        } else if (form.provider === 'postmark') {
            payload.settings = {
                message_stream: form.message_stream || 'outbound',
                track_opens:    !!form.track_opens,
                track_links:    form.track_links ? 'HtmlAndText' : 'None',
            };
        } else if (form.provider === 'elastic') {
            payload.settings = { is_transactional: form.email_type !== 'marketing' };
        } else if (form.provider === 'gmail' || form.provider === 'outlook') {
            payload.oauth = form.oauth;
        } else if (form.provider === 'smtp') {
            payload.host         = form.host;
            payload.port         = form.port;
            payload.encryption   = form.encryption;
            payload.auto_tls     = form.auto_tls;
            payload.auth_enabled = form.auth_enabled;
        }

        if (editing.value && !form.password) {
            payload.id = editing.value.id;
        }

        const res = await window.axios.post(route('smtp.test'), payload);
        testResult.value = { success: true, message: res.data.message };
    } catch (err) {
        const msg = err.response?.data?.message ?? err.message ?? 'Connection failed.';
        testResult.value = { success: false, message: msg };
    } finally {
        testing.value = false;
    }
}

// ── Check connection (per card, saved profile) ───────────────────
const checkingId  = ref(null);
const cardResults = reactive({});

async function checkConnection(config) {
    if (checkingId.value) return;
    checkingId.value = config.id;
    delete cardResults[config.id];

    try {
        const res = await window.axios.post(route('smtp.test'), { id: config.id });
        cardResults[config.id] = { success: true, message: res.data.message };
    } catch (err) {
        cardResults[config.id] = { success: false, message: err.response?.data?.message ?? err.message ?? 'Connection failed.' };
    } finally {
        checkingId.value = null;
        router.reload({ only: ['configs'] });
    }
}

// ── Send test email (per card) ───────────────────────────────────
const showTestModal   = ref(false);
const testTarget      = ref(null);
const testRecipient   = ref('');
const testSending     = ref(false);
const testModalResult = ref(null);

function openSendTest(config) {
    openMenuId.value      = null;
    testTarget.value      = config;
    testRecipient.value   = '';
    testModalResult.value = null;
    showTestModal.value   = true;
}

function closeSendTest() {
    showTestModal.value = false;
    testTarget.value    = null;
}

async function doSendTest() {
    if (testSending.value || !testTarget.value) return;
    testModalResult.value = null;
    testSending.value     = true;

    try {
        const payload = { id: testTarget.value.id };
        if (testRecipient.value) payload.to = testRecipient.value;

        const res = await window.axios.post(route('smtp.test'), payload);
        testModalResult.value = { success: true, message: res.data.message };
    } catch (err) {
        testModalResult.value = { success: false, message: err.response?.data?.message ?? err.message ?? 'Sending failed.' };
    } finally {
        testSending.value = false;
        router.reload({ only: ['configs'] });
    }
}

// ── Save ─────────────────────────────────────────────────────────
function save() {
    if (saving.value) return;
    errors.value = {};
    saving.value = true;

    const payload = { ...form };
    delete payload.region;
    delete payload.domain;
    delete payload.message_stream;
    delete payload.track_opens;
    delete payload.track_links;
    delete payload.email_type;
    delete payload.oauth;
    if (form.provider === 'ses') {
        payload.settings = { region: form.region };
    } else if (form.provider === 'mailgun') {
        payload.settings = { domain: form.domain, region: form.region };
    } else if (form.provider === 'postmark') {
        payload.settings = {
            message_stream: form.message_stream || 'outbound',
            track_opens:    !!form.track_opens,
            track_links:    form.track_links ? 'HtmlAndText' : 'None',
        };
    } else if (form.provider === 'elastic') {
        payload.settings = { is_transactional: form.email_type !== 'marketing' };
    } else if (form.provider === 'gmail' || form.provider === 'outlook') {
        payload.oauth = form.oauth;
    }
    if (!payload.password) delete payload.password;

    if (editing.value) {
        router.put(route('smtp.update', editing.value.id), payload, {
            onSuccess: () => { saving.value = false; closeModal(); },
            onError: (errs) => { errors.value = errs; saving.value = false; },
        });
    } else {
        router.post(route('smtp.store'), payload, {
            onSuccess: () => { saving.value = false; closeModal(); },
            onError: (errs) => { errors.value = errs; saving.value = false; },
        });
    }
}

// ── Set default ──────────────────────────────────────────────────
function setDefault(config) {
    openMenuId.value = null;
    router.post(route('smtp.default', config.id));
}

// ── Delete ───────────────────────────────────────────────────────
const showDeleteModal = ref(false);
const deletingConfig  = ref(null);

function confirmDelete(config) {
    openMenuId.value  = null;
    deletingConfig.value = config;
    showDeleteModal.value = true;
}

function doDelete() {
    if (!deletingConfig.value) return;
    router.delete(route('smtp.destroy', deletingConfig.value.id), {
        onSuccess: () => { showDeleteModal.value = false; deletingConfig.value = null; },
    });
}

// ── Card dropdown menus ──────────────────────────────────────────
const openMenuId  = ref(null);
const cardMenuRef = ref({});

function toggleMenu(id) {
    openMenuId.value = openMenuId.value === id ? null : id;
}

function handleOutsideClick(e) {
    if (openMenuId.value === null) return;
    const wrap = cardMenuRef.value[openMenuId.value];
    if (wrap && !wrap.contains(e.target)) {
        openMenuId.value = null;
    }
}

onMounted(() => document.addEventListener('click', handleOutsideClick));
onBeforeUnmount(() => document.removeEventListener('click', handleOutsideClick));
onBeforeUnmount(() => {
    clearInterval(googleAuthPoll);
    window.removeEventListener('message', handleGoogleAuthMessage);
    clearInterval(microsoftAuthPoll);
    window.removeEventListener('message', handleMicrosoftAuthMessage);
});

// ── Helpers ──────────────────────────────────────────────────────
const { formatDateTime: formatDate } = useTenantTimezone();

function maskKey(key) {
    if (!key) return '-';
    return key.slice(0, 4) + '••••••••';
}

function rateLimit(config) {
    return config.max_per_hour ? config.max_per_hour + ' / hour' : '-';
}

function cardSubtitle(config) {
    if (config.provider === 'ses')      return `Amazon SES · ${config.region || 'us-east-1'} · AWS API`;
    if (config.provider === 'mailgun')  return `Mailgun · ${config.domain || '-'} · ${(config.region || 'us').toUpperCase()} endpoint`;
    if (config.provider === 'postmark') return `Postmark · ${config.message_stream || 'outbound'} · HTTP API`;
    if (config.provider === 'elastic')  return `Elastic Email · ${(config.is_transactional ?? true) ? 'Transactional' : 'Marketing'} · HTTP API`;
    if (config.provider === 'phpmail')  return 'PHP Mail · Native (no API key)';
    if (config.provider === 'gmail')    return `Gmail / Google Workspace · ${config.google_email || 'not connected'} · Gmail API`;
    if (config.provider === 'outlook')  return `Outlook / Office365 · ${config.microsoft_email || 'not connected'} · Graph API`;
    if (API_KEY_FORMS[config.provider]) return `${providerName(config.provider)} · HTTP API`;
    return `${config.host} · Port ${config.port} · ${(config.encryption || 'none').toUpperCase()}`;
}

function cardMeta(config) {
    if (config.provider === 'ses') {
        return [
            { label: 'Region',     value: config.region || 'us-east-1' },
            { label: 'Access Key', value: maskKey(config.username) },
            { label: 'Sends via',  value: 'AWS API' },
            { label: 'Rate limit', value: rateLimit(config) },
        ];
    }
    if (config.provider === 'mailgun') {
        return [
            { label: 'Domain',     value: config.domain || '-' },
            { label: 'Region',     value: (config.region || 'us').toUpperCase() },
            { label: 'Sends via',  value: 'Mailgun API' },
            { label: 'Rate limit', value: rateLimit(config) },
        ];
    }
    if (config.provider === 'postmark') {
        const tracking = [config.track_opens ? 'Opens' : null, config.track_links && config.track_links !== 'None' ? 'Links' : null].filter(Boolean);
        return [
            { label: 'Message Stream', value: config.message_stream || 'outbound' },
            { label: 'Tracking',       value: tracking.length ? tracking.join(' + ') : 'Off' },
            { label: 'Sends via',      value: 'Postmark API' },
            { label: 'Rate limit',     value: rateLimit(config) },
        ];
    }
    if (config.provider === 'elastic') {
        return [
            { label: 'API Key',    value: '••••••••' },
            { label: 'Email Type', value: (config.is_transactional ?? true) ? 'Transactional' : 'Marketing' },
            { label: 'Sends via',  value: 'Elastic Email API' },
            { label: 'Rate limit', value: rateLimit(config) },
        ];
    }
    if (config.provider === 'phpmail') {
        return [
            { label: 'Method',     value: 'PHP mail() / sendmail' },
            { label: 'API Key',    value: 'Not required' },
            { label: 'Sends via',  value: 'Local Mail Agent' },
            { label: 'Rate limit', value: rateLimit(config) },
        ];
    }
    if (config.provider === 'gmail') {
        return [
            { label: 'Account',    value: config.google_email || '-' },
            { label: 'Status',     value: config.oauth_connected ? 'Connected' : 'Not connected' },
            { label: 'Sends via',  value: 'Gmail API' },
            { label: 'Rate limit', value: rateLimit(config) },
        ];
    }
    if (config.provider === 'outlook') {
        return [
            { label: 'Account',    value: config.microsoft_email || '-' },
            { label: 'Status',     value: config.oauth_connected ? 'Connected' : 'Not connected' },
            { label: 'Sends via',  value: 'Microsoft Graph API' },
            { label: 'Rate limit', value: rateLimit(config) },
        ];
    }
    if (API_KEY_FORMS[config.provider]) {
        return [
            { label: 'API Key',    value: '••••••••' },
            { label: 'Endpoint',   value: config.host || '-' },
            { label: 'Sends via',  value: providerName(config.provider) + ' API' },
            { label: 'Rate limit', value: rateLimit(config) },
        ];
    }
    return [
        { label: 'Host',       value: config.host },
        { label: 'Port',       value: String(config.port) },
        { label: 'Encryption', value: (config.encryption || 'none').toUpperCase() + (config.auto_tls ? ' · Auto TLS' : '') },
        { label: 'Rate limit', value: rateLimit(config) },
    ];
}
</script>

<style scoped>
/* ── Cards ──────────────────────────────────────────────────── */
.smtp-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.smtp-card {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    overflow: hidden;
}

.smtp-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    border-bottom: 1px solid var(--border-color);
    gap: 12px;
    flex-wrap: wrap;
}

.smtp-card-header-info { flex: 1; min-width: 200px; }

.smtp-card-title {
    font-size: 14px;
    font-weight: 600;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.smtp-provider-badge {
    font-size: 11px;
    font-weight: 600;
    background: var(--bg-hover-strong);
    color: var(--text-secondary);
    border-radius: 20px;
    padding: 1px 8px;
}

.smtp-default-badge {
    font-size: 11px;
    font-weight: 600;
    background: var(--active-bg);
    color: var(--active-text);
    border: 1px solid var(--border-color);
    border-radius: 20px;
    padding: 1px 8px;
}

.smtp-card-subtitle {
    font-size: 12px;
    color: var(--text-secondary);
    margin-top: 2px;
}

.smtp-card-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.smtp-card-body {
    padding: 16px 20px;
}

.smtp-meta-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 10px;
}

@media (max-width: 768px) {
    .smtp-meta-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}
@media (max-width: 480px) {
    .smtp-meta-grid {
        grid-template-columns: 1fr;
    }
}

.smtp-meta-label {
    font-size: 11px;
    font-weight: 600;
    color: var(--text-muted);
    text-transform: uppercase;
    letter-spacing: .06em;
    margin-bottom: 4px;
}

.smtp-meta-value {
    font-size: 13px;
    color: var(--text-primary);
    font-weight: 500;
}

.smtp-meta-note { font-size: 11px; color: var(--text-muted); font-weight: 400; }

.smtp-from-row,
.smtp-tested-row {
    font-size: 12px;
    color: var(--text-muted);
    margin-top: 4px;
}

.smtp-from-row { display: flex; gap: 6px; align-items: center; }
.smtp-from-row .smtp-meta-label { margin-bottom: 0; }

/* ── Badge dot variants ─────────────────────────────────────── */
.badge-dot { display: inline-flex; align-items: center; gap: 5px; font-size: 12px; font-weight: 500; padding: 3px 8px; border-radius: 20px; }
.badge-dot::before { content: ''; width: 6px; height: 6px; border-radius: 50%; flex-shrink: 0; }
.badge-dot--online  { background: var(--success-light); color: var(--success); } .badge-dot--online::before  { background: var(--success); }
.badge-dot--error   { background: var(--danger-light); color: var(--danger); } .badge-dot--error::before   { background: var(--danger); }
.badge-dot--idle    { background: var(--bg-hover); color: var(--text-muted); } .badge-dot--idle::before    { background: var(--border-color); }

/* ── Provider grid ──────────────────────────────────────────── */
.prov-label {
    font-size: 12px;
    font-weight: 600;
    color: var(--text-muted);
    text-transform: uppercase;
    letter-spacing: .05em;
    margin-bottom: 12px;
}

.prov-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 10px;
}

.prov-tile {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 18px 10px 14px;
    background: var(--bg-surface);
    border: 1.5px solid var(--border-color);
    border-radius: 10px;
    cursor: pointer;
    transition: border-color .15s, background .15s, transform .1s;
}
.prov-tile:hover:not(:disabled) { border-color: var(--active-text); background: var(--bg-hover); }
.prov-tile.is-selected { border-color: var(--active-text); background: var(--active-bg); }
.prov-tile.is-disabled { cursor: not-allowed; opacity: .55; }

.prov-logo {
    width: 40px;
    height: 40px;
    border-radius: 9px;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 11px;
    font-weight: 800;
    letter-spacing: .02em;
}
.prov-logo--sm { width: 28px; height: 28px; border-radius: 7px; font-size: 9px; }

.prov-name {
    font-size: 12px;
    font-weight: 600;
    color: var(--text-secondary);
    text-align: center;
    line-height: 1.3;
}

.prov-soon {
    position: absolute;
    top: 6px;
    right: 6px;
    font-size: 9px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .05em;
    background: var(--warning-light);
    color: var(--warning);
    border-radius: 8px;
    padding: 1px 6px;
}

.prov-current {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 14px;
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    margin-bottom: 18px;
}
.prov-current-name { font-size: 13px; font-weight: 600; color: var(--text-primary); flex: 1; }
.prov-change-btn {
    border: none;
    background: none;
    font-size: 12px;
    font-weight: 500;
    color: var(--active-text);
    cursor: pointer;
    padding: 4px 6px;
}
.prov-change-btn:hover { text-decoration: underline; }

/* ── Form sections ──────────────────────────────────────────── */
.smtp-section {
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 16px 18px;
    margin-bottom: 16px;
}

.smtp-section-title {
    font-size: 13px;
    font-weight: 700;
    color: var(--text-primary);
    margin-bottom: 14px;
}

.smtp-inline-row {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
    padding: 10px 0;
}

.smtp-inline-label {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-secondary);
    display: flex;
    align-items: baseline;
    gap: 8px;
    flex-wrap: wrap;
}

.smtp-inline-hint {
    font-size: 12px;
    color: var(--text-muted);
    font-weight: 400;
    flex: 1;
    min-width: 200px;
}

.hint-i {
    color: var(--active-text);
    cursor: help;
    font-size: 12px;
}

/* ── Encryption radios ──────────────────────────────────────── */
.enc-options { display: flex; align-items: center; gap: 6px; }
.enc-opt {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    font-weight: 500;
    color: var(--text-secondary);
    border: 1.5px solid var(--border-color);
    border-radius: 20px;
    padding: 5px 14px;
    cursor: pointer;
    transition: border-color .12s, color .12s, background .12s;
}
.enc-opt input { accent-color: var(--active-text); margin: 0; }
.enc-opt:hover { border-color: var(--active-text); }
.enc-opt.is-active { border-color: var(--active-text); color: var(--active-text); background: var(--active-bg); }

/* ── Switch toggle ──────────────────────────────────────────── */
.switch { position: relative; display: inline-block; width: 38px; height: 22px; flex-shrink: 0; }
.switch input { display: none; }
.switch-slider {
    position: absolute;
    inset: 0;
    background: var(--bg-hover-strong);
    border-radius: 22px;
    cursor: pointer;
    transition: background .15s;
}
.switch-slider::before {
    content: '';
    position: absolute;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background: #fff;
    top: 3px;
    left: 3px;
    transition: transform .15s;
    box-shadow: 0 1px 2px rgba(0,0,0,.2);
}
.switch input:checked + .switch-slider { background: var(--active-text); }
.switch input:checked + .switch-slider::before { transform: translateX(16px); }

/* ── Empty state ────────────────────────────────────────────── */
.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: var(--text-secondary);
}
.empty-state-icon {
    width: 56px;
    height: 56px;
    background: var(--bg-hover-strong);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 16px;
    color: var(--text-muted);
}
.empty-state-icon svg { width: 28px; height: 28px; }
.empty-state h3 { font-size: 16px; font-weight: 600; color: var(--text-primary); margin: 0 0 8px; }
.empty-state p  { font-size: 13px; margin: 0 0 20px; }

/* ── Region note ────────────────────────────────────────────── */
.smtp-region-note {
    background: var(--bg-hover-strong);
    border-radius: 8px;
    padding: 10px 14px;
    font-size: 12px;
    color: var(--text-secondary);
    line-height: 1.5;
    margin-top: 4px;
}

/* ── Help box ───────────────────────────────────────────────── */
.smtp-help {
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 14px 18px;
}
.smtp-help-title {
    display: flex;
    align-items: center;
    gap: 7px;
    font-size: 13px;
    font-weight: 700;
    color: var(--text-secondary);
    margin-bottom: 10px;
}
.smtp-help-title svg { color: var(--text-muted); flex-shrink: 0; }
.smtp-help-list {
    margin: 0;
    padding-left: 18px;
    display: flex;
    flex-direction: column;
    gap: 6px;
}
.smtp-help-list li {
    font-size: 12.5px;
    color: var(--text-secondary);
    line-height: 1.55;
}
.smtp-help-link {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    margin-top: 10px;
    font-size: 12.5px;
    font-weight: 600;
    color: var(--active-text);
    text-decoration: none;
}
.smtp-help-link:hover { text-decoration: underline; }

/* ── Test result banner ─────────────────────────────────────── */
.smtp-test-result {
    display: flex;
    align-items: center;
    gap: 10px;
    border-radius: 8px;
    padding: 12px 16px;
    font-size: 13px;
    font-weight: 500;
    margin-top: 16px;
}
.smtp-test-result svg { width: 18px; height: 18px; flex-shrink: 0; }
.smtp-test-result--success { background: var(--success-light); color: var(--success); border: 1px solid var(--success-border); }
.smtp-test-result--error   { background: var(--danger-light); color: var(--danger); border: 1px solid var(--danger-border); }

/* ── Misc form helpers ──────────────────────────────────────── */
.form-label-hint { font-size: 11px; font-weight: 400; color: #9ca3af; }
.form-check-label { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--text-secondary); cursor: pointer; }
.form-checkbox { width: 15px; height: 15px; accent-color: var(--active-text); flex-shrink: 0; }

.input-with-icon { position: relative; }
.input-icon--btn {
    border: none;
    background: none;
    cursor: pointer;
    padding: 0;
    pointer-events: auto;
}

.spin-icon { display: inline-flex; animation: spin .7s linear infinite; }
.spin-icon svg { width: 14px; height: 14px; }
@keyframes spin { to { transform: rotate(360deg); } }
</style>
