// Kanban view: 4 columns with HTML5 drag-and-drop. Filtered by activeProjectId.
const KBIcons = window.Icons;
const { COLUMNS: KBCOLS, taskProgress: kbProgress, relativeDate: kbRel, isOverdue: kbOverdue } = window.PMStore;
const { Tag: KBTag, Priority: KBPriority } = window.UI;

function Kanban({ state, onSelectTask, onUpdateTask, onDeleteTask, onAddTask, query }) {
  const [dragTaskId, setDragTaskId] = React.useState(null);
  const [dragOverCol, setDragOverCol] = React.useState(null);

  const tagById = Object.fromEntries(state.tags.map(t => [t.id, t]));
  const activeProject = state.projects.find(p => p.id === state.activeProjectId);

  const filtered = state.tasks.filter(t => {
    if (t.projectId !== state.activeProjectId) return false;
    if (!query) return true;
    const q = query.toLowerCase();
    return t.title.toLowerCase().includes(q) ||
           (t.description||'').toLowerCase().includes(q) ||
           t.tags.some(tid => (tagById[tid]?.name || '').toLowerCase().includes(q));
  });

  const tasksByCol = Object.fromEntries(KBCOLS.map(c => [c.id, []]));
  filtered.forEach(t => { (tasksByCol[t.status] || tasksByCol.todo).push(t); });

  const handleDrop = (e, colId) => {
    e.preventDefault();
    if (dragTaskId) {
      onUpdateTask(dragTaskId, { status: colId });
    }
    setDragTaskId(null);
    setDragOverCol(null);
  };

  if (!activeProject) {
    return (
      <div className="content">
        <div className="empty">
          <div className="empty-icon"><KBIcons.Folder size={20} /></div>
          <div className="empty-title">Proje seçilmedi</div>
          <div>Soldaki listeden bir proje seçin.</div>
        </div>
      </div>
    );
  }

  return (
    <div className="kanban">
      {KBCOLS.map(col => (
        <div key={col.id} className="kanban-col">
          <div className="kanban-col-header">
            <span className="dot" style={{ background: col.color }} />
            <span>{col.label}</span>
            <span className="col-count">{tasksByCol[col.id].length}</span>
            <button className="col-add" onClick={() => onAddTask({ status: col.id, projectId: state.activeProjectId })}>
              <KBIcons.Plus size={13} strokeWidth={2.5} />
            </button>
          </div>
          <div
            className={`kanban-list ${dragOverCol === col.id ? 'drag-over' : ''}`}
            onDragOver={(e) => { e.preventDefault(); setDragOverCol(col.id); }}
            onDragLeave={(e) => {
              if (e.currentTarget === e.target) setDragOverCol(null);
            }}
            onDrop={(e) => handleDrop(e, col.id)}
          >
            {tasksByCol[col.id].map(t => (
              <TaskCard
                key={t.id}
                task={t}
                tagById={tagById}
                dragging={dragTaskId === t.id}
                onDragStart={() => setDragTaskId(t.id)}
                onDragEnd={() => { setDragTaskId(null); setDragOverCol(null); }}
                onClick={() => onSelectTask(t.id)}
                onUpdateStatus={(status) => onUpdateTask(t.id, { status })}
                onDelete={() => onDeleteTask(t.id)}
              />
            ))}
            {tasksByCol[col.id].length === 0 && (
              <div style={{
                padding: 18, textAlign: 'center',
                fontSize: 12, color: 'var(--text-faint)',
                border: '1.5px dashed var(--border-strong)',
                borderRadius: 8,
              }}>Henüz görev yok</div>
            )}
          </div>
        </div>
      ))}
    </div>
  );
}

function TaskCard({ task, tagById, dragging, onDragStart, onDragEnd, onClick, onUpdateStatus, onDelete }) {
  const pct = kbProgress(task);
  const overdueT = kbOverdue(task.due, task.status);
  const taskTags = (task.tags || []).map(id => tagById[id]).filter(Boolean);
  const subtaskDone = (task.subtasks || []).filter(s => s.done).length;
  const subtaskTotal = (task.subtasks || []).length;

  return (
    <div
      className={`task-card ${dragging ? 'dragging' : ''}`}
      draggable
      onDragStart={(e) => {
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/plain', task.id);
        onDragStart();
      }}
      onDragEnd={onDragEnd}
      onClick={onClick}
    >
      <div className="task-card-actions" onClick={(e) => e.stopPropagation()}>
        <button onClick={onClick} title="Görevi düzenle">
          <KBIcons.Edit size={13} />
        </button>
        <button
          onClick={() => {
            if (window.confirm(`"${task.title}" görevi silinsin mi?`)) onDelete();
          }}
          title="Görevi sil"
        >
          <KBIcons.Trash size={13} />
        </button>
      </div>
      {taskTags.length > 0 && (
        <div className="task-card-tags">
          {taskTags.slice(0, 3).map(tag => <KBTag key={tag.id} tag={tag} />)}
        </div>
      )}
      <div className="task-card-title">{task.title}</div>
      {subtaskTotal > 0 && (
        <>
          <div className="task-card-progress">
            <div className="task-card-progress-fill" style={{ width: `${pct}%` }} />
          </div>
        </>
      )}
      <div className="task-card-footer">
        <KBPriority value={task.priority} />
        {task.due && (
          <span className="meta-pill" style={overdueT ? { color: 'var(--p-high)', fontWeight: 600 } : undefined}>
            <KBIcons.Clock size={11} />
            {kbRel(task.due)}
          </span>
        )}
        {subtaskTotal > 0 && (
          <span className="meta-pill">
            <KBIcons.CheckSquare size={11} />
            {subtaskDone}/{subtaskTotal}
          </span>
        )}
      </div>
      <div className="touch-status-control" onClick={(e) => e.stopPropagation()}>
        <span>Durum</span>
        <select
          value={task.status}
          onChange={(e) => onUpdateStatus(e.target.value)}
          aria-label={`${task.title} durumu`}
        >
          {KBCOLS.map(col => <option key={col.id} value={col.id}>{col.label}</option>)}
        </select>
      </div>
    </div>
  );
}

window.Kanban = Kanban;
