import { For, Show, createSignal, onMount } from 'solid-js';
import { Settings as SettingsIcon } from 'lucide-solid';
import { BTN_GHOST, BTN_ORANGE, BTN_PRIMARY, CARD, INPUT, LABEL } from '~/components/DashboardShell';

const API = '';
const NAVY = '#0D0D2A';
const ORANGE = '#FF5E13';

async function apiFetch(path: string, opts?: RequestInit) {
  const token =
    typeof window !== "undefined"
      ? window.sessionStorage.getItem("nxtgauge_access_token") || ""
      : "";
  return fetch(`${API}${path}`, {
    ...opts,
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(opts?.headers ?? {}),
    },
  });
}

type AutoApplySettings = {
  is_enabled: boolean;
  preferred_titles: string[];
  preferred_locations: string[];
  preferred_skills: string[];
  min_salary: number | null;
  max_salary: number | null;
  max_applications_per_day: number;
};

const DEFAULT_AUTO_APPLY: AutoApplySettings = {
  is_enabled: false,
  preferred_titles: [],
  preferred_locations: [],
  preferred_skills: [],
  min_salary: null,
  max_salary: null,
  max_applications_per_day: 3,
};

export default function SettingsPage(props: { roleKey?: string }) {
  const [currentPassword, setCurrentPassword] = createSignal('');
  const [newPassword, setNewPassword] = createSignal('');
  const [confirmPassword, setConfirmPassword] = createSignal('');
  const [emailNotif, setEmailNotif] = createSignal(true);
  const [appNotif, setAppNotif] = createSignal(true);
  const [smsNotif, setSmsNotif] = createSignal(false);
  const [deleteConfirm, setDeleteConfirm] = createSignal('');
  const [deleteReason, setDeleteReason] = createSignal('');
  const [loading, setLoading] = createSignal(true);
  const [savingPassword, setSavingPassword] = createSignal(false);
  const [savingNotifications, setSavingNotifications] = createSignal(false);
  const [requestingDelete, setRequestingDelete] = createSignal(false);
  const [deleteRequestStatus, setDeleteRequestStatus] = createSignal<'NONE' | 'DELETED'>('NONE');
  const [msg, setMsg] = createSignal('');
  const [err, setErr] = createSignal('');

  // Auto-apply settings (job seeker only)
  const [autoApply, setAutoApply] = createSignal<AutoApplySettings>({ ...DEFAULT_AUTO_APPLY });
  const [savingAutoApply, setSavingAutoApply] = createSignal(false);
  const [autoApplyMsg, setAutoApplyMsg] = createSignal('');
  const [autoApplyErr, setAutoApplyErr] = createSignal('');
  // Plan feature gate — null = loading, false = not allowed, true = allowed
  const [hasAutoApplyFeature, setHasAutoApplyFeature] = createSignal<boolean | null>(null);
  // Tag input helpers
  const [titleInput, setTitleInput] = createSignal('');
  const [locationInput, setLocationInput] = createSignal('');
  const [skillInput, setSkillInput] = createSignal('');

  const isJobSeeker = () => String(props.roleKey || '').toUpperCase() === 'JOB_SEEKER';

  const loadAutoApply = async () => {
    try {
      const res = await apiFetch('/api/ai/job-seeker/auto-apply/settings');
      if (res.ok) {
        const data = await res.json().catch(() => ({}));
        // Backend returns { settings: { ... } } — unwrap it
        const s = data.settings ?? data;
        if (s) {
          setAutoApply({
            is_enabled: Boolean(s.is_enabled),
            preferred_titles: Array.isArray(s.preferred_titles) ? s.preferred_titles : [],
            preferred_locations: Array.isArray(s.preferred_locations) ? s.preferred_locations : [],
            preferred_skills: Array.isArray(s.preferred_skills) ? s.preferred_skills : [],
            min_salary: s.min_salary ?? null,
            max_salary: s.max_salary ?? null,
            max_applications_per_day: s.max_applications_per_day ?? 3,
          });
        }
      }
    } catch { /* leave defaults */ }
  };

  const saveAutoApply = async () => {
    setAutoApplyErr('');
    setAutoApplyMsg('');
    setSavingAutoApply(true);
    try {
      const res = await apiFetch('/api/ai/job-seeker/auto-apply/settings', {
        method: 'POST',
        body: JSON.stringify(autoApply()),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setAutoApplyErr(data.error || data.message || 'Failed to save auto-apply settings.');
        return;
      }
      setAutoApplyMsg('Auto-apply settings saved.');
    } catch {
      setAutoApplyErr('Network error saving auto-apply settings.');
    } finally {
      setSavingAutoApply(false);
    }
  };

  const addTag = (field: 'preferred_titles' | 'preferred_locations' | 'preferred_skills', value: string) => {
    const v = value.trim();
    if (!v) return;
    setAutoApply(s => ({ ...s, [field]: [...s[field], v] }));
  };

  const removeTag = (field: 'preferred_titles' | 'preferred_locations' | 'preferred_skills', idx: number) => {
    setAutoApply(s => ({ ...s, [field]: s[field].filter((_, i) => i !== idx) }));
  };

  onMount(async () => {
    setLoading(true);
    setErr('');
    try {
      const loadTasks: Promise<unknown>[] = [
        apiFetch('/api/me/settings').then(async (settingsRes) => {
          if (settingsRes.ok) {
            const data = await settingsRes.json().catch(() => ({}));
            setEmailNotif(Boolean(data.email_notifications));
            setAppNotif(Boolean(data.in_app_notifications));
            setSmsNotif(Boolean(data.sms_notifications));
          }
        }),
        apiFetch('/api/me/settings/delete-account-request').then(async (deleteReqRes) => {
          if (deleteReqRes.ok) {
            const data = await deleteReqRes.json().catch(() => ({}));
            const status = String(data.status || 'NONE').toUpperCase();
            if (status === 'DELETED') setDeleteRequestStatus('DELETED');
          }
        }),
      ];
      if (isJobSeeker()) {
        // Check plan feature gate and load settings in parallel
        loadTasks.push(
          apiFetch('/api/ai/usage').then(async (usageRes) => {
            if (usageRes.ok) {
              const d = await usageRes.json().catch(() => ({}));
              const features: string[] = Array.isArray(d.allowed_features) ? d.allowed_features : [];
              const allowed = features.includes('auto_apply_execute');
              setHasAutoApplyFeature(allowed);
              if (allowed) await loadAutoApply();
            } else {
              setHasAutoApplyFeature(false);
            }
          })
        );
      }
      await Promise.all(loadTasks);
    } catch {
      setErr('Failed to load account settings.');
    } finally {
      setLoading(false);
    }
  });

  const saveNotificationPrefs = async () => {
    setErr('');
    setMsg('');
    setSavingNotifications(true);
    try {
      const res = await apiFetch('/api/me/settings/notifications', {
        method: 'PATCH',
        body: JSON.stringify({
          email_notifications: emailNotif(),
          in_app_notifications: appNotif(),
          sms_notifications: smsNotif(),
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setErr(data.error || data.message || 'Failed to save notification preferences.');
        return;
      }
      setMsg('Notification preferences saved.');
    } catch {
      setErr('Network error while saving notification preferences.');
    } finally {
      setSavingNotifications(false);
    }
  };

  const changePassword = async () => {
    setErr('');
    setMsg('');
    if (!currentPassword() || !newPassword() || !confirmPassword()) {
      setErr('Please fill all password fields.');
      return;
    }
    if (newPassword() !== confirmPassword()) {
      setErr('New password and confirm password do not match.');
      return;
    }
    if (newPassword().length < 8) {
      setErr('New password must be at least 8 characters.');
      return;
    }

    setSavingPassword(true);
    try {
      const res = await apiFetch('/api/auth/change-password', {
        method: 'POST',
        body: JSON.stringify({
          current_password: currentPassword(),
          new_password: newPassword(),
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setErr(data.error || data.message || 'Failed to update password.');
        return;
      }
      setMsg('Password updated successfully.');
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
    } catch {
      setErr('Network error while updating password.');
    } finally {
      setSavingPassword(false);
    }
  };

  const requestDeleteAccount = async () => {
    setErr('');
    setMsg('');
    if (deleteConfirm().trim().toUpperCase() !== 'DELETE') {
      setErr('Type DELETE to confirm account deletion request.');
      return;
    }
    setRequestingDelete(true);
    try {
      const res = await apiFetch('/api/me/settings/delete-account-request', {
        method: 'POST',
        body: JSON.stringify({
          reason: deleteReason().trim() || undefined,
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setErr(data.error || data.message || 'Failed to submit delete account request.');
        return;
      }
      setDeleteRequestStatus('DELETED');
      setMsg('Your account has been deleted. Redirecting to login...');
      setDeleteConfirm('');
      setDeleteReason('');
      try {
        window.localStorage.removeItem('nxtgauge_signup_profile_v1');
        window.localStorage.removeItem('nxtgauge_auth_user');
        window.localStorage.removeItem('nxtgauge_user');
        window.sessionStorage.removeItem('nxtgauge_access_token');
        window.sessionStorage.removeItem('nxtgauge_refresh_token');
        window.sessionStorage.removeItem('nxtgauge_auth_user');
        window.sessionStorage.removeItem('nxtgauge_user');
      } catch {
        // ignore storage cleanup errors
      }
      setTimeout(() => {
        window.location.href = '/login';
      }, 1200);
    } catch {
      setErr('Network error while submitting delete account request.');
    } finally {
      setRequestingDelete(false);
    }
  };

  return (
    <div style={{ 'max-width': '760px', display: 'grid', gap: '14px' }}>
      <div
        style={{
          background: NAVY,
          "border-radius": "12px",
          padding: "16px 20px",
          display: "flex",
          "align-items": "center",
          gap: "12px",
        }}
      >
        <span style={{ color: ORANGE }}>
          <SettingsIcon size={24} />
        </span>
        <div>
          <p style={{ margin: "0", "font-size": "18px", "font-weight": "800", color: "#fff" }}>
            Settings
          </p>
          <p style={{ margin: "4px 0 0", "font-size": "13px", color: "rgba(255,255,255,0.65)" }}>
            Manage account security, notifications, and privacy controls.
          </p>
        </div>
      </div>

      <Show when={loading()}>
        <div style={{ ...CARD, 'text-align': 'center', color: '#9CA3AF' }}>
          Loading settings...
        </div>
      </Show>

      <div style={CARD}>
        <p style={{ margin: '0 0 6px', 'font-size': '15px', 'font-weight': '700', color: '#111827' }}>
          Password & Login
        </p>
        <p style={{ margin: '0 0 12px', 'font-size': '13px', color: '#6B7280' }}>
          Change your account password.
        </p>
        <div style={{ display: 'grid', 'grid-template-columns': '1fr 1fr', gap: '12px' }}>
          <div style={{ 'grid-column': 'span 2' }}>
            <label style={LABEL}>Current Password</label>
            <input type="password" value={currentPassword()} onInput={(e) => setCurrentPassword(e.currentTarget.value)} style={INPUT} />
          </div>
          <div>
            <label style={LABEL}>New Password</label>
            <input type="password" value={newPassword()} onInput={(e) => setNewPassword(e.currentTarget.value)} style={INPUT} />
          </div>
          <div>
            <label style={LABEL}>Confirm New Password</label>
            <input type="password" value={confirmPassword()} onInput={(e) => setConfirmPassword(e.currentTarget.value)} style={INPUT} />
          </div>
        </div>
        <div style={{ display: 'flex', gap: '10px', 'margin-top': '12px' }}>
          <button type="button" onClick={changePassword} disabled={savingPassword()} style={{ ...BTN_PRIMARY, opacity: savingPassword() ? '0.7' : '1' }}>
            {savingPassword() ? 'Updating...' : 'Update Password'}
          </button>
        </div>
      </div>

      <div style={CARD}>
        <p style={{ margin: '0 0 6px', 'font-size': '15px', 'font-weight': '700', color: '#111827' }}>
          Notification Preferences
        </p>
        <p style={{ margin: '0 0 12px', 'font-size': '13px', color: '#6B7280' }}>
          Choose how you receive notifications.
        </p>
        <div style={{ display: 'flex', 'flex-direction': 'column', gap: '8px' }}>
          <label style={{ display: 'flex', 'justify-content': 'space-between', 'align-items': 'center', padding: '8px 0', 'border-bottom': '1px solid #F3F4F6' }}>
            <span style={{ 'font-size': '13px', color: '#374151', 'font-weight': '500' }}>Email Notifications</span>
            <input type="checkbox" checked={emailNotif()} onChange={(e) => setEmailNotif(e.currentTarget.checked)} />
          </label>
          <label style={{ display: 'flex', 'justify-content': 'space-between', 'align-items': 'center', padding: '8px 0', 'border-bottom': '1px solid #F3F4F6' }}>
            <span style={{ 'font-size': '13px', color: '#374151', 'font-weight': '500' }}>In-App Notifications</span>
            <input type="checkbox" checked={appNotif()} onChange={(e) => setAppNotif(e.currentTarget.checked)} />
          </label>
          <label style={{ display: 'flex', 'justify-content': 'space-between', 'align-items': 'center', padding: '8px 0' }}>
            <span style={{ 'font-size': '13px', color: '#374151', 'font-weight': '500' }}>SMS Alerts</span>
            <input type="checkbox" checked={smsNotif()} onChange={(e) => setSmsNotif(e.currentTarget.checked)} />
          </label>
        </div>
        <div style={{ display: 'flex', gap: '10px', 'margin-top': '12px' }}>
          <button type="button" onClick={saveNotificationPrefs} disabled={savingNotifications()} style={{ ...BTN_GHOST, opacity: savingNotifications() ? '0.7' : '1' }}>
            {savingNotifications() ? 'Saving...' : 'Save Preferences'}
          </button>
        </div>
      </div>

      {/* ── AI Auto-Apply (Job Seeker only) ──────────────────────────── */}
      <Show when={isJobSeeker() && hasAutoApplyFeature() !== null}>
        <div style={CARD}>
          <div style={{ display: 'flex', 'align-items': 'center', gap: '10px', 'margin-bottom': '14px' }}>
            <span style={{ 'font-size': '22px' }}>🤖</span>
            <div style={{ flex: 1 }}>
              <p style={{ margin: 0, 'font-size': '15px', 'font-weight': '700', color: '#111827' }}>AI Auto-Apply</p>
              <p style={{ margin: '3px 0 0', 'font-size': '13px', color: '#6B7280' }}>
                AI automatically applies to matching jobs as they go live — using your profile and a tailored cover letter.
              </p>
            </div>
          </div>

          {/* ── Upgrade CTA for users without the feature ── */}
          <Show when={!hasAutoApplyFeature()}>
            <div style={{ background: '#FFFBF5', border: `1px solid ${ORANGE}33`, 'border-radius': '10px', padding: '14px 16px', display: 'flex', 'align-items': 'center', gap: '14px' }}>
              <span style={{ 'font-size': '28px', 'flex-shrink': 0 }}>🔒</span>
              <div style={{ flex: 1 }}>
                <p style={{ margin: '0 0 3px', 'font-size': '13px', 'font-weight': '700', color: NAVY }}>Available on Pro &amp; Enterprise plans</p>
                <p style={{ margin: 0, 'font-size': '12px', color: '#6B7280', 'line-height': '1.5' }}>
                  Upgrade your AI plan to enable automatic job applications. Costs 5 AI credits per application.
                </p>
              </div>
              <a
                href="/dashboard/credits"
                style={{ ...BTN_ORANGE, 'text-decoration': 'none', 'white-space': 'nowrap', 'flex-shrink': 0, display: 'inline-flex', 'align-items': 'center' }}
              >
                Upgrade Plan
              </a>
            </div>
          </Show>

          {/* ── Settings form for users who have the feature ── */}
          <Show when={hasAutoApplyFeature()}>
            {/* Enable toggle */}
            <label style={{ display: 'flex', 'justify-content': 'space-between', 'align-items': 'center', padding: '10px 0', 'border-bottom': '1px solid #F3F4F6', 'margin-bottom': '12px' }}>
              <div>
                <span style={{ 'font-size': '13px', color: '#374151', 'font-weight': '600' }}>Enable AI Auto-Apply</span>
                <p style={{ margin: '2px 0 0', 'font-size': '11px', color: '#9CA3AF' }}>
                  {autoApply().is_enabled ? 'Active — AI will apply to matching jobs' : 'Inactive — no auto-apply will occur'}
                </p>
              </div>
              <div
                onClick={() => setAutoApply(s => ({ ...s, is_enabled: !s.is_enabled }))}
                style={{
                  width: '44px', height: '24px', 'border-radius': '12px', cursor: 'pointer',
                  background: autoApply().is_enabled ? ORANGE : '#D1D5DB',
                  transition: 'background 0.2s', position: 'relative', 'flex-shrink': 0,
                }}
              >
                <div style={{
                  position: 'absolute', top: '3px',
                  left: autoApply().is_enabled ? '23px' : '3px',
                  width: '18px', height: '18px', 'border-radius': '50%',
                  background: '#fff', transition: 'left 0.2s',
                  'box-shadow': '0 1px 3px rgba(0,0,0,0.2)',
                }} />
              </div>
            </label>

            <Show when={autoApply().is_enabled}>
              <div style={{ display: 'grid', gap: '14px' }}>
                {/* Max per day */}
                <div>
                  <label style={LABEL}>Max applications per day</label>
                  <select
                    value={String(autoApply().max_applications_per_day)}
                    onChange={(e) => setAutoApply(s => ({ ...s, max_applications_per_day: Number(e.currentTarget.value) }))}
                    style={{ ...INPUT, cursor: 'pointer' }}
                  >
                    <For each={[1, 2, 3, 5, 10]}>{n => <option value={String(n)}>{n} per day</option>}</For>
                  </select>
                </div>

                {/* Preferred job titles */}
                <div>
                  <label style={LABEL}>Preferred Job Titles</label>
                  <div style={{ display: 'flex', gap: '6px', 'margin-bottom': '6px', 'flex-wrap': 'wrap' }}>
                    <For each={autoApply().preferred_titles}>
                      {(tag, i) => (
                        <span style={{ display: 'inline-flex', 'align-items': 'center', gap: '4px', background: '#EFF6FF', color: '#1D4ED8', 'border-radius': '20px', padding: '3px 10px', 'font-size': '12px', 'font-weight': '600' }}>
                          {tag}
                          <button type="button" onClick={() => removeTag('preferred_titles', i())} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#93C5FD', padding: 0, 'font-size': '14px', 'line-height': 1 }}>×</button>
                        </span>
                      )}
                    </For>
                  </div>
                  <div style={{ display: 'flex', gap: '6px' }}>
                    <input type="text" placeholder="e.g. Software Engineer" value={titleInput()} onInput={(e) => setTitleInput(e.currentTarget.value)} onKeyDown={(e) => { if (e.key === 'Enter') { addTag('preferred_titles', titleInput()); setTitleInput(''); } }} style={{ ...INPUT, flex: 1 }} />
                    <button type="button" onClick={() => { addTag('preferred_titles', titleInput()); setTitleInput(''); }} style={{ ...BTN_GHOST, 'flex-shrink': 0 }}>Add</button>
                  </div>
                </div>

                {/* Preferred locations */}
                <div>
                  <label style={LABEL}>Preferred Locations</label>
                  <div style={{ display: 'flex', gap: '6px', 'margin-bottom': '6px', 'flex-wrap': 'wrap' }}>
                    <For each={autoApply().preferred_locations}>
                      {(tag, i) => (
                        <span style={{ display: 'inline-flex', 'align-items': 'center', gap: '4px', background: '#F0FDF4', color: '#15803D', 'border-radius': '20px', padding: '3px 10px', 'font-size': '12px', 'font-weight': '600' }}>
                          {tag}
                          <button type="button" onClick={() => removeTag('preferred_locations', i())} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#86EFAC', padding: 0, 'font-size': '14px', 'line-height': 1 }}>×</button>
                        </span>
                      )}
                    </For>
                  </div>
                  <div style={{ display: 'flex', gap: '6px' }}>
                    <input type="text" placeholder="e.g. Bangalore, Remote" value={locationInput()} onInput={(e) => setLocationInput(e.currentTarget.value)} onKeyDown={(e) => { if (e.key === 'Enter') { addTag('preferred_locations', locationInput()); setLocationInput(''); } }} style={{ ...INPUT, flex: 1 }} />
                    <button type="button" onClick={() => { addTag('preferred_locations', locationInput()); setLocationInput(''); }} style={{ ...BTN_GHOST, 'flex-shrink': 0 }}>Add</button>
                  </div>
                </div>

                {/* Preferred skills */}
                <div>
                  <label style={LABEL}>Preferred Skills / Keywords</label>
                  <div style={{ display: 'flex', gap: '6px', 'margin-bottom': '6px', 'flex-wrap': 'wrap' }}>
                    <For each={autoApply().preferred_skills}>
                      {(tag, i) => (
                        <span style={{ display: 'inline-flex', 'align-items': 'center', gap: '4px', background: '#FFF7ED', color: '#C2410C', 'border-radius': '20px', padding: '3px 10px', 'font-size': '12px', 'font-weight': '600' }}>
                          {tag}
                          <button type="button" onClick={() => removeTag('preferred_skills', i())} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#FDB89A', padding: 0, 'font-size': '14px', 'line-height': 1 }}>×</button>
                        </span>
                      )}
                    </For>
                  </div>
                  <div style={{ display: 'flex', gap: '6px' }}>
                    <input type="text" placeholder="e.g. React, Node.js" value={skillInput()} onInput={(e) => setSkillInput(e.currentTarget.value)} onKeyDown={(e) => { if (e.key === 'Enter') { addTag('preferred_skills', skillInput()); setSkillInput(''); } }} style={{ ...INPUT, flex: 1 }} />
                    <button type="button" onClick={() => { addTag('preferred_skills', skillInput()); setSkillInput(''); }} style={{ ...BTN_GHOST, 'flex-shrink': 0 }}>Add</button>
                  </div>
                </div>

                {/* Salary range */}
                <div style={{ display: 'grid', 'grid-template-columns': '1fr 1fr', gap: '10px' }}>
                  <div>
                    <label style={LABEL}>Min Salary (₹/month)</label>
                    <input type="number" placeholder="e.g. 30000" value={autoApply().min_salary ?? ''} onInput={(e) => setAutoApply(s => ({ ...s, min_salary: e.currentTarget.value ? Number(e.currentTarget.value) : null }))} style={INPUT} />
                  </div>
                  <div>
                    <label style={LABEL}>Max Salary (₹/month)</label>
                    <input type="number" placeholder="e.g. 80000" value={autoApply().max_salary ?? ''} onInput={(e) => setAutoApply(s => ({ ...s, max_salary: e.currentTarget.value ? Number(e.currentTarget.value) : null }))} style={INPUT} />
                  </div>
                </div>
              </div>
            </Show>

            <div style={{ display: 'flex', 'align-items': 'center', gap: '10px', 'margin-top': '14px' }}>
              <button type="button" onClick={saveAutoApply} disabled={savingAutoApply()} style={{ ...BTN_PRIMARY, opacity: savingAutoApply() ? '0.7' : '1' }}>
                {savingAutoApply() ? 'Saving...' : 'Save Auto-Apply Settings'}
              </button>
              <Show when={autoApplyMsg()}>
                <span style={{ 'font-size': '12px', color: '#16A34A', 'font-weight': '600' }}>{autoApplyMsg()}</span>
              </Show>
              <Show when={autoApplyErr()}>
                <span style={{ 'font-size': '12px', color: '#B91C1C', 'font-weight': '600' }}>{autoApplyErr()}</span>
              </Show>
            </div>
          </Show>
        </div>
      </Show>

      <div style={{ ...CARD, border: '1px solid #FECACA', background: '#FEF2F2' }}>
        <p style={{ margin: '0 0 6px', 'font-size': '15px', 'font-weight': '700', color: '#991B1B' }}>
          Delete Account
        </p>
        <p style={{ margin: '0 0 12px', 'font-size': '13px', color: '#7F1D1D' }}>
          This action is irreversible. Type <strong>DELETE</strong> to confirm.
        </p>
        <Show when={deleteRequestStatus() === 'DELETED'}>
          <p style={{ margin: '0 0 10px', 'font-size': '12px', color: '#92400E', 'font-weight': '700' }}>
            Your account is already deleted.
          </p>
        </Show>
        <div style={{ 'margin-bottom': '10px' }}>
          <label style={LABEL}>Reason (optional)</label>
          <textarea
            rows={3}
            placeholder="Tell us why you want to delete your account"
            value={deleteReason()}
            onInput={(e) => setDeleteReason(e.currentTarget.value)}
            style={{ ...INPUT, height: 'auto', padding: '10px 12px', resize: 'vertical' }}
          />
        </div>
        <div style={{ display: 'grid', 'grid-template-columns': '1fr auto', gap: '10px' }}>
          <input
            type="text"
            placeholder="Type DELETE"
            value={deleteConfirm()}
            onInput={(e) => setDeleteConfirm(e.currentTarget.value)}
            style={INPUT}
          />
          <button
            type="button"
            onClick={requestDeleteAccount}
            disabled={requestingDelete() || deleteRequestStatus() === 'DELETED'}
            style={{ ...BTN_ORANGE, background: '#DC2626', opacity: requestingDelete() || deleteRequestStatus() === 'DELETED' ? '0.7' : '1' }}
          >
            {requestingDelete() ? 'Submitting...' : 'Request Delete'}
          </button>
        </div>
      </div>

      <Show when={msg()}>
        <div style={{ ...CARD, padding: '12px 14px', border: '1px solid #BBF7D0', background: '#ECFDF5', color: '#065F46', 'font-size': '13px', 'font-weight': '600' }}>
          {msg()}
        </div>
      </Show>
      <Show when={err()}>
        <div style={{ ...CARD, padding: '12px 14px', border: '1px solid #FECACA', background: '#FEF2F2', color: '#B91C1C', 'font-size': '13px', 'font-weight': '600' }}>
          {err()}
        </div>
      </Show>
    </div>
  );
}
