// ============================================================
// MOORE AI v13 — TASKS TAB (Internal Kanban Board)
// Data stored in localStorage('moore_tasks')
// Requires: shared/utils.js, shared/components.jsx loaded first
// ============================================================

const TasksView = ({ tasks, setTasks }) => {
  const { useState, useMemo, useEffect } = React;

  // On mount: fetch any tasks queued from ElevenLabs calls and merge in
  useEffect(() => {
    API.fetchPendingTasks().then(data => {
      if (data.tasks && data.tasks.length > 0) {
        setTasks(prev => {
          const merged = [...data.tasks, ...prev];
          localStorage.setItem('moore_tasks', JSON.stringify(merged));
          return merged;
        });
      }
    }).catch(() => {});
  }, []);
  const [newTitle, setNewTitle] = useState('');
  const [newPriority, setNewPriority] = useState('medium');
  const [newContact, setNewContact] = useState('');
  const [showForm, setShowForm] = useState(false);

  const COLUMNS = ['todo', 'in-progress', 'done'];
  const COLUMN_LABELS = { 'todo': 'Todo', 'in-progress': 'In Progress', 'done': 'Done' };
  const COLUMN_COLORS = { 'todo': '#3b82f6', 'in-progress': '#f59e0b', 'done': '#10b981' };

  const priorityColors = {
    high: 'bg-red-950/30 text-red-400 border-red-700/40',
    medium: 'bg-amber-950/30 text-amber-400 border-amber-700/40',
    low: 'bg-slate-900/30 text-slate-400 border-slate-700/40'
  };

  const sourceBadge = {
    'AI Generated': 'text-indigo-400 bg-indigo-950/30 border-indigo-700/30',
    'Manual': 'text-slate-400 bg-slate-900/40 border-slate-700/30',
    'From Call': 'text-teal-400 bg-teal-950/30 border-teal-700/30'
  };

  const saveTasks = (updated) => {
    setTasks(updated);
    localStorage.setItem('moore_tasks', JSON.stringify(updated));
  };

  const addTask = () => {
    if (!newTitle.trim()) return;
    const task = {
      id: Date.now(),
      title: newTitle.trim(),
      priority: newPriority,
      contact: newContact.trim(),
      status: 'todo',
      source: 'Manual',
      createdAt: new Date().toISOString()
    };
    saveTasks([task, ...tasks]);
    setNewTitle(''); setNewContact(''); setNewPriority('medium'); setShowForm(false);
  };

  const moveTask = (id, newStatus) => {
    saveTasks(tasks.map(t => t.id === id ? { ...t, status: newStatus } : t));
  };

  const deleteTask = (id) => {
    saveTasks(tasks.filter(t => t.id !== id));
  };

  const columnTasks = (col) => tasks.filter(t => t.status === col);
  const openCount = tasks.filter(t => t.status !== 'done').length;

  return (
    <div className="h-full flex flex-col">
      {/* Header */}
      <div className="flex items-center justify-between px-6 py-4 border-b border-slate-800/50 shrink-0 bg-[#030712]/50">
        <div className="flex items-center gap-4">
          <div>
            <div className="text-xs mono text-slate-500 uppercase tracking-widest mb-0.5">Internal Board</div>
            <h2 className="font-black text-white text-xl italic tracking-tight">Tasks</h2>
          </div>
          {openCount > 0 && (
            <span className="text-xs mono bg-blue-600 text-white px-2 py-0.5 rounded-lg font-bold">{openCount} open</span>
          )}
        </div>
        <button onClick={() => setShowForm(v => !v)}
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-500 rounded-xl text-xs font-bold text-white transition-all">
          <Icon name="plus" size={13} /> New Task
        </button>
      </div>

      {/* Quick add form */}
      {showForm && (
        <div className="bg-slate-900/60 border-b border-blue-500/20 px-6 py-4 fade-in shrink-0">
          <div className="flex items-center gap-3 flex-wrap">
            <input value={newTitle} onChange={e => setNewTitle(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && addTask()}
              placeholder="Task title..."
              className="flex-1 min-w-48 bg-slate-900/80 border border-slate-700/60 rounded-xl px-4 py-2 text-sm text-white outline-none focus:border-blue-500/50 placeholder:text-slate-600" />
            <input value={newContact} onChange={e => setNewContact(e.target.value)}
              placeholder="Contact (optional)"
              className="w-44 bg-slate-900/80 border border-slate-700/60 rounded-xl px-3 py-2 text-sm text-white outline-none focus:border-blue-500/50 placeholder:text-slate-600" />
            <select value={newPriority} onChange={e => setNewPriority(e.target.value)}
              className="bg-slate-900/80 border border-slate-700/60 rounded-xl px-3 py-2 text-sm text-white outline-none focus:border-blue-500/50">
              <option value="high">High</option>
              <option value="medium">Medium</option>
              <option value="low">Low</option>
            </select>
            <button onClick={addTask} className="px-4 py-2 bg-blue-600 hover:bg-blue-500 rounded-xl text-sm font-bold text-white transition-all">Add</button>
            <button onClick={() => setShowForm(false)} className="px-3 py-2 text-slate-500 hover:text-white transition-colors text-sm">Cancel</button>
          </div>
        </div>
      )}

      {/* Kanban columns */}
      <div className="flex-1 overflow-x-auto overflow-y-hidden">
        <div className="flex gap-4 h-full p-5" style={{ minWidth: 900 }}>
          {COLUMNS.map(col => (
            <div key={col} className="flex flex-col flex-1 min-w-72 bg-slate-900/30 border border-slate-800/60 rounded-2xl overflow-hidden">
              {/* Column header */}
              <div className="px-4 py-3 border-b flex items-center justify-between shrink-0"
                style={{ borderColor: COLUMN_COLORS[col] + '40' }}>
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full shrink-0" style={{ background: COLUMN_COLORS[col] }} />
                  <div className="font-bold text-white text-sm">{COLUMN_LABELS[col]}</div>
                </div>
                <span className="text-[10px] mono text-slate-600 bg-slate-800/60 px-2 py-0.5 rounded-lg">
                  {columnTasks(col).length}
                </span>
              </div>

              {/* Cards */}
              <div className="flex-1 overflow-y-auto p-2.5 space-y-2">
                {columnTasks(col).length === 0 && (
                  <div className="py-8 text-center text-[10px] mono text-slate-800 uppercase tracking-widest">Empty</div>
                )}
                {columnTasks(col).map(task => (
                  <div key={task.id} className="bg-[#0d1424] border border-slate-800/70 rounded-xl p-3 hover:border-slate-600/70 transition-all group">
                    <div className="text-sm font-semibold text-white leading-snug mb-2">{task.title}</div>
                    {task.contact && (
                      <div className="text-[10px] mono text-slate-500 mb-2 flex items-center gap-1">
                        <Icon name="user" size={10} />
                        {task.contact}
                      </div>
                    )}
                    <div className="flex items-center justify-between flex-wrap gap-1">
                      <div className="flex items-center gap-1">
                        {task.priority && (
                          <span className={`text-[9px] mono px-1.5 py-0.5 rounded-md border font-bold uppercase ${priorityColors[task.priority] || priorityColors.medium}`}>
                            {task.priority}
                          </span>
                        )}
                        {task.source && (
                          <span className={`text-[9px] mono px-1.5 py-0.5 rounded-md border ${sourceBadge[task.source] || sourceBadge['Manual']}`}>
                            {task.source}
                          </span>
                        )}
                      </div>
                      <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        {col !== 'todo' && (
                          <button onClick={() => moveTask(task.id, COLUMNS[COLUMNS.indexOf(col) - 1])}
                            className="p-1 hover:bg-slate-700/60 rounded-lg transition-colors text-slate-600 hover:text-white" title="Move back">
                            <Icon name="chevron-left" size={12} />
                          </button>
                        )}
                        {col !== 'done' && (
                          <button onClick={() => moveTask(task.id, COLUMNS[COLUMNS.indexOf(col) + 1])}
                            className="p-1 hover:bg-slate-700/60 rounded-lg transition-colors text-slate-600 hover:text-white" title="Move forward">
                            <Icon name="chevron-right" size={12} />
                          </button>
                        )}
                        <button onClick={() => deleteTask(task.id)}
                          className="p-1 hover:bg-red-900/40 rounded-lg transition-colors text-slate-700 hover:text-red-400" title="Delete">
                          <Icon name="x" size={12} />
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};
