/* ============================================
   ARCHIVED VIEW — cold storage list with search
   ============================================ */

const ArchivedView = ({ tasks, onOpenTask, onUpdate, onRestore, onDelete }) => {
  const [search, setSearch] = React.useState('');
  const [sortBy, setSortBy] = React.useState('archivedAt');
  const [projectFilter, setProjectFilter] = React.useState('');

  const archived = tasks.filter(t => t.status === 'Archived');

  const filtered = archived
    .filter(t => {
      if (search) {
        const s = search.toLowerCase();
        if (!t.name.toLowerCase().includes(s) &&
            !(t.id || '').toLowerCase().includes(s) &&
            !(t.description || '').toLowerCase().includes(s)) return false;
      }
      if (projectFilter && t.project !== projectFilter) return false;
      return true;
    })
    .sort((a, b) => {
      if (sortBy === 'name') return a.name.localeCompare(b.name);
      if (sortBy === 'project') return (getProject(a.project)?.name || '').localeCompare(getProject(b.project)?.name || '');
      // archivedAt — fall back to dueDate / createdAt
      return new Date(b.dueDate || b.createdAt || 0) - new Date(a.dueDate || a.createdAt || 0);
    });

  // available projects in archive
  const archiveProjects = [...new Set(archived.map(t => t.project).filter(Boolean))];

  return (
    <div style={{ maxWidth: 1100, margin: '0 auto', padding: '24px 24px 60px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 8 }}>
        <span style={{
          width: 40, height: 40, borderRadius: 10,
          background: 'var(--surface-2)', color: 'var(--text-muted)',
          display: 'grid', placeItems: 'center', flexShrink: 0,
        }}>
          <Icon name="folder" size={20} />
        </span>
        <div style={{ flex: 1 }}>
          <h1 style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.03em', margin: 0 }}>Archived</h1>
          <p style={{ fontSize: 13, color: 'var(--text-muted)', margin: 0, marginTop: 2 }}>
            Cold storage for completed and abandoned tasks · {archived.length} total
          </p>
        </div>
      </div>

      {/* Toolbar */}
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', margin: '20px 0 14px', flexWrap: 'wrap' }}>
        <div className="tb-search" style={{ width: 320, flex: '0 1 320px' }}>
          <Icon name="search" size={14} />
          <input
            placeholder="Search archived tasks…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            autoFocus
          />
        </div>

        <select
          className="filter-chip"
          value={projectFilter}
          onChange={(e) => setProjectFilter(e.target.value)}
        >
          <option value="">Any project</option>
          {archiveProjects.map(pid => {
            const p = getProject(pid);
            return p ? <option key={pid} value={pid}>{p.name}</option> : null;
          })}
        </select>

        <select
          className="filter-chip"
          value={sortBy}
          onChange={(e) => setSortBy(e.target.value)}
        >
          <option value="archivedAt">Sort: Most recent</option>
          <option value="name">Sort: Name</option>
          <option value="project">Sort: Project</option>
        </select>

        <div style={{ marginLeft: 'auto', fontSize: 12.5, color: 'var(--text-muted)' }}>
          Showing <b style={{ color: 'var(--text)' }}>{filtered.length}</b> of {archived.length}
        </div>
      </div>

      {/* List */}
      {archived.length === 0 ? (
        <div className="empty-state">
          <div className="empty-state-icon"><Icon name="folder" size={28} /></div>
          <h3>No archived tasks</h3>
          <p>Move tasks to "Archived" status (via the task detail panel) to clean up your board.</p>
        </div>
      ) : filtered.length === 0 ? (
        <div className="empty-state">
          <div className="empty-state-icon"><Icon name="search" size={28} /></div>
          <h3>No matches</h3>
          <p>Try a different search term or clear filters.</p>
        </div>
      ) : (
        <div style={{
          background: 'var(--bg-elevated)',
          border: '1px solid var(--border)',
          borderRadius: 12,
          overflow: 'hidden',
        }}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: '1fr 180px 130px 130px 100px',
            padding: '10px 16px',
            background: 'var(--surface-2)',
            fontSize: 11, fontWeight: 700, textTransform: 'uppercase',
            letterSpacing: '0.05em', color: 'var(--text-subtle)',
            gap: 12,
          }}>
            <span>Task</span>
            <span>Project</span>
            <span>Assignee</span>
            <span>Archived</span>
            <span></span>
          </div>
          {filtered.map((t, idx) => {
            const proj = getProject(t.project);
            const assignee = getUser(t.assignee);
            return (
              <div
                key={t.id}
                onClick={() => onOpenTask(t.id)}
                style={{
                  display: 'grid',
                  gridTemplateColumns: '1fr 180px 130px 130px 100px',
                  padding: '12px 16px',
                  borderTop: '1px solid var(--border)',
                  cursor: 'pointer',
                  fontSize: 13,
                  gap: 12,
                  alignItems: 'center',
                  transition: 'background .1s ease',
                }}
                onMouseEnter={(e) => e.currentTarget.style.background = 'var(--surface-2)'}
                onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
              >
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
                  <Icon name="folder" size={14} style={{ color: 'var(--text-subtle)', flexShrink: 0 }} />
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: 'var(--text-muted)' }}>
                      {t.name}
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--text-subtle)', fontFamily: 'var(--font-mono)', marginTop: 1 }}>
                      {t.id}
                    </div>
                  </div>
                </div>
                {proj ? (
                  <span style={{
                    display: 'inline-flex', alignItems: 'center', gap: 5,
                    fontSize: 11.5, fontWeight: 600,
                    padding: '2px 8px', borderRadius: 5,
                    background: `${proj.color}1A`, color: proj.color,
                    width: 'fit-content',
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '100%',
                  }}>
                    <span style={{ width: 6, height: 6, borderRadius: '50%', background: proj.color, flexShrink: 0 }} />
                    {proj.name}
                  </span>
                ) : <span style={{ color: 'var(--text-subtle)' }}>—</span>}
                {assignee ? (
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                    <Avatar user={assignee} size="sm" />
                    <span style={{ color: 'var(--text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontSize: 12.5 }}>
                      {assignee.short}
                    </span>
                  </span>
                ) : <span style={{ color: 'var(--text-subtle)' }}>Unassigned</span>}
                <span style={{ color: 'var(--text-muted)', fontSize: 12.5 }}>
                  {formatDate(t.dueDate || t.createdAt)}
                </span>
                <div style={{ display: 'flex', gap: 4, justifyContent: 'flex-end' }}>
                  <button
                    className="icon-btn"
                    onClick={(e) => { e.stopPropagation(); onRestore(t.id); }}
                    title="Restore to backlog"
                  >
                    <Icon name="arrow" size={13} style={{ transform: 'rotate(180deg)' }} />
                  </button>
                  <button
                    className="icon-btn"
                    onClick={(e) => { e.stopPropagation(); if (confirm(`Permanently delete "${t.name}"?`)) onDelete(t.id); }}
                    title="Delete permanently"
                    style={{ color: 'var(--c-rose)' }}
                  >
                    <Icon name="trash" size={13} />
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

Object.assign(window, { ArchivedView });
