'use client'

import { useState, useCallback } from 'react'
import {
  User,
  Mail,
  Phone,
  Scale,
  CreditCard,
  Key,
  Plus,
  Trash2,
  Copy,
  Check,
  Bell,
  BellRing,
  FileCheck,
  AlertTriangle,
  Shield,
  Lock,
  Eye,
  EyeOff,
  Sparkles,
  Crown,
  Zap,
  Clock,
  ToggleLeft,
  ToggleRight,
  Loader2,
  AlertCircle,
  ChevronRight,
  HardDrive,
  Upload as UploadIcon,
} from 'lucide-react'

// ─── Types ──────────────────────────────────────────────────────────

interface UserData {
  id: string
  name: string
  email: string
  phone: string | null
  oabNumber: string | null
  oabState: string | null
  avatar: string | null
  plan: string
  credits: number
  createdAt: string
}

interface ApiKeyData {
  id: string
  name: string
  key: string
  active: boolean
  createdAt: string
}

interface SubscriptionData {
  plan: string
  status: string
  startDate: string
  endDate: string | null
}

interface StorageData {
  used: number
  limit: number
  count: number
}

interface Props {
  user: UserData
  apiKeys: ApiKeyData[]
  subscription: SubscriptionData | null
  storage: StorageData
}

// ─── Helpers ────────────────────────────────────────────────────────

const planConfig: Record<string, { label: string; color: string; icon: typeof Sparkles }> = {
  FREE: { label: 'Free', color: 'bg-zinc-700 text-zinc-300', icon: Zap },
  STARTER: { label: 'Starter', color: 'bg-blue-600/20 text-blue-400 border border-blue-500/30', icon: Zap },
  PRO: { label: 'Pro', color: 'bg-teal-600/20 text-teal-400 border border-teal-500/30', icon: Crown },
  ENTERPRISE: { label: 'Enterprise', color: 'bg-amber-600/20 text-amber-400 border border-amber-500/30', icon: Sparkles },
}

function formatDate(iso: string) {
  return new Intl.DateTimeFormat('pt-BR', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
  }).format(new Date(iso))
}

function formatDateTime(iso: string) {
  return new Intl.DateTimeFormat('pt-BR', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  }).format(new Date(iso))
}

// ─── Section wrapper ────────────────────────────────────────────────

function Section({
  id,
  title,
  icon: Icon,
  description,
  children,
  danger,
}: {
  id?: string
  title: string
  icon: typeof User
  description?: string
  children: React.ReactNode
  danger?: boolean
}) {
  return (
    <section
      id={id}
      className={`overflow-hidden rounded-2xl border ${
        danger
          ? 'border-red-500/20 bg-red-950/10'
          : 'border-white/5 bg-[#111b27]'
      }`}
    >
      <div className={`border-b px-6 py-4 ${danger ? 'border-red-500/10' : 'border-white/5'}`}>
        <div className="flex items-center gap-3">
          <div className={`rounded-lg p-2 ${danger ? 'bg-red-500/15' : 'bg-teal-500/15'}`}>
            <Icon className={`h-4 w-4 ${danger ? 'text-red-400' : 'text-teal-400'}`} />
          </div>
          <div>
            <h2 className="text-base font-semibold text-white">{title}</h2>
            {description && <p className="text-sm text-zinc-500">{description}</p>}
          </div>
        </div>
      </div>
      <div className="px-6 py-5">{children}</div>
    </section>
  )
}

// ─── Toggle component ───────────────────────────────────────────────

function Toggle({
  label,
  description,
  icon: Icon,
  enabled,
  onChange,
}: {
  label: string
  description: string
  icon: typeof Bell
  enabled: boolean
  onChange: (v: boolean) => void
}) {
  return (
    <div className="flex items-center justify-between gap-4 py-3">
      <div className="flex items-center gap-3">
        <Icon className="h-4 w-4 flex-shrink-0 text-zinc-500" />
        <div>
          <p className="text-sm font-medium text-zinc-200">{label}</p>
          <p className="text-xs text-zinc-500">{description}</p>
        </div>
      </div>
      <button
        onClick={() => onChange(!enabled)}
        className="flex-shrink-0 transition-colors"
        aria-label={`Toggle ${label}`}
      >
        {enabled ? (
          <ToggleRight className="h-7 w-7 text-teal-400" />
        ) : (
          <ToggleLeft className="h-7 w-7 text-zinc-600" />
        )}
      </button>
    </div>
  )
}

// ─── Main component ─────────────────────────────────────────────────

export default function SettingsClient({ user, apiKeys: initialKeys, subscription, storage }: Props) {
  // ── API Keys state ──
  const [keys, setKeys] = useState(initialKeys)
  const [newKeyName, setNewKeyName] = useState('')
  const [createdKey, setCreatedKey] = useState<string | null>(null)
  const [copiedKey, setCopiedKey] = useState(false)
  const [keyLoading, setKeyLoading] = useState(false)
  const [keyError, setKeyError] = useState<string | null>(null)
  const [deletingId, setDeletingId] = useState<string | null>(null)
  const [portalLoading, setPortalLoading] = useState(false)

  // ── Notifications state (local only for now) ──
  const [notifications, setNotifications] = useState({
    emailAlerts: true,
    documentReady: true,
    creditsLow: true,
    weeklyReport: false,
  })

  // ── Security state ──
  const [showCurrentPw, setShowCurrentPw] = useState(false)
  const [showNewPw, setShowNewPw] = useState(false)
  const [passwordForm, setPasswordForm] = useState({
    current: '',
    newPassword: '',
    confirm: '',
  })

  // ── Delete account state ──
  const [deleteConfirm, setDeleteConfirm] = useState('')
  const [showDeleteInput, setShowDeleteInput] = useState(false)

  // ── API Key handlers ──
  const createKey = useCallback(async () => {
    if (!newKeyName.trim()) return
    setKeyLoading(true)
    setKeyError(null)
    setCreatedKey(null)

    try {
      const res = await fetch('/api/keys', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: newKeyName.trim() }),
      })

      const data = await res.json()
      if (!res.ok) throw new Error(data.error || 'Erro ao criar chave')

      setCreatedKey(data.key)
      setKeys((prev) => [
        {
          id: data.id,
          name: data.name,
          key: data.key.slice(0, 8) + '••••••••' + data.key.slice(-4),
          active: true,
          createdAt: data.createdAt,
        },
        ...prev,
      ])
      setNewKeyName('')
    } catch (err) {
      setKeyError(err instanceof Error ? err.message : 'Erro ao criar chave')
    } finally {
      setKeyLoading(false)
    }
  }, [newKeyName])

  const deleteKey = useCallback(async (id: string) => {
    setDeletingId(id)
    try {
      const res = await fetch(`/api/keys/${id}`, { method: 'DELETE' })
      if (!res.ok) {
        const data = await res.json()
        throw new Error(data.error || 'Erro ao revogar chave')
      }
      setKeys((prev) => prev.filter((k) => k.id !== id))
    } catch (err) {
      setKeyError(err instanceof Error ? err.message : 'Erro ao revogar chave')
    } finally {
      setDeletingId(null)
    }
  }, [])

  const copyToClipboard = useCallback((text: string) => {
    navigator.clipboard.writeText(text)
    setCopiedKey(true)
    setTimeout(() => setCopiedKey(false), 2000)
  }, [])

  const plan = planConfig[user.plan] || planConfig.FREE

  // ── Mock billing history ──
  const billingHistory = [
    { date: '2025-06-01', description: 'Plano Pro — Mensal', amount: 'R$ 89,90', status: 'Pago' },
    { date: '2025-05-01', description: 'Plano Pro — Mensal', amount: 'R$ 89,90', status: 'Pago' },
    { date: '2025-04-01', description: 'Plano Pro — Mensal', amount: 'R$ 89,90', status: 'Pago' },
    { date: '2025-03-15', description: 'Créditos extras (50)', amount: 'R$ 29,90', status: 'Pago' },
  ]

  const initials = user.name
    .split(' ')
    .map((n) => n[0])
    .slice(0, 2)
    .join('')
    .toUpperCase()

  return (
    <div className="space-y-8 pb-12">
      {/* Page header */}
      <div>
        <h1 className="text-2xl font-bold text-white">Configurações</h1>
        <p className="mt-1 text-sm text-zinc-500">
          Gerencie seu perfil, assinatura, chaves de API e preferências de segurança.
        </p>
      </div>

      {/* ━━━ 1. Profile ━━━ */}
      <Section id="perfil" title="Perfil" icon={User} description="Informações da sua conta">
        <div className="flex flex-col gap-6 sm:flex-row sm:items-start">
          {/* Avatar */}
          <div className="flex flex-col items-center gap-2">
            {user.avatar ? (
              <img
                src={user.avatar}
                alt={user.name}
                className="h-20 w-20 rounded-2xl object-cover ring-2 ring-teal-500/30"
              />
            ) : (
              <div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-teal-600/20 text-2xl font-bold text-teal-400 ring-2 ring-teal-500/30">
                {initials}
              </div>
            )}
            <span className="text-[10px] uppercase tracking-wider text-zinc-600">
              Avatar
            </span>
          </div>

          {/* Fields */}
          <div className="flex-1 space-y-4">
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              {/* Name */}
              <div>
                <label className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-zinc-500">
                  <User className="h-3 w-3" /> Nome
                </label>
                <div className="rounded-xl border border-white/5 bg-white/[0.03] px-4 py-2.5 text-sm text-white">
                  {user.name}
                </div>
              </div>

              {/* Email */}
              <div>
                <label className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-zinc-500">
                  <Mail className="h-3 w-3" /> Email
                </label>
                <div className="rounded-xl border border-white/5 bg-white/[0.03] px-4 py-2.5 text-sm text-white">
                  {user.email}
                </div>
              </div>

              {/* OAB */}
              <div>
                <label className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-zinc-500">
                  <Scale className="h-3 w-3" /> OAB
                </label>
                <div className="rounded-xl border border-white/5 bg-white/[0.03] px-4 py-2.5 text-sm text-white">
                  {user.oabNumber && user.oabState
                    ? `${user.oabNumber} / ${user.oabState}`
                    : '—'}
                </div>
              </div>

              {/* Phone */}
              <div>
                <label className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-zinc-500">
                  <Phone className="h-3 w-3" /> Telefone
                </label>
                <div className="rounded-xl border border-white/5 bg-white/[0.03] px-4 py-2.5 text-sm text-white">
                  {user.phone || '—'}
                </div>
              </div>
            </div>

            <p className="text-xs text-zinc-600">
              Membro desde {formatDate(user.createdAt)}. Para editar seu perfil, entre em contato com o suporte.
            </p>
          </div>
        </div>
      </Section>

      {/* ━━━ 2. Subscription ━━━ */}
      <Section
        id="planos"
        title="Assinatura"
        icon={CreditCard}
        description="Seu plano atual e histórico de cobrança"
      >
        {/* Current plan */}
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex items-center gap-4">
            <div className="rounded-xl bg-teal-600/15 p-3">
              <plan.icon className="h-6 w-6 text-teal-400" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <span className="text-lg font-bold text-white">Plano {plan.label}</span>
                <span className={`rounded-full px-2.5 py-0.5 text-[10px] font-bold uppercase tracking-wider ${plan.color}`}>
                  Ativo
                </span>
              </div>
              <p className="text-sm text-zinc-500">
                {user.credits} créditos restantes
                {subscription?.endDate && (
                  <> · Renova em {formatDate(subscription.endDate)}</>
                )}
              </p>
            </div>
          </div>

          <div className="flex gap-3">
            {user.plan !== 'FREE' && (
              <button
                onClick={async () => {
                  setPortalLoading(true)
                  try {
                    const res = await fetch('/api/stripe/portal', { method: 'POST' })
                    const data = await res.json()
                    if (data.url) window.location.href = data.url
                    else alert(data.error || 'Erro')
                  } catch { alert('Erro ao conectar') }
                  finally { setPortalLoading(false) }
                }}
                disabled={portalLoading}
                className="inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/[0.03] px-5 py-2.5 text-sm font-medium text-zinc-300 transition-all hover:bg-white/[0.06] disabled:opacity-50"
              >
                {portalLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <CreditCard className="h-4 w-4" />}
                Gerenciar Assinatura
              </button>
            )}
            {user.plan !== 'ENTERPRISE' && (
              <a
                href="/pricing"
                className="inline-flex items-center gap-2 rounded-xl bg-teal-600 px-5 py-2.5 text-sm font-semibold text-white transition-all hover:bg-teal-500 hover:shadow-lg hover:shadow-teal-600/20"
              >
                <Sparkles className="h-4 w-4" />
                Upgrade
              </a>
            )}
          </div>
        </div>

        {/* Credits bar */}
        <div className="mt-6">
          <div className="mb-2 flex items-center justify-between text-xs">
            <span className="text-zinc-500">Créditos usados este mês</span>
            <span className="font-medium text-zinc-300">
              {Math.max(0, (user.plan === 'FREE' ? 5 : user.plan === 'PRO' ? 100 : 500) - user.credits)} / {user.plan === 'FREE' ? 5 : user.plan === 'PRO' ? 100 : 500}
            </span>
          </div>
          <div className="h-2 overflow-hidden rounded-full bg-white/5">
            <div
              className="h-full rounded-full bg-gradient-to-r from-teal-600 to-teal-400 transition-all"
              style={{
                width: `${Math.min(100, ((Math.max(0, (user.plan === 'FREE' ? 5 : user.plan === 'PRO' ? 100 : 500) - user.credits)) / (user.plan === 'FREE' ? 5 : user.plan === 'PRO' ? 100 : 500)) * 100)}%`,
              }}
            />
          </div>
        </div>

        {/* Billing history */}
        <div className="mt-6">
          <h3 className="mb-3 text-sm font-medium text-zinc-400">Histórico de cobrança</h3>
          <div className="overflow-hidden rounded-xl border border-white/5">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-white/5 text-left text-xs font-medium uppercase tracking-wider text-zinc-600">
                  <th className="px-4 py-2.5">Data</th>
                  <th className="hidden px-4 py-2.5 sm:table-cell">Descrição</th>
                  <th className="px-4 py-2.5 text-right">Valor</th>
                  <th className="px-4 py-2.5 text-right">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-white/5">
                {billingHistory.map((item, i) => (
                  <tr key={i} className="hover:bg-white/[0.02]">
                    <td className="px-4 py-2.5 text-zinc-400">{formatDate(item.date)}</td>
                    <td className="hidden px-4 py-2.5 text-zinc-300 sm:table-cell">{item.description}</td>
                    <td className="px-4 py-2.5 text-right font-medium text-white">{item.amount}</td>
                    <td className="px-4 py-2.5 text-right">
                      <span className="rounded-full bg-emerald-500/15 px-2 py-0.5 text-[10px] font-medium text-emerald-400">
                        {item.status}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </Section>

      {/* ━━━ 3. API Keys ━━━ */}
      <Section
        id="api-keys"
        title="Chaves de API"
        icon={Key}
        description="Gerencie suas chaves para integração com a API"
      >
        {/* Create new key */}
        <div className="flex gap-3">
          <input
            type="text"
            placeholder="Nome da chave (ex: meu-app)"
            value={newKeyName}
            onChange={(e) => setNewKeyName(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && createKey()}
            className="flex-1 rounded-xl border border-white/10 bg-white/[0.03] px-4 py-2.5 text-sm text-white placeholder-zinc-600 outline-none transition-colors focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/30"
          />
          <button
            onClick={createKey}
            disabled={keyLoading || !newKeyName.trim()}
            className="inline-flex items-center gap-2 rounded-xl bg-teal-600 px-4 py-2.5 text-sm font-medium text-white transition-all hover:bg-teal-500 disabled:cursor-not-allowed disabled:opacity-50"
          >
            {keyLoading ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Plus className="h-4 w-4" />
            )}
            Criar
          </button>
        </div>

        {/* Error */}
        {keyError && (
          <div className="mt-3 flex items-center gap-2 rounded-xl border border-red-500/20 bg-red-500/10 px-4 py-2.5 text-sm text-red-400">
            <AlertCircle className="h-4 w-4 flex-shrink-0" />
            {keyError}
          </div>
        )}

        {/* Just-created key (show once) */}
        {createdKey && (
          <div className="mt-3 rounded-xl border border-teal-500/30 bg-teal-500/10 p-4">
            <p className="mb-2 text-xs font-medium text-teal-300">
              ⚠️ Copie sua chave agora — ela não será exibida novamente:
            </p>
            <div className="flex items-center gap-2">
              <code className="flex-1 overflow-x-auto rounded-lg bg-black/40 px-3 py-2 font-mono text-xs text-teal-200">
                {createdKey}
              </code>
              <button
                onClick={() => copyToClipboard(createdKey)}
                className="rounded-lg bg-teal-600/30 p-2 text-teal-300 transition-colors hover:bg-teal-600/50"
              >
                {copiedKey ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
              </button>
            </div>
          </div>
        )}

        {/* Keys list */}
        {keys.length > 0 ? (
          <div className="mt-4 space-y-2">
            {keys.map((k) => (
              <div
                key={k.id}
                className={`flex items-center justify-between gap-3 rounded-xl border px-4 py-3 transition-all ${
                  k.active
                    ? 'border-white/5 bg-white/[0.02]'
                    : 'border-white/5 bg-white/[0.01] opacity-50'
                }`}
              >
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-medium text-white">{k.name}</span>
                    {!k.active && (
                      <span className="rounded-full bg-red-500/15 px-2 py-0.5 text-[10px] font-medium text-red-400">
                        Revogada
                      </span>
                    )}
                  </div>
                  <div className="flex items-center gap-3 text-xs text-zinc-600">
                    <code className="font-mono">{k.key}</code>
                    <span className="flex items-center gap-1">
                      <Clock className="h-3 w-3" />
                      {formatDateTime(k.createdAt)}
                    </span>
                  </div>
                </div>
                <button
                  onClick={() => deleteKey(k.id)}
                  disabled={deletingId === k.id}
                  className="rounded-lg p-2 text-zinc-600 transition-colors hover:bg-red-500/10 hover:text-red-400 disabled:opacity-50"
                  title="Revogar e excluir"
                >
                  {deletingId === k.id ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : (
                    <Trash2 className="h-4 w-4" />
                  )}
                </button>
              </div>
            ))}
          </div>
        ) : (
          !createdKey && (
            <div className="mt-4 flex flex-col items-center justify-center rounded-xl border border-dashed border-white/10 py-10 text-center">
              <Key className="h-8 w-8 text-zinc-700" />
              <p className="mt-2 text-sm text-zinc-500">Nenhuma chave de API criada</p>
              <p className="text-xs text-zinc-600">Crie uma chave para integrar com a API do LexMind</p>
            </div>
          )
        )}

        <p className="mt-3 text-xs text-zinc-600">
          Máximo de 5 chaves. As chaves têm prefixo <code className="text-zinc-500">jur_</code> e são hasheadas no banco.
        </p>
      </Section>


      {/* ━━━ Storage ━━━ */}
      <Section
        id="armazenamento"
        title="Armazenamento"
        icon={HardDrive}
        description="Espaço usado para uploads de documentos"
      >
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="rounded-xl bg-teal-600/15 p-3">
                <UploadIcon className="h-6 w-6 text-teal-400" />
              </div>
              <div>
                <p className="text-sm font-medium text-white">
                  {(storage.used / (1024 * 1024)).toFixed(1)} MB de {(storage.limit / (1024 * 1024 * 1024)).toFixed(0)} GB usados
                </p>
                <p className="text-xs text-zinc-500">{storage.count} arquivo{storage.count !== 1 ? 's' : ''} enviado{storage.count !== 1 ? 's' : ''}</p>
              </div>
            </div>
            <span className="text-sm font-bold text-teal-400">
              {Math.round((storage.used / storage.limit) * 100)}%
            </span>
          </div>
          <div className="h-3 overflow-hidden rounded-full bg-white/5">
            <div
              className={`h-full rounded-full transition-all ${
                (storage.used / storage.limit) > 0.9
                  ? 'bg-gradient-to-r from-red-600 to-red-400'
                  : (storage.used / storage.limit) > 0.7
                    ? 'bg-gradient-to-r from-amber-600 to-amber-400'
                    : 'bg-gradient-to-r from-teal-600 to-teal-400'
              }`}
              style={{ width: `${Math.min(100, (storage.used / storage.limit) * 100)}%` }}
            />
          </div>
          <div className="flex justify-between text-xs text-zinc-600">
            <span>0 GB</span>
            <span>{(storage.limit / (1024 * 1024 * 1024)).toFixed(0)} GB</span>
          </div>
        </div>
      </Section>

      {/* ━━━ 4. Notifications ━━━ */}
      <Section
        id="notificacoes"
        title="Notificações"
        icon={Bell}
        description="Configure como e quando você recebe alertas"
      >
        <div className="divide-y divide-white/5">
          <Toggle
            label="Alertas por email"
            description="Receba notificações importantes por email"
            icon={Mail}
            enabled={notifications.emailAlerts}
            onChange={(v) => setNotifications((p) => ({ ...p, emailAlerts: v }))}
          />
          <Toggle
            label="Documento pronto"
            description="Notificar quando uma peça jurídica terminar de ser gerada"
            icon={FileCheck}
            enabled={notifications.documentReady}
            onChange={(v) => setNotifications((p) => ({ ...p, documentReady: v }))}
          />
          <Toggle
            label="Créditos baixos"
            description="Avisar quando seus créditos estiverem abaixo de 20%"
            icon={AlertTriangle}
            enabled={notifications.creditsLow}
            onChange={(v) => setNotifications((p) => ({ ...p, creditsLow: v }))}
          />
          <Toggle
            label="Relatório semanal"
            description="Resumo da sua atividade enviado toda segunda-feira"
            icon={BellRing}
            enabled={notifications.weeklyReport}
            onChange={(v) => setNotifications((p) => ({ ...p, weeklyReport: v }))}
          />
        </div>

        <div className="mt-4 flex justify-end">
          <button className="rounded-xl bg-teal-600/15 px-4 py-2 text-sm font-medium text-teal-400 transition-colors hover:bg-teal-600/25">
            Salvar preferências
          </button>
        </div>
      </Section>

      {/* ━━━ 5. Security ━━━ */}
      <Section
        id="seguranca"
        title="Segurança"
        icon={Shield}
        description="Senha e autenticação em dois fatores"
      >
        {/* Change password */}
        <div className="space-y-4">
          <h3 className="text-sm font-medium text-zinc-300">Alterar senha</h3>

          <div className="max-w-md space-y-3">
            {/* Current password */}
            <div>
              <label className="mb-1.5 block text-xs font-medium text-zinc-500">Senha atual</label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-600" />
                <input
                  type={showCurrentPw ? 'text' : 'password'}
                  value={passwordForm.current}
                  onChange={(e) => setPasswordForm((p) => ({ ...p, current: e.target.value }))}
                  className="w-full rounded-xl border border-white/10 bg-white/[0.03] py-2.5 pl-10 pr-10 text-sm text-white placeholder-zinc-600 outline-none transition-colors focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/30"
                  placeholder="••••••••"
                />
                <button
                  type="button"
                  onClick={() => setShowCurrentPw(!showCurrentPw)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-zinc-600 hover:text-zinc-400"
                >
                  {showCurrentPw ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>

            {/* New password */}
            <div>
              <label className="mb-1.5 block text-xs font-medium text-zinc-500">Nova senha</label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-600" />
                <input
                  type={showNewPw ? 'text' : 'password'}
                  value={passwordForm.newPassword}
                  onChange={(e) => setPasswordForm((p) => ({ ...p, newPassword: e.target.value }))}
                  className="w-full rounded-xl border border-white/10 bg-white/[0.03] py-2.5 pl-10 pr-10 text-sm text-white placeholder-zinc-600 outline-none transition-colors focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/30"
                  placeholder="Mínimo 8 caracteres"
                />
                <button
                  type="button"
                  onClick={() => setShowNewPw(!showNewPw)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-zinc-600 hover:text-zinc-400"
                >
                  {showNewPw ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>

            {/* Confirm password */}
            <div>
              <label className="mb-1.5 block text-xs font-medium text-zinc-500">Confirmar nova senha</label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-600" />
                <input
                  type="password"
                  value={passwordForm.confirm}
                  onChange={(e) => setPasswordForm((p) => ({ ...p, confirm: e.target.value }))}
                  className="w-full rounded-xl border border-white/10 bg-white/[0.03] py-2.5 pl-10 pr-10 text-sm text-white placeholder-zinc-600 outline-none transition-colors focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/30"
                  placeholder="Repita a nova senha"
                />
              </div>
            </div>

            <button className="rounded-xl bg-teal-600 px-4 py-2.5 text-sm font-medium text-white transition-all hover:bg-teal-500">
              Alterar senha
            </button>
          </div>
        </div>

        {/* 2FA */}
        <div className="mt-8 flex items-center justify-between rounded-xl border border-white/5 bg-white/[0.02] px-5 py-4">
          <div className="flex items-center gap-3">
            <div className="rounded-lg bg-zinc-800 p-2">
              <Shield className="h-4 w-4 text-zinc-400" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <p className="text-sm font-medium text-zinc-300">Autenticação em dois fatores (2FA)</p>
                <span className="rounded-full bg-amber-500/15 px-2 py-0.5 text-[10px] font-medium text-amber-400">
                  Em breve
                </span>
              </div>
              <p className="text-xs text-zinc-600">
                Adicione uma camada extra de segurança à sua conta
              </p>
            </div>
          </div>
          <ChevronRight className="h-4 w-4 text-zinc-700" />
        </div>
      </Section>

      {/* ━━━ 6. Danger Zone ━━━ */}
      <Section
        id="perigo"
        title="Zona de Perigo"
        icon={AlertTriangle}
        description="Ações irreversíveis"
        danger
      >
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <p className="text-sm font-medium text-red-300">Excluir conta permanentemente</p>
            <p className="text-xs text-zinc-500">
              Todos os dados serão perdidos — documentos, chaves, histórico. Esta ação não pode ser desfeita.
            </p>
          </div>

          {!showDeleteInput ? (
            <button
              onClick={() => setShowDeleteInput(true)}
              className="flex-shrink-0 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-2.5 text-sm font-medium text-red-400 transition-all hover:bg-red-500/20"
            >
              Excluir minha conta
            </button>
          ) : (
            <div className="flex items-center gap-2">
              <input
                type="text"
                placeholder='Digite "EXCLUIR" para confirmar'
                value={deleteConfirm}
                onChange={(e) => setDeleteConfirm(e.target.value)}
                className="rounded-xl border border-red-500/30 bg-red-500/5 px-3 py-2 text-sm text-red-300 placeholder-red-800 outline-none focus:border-red-500/50"
              />
              <button
                disabled={deleteConfirm !== 'EXCLUIR'}
                className="rounded-xl bg-red-600 px-4 py-2 text-sm font-medium text-white transition-all hover:bg-red-500 disabled:cursor-not-allowed disabled:opacity-40"
              >
                Confirmar
              </button>
              <button
                onClick={() => {
                  setShowDeleteInput(false)
                  setDeleteConfirm('')
                }}
                className="rounded-xl px-3 py-2 text-sm text-zinc-500 hover:text-zinc-300"
              >
                Cancelar
              </button>
            </div>
          )}
        </div>
      </Section>
    </div>
  )
}
