
import React, { useState, useEffect, Component, ErrorInfo, ReactNode } from 'react';
import { createRoot } from 'react-dom/client';
import { 
  Building2, Menu, X, ArrowRight, TrendingUp, ShieldCheck, 
  Clock, Check, Loader2, CheckCircle, AlertTriangle, FileText, 
  Download, Briefcase, Cpu, Users, BarChart, Mail, Phone, Send,
  MoreVertical
} from 'lucide-react';
import { PieChart, Pie, Cell, ResponsiveContainer, Label } from 'recharts';
import { GoogleGenAI, Type } from "@google/genai";

// --- 1. TIPOS ---
type ViewState = 'home' | 'assessment' | 'analysis' | 'contact' | 'solutions';

interface Question {
  id: number;
  text: string;
  options: string[];
}

interface AssessmentAnswers {
  [key: number]: string;
}

interface AnalysisData {
  score: number;
  summary: string;
  strengths: string[];
  weaknesses: string[];
  recommendations: string[];
  financialMaturityLevel: 'Iniciante' | 'Em Desenvolvimento' | 'Profissional' | 'Otimizado';
}

// --- 2. DADOS ESTÁTICOS ---
const QUESTIONS_DATA: Question[] = [
  {
    id: 1,
    text: "Como é realizado o processo de conciliação bancária na sua empresa?",
    options: [
      "Totalmente manual (planilhas e extratos impressos).",
      "Parcialmente automatizado (importação de OFX no ERP, mas com ajustes manuais).",
      "Totalmente automatizado (integração direta via API/CNAB sem intervenção manual diária).",
    ]
  },
  {
    id: 2,
    text: "Qual a frequência de atualização do seu Fluxo de Caixa?",
    options: [
      "Não possuímos fluxo de caixa estruturado.",
      "Mensalmente, apenas para fechamento.",
      "Semanalmente.",
      "Diariamente, com projeção futura (Forecast).",
    ]
  },
  {
    id: 3,
    text: "Como são gerenciadas as aprovações de pagamentos?",
    options: [
      "Assinatura física em cheques ou bordereaux impressos.",
      "E-mail ou WhatsApp solicitando aprovação.",
      "Sistema bancário com alçadas e tokens (approver digital).",
      "Plataforma integrada de gestão de pagamentos com workflow automatizado.",
    ]
  },
  {
    id: 4,
    text: "Quantas contas bancárias a empresa movimenta ativamente?",
    options: [
      "1 a 2 bancos.",
      "3 a 5 bancos.",
      "Mais de 5 bancos.",
    ]
  },
  {
    id: 5,
    text: "Sua equipe financeira dedica quanto tempo a tarefas operacionais (digitação, conferência)?",
    options: [
      "Mais de 80% do tempo.",
      "Entre 50% e 80% do tempo.",
      "Menos de 50%, o foco é estratégico.",
    ]
  },
  {
    id: 6,
    text: "A empresa realiza cotação de taxas bancárias e produtos financeiros regularmente?",
    options: [
      "Nunca, aceitamos o que o banco oferece.",
      "Raramente, apenas em grandes operações.",
      "Sim, temos uma rotina constante de negociação com múltiplos bancos.",
    ]
  }
];

// --- 3. SERVIÇOS ---
const analyzeWithAI = async (answers: AssessmentAnswers): Promise<AnalysisData> => {
  const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
  
  let promptContext = "Analise as seguintes respostas de um diagnóstico financeiro industrial:\n\n";
  QUESTIONS_DATA.forEach((q) => {
    promptContext += `Pergunta: ${q.text}\nResposta: ${answers[q.id]}\n\n`;
  });

  try {
    const response = await ai.models.generateContent({
      model: 'gemini-3-pro-preview',
      contents: promptContext,
      config: {
        thinkingConfig: { thinkingBudget: 4096 },
        systemInstruction: "Você é um CFO consultor. Analise ineficiências, riscos e automação. Retorne JSON.",
        responseMimeType: "application/json",
        responseSchema: {
          type: Type.OBJECT,
          properties: {
            score: { type: Type.INTEGER },
            summary: { type: Type.STRING },
            strengths: { type: Type.ARRAY, items: { type: Type.STRING } },
            weaknesses: { type: Type.ARRAY, items: { type: Type.STRING } },
            recommendations: { type: Type.ARRAY, items: { type: Type.STRING } },
            financialMaturityLevel: { type: Type.STRING, enum: ['Iniciante', 'Em Desenvolvimento', 'Profissional', 'Otimizado'] }
          },
          required: ["score", "summary", "strengths", "weaknesses", "recommendations", "financialMaturityLevel"],
        },
      },
    });

    return JSON.parse(response.text || '{}');
  } catch (error) {
    console.error("Erro AI:", error);
    return {
      score: 45,
      summary: "Processos manuais detectados com risco operacional moderado.",
      strengths: ["Consciência da necessidade de mudança"],
      weaknesses: ["Alta dependência de planilhas"],
      recommendations: ["Implementar API Bancária", "Revisar fluxos de aprovação"],
      financialMaturityLevel: 'Iniciante'
    };
  }
};

// --- 4. COMPONENTES ---

const Header = ({ setView, currentView }: { setView: (v: ViewState) => void, currentView: ViewState }) => {
  const [isOpen, setIsOpen] = useState(false);

  const navItems: { label: string; value: ViewState }[] = [
    { label: 'Início', value: 'home' },
    { label: 'Soluções', value: 'solutions' },
    { label: 'Contato', value: 'contact' },
  ];

  const handleNav = (v: ViewState) => {
    setView(v);
    setIsOpen(false);
  };

  return (
    <header className="bg-white border-b border-gray-100 sticky top-0 z-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex justify-between items-center">
        {/* Logo */}
        <div className="flex items-center cursor-pointer" onClick={() => handleNav('home')}>
          <Building2 className="h-8 w-8 text-blue-600 mr-2" />
          <span className="text-xl font-bold text-slate-900">FinAdmin <span className="text-blue-600">Audit</span></span>
        </div>

        {/* Desktop Nav */}
        <nav className="hidden md:flex space-x-8 items-center">
          {navItems.map(item => (
            <button 
              key={item.value}
              onClick={() => handleNav(item.value)} 
              className={`text-sm font-medium transition-colors ${currentView === item.value ? 'text-blue-600' : 'text-gray-500 hover:text-blue-600'}`}
            >
              {item.label}
            </button>
          ))}
          <button 
            onClick={() => handleNav('assessment')} 
            className="bg-slate-900 text-white px-4 py-2 rounded-md text-sm font-medium hover:bg-slate-800 transition-shadow hover:shadow-lg"
          >
            Fazer Diagnóstico
          </button>
        </nav>

        {/* Mobile Toggle (Pontinhos / Hambúrguer) */}
        <div className="md:hidden flex items-center">
          <button 
            onClick={() => setIsOpen(!isOpen)}
            className="p-2 text-gray-500 hover:text-blue-600 focus:outline-none transition-transform active:scale-95"
            aria-label="Abrir menu"
          >
            {isOpen ? <X className="h-7 w-7" /> : <Menu className="h-7 w-7" />}
          </button>
        </div>
      </div>

      {/* Mobile Menu Overlay */}
      {isOpen && (
        <div className="md:hidden bg-white border-t border-gray-100 shadow-xl absolute top-16 left-0 w-full animate-in slide-in-from-top duration-300">
          <div className="px-4 pt-2 pb-6 space-y-1">
            {navItems.map(item => (
              <button
                key={item.value}
                onClick={() => handleNav(item.value)}
                className={`block w-full text-left px-4 py-4 text-base font-semibold rounded-xl transition-all ${
                  currentView === item.value 
                    ? 'bg-blue-50 text-blue-600' 
                    : 'text-gray-600 hover:bg-gray-50'
                }`}
              >
                {item.label}
              </button>
            ))}
            <div className="pt-4 px-2">
              <button
                onClick={() => handleNav('assessment')}
                className="w-full bg-slate-900 text-white px-6 py-4 rounded-xl font-bold text-center shadow-lg hover:bg-slate-800 transition-all active:scale-95"
              >
                Fazer Diagnóstico Agora
              </button>
            </div>
          </div>
        </div>
      )}
    </header>
  );
};

const Hero = ({ onStart }: { onStart: () => void }) => (
  <div className="bg-slate-900 relative overflow-hidden">
    <div className="absolute inset-0 opacity-10">
      <img src="https://images.unsplash.com/photo-1554469384-e58fac16e23a?w=800" className="w-full h-full object-cover" />
    </div>
    <div className="relative max-w-7xl mx-auto py-20 px-4 sm:py-24 sm:px-6 lg:px-8">
      <h1 className="text-3xl font-extrabold text-white sm:text-6xl leading-tight text-center md:text-left">
        O seu setor Administrativo Financeiro atua como um <span className="text-blue-500">banco</span> na sua empresa?
      </h1>
      <p className="mt-6 text-lg text-gray-300 max-w-3xl text-center md:text-left">
        Receba um diagnóstico imediato sobre a maturidade da sua tesouraria e automação bancária.
      </p>
      <div className="mt-10 flex justify-center md:justify-start">
        <button onClick={onStart} className="flex items-center px-8 py-4 bg-white text-slate-900 rounded-lg font-bold text-lg hover:bg-gray-100 transition-all shadow-xl hover:-translate-y-1">
          Começar Diagnóstico Agora <ArrowRight className="ml-2" />
        </button>
      </div>
    </div>
  </div>
);

const AssessmentForm = ({ onSubmit, isAnalyzing }: { onSubmit: (a: AssessmentAnswers) => void, isAnalyzing: boolean }) => {
  const [answers, setAnswers] = useState<AssessmentAnswers>({});
  const [step, setStep] = useState(0);

  if (isAnalyzing) return (
    <div className="min-h-[60vh] flex flex-col items-center justify-center p-8 text-center">
      <Loader2 className="h-12 w-12 text-blue-600 animate-spin mb-4" />
      <h2 className="text-2xl font-bold text-slate-900">Processando sua análise...</h2>
      <p className="text-gray-500 mt-2">Nossa IA está avaliando seus fluxos financeiros.</p>
    </div>
  );

  const currentQ = QUESTIONS_DATA[step];
  const progress = ((step + 1) / QUESTIONS_DATA.length) * 100;

  return (
    <div className="max-w-3xl mx-auto py-12 px-4">
      <div className="mb-8">
        <div className="flex justify-between text-xs font-bold text-gray-400 uppercase tracking-widest mb-2">
          <span>Questão {step + 1} de {QUESTIONS_DATA.length}</span>
          <span>{Math.round(progress)}%</span>
        </div>
        <div className="h-1.5 bg-gray-200 rounded-full"><div className="h-full bg-blue-600 rounded-full transition-all" style={{width: `${progress}%`}} /></div>
      </div>
      <div className="bg-white p-8 rounded-2xl shadow-xl border border-gray-100">
        <h2 className="text-xl md:text-2xl font-bold text-slate-900 mb-8 leading-tight">{currentQ.text}</h2>
        <div className="space-y-3">
          {currentQ.options.map((opt, i) => (
            <button key={i} onClick={() => setAnswers({...answers, [currentQ.id]: opt})} className={`w-full text-left p-4 rounded-xl border-2 transition-all flex justify-between items-center ${answers[currentQ.id] === opt ? 'border-blue-600 bg-blue-50' : 'border-gray-100 hover:border-gray-300'}`}>
              <span className={`text-sm md:text-base ${answers[currentQ.id] === opt ? 'font-medium text-blue-900' : 'text-gray-600'}`}>{opt}</span>
              {answers[currentQ.id] === opt && <Check className="text-blue-600 flex-shrink-0 ml-2" />}
            </button>
          ))}
        </div>
        <div className="mt-8 flex justify-end">
          <button disabled={!answers[currentQ.id]} onClick={() => step < QUESTIONS_DATA.length - 1 ? setStep(step+1) : onSubmit(answers)} className="w-full md:w-auto px-8 py-3 bg-slate-900 text-white rounded-lg font-bold disabled:opacity-30 hover:bg-slate-800 transition-colors">
            {step === QUESTIONS_DATA.length - 1 ? 'Finalizar' : 'Próxima'}
          </button>
        </div>
      </div>
    </div>
  );
};

const AnalysisResult = ({ data, onContact }: { data: AnalysisData, onContact: () => void }) => {
  const chartData = [{ v: data.score }, { v: 100 - data.score }];
  const color = data.score > 75 ? '#22c55e' : data.score > 50 ? '#eab308' : '#ef4444';

  return (
    <div className="bg-gray-50 min-h-screen">
      <div className="bg-slate-900 text-white py-16 px-4 text-center">
        <h1 className="text-2xl md:text-3xl font-bold">Diagnóstico Concluído</h1>
        <p className="text-gray-400 mt-2">Veja os insights da sua operação financeira</p>
      </div>
      <div className="max-w-6xl mx-auto px-4 -mt-12 pb-20">
        <div className="bg-white rounded-3xl shadow-2xl overflow-hidden grid lg:grid-cols-3">
          <div className="p-10 bg-slate-50 flex flex-col items-center justify-center border-r">
            <h3 className="font-bold text-slate-500 uppercase text-xs tracking-widest mb-4">Pontuação Geral</h3>
            <div className="h-60 w-full relative">
              <ResponsiveContainer>
                <PieChart>
                  <Pie data={chartData} dataKey="v" innerRadius={70} outerRadius={90} startAngle={180} endAngle={0}>
                    <Cell fill={color} /><Cell fill="#e2e8f0" />
                    <Label value={data.score} position="center" className="text-5xl font-bold fill-slate-900" dy={-10} />
                  </Pie>
                </PieChart>
              </ResponsiveContainer>
              <div className="absolute bottom-10 left-0 right-0 text-center font-bold" style={{color}}>
                {data.financialMaturityLevel}
              </div>
            </div>
          </div>
          <div className="lg:col-span-2 p-10">
            <h2 className="text-xl md:text-2xl font-bold mb-4 flex items-center"><FileText className="mr-2 text-blue-600" /> Resumo Estratégico</h2>
            <p className="text-gray-600 leading-relaxed text-base md:text-lg mb-8">{data.summary}</p>
            <div className="grid md:grid-cols-2 gap-6">
              <div className="bg-green-50 p-6 rounded-2xl border border-green-100">
                <h4 className="font-bold text-green-800 mb-2 flex items-center"><CheckCircle className="mr-2 h-4" /> Pontos Fortes</h4>
                <ul className="text-sm text-green-700 space-y-1">{data.strengths.map((s,i) => <li key={i}>• {s}</li>)}</ul>
              </div>
              <div className="bg-red-50 p-6 rounded-2xl border border-red-100">
                <h4 className="font-bold text-red-800 mb-2 flex items-center"><AlertTriangle className="mr-2 h-4" /> Atenção</h4>
                <ul className="text-sm text-red-700 space-y-1">{data.weaknesses.map((w,i) => <li key={i}>• {w}</li>)}</ul>
              </div>
            </div>
          </div>
        </div>
        <div className="mt-8 bg-white p-6 md:p-10 rounded-3xl shadow-xl">
           <h2 className="text-xl md:text-2xl font-bold mb-6 flex items-center"><TrendingUp className="mr-2 text-blue-600" /> Plano de Ação</h2>
           <div className="grid md:grid-cols-3 gap-6">
             {data.recommendations.map((r,i) => (
               <div key={i} className="p-6 bg-slate-50 rounded-xl border border-slate-100">
                 <div className="h-8 w-8 bg-slate-900 text-white rounded-full flex items-center justify-center font-bold mb-4">{i+1}</div>
                 <p className="font-medium text-slate-800 text-sm md:text-base">{r}</p>
               </div>
             ))}
           </div>
           <div className="mt-12 p-8 bg-blue-600 rounded-2xl text-white text-center">
             <h3 className="text-xl font-bold mb-4">Quer implementar estas melhorias?</h3>
             <button onClick={onContact} className="px-8 py-3 bg-white text-blue-600 rounded-lg font-bold hover:bg-gray-100 transition-all hover:scale-105 active:scale-95 shadow-lg">Falar com Consultor</button>
           </div>
        </div>
      </div>
    </div>
  );
};

// --- 5. COMPONENTE PRINCIPAL (APP) ---

function App() {
  const [view, setView] = useState<ViewState>('home');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<AnalysisData | null>(null);

  const handleSubmit = async (answers: AssessmentAnswers) => {
    setLoading(true);
    const data = await analyzeWithAI(answers);
    setResult(data);
    setLoading(false);
    setView('analysis');
    window.scrollTo(0, 0);
  };

  const emailLink = "mailto:luiz@yagura.com.br?subject=Diagnóstico FinAdmin Audit - Solicitação de Consultoria";
  const phoneLink = "tel:+5511971712993";

  return (
    <div className="min-h-screen flex flex-col">
      <Header setView={setView} currentView={view} />
      <main className="flex-grow">
        {view === 'home' && <Hero onStart={() => setView('assessment')} />}
        {view === 'assessment' && <AssessmentForm onSubmit={handleSubmit} isAnalyzing={loading} />}
        {view === 'analysis' && result && <AnalysisResult data={result} onContact={() => setView('contact')} />}
        {view === 'solutions' && (
          <div className="py-12 md:py-20 text-center max-w-4xl mx-auto px-4">
            <h2 className="text-2xl md:text-3xl font-bold mb-8">Nossas Soluções</h2>
            <div className="grid md:grid-cols-2 gap-8">
              <div className="p-8 bg-white shadow-lg rounded-2xl border hover:border-blue-200 transition-colors">
                <Briefcase className="h-12 w-12 text-blue-600 mb-4 mx-auto" />
                <h3 className="font-bold text-xl mb-2">BPO Financeiro</h3>
                <p className="text-gray-500">Terceirização completa da sua tesouraria operacional para focar no core business.</p>
              </div>
              <div className="p-8 bg-white shadow-lg rounded-2xl border hover:border-blue-200 transition-colors">
                <Cpu className="h-12 w-12 text-blue-600 mb-4 mx-auto" />
                <h3 className="font-bold text-xl mb-2">Automação RPA</h3>
                <p className="text-gray-500">Integração de ERP e bancos via API para eliminar digitação manual de boletos e extratos.</p>
              </div>
            </div>
          </div>
        )}
        {view === 'contact' && (
          <div className="py-12 md:py-20 max-w-xl mx-auto px-4 animate-in fade-in slide-in-from-bottom-4 duration-500">
            <div className="bg-white p-6 md:p-10 rounded-3xl shadow-2xl border text-center relative overflow-hidden">
              <div className="absolute top-0 left-0 w-full h-2 bg-blue-600"></div>
              <h2 className="text-2xl md:text-3xl font-bold mb-4">Contato Direto</h2>
              <p className="text-gray-500 mb-10 text-sm md:text-base">Inicie sua transformação financeira agora mesmo falando com nossa equipe.</p>
              
              <div className="space-y-4 md:space-y-6 text-left mb-10">
                <a 
                  href={emailLink}
                  className="group flex items-center p-4 md:p-5 bg-slate-50 rounded-2xl border border-slate-100 hover:border-blue-300 hover:bg-blue-50 transition-all duration-300"
                >
                  <div className="h-10 w-10 md:h-12 md:w-12 bg-white rounded-xl shadow-sm flex items-center justify-center mr-4 group-hover:bg-blue-600 group-hover:text-white transition-colors">
                    <Mail className="h-5 w-5 md:h-6 md:w-6 text-blue-600 group-hover:text-white" />
                  </div>
                  <div>
                    <span className="block text-[10px] font-bold text-gray-400 uppercase tracking-widest">E-mail Corporativo</span>
                    <span className="text-base md:text-lg font-medium text-slate-900">luiz@yagura.com.br</span>
                  </div>
                </a>

                <a 
                  href={phoneLink}
                  className="group flex items-center p-4 md:p-5 bg-slate-50 rounded-2xl border border-slate-100 hover:border-green-300 hover:bg-green-50 transition-all duration-300"
                >
                  <div className="h-10 w-10 md:h-12 md:w-12 bg-white rounded-xl shadow-sm flex items-center justify-center mr-4 group-hover:bg-green-600 group-hover:text-white transition-colors">
                    <Phone className="h-5 w-5 md:h-6 md:w-6 text-blue-600 group-hover:text-white" />
                  </div>
                  <div>
                    <span className="block text-[10px] font-bold text-gray-400 uppercase tracking-widest">WhatsApp / Celular</span>
                    <span className="text-base md:text-lg font-medium text-slate-900">(11) 97171-2993</span>
                  </div>
                </a>
              </div>

              <div className="grid grid-cols-1 gap-4">
                <a 
                  href={emailLink}
                  className="flex items-center justify-center gap-2 px-8 py-4 bg-blue-600 text-white rounded-2xl font-bold hover:bg-blue-700 transition-all shadow-lg hover:shadow-blue-200 active:scale-95"
                >
                  <Send className="h-5 w-5" />
                  Enviar E-mail Agora
                </a>
                <p className="text-xs text-gray-400">Resposta garantida em até 24h úteis.</p>
              </div>
            </div>
          </div>
        )}
      </main>
      <footer className="bg-slate-900 text-gray-400 py-12 px-4 border-t border-slate-800 mt-auto text-sm md:text-base">
        <div className="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-center gap-6 text-center md:text-left">
          <div className="flex items-center">
            <Building2 className="h-6 w-6 text-blue-500 mr-2" />
            <div className="font-bold text-white text-xl">FinAdmin <span className="text-blue-500">Audit</span></div>
          </div>
          <div>
            © 2024 Yagura Consultoria Financeira. <br className="md:hidden" /> Todos os direitos reservados.
          </div>
        </div>
      </footer>
    </div>
  );
}

// Inicialização
const container = document.getElementById('root');
if (container) {
  const root = createRoot(container);
  root.render(<App />);
}
