import React, { useState, useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { 
  Plus, 
  Inbox, 
  Calendar as CalendarIcon, 
  Settings, 
  CheckCircle, 
  Circle, 
  Trash2, 
  Database,
  AlertCircle,
  Clock,
  ChevronLeft,
  ChevronRight,
  ChevronDown,
  ChevronUp,
  X,
  Tag,
  Save,
  Zap,
  PauseCircle,
  Archive,
  List,
  ArrowRightCircle,
  Grid,
  Folder,
  FolderPlus,
  CornerUpLeft,
  Briefcase,
  Layout,
  PieChart,
  BrainCircuit,
  Check
} from 'lucide-react';

// --- Constantes ---

const CATEGORIES = [
  "💻 Trabajo",
  "🏠 Personal",
  "💼 Gestión / Administración",
  "📈 Negocio",
  "🎯 Marketing",
  "🤝 Clientes",
  "💰 Finanzas",
  "📞 Llamadas",
  "✉️ Emails",
  "🛠️ Mantenimiento / Soporte",
  "📦 Compras / Pendientes",
  "🎓 Formación"
];

// --- Componentes UI Básicos ---

const Button = ({ children, onClick, variant = 'primary', className = '', type = 'button' }) => {
  const baseStyle = "px-4 py-3 rounded-xl font-medium transition-all duration-200 flex items-center justify-center gap-2 active:scale-95 text-sm";
  const variants = {
    primary: "bg-violet-600 text-white hover:bg-violet-700 shadow-lg shadow-violet-200", 
    secondary: "bg-white border border-[#e7e5e4] text-stone-600 hover:bg-[#faf9f6]", 
    action: "bg-indigo-600 text-white hover:bg-indigo-700 shadow-md shadow-indigo-200",
    danger: "bg-red-50 text-red-600 hover:bg-red-100",
    ghost: "bg-transparent text-stone-500 hover:text-stone-900", 
    icon: "p-2 rounded-full hover:bg-[#faf9f6] text-stone-600" 
  };
  
  return (
    <button type={type} onClick={onClick} className={`${baseStyle} ${variants[variant]} ${className}`}>
      {children}
    </button>
  );
};

const Input = ({ label, value, onChange, placeholder, type = "text", className = "" }) => (
  <div className={`flex flex-col gap-1 mb-3 ${className}`}>
    {label && <label className="text-xs font-bold text-stone-400 uppercase tracking-wide ml-1">{label}</label>}
    <input 
      type={type}
      value={value} 
      onChange={onChange} 
      placeholder={placeholder}
      className="w-full p-3.5 bg-[#faf9f6] border border-[#e7e5e4] rounded-xl focus:outline-none focus:ring-2 focus:ring-violet-500 focus:bg-white transition-all text-stone-800 placeholder-stone-400"
    />
  </div>
);

const TextArea = ({ label, value, onChange, placeholder }) => (
  <div className="flex flex-col gap-1 mb-3">
    {label && <label className="text-xs font-bold text-stone-400 uppercase tracking-wide ml-1">{label}</label>}
    <textarea 
      value={value} 
      onChange={onChange} 
      placeholder={placeholder}
      rows={3}
      className="w-full p-3.5 bg-[#faf9f6] border border-[#e7e5e4] rounded-xl focus:outline-none focus:ring-2 focus:ring-violet-500 focus:bg-white transition-all resize-none font-sans text-stone-800 placeholder-stone-400"
    />
  </div>
);

const Badge = ({ children, color = 'gray' }) => {
  const colors = {
    gray: 'bg-[#f5f5f4] text-stone-600', 
    blue: 'bg-blue-100 text-blue-700',
    green: 'bg-green-100 text-green-700',
    orange: 'bg-orange-100 text-orange-700',
    purple: 'bg-purple-100 text-purple-700',
    indigo: 'bg-indigo-100 text-indigo-700',
    amber: 'bg-amber-100 text-amber-800', 
    teal: 'bg-teal-100 text-teal-800',
    pink: 'bg-pink-100 text-pink-700',
    cyan: 'bg-cyan-100 text-cyan-800',
    violet: 'bg-violet-100 text-violet-700',
  };
  return (
    <span className={`text-[10px] uppercase font-bold px-2 py-1 rounded-md ${colors[color] || colors.gray} truncate max-w-[120px]`}>
      {children}
    </span>
  );
};

// --- Componente Principal ---

export default function App() {
  // Estados Generales
  const [activeTab, setActiveTab] = useState('inbox'); 
  const [tasks, setTasks] = useState([]);
  const [projects, setProjects] = useState([]); 
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [isProjectModalOpen, setIsProjectModalOpen] = useState(false); 
  
  // Estado para Navegación de Proyectos
  const [projectPath, setProjectPath] = useState([]); 

  // Estado para Detalle/Edición
  const [selectedTask, setSelectedTask] = useState(null);

  // Estados del Calendario Grid (Mes)
  const [currentDate, setCurrentDate] = useState(new Date());
  const [selectedCalendarDate, setSelectedCalendarDate] = useState(new Date());

  // Estado para colapsar días en la vista Agenda
  const [collapsedDays, setCollapsedDays] = useState({});

  // Estado para nueva tarea
  const [newTaskTitle, setNewTaskTitle] = useState('');
  const [newTaskDate, setNewTaskDate] = useState('');
  const [newTaskTime, setNewTaskTime] = useState('');
  const [newTaskDesc, setNewTaskDesc] = useState(''); 
  const [newTaskTag, setNewTaskTag] = useState(CATEGORIES[0]);
  const [newTaskProject, setNewTaskProject] = useState(''); // ID del proyecto seleccionado

  // Estados para Creación Rápida de Proyecto (dentro de Modal Tarea)
  const [isQuickProjectMode, setIsQuickProjectMode] = useState(false);
  const [quickProjectTitle, setQuickProjectTitle] = useState('');

  // Estado para nuevo proyecto (Modal Proyectos Completo)
  const [newProjectTitle, setNewProjectTitle] = useState('');
  const [newProjectIcon, setNewProjectIcon] = useState('📁');

  // Configuración Notion
  const [notionConfig, setNotionConfig] = useState({ apiKey: '', databaseId: '' });
  const [toast, setToast] = useState(null);

  // --- Efectos ---
  useEffect(() => {
    const savedTasks = localStorage.getItem('rentalme-tasks-gtd');
    const savedProjects = localStorage.getItem('rentalme-projects'); 
    const savedNotion = localStorage.getItem('rentalme-notion-config');
    
    if (savedTasks) setTasks(JSON.parse(savedTasks));
    if (savedProjects) setProjects(JSON.parse(savedProjects));
    if (savedNotion) setNotionConfig(JSON.parse(savedNotion));
  }, []);

  useEffect(() => {
    localStorage.setItem('rentalme-tasks-gtd', JSON.stringify(tasks));
  }, [tasks]);

  useEffect(() => {
    localStorage.setItem('rentalme-projects', JSON.stringify(projects));
  }, [projects]);

  useEffect(() => {
    localStorage.setItem('rentalme-notion-config', JSON.stringify(notionConfig));
  }, [notionConfig]);

  // --- Helpers de Fecha ---
  const getDaysInMonth = (date) => new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
  const getFirstDayOfMonth = (date) => {
    let day = new Date(date.getFullYear(), date.getMonth(), 1).getDay();
    return day === 0 ? 6 : day - 1; 
  };

  const changeMonth = (increment) => {
    const newDate = new Date(currentDate.setMonth(currentDate.getMonth() + increment));
    setCurrentDate(new Date(newDate));
  };

  const isSameDay = (d1, d2) => {
    return d1.getDate() === d2.getDate() &&
           d1.getMonth() === d2.getMonth() &&
           d1.getFullYear() === d2.getFullYear();
  };

  const tasksForDate = (date) => {
    const dateStr = date.toISOString().split('T')[0];
    return tasks.filter(t => t.date === dateStr && !t.completed);
  };

  const formatDateHeader = (dateStr) => {
    const date = new Date(dateStr);
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    today.setHours(0,0,0,0);
    tomorrow.setHours(0,0,0,0);
    const checkDate = new Date(date);
    checkDate.setHours(0,0,0,0);
    if (checkDate.getTime() === today.getTime()) return "Hoy";
    if (checkDate.getTime() === tomorrow.getTime()) return "Mañana";
    return date.toLocaleDateString('es-ES', { weekday: 'long', day: 'numeric', month: 'long' });
  };

  const isExpandedByDefault = (dateStr) => {
    const today = new Date();
    today.setHours(0,0,0,0);
    const [y, m, d] = dateStr.split('-').map(Number);
    const target = new Date(y, m - 1, d); 
    const diffTime = target - today;
    const diffDays = Math.round(diffTime / (1000 * 60 * 60 * 24));
    return diffDays >= 0 && diffDays <= 2;
  };

  const toggleDayCollapse = (dateStr) => {
    setCollapsedDays(prev => {
      const isDefaultOpen = isExpandedByDefault(dateStr);
      const currentlyCollapsed = prev[dateStr] !== undefined ? prev[dateStr] : !isDefaultOpen;
      return { ...prev, [dateStr]: !currentlyCollapsed };
    });
  };

  // --- Helpers de Proyecto ---
  
  const getSubprojects = (parentId) => {
    return projects.filter(p => p.parentId === (parentId || null));
  };

  const getProjectProgress = (projectId) => {
    const projectTasks = tasks.filter(t => t.projectId === projectId);
    if (projectTasks.length === 0) return 0;
    const completed = projectTasks.filter(t => t.completed).length;
    return Math.round((completed / projectTasks.length) * 100);
  };

  const deleteProject = (projectId) => {
    if (window.confirm("¿Borrar proyecto y todas sus tareas?")) {
      setProjects(projects.filter(p => p.id !== projectId));
      setTasks(tasks.filter(t => t.projectId !== projectId));
      showToast('Proyecto eliminado', 'neutral');
    }
  };

  const createQuickProject = () => {
    if (!quickProjectTitle.trim()) return;
    
    const newProj = {
      id: Date.now(),
      title: quickProjectTitle,
      icon: '📁',
      parentId: null, // Se crea en raíz para simplificar desde quick add
      createdAt: new Date().toISOString()
    };

    setProjects([...projects, newProj]);
    setNewTaskProject(newProj.id); // Auto seleccionar el nuevo proyecto
    setQuickProjectTitle('');
    setIsQuickProjectMode(false);
    showToast('Proyecto creado y seleccionado');
  };

  // --- Acciones ---
  const showToast = (message, type = 'success') => {
    setToast({ message, type });
    setTimeout(() => setToast(null), 3000);
  };

  const closeAddModal = () => {
    setIsAddModalOpen(false);
    setNewTaskTitle('');
    setNewTaskDate('');
    setNewTaskTime('');
    setNewTaskDesc('');
    setNewTaskTag(CATEGORIES[0]);
    setNewTaskProject(''); 
    setIsQuickProjectMode(false);
    setQuickProjectTitle('');
  };

  const addTask = (e) => {
    e.preventDefault();
    if (!newTaskTitle.trim()) return;

    const initialStatus = newTaskDate ? 'next' : 'inbox'; 
    let targetProjectId = null;
    if (newTaskProject) {
      targetProjectId = parseInt(newTaskProject);
    } else if (projectPath.length > 0) {
      targetProjectId = projectPath[projectPath.length - 1];
    }

    const task = {
      id: Date.now(),
      title: newTaskTitle,
      date: newTaskDate || null, 
      time: newTaskTime || null,
      description: newTaskDesc || '', 
      tag: newTaskTag,
      status: initialStatus,
      completed: false,
      syncedToNotion: false,
      projectId: targetProjectId,
      createdAt: new Date().toISOString()
    };

    setTasks([task, ...tasks]);
    
    closeAddModal();
    showToast(initialStatus === 'inbox' ? 'Capturado en Inbox' : 'Añadido al Calendario');
  };

  const addProject = (e) => {
    e.preventDefault();
    if (!newProjectTitle.trim()) return;

    const parentId = projectPath.length > 0 ? projectPath[projectPath.length - 1] : null;

    const project = {
      id: Date.now(),
      title: newProjectTitle,
      icon: newProjectIcon,
      parentId: parentId,
      createdAt: new Date().toISOString()
    };

    setProjects([...projects, project]);
    setNewProjectTitle('');
    setIsProjectModalOpen(false);
    showToast('Proyecto creado');
  };

  const toggleTask = (id) => {
    setTasks(tasks.map(t => t.id === id ? { ...t, completed: !t.completed } : t));
  };

  const saveEditedTask = () => {
    if (!selectedTask || !selectedTask.title.trim()) return;
    setTasks(tasks.map(t => t.id === selectedTask.id ? selectedTask : t));
    setSelectedTask(null);
    showToast('Tarea actualizada');
  };

  const deleteTask = (id) => {
    setTasks(tasks.filter(t => t.id !== id));
    if (selectedTask && selectedTask.id === id) setSelectedTask(null);
    showToast('Tarea eliminada', 'neutral');
  };

  const changeStatus = (taskId, newStatus) => {
    setTasks(tasks.map(t => t.id === taskId ? { ...t, status: newStatus } : t));
    if (selectedTask && selectedTask.id === taskId) {
      setSelectedTask({ ...selectedTask, status: newStatus });
    }
    showToast('Tarea movida');
  };

  const syncToNotion = async () => {
    if (!notionConfig.apiKey || !notionConfig.databaseId) {
      showToast('Falta API Key', 'error');
      return;
    }
    showToast('Sincronizando...', 'neutral');
    setTimeout(() => {
      setTasks(tasks.map(t => ({ ...t, syncedToNotion: true })));
      showToast('¡Sincronizado!', 'success');
    }, 1500);
  };

  const getTagColor = (tag) => {
    if (!tag) return 'gray';
    if (tag.includes('Trabajo')) return 'violet';
    if (tag.includes('Personal')) return 'green';
    if (tag.includes('Gestión')) return 'purple';
    if (tag.includes('Negocio')) return 'indigo';
    if (tag.includes('Marketing')) return 'pink';
    if (tag.includes('Clientes')) return 'teal';
    if (tag.includes('Finanzas')) return 'amber';
    if (tag.includes('Llamadas')) return 'cyan';
    if (tag.includes('Emails')) return 'gray';
    if (tag.includes('Mantenimiento')) return 'orange';
    if (tag.includes('Compras')) return 'amber';
    if (tag.includes('Formación')) return 'indigo';
    return 'gray';
  };

  // --- FILTRADO Y AGRUPACIÓN ---
  
  const inboxTasks = tasks.filter(t => !t.completed && t.status === 'inbox');
  const somedayTasks = tasks.filter(t => !t.completed && t.status === 'someday'); // Tareas a futuro
  
  const getGroupedAgendaTasks = () => {
    // Agenda muestra tareas con fecha (independientemente del estado GTD antiguo)
    const agendaTasks = tasks.filter(t => 
      !t.completed && 
      t.date
    );

    agendaTasks.sort((a, b) => {
      if (a.date !== b.date) return a.date.localeCompare(b.date);
      if (!a.time) return 1;
      if (!b.time) return -1;
      return a.time.localeCompare(b.time);
    });

    const groups = {};
    agendaTasks.forEach(task => {
      if (!groups[task.date]) groups[task.date] = [];
      groups[task.date].push(task);
    });
    return groups;
  };

  const agendaGroups = getGroupedAgendaTasks();
  const sortedDates = Object.keys(agendaGroups).sort();

  // --- Componente TaskCard ---
  const TaskCard = ({ task, onClick, showTime = true }) => {
    const taskProject = task.projectId ? projects.find(p => p.id === parseInt(task.projectId)) : null;

    return (
      <div 
        onClick={onClick}
        className="bg-white p-4 rounded-xl shadow-sm border border-stone-100 mb-2 flex items-start gap-3 transition-all hover:shadow-md cursor-pointer active:scale-[0.98] group"
      >
        <button 
          onClick={(e) => { e.stopPropagation(); toggleTask(task.id); }}
          className={`mt-1 flex-shrink-0 transition-colors ${task.completed ? 'text-green-500' : 'text-stone-300 hover:text-violet-500'}`}
        >
          {task.completed ? <CheckCircle size={22} /> : <Circle size={22} />}
        </button>
        
        <div className="flex-1 overflow-hidden">
          <h3 className={`font-medium text-stone-800 truncate ${task.completed ? 'line-through text-stone-400' : ''}`}>
            {task.title}
          </h3>
          {task.description && (
            <p className="text-xs text-stone-400 truncate mt-0.5">{task.description}</p>
          )}
          
          <div className="flex flex-wrap items-center gap-2 mt-2">
            {taskProject && (
               <span className="flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded bg-[#faf9f6] text-stone-500 border border-stone-200 truncate max-w-[100px]">
                 <Folder size={10} /> {taskProject.title}
               </span>
            )}

            {showTime && task.time && (
              <span className="flex items-center gap-1 text-xs px-2 py-0.5 rounded-md bg-violet-50 text-violet-700 font-bold border border-violet-100">
                <Clock size={12} />
                {task.time}
              </span>
            )}
            {!showTime && task.date && (
               <span className="flex items-center gap-1 text-xs px-2 py-0.5 rounded-md bg-[#faf9f6] text-stone-500 border border-stone-100">
                 {new Date(task.date).toLocaleDateString('es-ES', {day: 'numeric', month: 'short'})}
               </span>
            )}
            <Badge color={getTagColor(task.tag)}>{task.tag}</Badge>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="h-screen w-full bg-[#fbfaf8] flex flex-col font-sans max-w-md mx-auto relative overflow-hidden shadow-2xl">
      
      {/* Header Compacto con Rebranding, Ajustes y Futuro */}
      <header className="bg-white px-6 pt-12 pb-3 shadow-sm z-10 border-b border-stone-100 flex justify-between items-center">
        <div className="flex items-center gap-3">
           <div className="h-9 w-9 bg-violet-600 rounded-full flex items-center justify-center text-white text-xs font-bold shadow-violet-200 shadow-md">
              <BrainCircuit size={18} />
           </div>
           <h1 className="text-xl font-bold text-stone-800 tracking-tight">BrainSync</h1>
        </div>
        <div className="flex items-center gap-2">
            <button 
              onClick={() => setActiveTab('future')} 
              className={`p-2 rounded-full transition-colors ${activeTab === 'future' ? 'bg-violet-100 text-violet-700' : 'text-stone-400 hover:bg-[#faf9f6]'}`}
            >
               <Archive size={22} className="drop-shadow-sm" />
            </button>
            <button 
              onClick={() => setActiveTab('settings')} 
              className={`p-2 rounded-full transition-colors ${activeTab === 'settings' ? 'bg-violet-100 text-violet-700' : 'text-stone-400 hover:bg-[#faf9f6]'}`}
            >
               <Settings size={22} className="drop-shadow-sm" />
            </button>
        </div>
      </header>

      {/* Contenido Principal */}
      <main className="flex-1 overflow-y-auto pb-24 scroll-smooth">
        
        {/* --- INBOX --- */}
        {activeTab === 'inbox' && (
          <div className="p-4 animate-fade-in">
            <div className="bg-[#f5f3ff] p-4 rounded-xl mb-6 border border-violet-100">
              <div className="flex items-center gap-3 mb-2">
                <div className="p-2 bg-white rounded-full text-violet-600 shadow-sm"><Inbox size={20}/></div>
                <div>
                  <h2 className="font-bold text-violet-900">Bandeja de Entrada</h2>
                  <p className="text-xs text-violet-600 opacity-80">Tareas sin fecha o pendientes de procesar.</p>
                </div>
              </div>
            </div>

            {inboxTasks.length === 0 ? (
              <div className="text-center py-12 opacity-60 flex flex-col items-center">
                <div className="bg-[#faf9f6] p-4 rounded-full mb-4">
                   <Inbox size={32} className="text-stone-300" />
                </div>
                <p className="text-stone-500 font-medium">Bandeja vacía.</p>
                <p className="text-xs text-stone-400 mt-1">Todas las tareas están organizadas.</p>
              </div>
            ) : (
              <div>
                <p className="text-xs font-bold text-stone-400 uppercase mb-3 pl-1">Pendientes ({inboxTasks.length})</p>
                {inboxTasks.map(task => (
                  <TaskCard key={task.id} task={task} onClick={() => setSelectedTask(task)} showTime={false} />
                ))}
              </div>
            )}
          </div>
        )}

        {/* --- FUTURO --- */}
        {activeTab === 'future' && (
          <div className="p-4 animate-fade-in">
            <div className="bg-[#f0fdfa] p-4 rounded-xl mb-6 border border-teal-100">
              <div className="flex items-center gap-3 mb-2">
                <div className="p-2 bg-white rounded-full text-teal-600 shadow-sm"><Archive size={20}/></div>
                <div>
                  <h2 className="font-bold text-teal-900">Futuro / Someday</h2>
                  <p className="text-xs text-teal-600 opacity-80">Ideas y tareas para más adelante.</p>
                </div>
              </div>
            </div>

            {somedayTasks.length === 0 ? (
              <div className="text-center py-12 opacity-60 flex flex-col items-center">
                <div className="bg-[#faf9f6] p-4 rounded-full mb-4">
                   <Archive size={32} className="text-stone-300" />
                </div>
                <p className="text-stone-500 font-medium">No hay tareas archivadas.</p>
              </div>
            ) : (
              <div>
                <p className="text-xs font-bold text-stone-400 uppercase mb-3 pl-1">Guardadas ({somedayTasks.length})</p>
                {somedayTasks.map(task => (
                  <TaskCard key={task.id} task={task} onClick={() => setSelectedTask(task)} showTime={false} />
                ))}
              </div>
            )}
          </div>
        )}

        {/* --- AGENDA --- */}
        {activeTab === 'agenda' && (
          <div className="p-4 animate-fade-in">
            <div className="flex justify-between items-end mb-4">
              <h2 className="text-lg font-bold text-stone-800 flex items-center gap-2">
                <CalendarIcon size={20} className="text-violet-600"/> Mi Calendario
              </h2>
            </div>
            {sortedDates.length === 0 ? (
              <div className="text-center py-10 opacity-50">
                <p className="text-stone-500">No hay tareas programadas próximamente.</p>
              </div>
            ) : (
              <div className="space-y-6">
                {sortedDates.map(dateStr => {
                  const tasksForDay = agendaGroups[dateStr];
                  const headerText = formatDateHeader(dateStr);
                  const isToday = headerText === 'Hoy';
                  const isDefaultOpen = isExpandedByDefault(dateStr);
                  const isCollapsed = collapsedDays[dateStr] !== undefined ? collapsedDays[dateStr] : !isDefaultOpen;

                  return (
                    <div key={dateStr} className="animate-fade-in">
                      <button 
                        onClick={() => toggleDayCollapse(dateStr)}
                        className={`w-full flex items-center justify-between mb-3 px-1 py-1 rounded-lg transition-colors ${isToday ? 'text-violet-800' : 'text-stone-500 hover:bg-[#faf9f6]'}`}
                      >
                        <div className="flex items-center gap-2">
                          <span className={`text-sm font-bold uppercase tracking-wide ${isToday ? 'text-violet-600' : 'text-stone-600'}`}>
                            {headerText}
                          </span>
                          <span className="text-xs font-normal opacity-60">
                             {new Date(dateStr).toLocaleDateString('es-ES', {day:'numeric', month:'numeric'})}
                          </span>
                        </div>
                        <div className="flex items-center gap-2">
                          <span className="text-xs bg-[#e7e5e4] px-2 py-0.5 rounded-full text-stone-600 font-bold">{tasksForDay.length}</span>
                          {isCollapsed ? <ChevronDown size={16}/> : <ChevronUp size={16}/>}
                        </div>
                      </button>
                      {!isCollapsed && (
                        <div className="space-y-1 pl-1">
                          {tasksForDay.map(task => (
                            <TaskCard key={task.id} task={task} onClick={() => setSelectedTask(task)} showTime={true} />
                          ))}
                        </div>
                      )}
                      {isCollapsed && <div className="h-1 bg-[#e7e5e4] rounded-full mx-2 opacity-50"></div>}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        )}

        {/* --- PROYECTOS --- */}
        {activeTab === 'projects' && (
          <div className="p-4 animate-fade-in">
             <div className="flex justify-between items-center mb-4">
                <h2 className="text-lg font-bold text-stone-800 flex items-center gap-2">
                  <Folder size={20} className="text-violet-600"/> Proyectos
                </h2>
                {projectPath.length > 0 && (
                   <button onClick={() => setProjectPath(prev => prev.slice(0, -1))} className="text-xs bg-[#e7e5e4] px-3 py-1.5 rounded-full flex items-center gap-1 hover:bg-[#d6d3d1] text-stone-600">
                     <CornerUpLeft size={12}/> Volver
                   </button>
                )}
             </div>

             {/* Breadcrumb */}
             <div className="text-xs text-stone-400 mb-4 flex items-center gap-1 overflow-x-auto whitespace-nowrap pb-2">
                <span onClick={() => setProjectPath([])} className={`cursor-pointer ${projectPath.length === 0 ? 'font-bold text-stone-700' : 'hover:text-violet-600'}`}>Inicio</span>
                {projectPath.map((pid, idx) => {
                   const p = projects.find(proj => proj.id === pid);
                   if (!p) return null;
                   const isLast = idx === projectPath.length - 1;
                   return (
                     <React.Fragment key={pid}>
                       <ChevronRight size={10} />
                       <span 
                         onClick={() => setProjectPath(projectPath.slice(0, idx + 1))}
                         className={`cursor-pointer ${isLast ? 'font-bold text-stone-700' : 'hover:text-violet-600'}`}
                       >
                         {p.title}
                       </span>
                     </React.Fragment>
                   );
                })}
             </div>
             
             <div className="space-y-6">
                <div>
                  <div className="flex justify-between items-center mb-2">
                    <h3 className="text-xs font-bold text-stone-400 uppercase">
                      {projectPath.length === 0 ? 'Mis Proyectos' : 'Subproyectos'}
                    </h3>
                    <button onClick={() => setIsProjectModalOpen(true)} className="text-violet-600 hover:bg-violet-50 p-1 rounded-full"><FolderPlus size={18}/></button>
                  </div>
                  
                  {getSubprojects(projectPath.length > 0 ? projectPath[projectPath.length - 1] : null).length === 0 ? (
                    <div className="text-center py-6 border-2 border-dashed border-[#e7e5e4] rounded-xl bg-[#faf9f6]">
                       <p className="text-stone-400 text-xs">No hay {projectPath.length === 0 ? 'proyectos' : 'subproyectos'}.</p>
                    </div>
                  ) : (
                    <div className="grid grid-cols-2 gap-3">
                      {getSubprojects(projectPath.length > 0 ? projectPath[projectPath.length - 1] : null).map(proj => {
                        const progress = getProjectProgress(proj.id);
                        return (
                          <div 
                            key={proj.id} 
                            onClick={() => setProjectPath([...projectPath, proj.id])}
                            className="bg-white p-3 rounded-xl shadow-sm border border-stone-100 hover:shadow-md transition-all cursor-pointer relative group"
                          >
                            <div className="flex items-start justify-between mb-2">
                               <span className="text-2xl">{proj.icon}</span>
                               <button 
                                 onClick={(e) => {e.stopPropagation(); deleteProject(proj.id)}}
                                 className="opacity-0 group-hover:opacity-100 text-stone-300 hover:text-red-500 transition-opacity"
                               >
                                 <X size={14}/>
                               </button>
                            </div>
                            <h4 className="font-bold text-stone-800 text-sm truncate mb-1">{proj.title}</h4>
                            <div className="w-full bg-[#f5f5f4] h-1.5 rounded-full overflow-hidden">
                               <div className="bg-violet-500 h-full rounded-full transition-all duration-500" style={{width: `${progress}%`}}></div>
                            </div>
                            <p className="text-[10px] text-stone-400 mt-1 text-right">{progress}%</p>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>

                {projectPath.length > 0 && (
                  <div>
                    <div className="flex justify-between items-center mb-2 mt-4">
                      <h3 className="text-xs font-bold text-stone-400 uppercase">Tareas del Proyecto</h3>
                      <button 
                        onClick={() => { setIsAddModalOpen(true); }}
                        className="text-violet-600 hover:bg-violet-50 p-1 rounded-full"
                      >
                        <Plus size={18}/>
                      </button>
                    </div>

                    {tasks.filter(t => t.projectId === projectPath[projectPath.length - 1]).length === 0 ? (
                       <p className="text-stone-400 text-xs italic p-4 text-center">Este proyecto no tiene tareas asignadas.</p>
                    ) : (
                       tasks.filter(t => t.projectId === projectPath[projectPath.length - 1]).map(task => (
                          <TaskCard key={task.id} task={task} onClick={() => setSelectedTask(task)} showTime={!!task.time} />
                       ))
                    )}
                  </div>
                )}
             </div>
          </div>
        )}

        {/* --- MES --- */}
        {activeTab === 'month' && (
          <div className="animate-fade-in flex flex-col h-full">
            <div className="bg-white p-4 shadow-sm z-10 rounded-b-xl mb-4 border border-stone-100">
              <div className="flex items-center justify-between mb-4">
                <button onClick={() => changeMonth(-1)} className="p-1 hover:bg-[#faf9f6] rounded-full text-stone-600"><ChevronLeft size={20}/></button>
                <h2 className="font-bold text-lg capitalize text-stone-800">
                  {currentDate.toLocaleDateString('es-ES', { month: 'long', year: 'numeric' })}
                </h2>
                <button onClick={() => changeMonth(1)} className="p-1 hover:bg-[#faf9f6] rounded-full text-stone-600"><ChevronRight size={20}/></button>
              </div>
              <div className="grid grid-cols-7 mb-2">
                {['L', 'M', 'X', 'J', 'V', 'S', 'D'].map(day => (
                  <div key={day} className="text-center text-xs font-bold text-stone-400">{day}</div>
                ))}
              </div>
              <div className="grid grid-cols-7 gap-y-1">
                {(() => {
                    const days = [];
                    const startDay = getFirstDayOfMonth(currentDate);
                    for (let i = 0; i < startDay; i++) days.push(<div key={`e-${i}`} className="h-9"></div>);
                    for (let i = 1; i <= getDaysInMonth(currentDate); i++) {
                      const d = new Date(currentDate.getFullYear(), currentDate.getMonth(), i);
                      const t = tasksForDate(d);
                      const isSel = isSameDay(d, selectedCalendarDate);
                      days.push(
                        <button key={i} onClick={() => setSelectedCalendarDate(d)} className={`h-9 rounded-lg flex flex-col items-center justify-center relative ${isSel ? 'bg-violet-600 text-white shadow-md' : 'hover:bg-[#faf9f6] text-stone-700'}`}>
                          <span className="text-xs font-medium">{i}</span>
                          <div className="flex gap-0.5 mt-0.5 h-1">
                            {t.length > 0 && <div className={`w-1 h-1 rounded-full ${isSel ? 'bg-white' : 'bg-amber-400'}`}></div>}
                          </div>
                        </button>
                      );
                    }
                    return days;
                })()}
              </div>
            </div>
            <div className="flex-1 p-4">
               <h3 className="text-xs font-bold text-stone-400 uppercase mb-3">
                {selectedCalendarDate.toLocaleDateString('es-ES', { weekday: 'long', day: 'numeric' })}
              </h3>
              {tasksForDate(selectedCalendarDate).map(task => (
                <TaskCard key={task.id} task={task} onClick={() => setSelectedTask(task)} showTime={true} />
              ))}
            </div>
          </div>
        )}

        {/* --- AJUSTES --- */}
        {activeTab === 'settings' && (
           <div className="p-4 animate-fade-in">
             <div className="bg-white p-5 rounded-xl border border-stone-200 shadow-sm">
              <div className="flex items-center gap-2 mb-4">
                <Database className="text-stone-800" size={24} />
                <h3 className="font-bold text-stone-800">Conexión Notion</h3>
              </div>
              <p className="text-xs text-stone-500 mb-4">Integration Token & Database ID</p>
              <Input placeholder="secret_..." value={notionConfig.apiKey} onChange={(e) => setNotionConfig({...notionConfig, apiKey: e.target.value})} type="password" />
              <Input placeholder="Database ID" value={notionConfig.databaseId} onChange={(e) => setNotionConfig({...notionConfig, databaseId: e.target.value})} />
              <Button onClick={syncToNotion} className="w-full mt-2" variant="secondary">Probar Conexión</Button>
            </div>
          </div>
        )}
      </main>

      {/* --- FAB (Capturar) --- */}
      <button 
        onClick={() => setIsAddModalOpen(true)}
        className="absolute bottom-24 right-6 bg-violet-600 text-white p-4 rounded-full shadow-lg shadow-violet-300 hover:bg-violet-700 hover:scale-110 transition-all z-20 group"
      >
        <Plus size={28} className="group-active:rotate-90 transition-transform duration-200"/>
      </button>

      {/* --- Bottom Nav --- */}
      <nav className="bg-white border-t border-stone-100 px-2 py-2 flex justify-between items-center z-20 absolute bottom-0 w-full pb-6">
        {[
          { id: 'inbox', icon: Inbox, label: 'Inbox', count: inboxTasks.length },
          { id: 'agenda', icon: CalendarIcon, label: 'Agenda' },
          { id: 'projects', icon: Folder, label: 'Proyectos' }, 
          { id: 'month', icon: Grid, label: 'Mes' }
        ].map(item => (
          <button 
            key={item.id}
            onClick={() => setActiveTab(item.id)}
            className={`flex flex-col items-center gap-1 min-w-[50px] relative ${activeTab === item.id ? 'text-violet-600' : 'text-stone-400'}`}
          >
            {item.count > 0 && (
              <span className="absolute top-0 right-1 w-4 h-4 bg-red-500 text-white text-[9px] font-bold flex items-center justify-center rounded-full z-10 border border-white">
                {item.count}
              </span>
            )}
            <item.icon size={22} strokeWidth={activeTab === item.id ? 2.5 : 2} />
            <span className="text-[9px] font-medium">{item.label}</span>
          </button>
        ))}
      </nav>

      {/* --- MODAL EDICIÓN --- */}
      {selectedTask && (
        <div className="absolute inset-0 z-50 flex items-center justify-center p-4 bg-stone-900/40 backdrop-blur-sm animate-fade-in" onClick={() => setSelectedTask(null)}>
          <div className="bg-white w-full max-w-sm rounded-2xl shadow-2xl overflow-hidden animate-slide-up flex flex-col max-h-[85vh]" onClick={e => e.stopPropagation()}>
            <div className="flex justify-between items-center p-4 border-b border-stone-100 bg-[#faf9f6]">
               <div className="flex items-center gap-2">
                 <Badge color={getTagColor(selectedTask.tag)}>{selectedTask.tag}</Badge>
               </div>
               <button onClick={() => setSelectedTask(null)} className="text-stone-400 hover:text-stone-600 bg-white p-1.5 rounded-full border border-stone-200 shadow-sm">
                <X size={18} />
              </button>
            </div>
            <div className="p-5 overflow-y-auto">
              <input 
                value={selectedTask.title}
                onChange={(e) => setSelectedTask({...selectedTask, title: e.target.value})}
                className="w-full text-xl font-bold text-stone-800 bg-transparent border-none focus:ring-0 p-0 mb-4 placeholder-stone-300"
                placeholder="Nombre de la tarea"
              />

              {/* Selector de Proyecto en Edición */}
              <div className="mb-4">
                 <label className="text-[10px] font-bold text-stone-400 uppercase mb-1 block">Proyecto Asociado</label>
                 <select 
                   value={selectedTask.projectId || ''} 
                   onChange={(e) => setSelectedTask({...selectedTask, projectId: e.target.value ? parseInt(e.target.value) : null})}
                   className="w-full p-2.5 bg-[#faf9f6] border border-[#e7e5e4] rounded-lg text-sm text-stone-700"
                  >
                    <option value="">(Sin proyecto)</option>
                    {projects.map(p => (
                      <option key={p.id} value={p.id}>{p.title}</option>
                    ))}
                  </select>
              </div>

              <div className="mb-6">
                <p className="text-xs font-bold text-stone-400 uppercase tracking-wide mb-2">Mover a</p>
                <div className="grid grid-cols-4 gap-2">
                  <button onClick={() => changeStatus(selectedTask.id, 'next')} className={`flex flex-col items-center justify-center p-2 rounded-lg border transition-all ${selectedTask.status === 'next' ? 'bg-violet-50 border-violet-500 text-violet-700' : 'border-[#e7e5e4] hover:bg-[#faf9f6] text-stone-600'}`}>
                    <CalendarIcon size={20} className="mb-1"/> <span className="text-[9px] font-bold">Agenda</span>
                  </button>
                  <button onClick={() => changeStatus(selectedTask.id, 'waiting')} className={`flex flex-col items-center justify-center p-2 rounded-lg border transition-all ${selectedTask.status === 'waiting' ? 'bg-amber-50 border-amber-500 text-amber-700' : 'border-[#e7e5e4] hover:bg-[#faf9f6] text-stone-600'}`}>
                    <PauseCircle size={20} className="mb-1"/> <span className="text-[9px] font-bold">Esperar</span>
                  </button>
                  <button onClick={() => changeStatus(selectedTask.id, 'someday')} className={`flex flex-col items-center justify-center p-2 rounded-lg border transition-all ${selectedTask.status === 'someday' ? 'bg-teal-50 border-teal-500 text-teal-700' : 'border-[#e7e5e4] hover:bg-[#faf9f6] text-stone-600'}`}>
                    <Archive size={20} className="mb-1"/> <span className="text-[9px] font-bold">Futuro</span>
                  </button>
                  <button onClick={() => changeStatus(selectedTask.id, 'inbox')} className={`flex flex-col items-center justify-center p-2 rounded-lg border transition-all ${selectedTask.status === 'inbox' ? 'bg-indigo-50 border-indigo-500 text-indigo-700' : 'border-[#e7e5e4] hover:bg-[#faf9f6] text-stone-600'}`}>
                    <Inbox size={20} className="mb-1"/> <span className="text-[9px] font-bold">Inbox</span>
                  </button>
                </div>
              </div>

              <div className="space-y-4">
                 <div className="grid grid-cols-2 gap-3">
                    <input type="date" className="p-2 bg-[#faf9f6] rounded-lg text-sm w-full border border-[#e7e5e4] text-stone-700" value={selectedTask.date || ''} onChange={(e) => setSelectedTask({...selectedTask, date: e.target.value})} />
                    <input type="time" className="p-2 bg-[#faf9f6] rounded-lg text-sm w-full border border-[#e7e5e4] text-stone-700" value={selectedTask.time || ''} onChange={(e) => setSelectedTask({...selectedTask, time: e.target.value})} />
                 </div>
                 <select 
                   value={selectedTask.tag}
                   onChange={(e) => setSelectedTask({...selectedTask, tag: e.target.value})}
                   className="w-full p-2.5 bg-[#faf9f6] border border-[#e7e5e4] rounded-lg text-sm text-stone-700"
                 >
                   {CATEGORIES.map(cat => (
                     <option key={cat} value={cat}>{cat}</option>
                   ))}
                 </select>
                 <textarea 
                  className="w-full p-3 bg-[#faf9f6] border border-[#e7e5e4] rounded-lg text-sm resize-none text-stone-700"
                  rows={3}
                  placeholder="Notas adicionales..."
                  value={selectedTask.description || ''}
                  onChange={(e) => setSelectedTask({...selectedTask, description: e.target.value})}
                 />
              </div>
            </div>
            <div className="p-4 border-t border-stone-100 flex gap-3 bg-[#faf9f6]">
              <Button variant="danger" className="px-3" onClick={() => deleteTask(selectedTask.id)}><Trash2 size={18} /></Button>
              <Button variant="primary" className="flex-1" onClick={saveEditedTask}><Save size={18}/> Guardar</Button>
            </div>
          </div>
        </div>
      )}

       {/* --- MODAL NUEVO PROYECTO --- */}
      {isProjectModalOpen && (
        <div className="absolute inset-0 bg-stone-900/40 z-50 flex items-center justify-center animate-fade-in backdrop-blur-sm p-4">
          <div className="bg-white w-full max-w-sm rounded-2xl p-6 shadow-2xl animate-slide-up">
             <h2 className="text-xl font-bold text-stone-800 mb-4">
                {projectPath.length === 0 ? 'Nuevo Proyecto' : 'Nuevo Subproyecto'}
             </h2>
             <form onSubmit={addProject}>
                <Input 
                   label="Nombre del Proyecto" 
                   value={newProjectTitle} 
                   onChange={(e) => setNewProjectTitle(e.target.value)} 
                   placeholder="Ej. Nueva Web, Reforma Cocina..." 
                   autoFocus
                />
                
                <div className="mb-4">
                   <label className="text-xs font-bold text-stone-400 uppercase tracking-wide ml-1">Icono</label>
                   <div className="flex gap-2 overflow-x-auto py-2">
                      {['📁', '🚀', '🏠', '💻', '🏗️', '🛒', '🎓', '✈️', '🎨'].map(icon => (
                          <button 
                            key={icon}
                            type="button"
                            onClick={() => setNewProjectIcon(icon)}
                            className={`w-10 h-10 rounded-full flex items-center justify-center text-xl border ${newProjectIcon === icon ? 'bg-violet-100 border-violet-500 scale-110' : 'bg-[#faf9f6] border-[#e7e5e4]'}`}
                          >
                             {icon}
                          </button>
                      ))}
                   </div>
                </div>

                <div className="flex gap-3 mt-6">
                   <Button variant="ghost" className="flex-1" onClick={() => setIsProjectModalOpen(false)}>Cancelar</Button>
                   <Button variant="primary" className="flex-1" type="submit">Crear</Button>
                </div>
             </form>
          </div>
        </div>
      )}

      {/* --- MODAL NUEVA TAREA (Captura Rápida) --- */}
      {isAddModalOpen && (
        <div className="absolute inset-0 bg-stone-900/40 z-50 flex items-end sm:items-center justify-center animate-fade-in backdrop-blur-sm">
          <div className="bg-white w-full sm:w-11/12 rounded-t-2xl sm:rounded-2xl p-6 shadow-2xl animate-slide-up flex flex-col max-h-[85vh]">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-xl font-bold text-stone-800">Captura Rápida</h2>
              <button onClick={closeAddModal} className="bg-[#faf9f6] p-1 rounded-full"><X size={20} className="text-stone-500"/></button>
            </div>
            <form onSubmit={addTask} className="overflow-y-auto">
              <Input 
                placeholder="¿Qué hay que hacer?" 
                value={newTaskTitle} 
                onChange={(e) => setNewTaskTitle(e.target.value)}
                autoFocus
                className="mb-4"
              />
              <div className="bg-[#faf9f6] p-3 rounded-xl mb-4 border border-[#e7e5e4]">
                <p className="text-xs font-bold text-stone-400 mb-2 uppercase">Detalles (Opcional)</p>
                <div className="flex gap-2 mb-3">
                   <div className="flex-1">
                     <label className="text-[10px] font-bold text-stone-400 uppercase mb-1 block">Fecha</label>
                     <input type="date" className="w-full p-2 text-sm border border-[#e7e5e4] rounded-lg bg-white text-stone-700" value={newTaskDate} onChange={(e) => setNewTaskDate(e.target.value)} />
                   </div>
                   <div className="flex-1">
                     <label className="text-[10px] font-bold text-stone-400 uppercase mb-1 block">Hora</label>
                     <input type="time" className="w-full p-2 text-sm border border-[#e7e5e4] rounded-lg bg-white text-stone-700" value={newTaskTime} onChange={(e) => setNewTaskTime(e.target.value)} />
                   </div>
                </div>
                
                {/* SELECTOR DE PROYECTO + CREACIÓN RÁPIDA (ACTUALIZADO) */}
                {projectPath.length === 0 && (
                   <div className="mb-3">
                     <div className="flex justify-between items-end mb-1">
                        <label className="text-[10px] font-bold text-stone-400 uppercase block">Proyecto</label>
                        {!isQuickProjectMode ? (
                          <button type="button" onClick={() => setIsQuickProjectMode(true)} className="text-[10px] text-violet-600 font-bold hover:underline flex items-center gap-1">+ Nuevo</button>
                        ) : (
                          <button type="button" onClick={() => setIsQuickProjectMode(false)} className="text-[10px] text-red-400 font-bold hover:underline">Cancelar</button>
                        )}
                     </div>
                     
                     {!isQuickProjectMode ? (
                        <select value={newTaskProject} onChange={(e) => setNewTaskProject(e.target.value)} className="w-full p-2 text-sm border border-[#e7e5e4] rounded-lg bg-white text-stone-700">
                          <option value="">(Sin proyecto)</option>
                          {projects.map(p => (
                            <option key={p.id} value={p.id}>{p.icon} {p.title}</option>
                          ))}
                        </select>
                     ) : (
                        <div className="flex gap-2 animate-fade-in">
                          <input 
                            type="text" 
                            className="flex-1 p-2 text-sm border border-[#e7e5e4] rounded-lg bg-white text-stone-800 placeholder-stone-300"
                            placeholder="Nombre del proyecto..."
                            value={quickProjectTitle}
                            onChange={(e) => setQuickProjectTitle(e.target.value)}
                            autoFocus
                          />
                          <button 
                            type="button" 
                            onClick={createQuickProject} 
                            className="bg-violet-600 text-white p-2 rounded-lg hover:bg-violet-700 disabled:opacity-50"
                            disabled={!quickProjectTitle.trim()}
                          >
                            <Check size={16} />
                          </button>
                        </div>
                     )}
                   </div>
                )}
                
                <div className="mb-3">
                   <label className="text-[10px] font-bold text-stone-400 uppercase mb-1 block">Categoría</label>
                   <select value={newTaskTag} onChange={(e) => setNewTaskTag(e.target.value)} className="w-full p-2 text-sm border border-[#e7e5e4] rounded-lg bg-white text-stone-700">
                      {CATEGORIES.map(cat => (
                        <option key={cat} value={cat}>{cat}</option>
                      ))}
                   </select>
                </div>
                <div>
                  <label className="text-[10px] font-bold text-stone-400 uppercase mb-1 block">Notas / Info Adicional</label>
                  <textarea 
                    className="w-full p-2 text-sm border border-[#e7e5e4] rounded-lg bg-white resize-none text-stone-700"
                    rows={2}
                    placeholder="Detalles, códigos, etc..."
                    value={newTaskDesc} 
                    onChange={(e) => setNewTaskDesc(e.target.value)}
                  />
                </div>
              </div>
              <div className="flex gap-3">
                <Button variant="primary" className="w-full py-4 text-lg" type="submit">
                   <Inbox size={20}/> Capturar
                </Button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Toast Notification */}
      {toast && (
        <div className={`absolute top-6 left-1/2 -translate-x-1/2 px-4 py-2 rounded-full shadow-lg text-sm font-medium z-50 flex items-center gap-2 animate-bounce-in ${toast.type === 'error' ? 'bg-red-500 text-white' : 'bg-stone-800 text-white'}`}>
          {toast.type === 'success' && <CheckCircle size={16} />}
          {toast.type === 'error' && <AlertCircle size={16} />}
          {toast.message}
        </div>
      )}

      <style>{`
        .animate-fade-in { animation: fadeIn 0.2s ease-out; }
        .animate-slide-up { animation: slideUp 0.3s cubic-bezier(0.16, 1, 0.3, 1); }
        .animate-bounce-in { animation: bounceIn 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55); }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
        @keyframes bounceIn { from { transform: translate(-50%, -20px); opacity: 0; } to { transform: translate(-50%, 0); opacity: 1; } }
      `}</style>
    </div>
  );
}

// --- Montaje de la Aplicación (Crucial para Hostinger) ---
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);