'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { AlertTriangle, CheckCircle2, Info, KeyRound, Loader2, Send } from 'lucide-react';
import { useId } from 'react';
import { SettingsCard, SettingsSaveBar, SettingsToggleRow } from './components.js';
import { EMAIL_PROVIDER_OPTIONS, useEmailSettings, } from './useEmailSettings.js';
const INPUT_CLASS = 'w-full max-w-md rounded-md border border-border bg-input-background px-3 py-2 text-base text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-60';
const LABEL_CLASS = 'mb-1 block text-sm font-medium text-foreground';
const HELP_CLASS = 'mt-1 text-sm text-muted-foreground';
const PROVIDER_LABEL = {
    resend: 'Resend',
    smtpcom: 'SMTP.com',
    ses: 'Amazon SES',
    smtp: 'SMTP server',
};
function Field({ id, label, help, children, }) {
    return (_jsxs("div", { children: [_jsx("label", { htmlFor: id, className: LABEL_CLASS, children: label }), children, help && _jsx("p", { className: HELP_CLASS, children: help })] }));
}
function SecretField({ id, label, value, onChange, disabled, hasStored, last4, help, }) {
    return (_jsx(Field, { id: id, label: label, help: hasStored && !value
            ? `A ${label.toLowerCase()} is saved${last4 ? ` (ends in ${last4})` : ''}. Enter a new value to replace it.`
            : help, children: _jsxs("div", { className: "relative max-w-md", children: [_jsx(KeyRound, { size: 16, "aria-hidden": "true", className: "text-muted-foreground pointer-events-none absolute top-1/2 left-3 -translate-y-1/2" }), _jsx("input", { id: id, type: "password", autoComplete: "off", value: value, disabled: disabled, onChange: (e) => onChange(e.target.value), placeholder: hasStored ? `••••••••${last4 ? last4 : ''}` : 'Enter value', className: `${INPUT_CLASS} pl-9` })] }) }));
}
function Notice({ tone, children, }) {
    const toneClass = tone === 'warning'
        ? 'border-warning/30 bg-warning/10 text-warning'
        : tone === 'success'
            ? 'border-success/30 bg-success/10 text-success'
            : tone === 'error'
                ? 'border-destructive/30 bg-destructive/10 text-destructive'
                : 'border-border bg-muted text-muted-foreground';
    const Icon = tone === 'success' ? CheckCircle2 : tone === 'info' ? Info : AlertTriangle;
    return (_jsxs("div", { role: "status", "aria-live": "polite", className: `flex items-start gap-2.5 rounded-lg border p-3 text-sm ${toneClass}`, children: [_jsx(Icon, { size: 16, className: "mt-0.5 shrink-0", "aria-hidden": "true" }), _jsx("div", { className: "min-w-0", children: children })] }));
}
function ProviderFields({ s, canEdit }) {
    const ids = {
        from: useId(),
        apiKey: useId(),
        channel: useId(),
        region: useId(),
        host: useId(),
        port: useId(),
        user: useId(),
        pass: useId(),
    };
    const { form, setField, stored } = s;
    const disabled = !canEdit;
    if (form.provider === '')
        return null;
    const sameProvider = stored.sameProvider;
    return (_jsxs("div", { className: "space-y-4", children: [_jsx(Field, { id: ids.from, label: "Sender address", help: "The From address for invitations, password resets, and form notifications. Must be verified with your provider.", children: _jsx("input", { id: ids.from, type: "email", value: form.from, disabled: disabled, onChange: (e) => setField('from', e.target.value), placeholder: "noreply@yoursite.com", className: INPUT_CLASS }) }), (form.provider === 'resend' || form.provider === 'smtpcom') && (_jsx(SecretField, { id: ids.apiKey, label: "API key", value: form.apiKey, onChange: (v) => setField('apiKey', v), disabled: disabled, hasStored: sameProvider && stored.hasApiKey, last4: stored.apiKeyLast4, help: form.provider === 'resend'
                    ? 'Your Resend API key (starts with re_). Stored encrypted.'
                    : 'Your SMTP.com v4 API key. Stored encrypted.' })), form.provider === 'smtpcom' && (_jsx(Field, { id: ids.channel, label: "Sender channel", help: "Optional. The SMTP.com channel to send through; defaults to your account default.", children: _jsx("input", { id: ids.channel, type: "text", value: form.channel, disabled: disabled, onChange: (e) => setField('channel', e.target.value), placeholder: "default", className: INPUT_CLASS }) })), form.provider === 'ses' && (_jsx(Field, { id: ids.region, label: "AWS region", help: "SES sends with your deployment's AWS credentials (env vars or IAM role); only the region is stored here.", children: _jsx("input", { id: ids.region, type: "text", value: form.region, disabled: disabled, onChange: (e) => setField('region', e.target.value), placeholder: "us-east-1", className: INPUT_CLASS }) })), form.provider === 'smtp' && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "grid max-w-md grid-cols-1 gap-4 sm:grid-cols-[1fr_8rem]", children: [_jsx(Field, { id: ids.host, label: "Host", children: _jsx("input", { id: ids.host, type: "text", value: form.host, disabled: disabled, onChange: (e) => setField('host', e.target.value), placeholder: "smtp.example.com", className: INPUT_CLASS }) }), _jsx(Field, { id: ids.port, label: "Port", children: _jsx("input", { id: ids.port, type: "text", inputMode: "numeric", value: form.port, disabled: disabled, onChange: (e) => setField('port', e.target.value.replace(/[^\d]/g, '')), placeholder: "587", className: INPUT_CLASS }) })] }), _jsx("div", { className: "max-w-md", children: _jsx(SettingsToggleRow, { label: "Implicit TLS", description: "Enable for port 465. Leave off for STARTTLS (port 587, the common default).", checked: form.secure, disabled: disabled, onChange: (v) => setField('secure', v) }) }), _jsx(Field, { id: ids.user, label: "Username", help: "Leave blank for relays that authenticate by IP address.", children: _jsx("input", { id: ids.user, type: "text", autoComplete: "off", value: form.smtpUser, disabled: disabled, onChange: (e) => setField('smtpUser', e.target.value), className: INPUT_CLASS }) }), _jsx(SecretField, { id: ids.pass, label: "Password", value: form.smtpPass, onChange: (v) => setField('smtpPass', v), disabled: disabled, hasStored: sameProvider && stored.hasSmtpPass, help: "Stored encrypted." })] }))] }));
}
export function EmailSettingsTab({ role }) {
    const canEdit = String(role ?? '').toUpperCase() === 'ADMIN';
    const s = useEmailSettings(canEdit);
    const providerGroupId = useId();
    if (s.loading) {
        return (_jsx("div", { className: "flex h-48 items-center justify-center", "aria-label": "Loading email settings", children: _jsx(Loader2, { className: "text-brand h-6 w-6 animate-spin", "aria-hidden": "true" }) }));
    }
    if (s.loadError) {
        return (_jsxs("div", { role: "alert", className: "border-destructive/30 bg-destructive/10 text-destructive flex items-center gap-3 rounded-lg border p-3 text-sm", children: [_jsx(AlertTriangle, { size: 20, className: "shrink-0", "aria-hidden": "true" }), _jsx("span", { className: "flex-1", children: s.loadError }), _jsx("button", { onClick: s.reload, className: "border-destructive/40 rounded-md border px-3 py-1 transition-colors hover:opacity-80", children: "Retry" })] }));
    }
    const configured = s.form.provider !== '';
    return (_jsxs("div", { className: "space-y-4", children: [!canEdit && (_jsx(Notice, { tone: "info", children: "You have read-only access to email settings. Ask an administrator to make changes." })), s.platformAdapter && (_jsxs(Notice, { tone: "info", children: ["A platform email adapter is configured in code (", _jsx("code", { children: "platform.email" }), "); it takes precedence over the settings on this page."] })), !s.platformAdapter && s.env.provider && (_jsxs(Notice, { tone: "info", children: ["Environment variables currently configure", ' ', _jsx("strong", { children: PROVIDER_LABEL[s.env.provider] }), ". Settings saved here take precedence over the environment configuration."] })), configured && !s.factoryAvailable && (_jsxs(Notice, { tone: "warning", children: ["Sending with these settings requires the email plugin. Add ", _jsx("code", { children: "emailPlugin()" }), " from", ' ', _jsx("code", { children: "@actuate-media/plugin-email" }), " to your ", _jsx("code", { children: "actuate.config.ts" }), "."] })), _jsxs(SettingsCard, { title: "Email delivery", description: "Transactional email provider for invitations, password resets, and form notifications. Credentials are encrypted at rest.", actions: _jsxs("button", { type: "button", onClick: () => void s.sendTest(), disabled: s.testing || s.dirty || (!configured && !s.env.senderActive), title: s.dirty ? 'Save your changes before sending a test.' : undefined, className: "border-border text-foreground hover:bg-accent inline-flex items-center gap-2 rounded-md border px-3 py-1.5 text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50", children: [s.testing ? (_jsx(Loader2, { size: 14, className: "animate-spin", "aria-hidden": "true" })) : (_jsx(Send, { size: 14, "aria-hidden": "true" })), "Send test email"] }), children: [_jsxs("div", { className: "space-y-5", children: [_jsxs("div", { children: [_jsx("span", { id: providerGroupId, className: LABEL_CLASS, children: "Provider" }), _jsx("div", { role: "radiogroup", "aria-labelledby": providerGroupId, className: "flex flex-wrap gap-2", children: [{ value: '', label: 'None' }, ...EMAIL_PROVIDER_OPTIONS].map((opt) => {
                                            const active = s.form.provider === opt.value;
                                            return (_jsx("button", { type: "button", role: "radio", "aria-checked": active, disabled: !canEdit, onClick: () => s.setField('provider', opt.value), className: `rounded-md border px-3 py-1.5 text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${active
                                                    ? 'border-brand bg-brand/10 text-brand font-medium'
                                                    : 'border-border text-muted-foreground hover:text-foreground hover:bg-accent'}`, children: opt.label }, opt.value || 'none'));
                                        }) }), !configured && (_jsx("p", { className: HELP_CLASS, children: s.env.senderActive
                                            ? 'No provider is configured here, but an environment-configured sender is active.'
                                            : 'No email provider configured. Transactional email (invites, password resets, form notifications) is skipped.' }))] }), _jsx(ProviderFields, { s: s, canEdit: canEdit }), s.testResult && (_jsx(Notice, { tone: s.testResult.success ? 'success' : 'error', children: s.testResult.message })), !s.testResult && s.lastTest.status && (_jsxs("p", { className: "text-muted-foreground text-sm", children: ["Last test ", s.lastTest.status === 'success' ? 'succeeded' : `failed`, s.lastTest.testedAt ? ` on ${new Date(s.lastTest.testedAt).toLocaleString()}` : '', s.lastTest.status === 'failed' && s.lastTest.error ? ` — ${s.lastTest.error}` : ''] }))] }), s.saveError && (_jsx("p", { className: "text-destructive mt-4 text-sm", role: "alert", children: s.saveError }))] }), _jsx(SettingsSaveBar, { dirty: s.dirty, canEdit: canEdit, hasErrors: false, saveState: s.saveState, onSave: () => void s.save(), onReset: s.reset })] }));
}
//# sourceMappingURL=EmailSettingsTab.js.map