// "Tüm Görevler" view: all tasks across projects with grouping + filters.
const LSIcons = window.Icons;
const { COLUMNS: LSCOLS, relativeDate: lsRel, formatDate: lsFmt, isOverdue: lsOverdue, parseDateKey: lsDate } = window.PMStore;
const { Tag: LSTag, Priority: LSPriority, StatusPill: LSStatus, Checkbox: LSCheckbox, PRIORITY_META: LS_PRIO, STATUS_META: LS_STATUS } = window.UI;

function ListView({ state, onSelectTask, onToggleDone, onDeleteTask, query, scope = 'all' }) {
  const [filterStatus, setFilterStatus] = React.useState('all');
  const [filterPriority, setFilterPriority] = React.useState('all');
  const [filterProject, setFilterProject] = React.useState(scope === 'project' ? state.activeProjectId : 'all');
  const [groupBy, setGroupBy] = React.useState(scope === 'project' ? 'status' : 'project');
  const [sortBy, setSortBy] = React.useState('due');

  React.useEffect(() => {
    if (scope === 'project') setFilterProject(state.activeProjectId);
  }, [scope, state.activeProjectId]);

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

  let tasks = state.tasks.filter(t => {
    if (filterProject !== 'all' && t.projectId !== filterProject) return false;
    if (filterStatus !== 'all' && t.status !== filterStatus) return false;
    if (filterPriority !== 'all' && t.priority !== filterPriority) return false;
    if (query) {
      const q = query.toLowerCase();
      if (!t.title.toLowerCase().includes(q) &&
          !(t.description||'').toLowerCase().includes(q) &&
          !t.tags.some(tid => (tagById[tid]?.name || '').toLowerCase().includes(q)))
        return false;
    }
    return true;
  });

  // Sort within groups
  const sortFn = (a, b) => {
    if (sortBy === 'due') {
      if (!a.due && !b.due) return 0;
      if (!a.due) return 1;
      if (!b.due) return -1;
      return lsDate(a.due) - lsDate(b.due);
    }
    if (sortBy === 'priority') {
      const order = { high: 0, medium: 1, low: 2 };
      return order[a.priority] - order[b.priority];
    }
    if (sortBy === 'title') return a.title.localeCompare(b.title, 'tr');
    return 0;
  };
  tasks = [...tasks].sort(sortFn);

  // Group
  const groups = groupTasks(tasks, groupBy, state);

  const total = tasks.length;
  const doneTotal = tasks.filter(t => t.status === 'done').length;

  return (
    <div className="content">
      {/* Summary header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, flexWrap: 'wrap', gap: 12 }}>
        <div style={{ fontSize: 13, color: 'var(--text-muted)', fontWeight: 500 }}>
          <strong style={{ color: 'var(--text)', fontWeight: 700, fontSize: 14 }}>{total}</strong>
          {' '}görev
          {total > 0 && <> · {doneTotal} tamamlandı · {total - doneTotal} aktif</>}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="filter-label">Grupla</span>
          <select className="select-control" value={groupBy} onChange={e => setGroupBy(e.target.value)}>
            <option value="none">Gruplama yok</option>
            <option value="project">Projeye göre</option>
            <option value="status">Duruma göre</option>
            <option value="priority">Önceliğe göre</option>
            <option value="due">Tarihe göre</option>
          </select>
          <span className="filter-label" style={{ marginLeft: 8 }}>Sırala</span>
          <select className="select-control" value={sortBy} onChange={e => setSortBy(e.target.value)}>
            <option value="due">Teslim Tarihi</option>
            <option value="priority">Öncelik</option>
            <option value="title">Başlık</option>
          </select>
        </div>
      </div>

      <div className="filter-bar">
        <span className="filter-label"><LSIcons.Filter size={12} /> Durum</span>
        <Chip active={filterStatus === 'all'} onClick={() => setFilterStatus('all')}>Hepsi</Chip>
        {LSCOLS.map(c => (
          <Chip key={c.id} active={filterStatus === c.id} onClick={() => setFilterStatus(c.id)} dot={c.color}>{c.label}</Chip>
        ))}

        <div className="filter-divider" />

        <span className="filter-label">Öncelik</span>
        <Chip active={filterPriority === 'all'} onClick={() => setFilterPriority('all')}>Hepsi</Chip>
        <Chip active={filterPriority === 'high'} onClick={() => setFilterPriority('high')}>Yüksek</Chip>
        <Chip active={filterPriority === 'medium'} onClick={() => setFilterPriority('medium')}>Orta</Chip>
        <Chip active={filterPriority === 'low'} onClick={() => setFilterPriority('low')}>Düşük</Chip>

        {scope !== 'project' && (
          <>
            <div className="filter-divider" />
            <span className="filter-label">Proje</span>
            <Chip active={filterProject === 'all'} onClick={() => setFilterProject('all')}>Hepsi</Chip>
            {state.projects.map(p => (
              <Chip key={p.id} active={filterProject === p.id} onClick={() => setFilterProject(p.id)} dot={p.color}>{p.name}</Chip>
            ))}
          </>
        )}
      </div>

      {tasks.length === 0 ? (
        <div className="card">
          <div className="empty">
            <div className="empty-icon"><LSIcons.Search size={22} /></div>
            <div className="empty-title">Görev bulunamadı</div>
            <div>Filtreleri temizleyin veya yeni görev ekleyin.</div>
          </div>
        </div>
      ) : (
        <div className="list-table">
          <div className="list-header">
            <span></span>
            <span>Görev</span>
            <span>Proje</span>
            <span>Durum</span>
            <span>Teslim</span>
            <span>Öncelik</span>
            <span></span>
          </div>
          {groups.map(grp => (
            <React.Fragment key={grp.id}>
              {groupBy !== 'none' && (
                <div className="list-group-header">
                  {grp.dot && <span className="project-dot" style={{ background: grp.dot, width: 10, height: 10 }} />}
                  <span>{grp.label}</span>
                  <span className="group-count">{grp.tasks.length}</span>
                </div>
              )}
              {grp.tasks.map(t => {
                const proj = projById[t.projectId];
                const overdueT = lsOverdue(t.due, t.status);
                const taskTags = (t.tags || []).map(id => tagById[id]).filter(Boolean);
                return (
                  <div key={t.id} className={`list-row ${t.status === 'done' ? 'done' : ''}`} onClick={() => onSelectTask(t.id)}>
                    <LSCheckbox checked={t.status === 'done'} onChange={() => onToggleDone(t.id)} />
                    <div className="list-main" style={{ minWidth: 0 }}>
                      <div className="list-title">{t.title}</div>
                      {taskTags.length > 0 && (
                        <div style={{ marginTop: 6, display: 'flex', gap: 5, flexWrap: 'wrap' }}>
                          {taskTags.slice(0, 4).map(tag => <LSTag key={tag.id} tag={tag} />)}
                        </div>
                      )}
                    </div>
                    <div className="list-project" style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--text-muted)', minWidth: 0 }}>
                      {proj && <>
                        <span className="project-dot" style={{ background: proj.color }} />
                        <span style={{overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap', fontWeight: 500}}>{proj.name}</span>
                      </>}
                    </div>
                    <div className="list-status"><LSStatus status={t.status} /></div>
                    <div className={`meta ${overdueT ? 'overdue' : ''}`}>
                      {t.due ? lsRel(t.due) : '—'}
                    </div>
                    <div className="list-priority"><LSPriority value={t.priority} /></div>
                    <div className="list-actions" onClick={(e) => e.stopPropagation()}>
                      <button className="icon-btn icon-btn-sm" onClick={() => onSelectTask(t.id)} title="Görevi düzenle">
                        <LSIcons.Edit size={14} />
                      </button>
                      <button
                        className="icon-btn icon-btn-sm danger"
                        onClick={() => {
                          if (window.confirm(`"${t.title}" görevi silinsin mi?`)) onDeleteTask(t.id);
                        }}
                        title="Görevi sil"
                      >
                        <LSIcons.Trash size={14} />
                      </button>
                    </div>
                  </div>
                );
              })}
            </React.Fragment>
          ))}
        </div>
      )}
    </div>
  );
}

function groupTasks(tasks, groupBy, state) {
  if (groupBy === 'none') {
    return [{ id: 'all', label: 'Tümü', tasks }];
  }
  if (groupBy === 'project') {
    const map = new Map();
    state.projects.forEach(p => map.set(p.id, { id: p.id, label: p.name, dot: p.color, tasks: [] }));
    tasks.forEach(t => map.get(t.projectId)?.tasks.push(t));
    return [...map.values()].filter(g => g.tasks.length > 0);
  }
  if (groupBy === 'status') {
    const map = new Map();
    LSCOLS.forEach(c => map.set(c.id, { id: c.id, label: c.label, dot: c.color, tasks: [] }));
    tasks.forEach(t => map.get(t.status)?.tasks.push(t));
    return [...map.values()].filter(g => g.tasks.length > 0);
  }
  if (groupBy === 'priority') {
    const labels = { high: 'Yüksek Öncelik', medium: 'Orta Öncelik', low: 'Düşük Öncelik' };
    const dots = { high: '#b91c1c', medium: '#b45309', low: '#1d4ed8' };
    const map = new Map();
    ['high','medium','low'].forEach(p => map.set(p, { id: p, label: labels[p], dot: dots[p], tasks: [] }));
    tasks.forEach(t => map.get(t.priority)?.tasks.push(t));
    return [...map.values()].filter(g => g.tasks.length > 0);
  }
  if (groupBy === 'due') {
    const today = new Date(); today.setHours(0,0,0,0);
    const week = new Date(today); week.setDate(week.getDate() + 7);
    const buckets = {
      overdue: { id: 'overdue', label: 'Gecikmiş', dot: '#b91c1c', tasks: [] },
      today:   { id: 'today',   label: 'Bugün',    dot: '#b45309', tasks: [] },
      week:    { id: 'week',    label: 'Bu Hafta', dot: '#1d4ed8', tasks: [] },
      later:   { id: 'later',   label: 'Daha Sonra', dot: '#6d28d9', tasks: [] },
      none:    { id: 'none',    label: 'Tarihsiz',  dot: '#94a3b8', tasks: [] },
    };
    tasks.forEach(t => {
      if (!t.due) return buckets.none.tasks.push(t);
      const d = lsDate(t.due); d.setHours(0,0,0,0);
      if (d < today && t.status !== 'done') return buckets.overdue.tasks.push(t);
      if (d.getTime() === today.getTime()) return buckets.today.tasks.push(t);
      if (d < week) return buckets.week.tasks.push(t);
      return buckets.later.tasks.push(t);
    });
    return Object.values(buckets).filter(g => g.tasks.length > 0);
  }
  return [{ id: 'all', label: 'Tümü', tasks }];
}

function Chip({ active, onClick, children, dot }) {
  return (
    <button className={`filter-chip ${active ? 'active' : ''}`} onClick={onClick}>
      {dot && <span className="project-dot" style={{ background: dot }} />}
      {children}
    </button>
  );
}

window.ListView = ListView;
