// fichaje.eu — Screen: Tareas (kanban)

const COLS = [
  { key: 'backlog', label: 'Backlog',     tone: 'slate'   },
  { key: 'todo',    label: 'Por hacer',   tone: 'brand'   },
  { key: 'doing',   label: 'En curso',    tone: 'warning' },
  { key: 'review',  label: 'En revisión', tone: 'violet' },
  { key: 'done',    label: 'Hecho',       tone: 'success' },
];
const colIdx = (k) => COLS.findIndex(c => c.key === k);

async function refresh() {
  if (!window.api) return;
  await window.api.reloadBootstrap();
  window.location.reload();
}

async function quickCreateTask(colKey) {
  const title = window.prompt('Título de la nueva tarea');
  if (!title || !window.api) return;
  await window.api.createTask({ title, board_col: colKey, priority: 'media' });
  await refresh();
}

async function moveCol(t, delta) {
  if (!window.api) return;
  const cur = colIdx(t.board_col || 'todo');
  const next = COLS[Math.max(0, Math.min(COLS.length - 1, cur + delta))];
  if (!next || next.key === (t.board_col || 'todo')) return;
  await window.api.moveTask(t.id, next.key);
  await refresh();
}

async function deleteTask(t) {
  if (!window.api) return;
  if (!window.confirm(`¿Eliminar tarea "${t.title}"?`)) return;
  await window.api.deleteTask(t.id);
  await refresh();
}

const ScreenTareas = () => {
  const cols = COLS;
  const totalTasks = Object.values(TASKS).reduce((a, c) => a + c.length, 0);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Toolbar */}
      <Card style={{ padding: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div>
            <div style={{ fontSize: 15, fontWeight: 700 }}>Plataforma — Sprint 14</div>
            <div style={{ fontSize: 12, color: 'var(--slate-500)' }}>{totalTasks} tareas · 5 personas · cierra el 24 may</div>
          </div>
          <div style={{ flex: 1 }}/>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            {TEAM.slice(0, 5).map(p => <Avatar key={p.name} name={p.name} size={28}/>)}
          </div>
          <Divider vertical style={{ height: 24 }}/>
          <Btn variant="ghost" size="sm" icon={<IFilter size={14}/>}>Filtrar</Btn>
          <Btn variant="secondary" size="sm" icon={<IList size={14}/>}>Vista</Btn>
          <Btn variant="primary" size="sm" icon={<IPlus size={14}/>} onClick={() => quickCreateTask('todo')}>Nueva tarea</Btn>
        </div>
      </Card>

      {/* Kanban */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 14, alignItems: 'flex-start' }}>
        {cols.map(col => {
          const items = TASKS[col.key];
          return (
            <div key={col.key} style={{
              background: 'var(--slate-50)',
              borderRadius: 'var(--r-lg)',
              padding: 10,
              minHeight: 480,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 6px 12px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Badge tone={col.tone} dot>{col.label}</Badge>
                  <span className="tnum" style={{ fontSize: 12, fontWeight: 600, color: 'var(--slate-500)' }}>{items.length}</span>
                </div>
                <button style={{ color: 'var(--slate-400)', padding: 2, cursor: 'pointer' }} onClick={() => quickCreateTask(col.key)} title="Nueva tarea en esta columna"><IPlus size={14}/></button>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {items.map(t => <TaskCard key={t.id} t={t} colKey={col.key}/>)}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

const TaskCard = ({ t, colKey }) => {
  const priorityColors = {
    alta:  { bg: 'var(--danger-100)', fg: 'var(--danger-600)' },
    media: { bg: 'var(--warning-100)', fg: 'var(--warning-600)' },
    baja:  { bg: 'var(--slate-200)', fg: 'var(--slate-600)' },
  };
  const tagColors = {
    cliente:        'brand',
    investigación:  'violet',
    comercial:      'success',
    infra:          'slate',
    marketing:      'pink',
    plataforma:     'teal',
    interno:        'warning',
  };
  const tWithCol = { ...t, board_col: colKey };
  const ci = colIdx(colKey);
  const canPrev = ci > 0;
  const canNext = ci < COLS.length - 1;
  const btnArrow = {
    width: 22, height: 22, borderRadius: 6,
    border: '1px solid var(--slate-200)', background: 'var(--white)',
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    fontSize: 13, lineHeight: 1, color: 'var(--slate-600)', cursor: 'pointer',
  };
  return (
    <div style={{
      background: 'var(--white)',
      borderRadius: 'var(--r-md)',
      padding: 12,
      border: '1px solid var(--slate-150)',
      boxShadow: 'var(--shadow-xs)',
      position: 'relative',
    }}>
      <div style={{ display: 'flex', gap: 6, marginBottom: 8, flexWrap: 'wrap' }}>
        <Badge tone={tagColors[t.tag] || 'slate'} style={{ fontSize: 10.5, padding: '2px 7px' }}>{t.tag}</Badge>
        <Badge tone="slate" style={{ fontSize: 10.5, padding: '2px 7px', background: priorityColors[t.priority].bg, color: priorityColors[t.priority].fg }}>
          {t.priority === 'alta' && '↑ '}{t.priority === 'baja' && '↓ '}{t.priority}
        </Badge>
      </div>
      <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)', lineHeight: 1.4 }}>{t.title}</div>

      {t.progress && (
        <div style={{ marginTop: 10 }}>
          <ProgressBar value={t.progress} color="var(--brand-500)" height={4}/>
          <div style={{ fontSize: 11, color: 'var(--slate-500)', marginTop: 4 }}>{t.progress}% completado</div>
        </div>
      )}

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 12 }}>
        <Avatar name={t.assignee} size={22}/>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11.5, color: 'var(--slate-500)' }}>
          {colKey === 'done' ? (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, color: 'var(--success-600)' }}>
              <ICheck size={12}/> {t.done}
            </span>
          ) : t.due !== '—' ? (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}>
              <IClock size={12}/> {t.due}
            </span>
          ) : null}
        </div>
      </div>

      <div style={{ marginTop: 10, paddingTop: 8, borderTop: '1px dashed var(--slate-150)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', gap: 4 }}>
          <button style={{ ...btnArrow, opacity: canPrev ? 1 : 0.3 }} disabled={!canPrev}
            onClick={() => moveCol(tWithCol, -1)} title="Mover ←">←</button>
          <button style={{ ...btnArrow, opacity: canNext ? 1 : 0.3 }} disabled={!canNext}
            onClick={() => moveCol(tWithCol, +1)} title="Mover →">→</button>
        </div>
        <button style={{ ...btnArrow, color: 'var(--danger-600)', borderColor: 'var(--danger-100)' }}
          onClick={() => deleteTask(tWithCol)} title="Eliminar tarea">×</button>
      </div>
    </div>
  );
};

Object.assign(window, { ScreenTareas });
