import React, { useState, useEffect, useRef } from 'react';

import { 

  BarChart3, 

  Flame, 

  Briefcase, 

  Target, 

  AlertTriangle, 

  CheckCircle2, 

  Send,

  Loader2,

  Table as TableIcon,

  TrendingUp,

  BrainCircuit

} from 'lucide-react';


// Mandato del entorno: La API Key se deja vacía para inyección automática.

const apiKey = "";


const App = () => {

  const [input, setInput] = useState('');

  const [loading, setLoading] = useState(false);

  const [analysis, setAnalysis] = useState(null);

  const [error, setError] = useState(null);

  const [mode, setMode] = useState('critical'); // 'critical' o 'strategic'

  

  const scrollRef = useRef(null);


  const performAnalysis = async () => {

    if (!input.trim()) return;

    

    setLoading(true);

    setError(null);

    

    const systemPrompt = `

      Eres un consultor de estrategia empresarial de alto nivel con 20 años de experiencia en Gestión de Proyectos (ISO 9001) y experto en la industria gastronómica (específicamente BBQ y ahumados).

      

      Tu cliente es Aleph Moreno. Debes usar un tono ejecutivo, técnico y proactivo. 

      ${mode === 'critical' ? 'REGLA CRÍTICA: No seas complaciente. Si la idea del cliente no es coherente, es arriesgada o carece de viabilidad financiera/operativa, debes desmontarla con argumentos técnicos.' : 'ENFOQUE: Optimización estratégica y escalabilidad.'}

      

      Formatea tu respuesta siempre en JSON con la siguiente estructura:

      {

        "resumen_ejecutivo": "string",

        "analisis_viabilidad": { "puntuacion": 1-10, "comentario": "string" },

        "kpis_proyectados": [ { "indicador": "string", "valor_estimado": "string", "justificacion": "string" } ],

        "riesgos_detectados": [ { "riesgo": "string", "impacto": "Alto|Medio|Bajo", "mitigacion": "string" } ],

        "veredicto_final": "string (Aprobado | Rechazado | Requiere Reestructuración)"

      }

    `;


    try {

      const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key=${apiKey}`, {

        method: 'POST',

        headers: { 'Content-Type': 'application/json' },

        body: JSON.stringify({

          contents: [{ parts: [{ text: input }] }],

          systemInstruction: { parts: [{ text: systemPrompt }] },

          generationConfig: { responseMimeType: "application/json" }

        })

      });


      if (!response.ok) throw new Error('Error en la comunicación con la API de Gemini.');

      

      const data = await response.json();

      const result = JSON.parse(data.candidates[0].content.parts[0].text);

      setAnalysis(result);

    } catch (err) {

      setError(err.message);

    } finally {

      setLoading(false);

    }

  };


  return (

    <div className="min-h-screen bg-slate-50 text-slate-900 font-sans p-4 md:p-8">

      {/* Header */}

      <header className="max-w-6xl mx-auto mb-8 flex flex-col md:flex-row md:items-center justify-between gap-4 border-b pb-6">

        <div>

          <h1 className="text-3xl font-bold flex items-center gap-2">

            <BrainCircuit className="text-orange-600" />

            Strategic Intelligence Hub

          </h1>

          <p className="text-slate-500 font-medium">Asistente Ejecutivo para Proyectos y Gastronomía | Aleph Moreno</p>

        </div>

        <div className="flex gap-2 bg-white p-1 rounded-lg shadow-sm border">

          <button 

            onClick={() => setMode('critical')}

            className={`px-4 py-2 rounded-md text-sm font-semibold transition-all ${mode === 'critical' ? 'bg-orange-600 text-white shadow-md' : 'text-slate-600 hover:bg-slate-100'}`}

          >

            Pensamiento Crítico

          </button>

          <button 

            onClick={() => setMode('strategic')}

            className={`px-4 py-2 rounded-md text-sm font-semibold transition-all ${mode === 'strategic' ? 'bg-blue-600 text-white shadow-md' : 'text-slate-600 hover:bg-slate-100'}`}

          >

            Optimización

          </button>

        </div>

      </header>


      <main className="max-w-6xl mx-auto grid grid-cols-1 lg:grid-cols-12 gap-8">

        {/* Input Section */}

        <div className="lg:col-span-5 space-y-4">

          <div className="bg-white p-6 rounded-xl shadow-sm border border-slate-200">

            <h2 className="text-lg font-bold mb-4 flex items-center gap-2">

              <Send size={18} className="text-blue-600" />

              Ingreso de Proyecto / Idea

            </h2>

            <textarea 

              className="w-full h-48 p-4 bg-slate-50 border border-slate-200 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent outline-none transition-all resize-none mb-4"

              placeholder="Ej: Propuesta para expansión de 'Humo Negro' a mercados internacionales mediante modelo de franquicias ISO 9001..."

              value={input}

              onChange={(e) => setInput(e.target.value)}

            />

            <button 

              onClick={performAnalysis}

              disabled={loading || !input.trim()}

              className="w-full bg-slate-900 text-white py-3 rounded-lg font-bold flex items-center justify-center gap-2 hover:bg-slate-800 disabled:opacity-50 transition-colors"

            >

              {loading ? <Loader2 className="animate-spin" /> : <BarChart3 size={20} />}

              {loading ? 'Procesando Datos...' : 'Ejecutar Auditoría Técnica'}

            </button>

          </div>


          {error && (

            <div className="bg-red-50 border border-red-200 text-red-700 p-4 rounded-lg flex items-center gap-3">

              <AlertTriangle className="flex-shrink-0" />

              <p className="text-sm">{error}</p>

            </div>

          )}


          {/* Quick Stats Cards */}

          <div className="grid grid-cols-2 gap-4">

            <div className="bg-orange-50 p-4 rounded-xl border border-orange-100">

              <Flame className="text-orange-600 mb-2" />

              <div className="text-xs text-orange-800 font-bold uppercase tracking-wider">Unidad Táctica</div>

              <div className="text-xl font-black text-orange-900">Asados</div>

            </div>

            <div className="bg-blue-50 p-4 rounded-xl border border-blue-100">

              <Briefcase className="text-blue-600 mb-2" />

              <div className="text-xs text-blue-800 font-bold uppercase tracking-wider">Consultoría</div>

              <div className="text-xl font-black text-blue-900">Maestro a la Carta</div>

            </div>

          </div>

        </div>


        {/* Output Section */}

        <div className="lg:col-span-7">

          {!analysis && !loading && (

            <div className="h-full min-h-[400px] border-2 border-dashed border-slate-300 rounded-xl flex flex-col items-center justify-center text-slate-400 p-8 text-center">

              <Target size={48} className="mb-4 opacity-20" />

              <p className="text-lg font-medium">Esperando datos de entrada para iniciar el análisis estratégico.</p>

              <p className="text-sm">La IA evaluará viabilidad, KPIs y riesgos operativos.</p>

            </div>

          )}


          {loading && (

            <div className="h-full min-h-[400px] bg-white rounded-xl shadow-sm border border-slate-200 flex flex-col items-center justify-center space-y-4">

              <Loader2 size={40} className="animate-spin text-orange-600" />

              <p className="font-bold text-slate-700">Analizando factibilidad técnica...</p>

            </div>

          )}


          {analysis && !loading && (

            <div className="space-y-6 animate-in fade-in duration-500">

              {/* Executive Result */}

              <div className={`p-6 rounded-xl border shadow-sm ${

                analysis.veredicto_final === 'Aprobado' ? 'bg-green-50 border-green-200' : 

                analysis.veredicto_final === 'Rechazado' ? 'bg-red-50 border-red-200' : 'bg-yellow-50 border-yellow-200'

              }`}>

                <div className="flex justify-between items-start mb-4">

                  <h3 className="text-xl font-bold flex items-center gap-2">

                    {analysis.veredicto_final === 'Aprobado' ? <CheckCircle2 className="text-green-600" /> : <AlertTriangle className="text-yellow-600" />}

                    Veredicto: {analysis.veredicto_final}

                  </h3>

                  <div className="text-right">

                    <span className="text-xs font-bold uppercase text-slate-500">Viabilidad</span>

                    <div className="text-2xl font-black">{analysis.analisis_viabilidad.puntuacion}/10</div>

                  </div>

                </div>

                <p className="text-slate-700 leading-relaxed italic border-l-4 border-slate-300 pl-4">

                  "{analysis.resumen_ejecutivo}"

                </p>

              </div>


              {/* KPI Table */}

              <div className="bg-white p-6 rounded-xl shadow-sm border border-slate-200">

                <h3 className="text-lg font-bold mb-4 flex items-center gap-2">

                  <TrendingUp className="text-blue-600" />

                  KPIs y Proyecciones de Negocio

                </h3>

                <div className="overflow-x-auto">

                  <table className="w-full text-sm text-left">

                    <thead className="bg-slate-50 text-slate-600">

                      <tr>

                        <th className="p-3 font-bold border-b">Indicador</th>

                        <th className="p-3 font-bold border-b">Valor Est.</th>

                        <th className="p-3 font-bold border-b">Justificación</th>

                      </tr>

                    </thead>

                    <tbody className="divide-y">

                      {analysis.kpis_proyectados.map((kpi, idx) => (

                        <tr key={idx} className="hover:bg-slate-50 transition-colors">

                          <td className="p-3 font-semibold text-slate-900">{kpi.indicador}</td>

                          <td className="p-3 text-blue-600 font-bold">{kpi.valor_estimado}</td>

                          <td className="p-3 text-slate-600">{kpi.justificacion}</td>

                        </tr>

                      ))}

                    </tbody>

                  </table>

                </div>

              </div>


              {/* Risks & Mitigation */}

              <div className="bg-white p-6 rounded-xl shadow-sm border border-slate-200">

                <h3 className="text-lg font-bold mb-4 flex items-center gap-2">

                  <AlertTriangle className="text-red-600" />

                  Análisis de Riesgos (ISO Context)

                </h3>

                <div className="space-y-4">

                  {analysis.riesgos_detectados.map((risk, idx) => (

                    <div key={idx} className="p-4 rounded-lg bg-slate-50 border-l-4 border-red-500">

                      <div className="flex justify-between mb-1">

                        <span className="font-bold text-slate-800">{risk.riesgo}</span>

                        <span className={`text-[10px] px-2 py-0.5 rounded-full font-bold ${

                          risk.impacto === 'Alto' ? 'bg-red-100 text-red-700' : 'bg-yellow-100 text-yellow-700'

                        }`}>IMPACTO {risk.impacto}</span>

                      </div>

                      <p className="text-xs text-slate-600 font-medium">Mitigación: {risk.mitigacion}</p>

                    </div>

                  ))}

                </div>

              </div>

            </div>

          )}

        </div>

      </main>

      

      <footer className="max-w-6xl mx-auto mt-12 pt-8 border-t text-center text-slate-400 text-sm">

        <p>© 2026 - Estrategia Ejecutiva | El Señor de las Brasas & Partners</p>

      </footer>

    </div>

  );

};


export default App;