'use client'

import { useState, useRef, useCallback, useEffect } from 'react'
import { useSearchParams } from 'next/navigation'
import { motion, AnimatePresence, type Variants } from 'framer-motion'
import ReactMarkdown from 'react-markdown'
import FileUpload from '@/components/FileUpload'
import { stripMarkdown, downloadAsWord } from "@/lib/utils"
import {
  FileText, Scale, Gavel, Shield, BookOpen, FileCheck,
  AlertTriangle, Lock, ScrollText, Landmark, Ban, ArrowUpRight,
  Hammer, MoreHorizontal, ChevronRight, ChevronLeft, Check,
  Users, ClipboardList, BookMarked, MessageSquare, Upload,
  Sparkles, Copy, Download, Edit3, RotateCcw, Loader2,
  Home, Briefcase, Heart, Building2, ShoppingCart, Settings,
  ArrowLeft, Eye, Zap, CheckCircle2
} from 'lucide-react'

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

interface DocumentType {
  id: string
  name: string
  icon: React.ReactNode
  description: string
}

interface LegalArea {
  id: string
  name: string
  icon: React.ReactNode
  color: string
}

interface FormDetails {
  autor: string
  reu: string
  fatos: string
  fundamentos: string
  pedidos: string
  contexto: string
}

// ─── Data ───────────────────────────────────────────────────────────

const DOCUMENT_TYPES: DocumentType[] = [
  { id: 'peticao-inicial', name: 'Petição Inicial', icon: <FileText className="w-6 h-6" />, description: 'Peça inaugural do processo judicial' },
  { id: 'contestacao', name: 'Contestação', icon: <Shield className="w-6 h-6" />, description: 'Resposta do réu à ação judicial' },
  { id: 'apelacao-civel', name: 'Apelação Cível', icon: <ArrowUpRight className="w-6 h-6" />, description: 'Recurso contra sentença cível' },
  { id: 'apelacao-criminal', name: 'Apelação Criminal', icon: <Gavel className="w-6 h-6" />, description: 'Recurso contra sentença criminal' },
  { id: 'recurso', name: 'Recurso', icon: <RotateCcw className="w-6 h-6" />, description: 'Recurso genérico (ordinário/inominado)' },
  { id: 'contrato', name: 'Contrato', icon: <FileCheck className="w-6 h-6" />, description: 'Contratos e instrumentos particulares' },
  { id: 'parecer', name: 'Parecer', icon: <BookOpen className="w-6 h-6" />, description: 'Opinião jurídica fundamentada' },
  { id: 'impugnacao', name: 'Impugnação', icon: <AlertTriangle className="w-6 h-6" />, description: 'Impugnação ao cumprimento de sentença' },
  { id: 'habeas-corpus', name: 'Habeas Corpus', icon: <Lock className="w-6 h-6" />, description: 'Proteção da liberdade de locomoção' },
  { id: 'mandado-seguranca', name: 'Mandado de Segurança', icon: <Landmark className="w-6 h-6" />, description: 'Proteção de direito líquido e certo' },
  { id: 'embargo', name: 'Embargo', icon: <Ban className="w-6 h-6" />, description: 'Embargos de declaração/execução' },
  { id: 'recurso-especial', name: 'Recurso Especial', icon: <ScrollText className="w-6 h-6" />, description: 'Recurso ao STJ por violação de lei federal' },
  { id: 'agravo', name: 'Agravo', icon: <Hammer className="w-6 h-6" />, description: 'Agravo de instrumento/interno' },
  { id: 'outros', name: 'Outros', icon: <MoreHorizontal className="w-6 h-6" />, description: 'Outros tipos de peças jurídicas' },
]

const LEGAL_AREAS: LegalArea[] = [
  { id: 'civil', name: 'Civil', icon: <Scale className="w-6 h-6" />, color: '#8b5cf6' },
  { id: 'trabalhista', name: 'Trabalhista', icon: <Briefcase className="w-6 h-6" />, color: '#f59e0b' },
  { id: 'penal', name: 'Penal', icon: <Gavel className="w-6 h-6" />, color: '#ef4444' },
  { id: 'tributario', name: 'Tributário', icon: <Building2 className="w-6 h-6" />, color: '#10b981' },
  { id: 'familia', name: 'Família', icon: <Heart className="w-6 h-6" />, color: '#ec4899' },
  { id: 'empresarial', name: 'Empresarial', icon: <Home className="w-6 h-6" />, color: '#3b82f6' },
  { id: 'consumidor', name: 'Consumidor', icon: <ShoppingCart className="w-6 h-6" />, color: '#f97316' },
  { id: 'administrativo', name: 'Administrativo', icon: <Settings className="w-6 h-6" />, color: '#6366f1' },
]

const STEPS = [
  { label: 'Tipo', icon: <FileText className="w-4 h-4" /> },
  { label: 'Área', icon: <Scale className="w-4 h-4" /> },
  { label: 'Detalhes', icon: <ClipboardList className="w-4 h-4" /> },
  { label: 'Revisar', icon: <Eye className="w-4 h-4" /> },
  { label: 'Resultado', icon: <Sparkles className="w-4 h-4" /> },
]

// ─── Animation Variants ─────────────────────────────────────────────

const pageVariants = {
  initial: { opacity: 0, x: 60 },
  animate: { opacity: 1, x: 0, transition: { duration: 0.4, ease: [0.25, 0.46, 0.45, 0.94] } },
  exit: { opacity: 0, x: -60, transition: { duration: 0.3 } },
} as const

const cardVariants: Variants = {
  initial: { opacity: 0, y: 20, scale: 0.95 },
  animate: (i: number) => ({
    opacity: 1, y: 0, scale: 1,
    transition: { delay: i * 0.04, duration: 0.4, ease: [0.25, 0.46, 0.45, 0.94] },
  }),
  hover: { scale: 1.03, transition: { duration: 0.2 } },
  tap: { scale: 0.97 },
}

const staggerContainer = {
  animate: { transition: { staggerChildren: 0.04 } },
} as const

// ─── Component ──────────────────────────────────────────────────────

export default function NovaPecaPage() {
  const [step, setStep] = useState(0)
  const [selectedType, setSelectedType] = useState<string | null>(null)
  const [selectedArea, setSelectedArea] = useState<string | null>(null)
  const [details, setDetails] = useState<FormDetails>({
    autor: '', reu: '', fatos: '', fundamentos: '', pedidos: '', contexto: '',
  })
  const [generatedContent, setGeneratedContent] = useState('')
  const [isGenerating, setIsGenerating] = useState(false)
  const [wordCount, setWordCount] = useState(0)
  const [copied, setCopied] = useState(false)
  const [isEditing, setIsEditing] = useState(false)
  const [documentId, setDocumentId] = useState<string | null>(null)
  const contentRef = useRef<HTMLDivElement>(null)
  const editRef = useRef<HTMLTextAreaElement>(null)
  const searchParams = useSearchParams()
  const [analysisSource, setAnalysisSource] = useState<{ filename: string; title: string } | null>(null)
  const [loadingAnalysis, setLoadingAnalysis] = useState(false)

  // Load pre-filled data from analysis
  useEffect(() => {
    const analysisId = searchParams.get('from_analysis')
    if (!analysisId) return

    setLoadingAnalysis(true)
    fetch(`/api/analise-processo/${analysisId}/peticao`)
      .then(res => {
        if (!res.ok) throw new Error('Failed to load analysis')
        return res.json()
      })
      .then(data => {
        setSelectedType('peticao-inicial')
        setSelectedArea(data.extracted.area || 'civil')
        setDetails({
          autor: data.extracted.autor || '',
          reu: data.extracted.reu || '',
          fatos: data.extracted.fatos || '',
          fundamentos: data.extracted.fundamentos || '',
          pedidos: data.extracted.pedidos || '',
          contexto: `[PARECER JURÍDICO COMPLETO - usar como base para a petição]\n\n${data.parecer}`,
        })
        setAnalysisSource({ filename: data.filename, title: data.title })
        setStep(2) // Go directly to details step
      })
      .catch(err => {
        console.error('Error loading analysis:', err)
      })
      .finally(() => setLoadingAnalysis(false))
  }, [searchParams])

  // Word count tracker
  useEffect(() => {
    if (generatedContent) {
      setWordCount(generatedContent.split(/\s+/).filter(Boolean).length)
    }
  }, [generatedContent])

  const selectedTypeData = DOCUMENT_TYPES.find(t => t.id === selectedType)
  const selectedAreaData = LEGAL_AREAS.find(a => a.id === selectedArea)

  const handleGenerate = useCallback(async () => {
    setIsGenerating(true)
    setGeneratedContent('')
    setStep(4)

    try {
      const res = await fetch('/api/documents/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: selectedType,
          area: selectedArea,
          details,
        }),
      })

      if (!res.ok) {
        const err = await res.json()
        throw new Error(err.error || 'Erro ao gerar documento')
      }

      const reader = res.body?.getReader()
      const decoder = new TextDecoder()

      if (!reader) throw new Error('Stream não disponível')

      let buffer = ''
      while (true) {
        const { done, value } = await reader.read()
        if (done) break

        buffer += decoder.decode(value, { stream: true })
        const lines = buffer.split('\n\n')
        buffer = lines.pop() || ''

        for (const line of lines) {
          if (!line.startsWith('data: ')) continue
          try {
            const data = JSON.parse(line.slice(6))
            if (data.done) {
              setDocumentId(data.documentId)
              break
            }
            if (data.content) {
              setGeneratedContent(prev => prev + data.content)
            }
            if (data.documentId) {
              setDocumentId(data.documentId)
            }
          } catch {
            // skip
          }
        }
      }
    } catch (error) {
      console.error('Generation error:', error)
      setGeneratedContent('Erro ao gerar documento. Por favor, tente novamente.')
    } finally {
      setIsGenerating(false)
    }
  }, [selectedType, selectedArea, details])

  const handleCopy = useCallback(() => {
    navigator.clipboard.writeText(stripMarkdown(generatedContent))
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }, [generatedContent])

  const [isDownloading, setIsDownloading] = useState(false)

  const handleDownload = useCallback(async () => {
    setIsDownloading(true)
    try {
      const title = `${selectedTypeData?.name || 'Documento'} - ${selectedAreaData?.name || 'Jurídico'}`
      await downloadAsWord(title, generatedContent)
    } catch (err) {
      console.error('Download error:', err)
    } finally {
      setIsDownloading(false)
    }
  }, [generatedContent, selectedTypeData, selectedAreaData])

  const canProceed = () => {
    switch (step) {
      case 0: return !!selectedType
      case 1: return !!selectedArea
      case 2: return details.fatos.trim().length > 10
      case 3: return true
      default: return false
    }
  }

  const goNext = () => {
    if (step < 4 && canProceed()) setStep(step + 1)
  }

  const goBack = () => {
    if (step > 0 && !isGenerating) setStep(step - 1)
  }

  // ─── Stepper ────────────────────────────────────────────────────

  const renderStepper = () => (
    <div className="flex items-center justify-center gap-1 mb-8">
      {STEPS.map((s, i) => {
        const isActive = i === step
        const isCompleted = i < step
        return (
          <div key={s.label} className="flex items-center">
            <button
              onClick={() => { if (i < step && !isGenerating) setStep(i) }}
              disabled={i > step || isGenerating}
              className={`
                flex items-center gap-2 px-3 py-2 rounded-xl text-sm font-medium transition-all duration-300
                ${isActive
                  ? 'bg-teal-600/30 text-teal-300 border border-teal-500/50 shadow-lg shadow-teal-500/20'
                  : isCompleted
                    ? 'bg-teal-900/20 text-teal-400 border border-teal-700/30 cursor-pointer hover:bg-teal-800/20'
                    : 'bg-white/[0.02] text-white/30 border border-white/[0.05]'
                }
              `}
            >
              {isCompleted ? (
                <CheckCircle2 className="w-4 h-4 text-green-400" />
              ) : (
                <span className={isActive ? 'text-teal-300' : ''}>{s.icon}</span>
              )}
              <span className="hidden sm:inline">{s.label}</span>
            </button>
            {i < STEPS.length - 1 && (
              <ChevronRight className={`w-4 h-4 mx-1 ${i < step ? 'text-teal-500' : 'text-white/10'}`} />
            )}
          </div>
        )
      })}
    </div>
  )

  // ─── Step 0: Document Type ──────────────────────────────────────

  const renderTypeSelection = () => (
    <motion.div key="step-type" variants={pageVariants} initial="initial" animate="animate" exit="exit">
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold gradient-text mb-2">Que tipo de peça deseja gerar?</h2>
        <p className="text-white/50">Selecione o tipo de documento jurídico</p>
      </div>
      <motion.div
        className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3"
        variants={staggerContainer}
        initial="initial"
        animate="animate"
      >
        {DOCUMENT_TYPES.map((type, i) => (
          <motion.button
            key={type.id}
            custom={i}
            variants={cardVariants}
            whileHover="hover"
            whileTap="tap"
            onClick={() => { setSelectedType(type.id); setStep(1) }}
            className={`
              relative group flex flex-col items-center gap-3 p-5 rounded-2xl text-center transition-all duration-300
              ${selectedType === type.id
                ? 'glass-strong glow-purple border-teal-500/50'
                : 'glass hover:border-teal-500/30'
              }
            `}
          >
            <div className={`
              p-3 rounded-xl transition-all duration-300
              ${selectedType === type.id
                ? 'bg-teal-500/30 text-teal-300'
                : 'bg-white/[0.03] text-white/50 group-hover:text-teal-400 group-hover:bg-teal-500/10'
              }
            `}>
              {type.icon}
            </div>
            <div>
              <p className="font-semibold text-sm text-white/90">{type.name}</p>
              <p className="text-[11px] text-white/40 mt-1 leading-tight">{type.description}</p>
            </div>
            {selectedType === type.id && (
              <motion.div
                layoutId="type-check"
                className="absolute top-2 right-2 w-5 h-5 bg-teal-500 rounded-full flex items-center justify-center"
                initial={{ scale: 0 }}
                animate={{ scale: 1 }}
              >
                <Check className="w-3 h-3 text-white" />
              </motion.div>
            )}
          </motion.button>
        ))}
      </motion.div>
    </motion.div>
  )

  // ─── Step 1: Legal Area ─────────────────────────────────────────

  const renderAreaSelection = () => (
    <motion.div key="step-area" variants={pageVariants} initial="initial" animate="animate" exit="exit">
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold gradient-text mb-2">Área do Direito</h2>
        <p className="text-white/50">
          Gerando: <span className="text-teal-400 font-medium">{selectedTypeData?.name}</span>
        </p>
      </div>
      <motion.div
        className="grid grid-cols-2 sm:grid-cols-4 gap-4 max-w-3xl mx-auto"
        variants={staggerContainer}
        initial="initial"
        animate="animate"
      >
        {LEGAL_AREAS.map((area, i) => (
          <motion.button
            key={area.id}
            custom={i}
            variants={cardVariants}
            whileHover="hover"
            whileTap="tap"
            onClick={() => { setSelectedArea(area.id); setStep(2) }}
            className={`
              relative group flex flex-col items-center gap-3 p-6 rounded-2xl transition-all duration-300
              ${selectedArea === area.id
                ? 'glass-strong border-teal-500/50'
                : 'glass hover:border-teal-500/30'
              }
            `}
            style={{
              boxShadow: selectedArea === area.id ? `0 0 30px ${area.color}30` : undefined,
            }}
          >
            <div
              className="p-3 rounded-xl transition-all duration-300"
              style={{
                background: selectedArea === area.id ? `${area.color}25` : 'rgba(255,255,255,0.03)',
                color: selectedArea === area.id ? area.color : 'rgba(255,255,255,0.5)',
              }}
            >
              {area.icon}
            </div>
            <p className="font-semibold text-white/90">{area.name}</p>
            {selectedArea === area.id && (
              <motion.div
                layoutId="area-check"
                className="absolute top-2 right-2 w-5 h-5 rounded-full flex items-center justify-center"
                style={{ background: area.color }}
                initial={{ scale: 0 }}
                animate={{ scale: 1 }}
              >
                <Check className="w-3 h-3 text-white" />
              </motion.div>
            )}
          </motion.button>
        ))}
      </motion.div>
    </motion.div>
  )

  // ─── Step 2: Details Form ───────────────────────────────────────

  const renderDetailsForm = () => (
    <motion.div key="step-details" variants={pageVariants} initial="initial" animate="animate" exit="exit">
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold gradient-text mb-2">Detalhes da Peça</h2>
        <p className="text-white/50">
          <span className="text-teal-400">{selectedTypeData?.name}</span> · <span className="text-teal-400">{selectedAreaData?.name}</span>
        </p>
      </div>
      <div className="max-w-3xl mx-auto space-y-5">
        {/* Parties */}
        <motion.div
          className="grid grid-cols-1 sm:grid-cols-2 gap-4"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
        >
          <div>
            <label className="flex items-center gap-2 text-sm font-medium text-white/70 mb-2">
              <Users className="w-4 h-4 text-teal-400" />
              Autor / Requerente
            </label>
            <input
              type="text"
              value={details.autor}
              onChange={e => setDetails(d => ({ ...d, autor: e.target.value }))}
              placeholder="Nome completo do autor"
              className="w-full px-4 py-3 rounded-xl glass text-white placeholder-white/30 focus:outline-none focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/30 transition-all"
            />
          </div>
          <div>
            <label className="flex items-center gap-2 text-sm font-medium text-white/70 mb-2">
              <Users className="w-4 h-4 text-red-400" />
              Réu / Requerido
            </label>
            <input
              type="text"
              value={details.reu}
              onChange={e => setDetails(d => ({ ...d, reu: e.target.value }))}
              placeholder="Nome completo do réu"
              className="w-full px-4 py-3 rounded-xl glass text-white placeholder-white/30 focus:outline-none focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/30 transition-all"
            />
          </div>
        </motion.div>

        {/* Facts */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}>
          <label className="flex items-center gap-2 text-sm font-medium text-white/70 mb-2">
            <BookMarked className="w-4 h-4 text-teal-400" />
            Fatos <span className="text-red-400">*</span>
          </label>
          <textarea
            value={details.fatos}
            onChange={e => setDetails(d => ({ ...d, fatos: e.target.value }))}
            placeholder="Descreva os fatos de forma clara e cronológica. Quanto mais detalhado, melhor será a peça gerada..."
            rows={5}
            className="w-full px-4 py-3 rounded-xl glass text-white placeholder-white/30 focus:outline-none focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/30 transition-all resize-none"
          />
          <p className="text-xs text-white/30 mt-1">{details.fatos.length} caracteres · mínimo 10</p>
        </motion.div>

        {/* Legal Grounds */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.3 }}>
          <label className="flex items-center gap-2 text-sm font-medium text-white/70 mb-2">
            <BookOpen className="w-4 h-4 text-teal-400" />
            Fundamentos Jurídicos
          </label>
          <textarea
            value={details.fundamentos}
            onChange={e => setDetails(d => ({ ...d, fundamentos: e.target.value }))}
            placeholder="Artigos de lei, jurisprudência ou teses jurídicas que fundamentam o pedido (opcional - a IA também citará automaticamente)"
            rows={3}
            className="w-full px-4 py-3 rounded-xl glass text-white placeholder-white/30 focus:outline-none focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/30 transition-all resize-none"
          />
        </motion.div>

        {/* Requests */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.4 }}>
          <label className="flex items-center gap-2 text-sm font-medium text-white/70 mb-2">
            <MessageSquare className="w-4 h-4 text-teal-400" />
            Pedidos
          </label>
          <textarea
            value={details.pedidos}
            onChange={e => setDetails(d => ({ ...d, pedidos: e.target.value }))}
            placeholder="Descreva os pedidos que deseja formular (tutela antecipada, indenização, etc.)"
            rows={3}
            className="w-full px-4 py-3 rounded-xl glass text-white placeholder-white/30 focus:outline-none focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/30 transition-all resize-none"
          />
        </motion.div>

        {/* Additional Context */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.5 }}>
          <label className="flex items-center gap-2 text-sm font-medium text-white/70 mb-2">
            <ClipboardList className="w-4 h-4 text-teal-400" />
            Contexto Adicional
          </label>
          <textarea
            value={details.contexto}
            onChange={e => setDetails(d => ({ ...d, contexto: e.target.value }))}
            placeholder="Qualquer informação adicional relevante (valor da causa, urgência, detalhes processuais...)"
            rows={2}
            className="w-full px-4 py-3 rounded-xl glass text-white placeholder-white/30 focus:outline-none focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/30 transition-all resize-none"
          />
        </motion.div>

        {/* File Upload */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.6 }}>
          <label className="flex items-center gap-2 text-sm font-medium text-white/70 mb-2">
            <Upload className="w-4 h-4 text-teal-400" />
            Documentos de Referência
          </label>
          <FileUpload compact label="Documentos de Referência" maxFiles={5} />
        </motion.div>
      </div>
    </motion.div>
  )

  // ─── Step 3: Review ─────────────────────────────────────────────

  const renderReview = () => {
    const summaryItems = [
      { label: 'Tipo de Peça', value: selectedTypeData?.name || '-', icon: <FileText className="w-4 h-4" /> },
      { label: 'Área do Direito', value: selectedAreaData?.name || '-', icon: <Scale className="w-4 h-4" /> },
      { label: 'Autor', value: details.autor || 'Não informado', icon: <Users className="w-4 h-4" /> },
      { label: 'Réu', value: details.reu || 'Não informado', icon: <Users className="w-4 h-4" /> },
    ]

    return (
      <motion.div key="step-review" variants={pageVariants} initial="initial" animate="animate" exit="exit">
        <div className="text-center mb-8">
          <h2 className="text-2xl font-bold gradient-text mb-2">Revisar e Gerar</h2>
          <p className="text-white/50">Confira os dados antes de gerar a peça</p>
        </div>
        <div className="max-w-3xl mx-auto space-y-6">
          {/* Summary Cards */}
          <motion.div
            className="grid grid-cols-2 gap-3"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.1 }}
          >
            {summaryItems.map((item, i) => (
              <div key={i} className="glass rounded-xl p-4">
                <div className="flex items-center gap-2 text-white/40 text-xs mb-1">
                  <span className="text-teal-400">{item.icon}</span>
                  {item.label}
                </div>
                <p className="text-white font-medium text-sm">{item.value}</p>
              </div>
            ))}
          </motion.div>

          {/* Content Preview */}
          {details.fatos && (
            <motion.div
              className="glass rounded-xl p-5"
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.2 }}
            >
              <h4 className="text-sm font-medium text-teal-400 mb-2">Fatos</h4>
              <p className="text-white/70 text-sm whitespace-pre-wrap">{details.fatos}</p>
            </motion.div>
          )}

          {details.fundamentos && (
            <motion.div
              className="glass rounded-xl p-5"
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.25 }}
            >
              <h4 className="text-sm font-medium text-teal-400 mb-2">Fundamentos Jurídicos</h4>
              <p className="text-white/70 text-sm whitespace-pre-wrap">{details.fundamentos}</p>
            </motion.div>
          )}

          {details.pedidos && (
            <motion.div
              className="glass rounded-xl p-5"
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.3 }}
            >
              <h4 className="text-sm font-medium text-teal-400 mb-2">Pedidos</h4>
              <p className="text-white/70 text-sm whitespace-pre-wrap">{details.pedidos}</p>
            </motion.div>
          )}

          {/* Credit Notice */}
          <motion.div
            className="flex items-center gap-3 p-4 rounded-xl bg-teal-500/10 border border-teal-500/20"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.4 }}
          >
            <Zap className="w-5 h-5 text-yellow-400 shrink-0" />
            <div>
              <p className="text-sm text-white/80">Esta geração consumirá <span className="text-teal-300 font-bold">1 crédito</span></p>
              <p className="text-xs text-white/40 mt-0.5">O documento será gerado por IA e pode ser editado depois</p>
            </div>
          </motion.div>

          {/* Generate Button */}
          <motion.button
            onClick={handleGenerate}
            className="w-full py-4 rounded-2xl bg-gradient-to-r from-teal-600 to-teal-700 hover:from-teal-500 hover:to-teal-600 text-white font-bold text-lg flex items-center justify-center gap-3 transition-all duration-300 glow-purple-strong"
            whileHover={{ scale: 1.01 }}
            whileTap={{ scale: 0.98 }}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.5 }}
          >
            <Sparkles className="w-5 h-5" />
            Gerar Peça com IA
          </motion.button>
        </div>
      </motion.div>
    )
  }

  // ─── Step 4: Result ─────────────────────────────────────────────

  const renderResult = () => (
    <motion.div key="step-result" variants={pageVariants} initial="initial" animate="animate" exit="exit">
      <div className="max-w-4xl mx-auto">
        {/* Header Bar */}
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6">
          <div>
            <h2 className="text-2xl font-bold gradient-text">
              {isGenerating ? 'Gerando documento...' : 'Documento Gerado'}
            </h2>
            <div className="flex items-center gap-4 mt-1 text-sm text-white/50">
              <span>{selectedTypeData?.name}</span>
              <span>·</span>
              <span>{selectedAreaData?.name}</span>
              {!isGenerating && (
                <>
                  <span>·</span>
                  <span>{wordCount.toLocaleString('pt-BR')} palavras</span>
                </>
              )}
            </div>
          </div>

          {!isGenerating && generatedContent && (
            <motion.div
              className="flex items-center gap-2"
              initial={{ opacity: 0, y: -10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.3 }}
            >
              <button
                onClick={handleCopy}
                className="flex items-center gap-2 px-4 py-2 rounded-xl glass hover:bg-teal-500/10 text-sm transition-all"
              >
                {copied ? <CheckCircle2 className="w-4 h-4 text-green-400" /> : <Copy className="w-4 h-4" />}
                {copied ? 'Copiado!' : 'Copiar'}
              </button>
              <button
                onClick={handleDownload}
                className="flex items-center gap-2 px-4 py-2 rounded-xl glass hover:bg-teal-500/10 text-sm transition-all"
              >
                <Download className="w-4 h-4" />
                {isDownloading ? 'Gerando...' : 'Baixar Word'}
              </button>
              <button
                onClick={() => {
                  setIsEditing(!isEditing)
                  if (!isEditing) setTimeout(() => editRef.current?.focus(), 100)
                }}
                className={`flex items-center gap-2 px-4 py-2 rounded-xl text-sm transition-all ${
                  isEditing ? 'bg-teal-500/20 text-teal-300 border border-teal-500/30' : 'glass hover:bg-teal-500/10'
                }`}
              >
                <Edit3 className="w-4 h-4" />
                {isEditing ? 'Visualizar' : 'Editar'}
              </button>
            </motion.div>
          )}
        </div>

        {/* Content Area */}
        <motion.div
          className="glass-strong rounded-2xl p-6 sm:p-8 min-h-[400px] relative overflow-hidden"
          initial={{ opacity: 0, scale: 0.98 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ delay: 0.1 }}
        >
          {isGenerating && (
            <motion.div
              className="absolute top-0 left-0 h-1 bg-gradient-to-r from-teal-500 via-pink-500 to-teal-500 rounded-full"
              initial={{ width: '0%' }}
              animate={{ width: '100%' }}
              transition={{ duration: 30, ease: 'linear' }}
            />
          )}

          {isEditing ? (
            <textarea
              ref={editRef}
              value={generatedContent}
              onChange={e => setGeneratedContent(e.target.value)}
              className="w-full h-[600px] bg-transparent text-white/90 text-sm leading-relaxed font-mono resize-none focus:outline-none"
            />
          ) : (
            <div
              ref={contentRef}
              className="prose prose-invert prose-sm max-w-none prose-headings:text-white prose-headings:font-bold prose-strong:text-white prose-code:text-teal-300 prose-blockquote:border-teal-500/30 prose-blockquote:text-zinc-400 prose-a:text-teal-400 prose-li:text-gray-300 prose-li:marker:text-teal-500 selection:bg-teal-500/30"
            >
              {generatedContent ? (
                <ReactMarkdown>{generatedContent}</ReactMarkdown>
              ) : (
                <div className="flex flex-col items-center justify-center h-[300px] gap-4">
                  <Loader2 className="w-8 h-8 text-teal-400 animate-spin" />
                  <p className="text-white/40">Gerando sua peça jurídica...</p>
                  <p className="text-xs text-white/20">Isso pode levar até 1 minuto</p>
                </div>
              )}
              {isGenerating && generatedContent && (
                <motion.span
                  className="inline-block w-2 h-5 bg-teal-400 ml-0.5"
                  animate={{ opacity: [1, 0] }}
                  transition={{ duration: 0.8, repeat: Infinity }}
                />
              )}
            </div>
          )}
        </motion.div>

        {/* New Document Button */}
        {!isGenerating && generatedContent && (
          <motion.div
            className="flex justify-center mt-6"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.5 }}
          >
            <button
              onClick={() => {
                setStep(0)
                setSelectedType(null)
                setSelectedArea(null)
                setDetails({ autor: '', reu: '', fatos: '', fundamentos: '', pedidos: '', contexto: '' })
                setGeneratedContent('')
                setDocumentId(null)
                setIsEditing(false)
              }}
              className="flex items-center gap-2 px-6 py-3 rounded-xl glass hover:bg-teal-500/10 text-white/70 hover:text-white transition-all"
            >
              <RotateCcw className="w-4 h-4" />
              Gerar Nova Peça
            </button>
          </motion.div>
        )}
      </div>
    </motion.div>
  )

  // ─── Main Render ────────────────────────────────────────────────

  return (
    <div className="min-h-screen bg-[#0a0f1a] bg-grid">
      {/* Background Effects */}
      <div className="fixed inset-0 bg-radial-purple pointer-events-none" />

      <div className="relative z-10 max-w-7xl mx-auto px-4 sm:px-6 py-8">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            <a
              href="/dashboard"
              className="p-2 rounded-xl glass hover:bg-teal-500/10 transition-all"
            >
              <ArrowLeft className="w-5 h-5 text-white/60" />
            </a>
            <div>
              <h1 className="text-xl font-bold text-white flex items-center gap-2">
                <Sparkles className="w-5 h-5 text-teal-400" />
                Nova Peça Jurídica
              </h1>
              <p className="text-xs text-white/40">Gerador de documentos com IA</p>
            </div>
          </div>
        </div>

        {/* Analysis Source Banner */}
        {analysisSource && (
          <div className="mb-4 flex items-center gap-3 rounded-xl border border-teal-500/20 bg-teal-500/10 px-5 py-3">
            <FileText className="h-5 w-5 text-teal-400 shrink-0" />
            <div className="flex-1">
              <p className="text-sm font-medium text-teal-300">
                📋 Petição baseada no parecer de: <span className="text-white">{analysisSource.filename}</span>
              </p>
              <p className="text-xs text-teal-400/60 mt-0.5">Os campos foram pré-preenchidos com dados extraídos da análise</p>
            </div>
          </div>
        )}

        {/* Loading Analysis */}
        {loadingAnalysis && (
          <div className="mb-4 flex items-center justify-center gap-3 rounded-xl border border-white/5 bg-white/[0.02] px-5 py-6">
            <Loader2 className="h-5 w-5 text-teal-400 animate-spin" />
            <p className="text-sm text-white/60">Carregando dados do parecer...</p>
          </div>
        )}

        {/* Stepper */}
        {renderStepper()}

        {/* Step Content */}
        <AnimatePresence mode="wait">
          {step === 0 && renderTypeSelection()}
          {step === 1 && renderAreaSelection()}
          {step === 2 && renderDetailsForm()}
          {step === 3 && renderReview()}
          {step === 4 && renderResult()}
        </AnimatePresence>

        {/* Navigation Buttons (steps 1-2) */}
        {step > 0 && step < 4 && (
          <motion.div
            className="flex items-center justify-between max-w-3xl mx-auto mt-8"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.3 }}
          >
            <button
              onClick={goBack}
              className="flex items-center gap-2 px-5 py-2.5 rounded-xl glass hover:bg-teal-500/10 text-white/60 hover:text-white transition-all"
            >
              <ChevronLeft className="w-4 h-4" />
              Voltar
            </button>
            {step < 3 && (
              <button
                onClick={goNext}
                disabled={!canProceed()}
                className={`
                  flex items-center gap-2 px-6 py-2.5 rounded-xl font-medium transition-all
                  ${canProceed()
                    ? 'bg-teal-600 hover:bg-teal-500 text-white glow-purple'
                    : 'bg-white/5 text-white/20 cursor-not-allowed'
                  }
                `}
              >
                Próximo
                <ChevronRight className="w-4 h-4" />
              </button>
            )}
          </motion.div>
        )}
      </div>
    </div>
  )
}
