/* ============================================================
   page-tasks.jsx — Tasks parsed from standup check-in messages
   ============================================================ */

/* Re-bind parseDetail — set by primitives.jsx */
const parseDetail = window.parseDetail || ((body, status) => (body && (body.detail || body.message)) || `HTTP ${status}`);

const STATUS_TABS = [
  { id: 'all',       label: 'All' },
  { id: 'active',    label: 'Active' },     // A8 fix: in-progress tasks now visible
  { id: 'blocked',   label: 'Blocked' },
  { id: 'stalled',   label: 'Stalled' },
  { id: 'repeated',  label: 'Repeated' },
  { id: 'completed', label: 'Completed' },
  { id: 'dropped',   label: 'Auto-closed' }, // task omitted from a later standup
];

const STATUS_COLORS = {
  active:    { bg: 'var(--brand-dim, #4a6cf7)', text: '#fff' },
  blocked:   { bg: 'var(--err)',    text: '#fff' },
  stalled:   { bg: 'var(--warn)',   text: '#000' },
  repeated:  { bg: 'var(--brand)',  text: '#fff' },
  completed: { bg: 'var(--ok)',     text: '#fff' },
  dropped:   { bg: 'var(--bg-elev-2)', text: 'var(--text-2)' },
};

function StatusPillTask({ s }) {
  const c = STATUS_COLORS[s] || { bg: 'var(--bg-elev-2)', text: 'var(--text-1)' };
  return (
    <span style={{
      display: 'inline-block',
      padding: '2px 8px',
      borderRadius: 999,
      fontSize: 11,
      fontWeight: 600,
      letterSpacing: '0.03em',
      background: c.bg,
      color: c.text,
      textTransform: 'capitalize',
    }}>
      {(window.appT||(s=>s))(s)}
    </span>
  );
}

function TasksPage() {
  const [activeTab, setActiveTab] = useState('all');
  const [days, setDays]           = useState(7);
  const [data, setData]           = useState([]);
  const [loading, setLoading]     = useState(false);
  const [error, setError]         = useState(null);
  const toast                     = useToast ? useToast() : { push: () => {} };

  const fetchTasks = async (tab, d) => {
    setLoading(true);
    setError(null);
    try {
      const r = await fetch(`/api/tasks/by-status?status=${tab}&days=${d}`, { credentials: 'same-origin' });
      if (!r.ok) {
        const body = await r.json().catch(() => null);
        throw new Error(parseDetail(body, r.status));
      }
      setData(await r.json());
    } catch (e) {
      setError(e.message);
      toast.push && toast.push({ msg: ((window.appLang&&window.appLang()==='ar') ? `فشل جلب المهام: ${e.message}` : `Tasks fetch failed: ${e.message}`), kind: 'err' });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchTasks(activeTab, days); }, [activeTab, days]);

  const counts = {};
  STATUS_TABS.slice(1).forEach(t => {
    counts[t.id] = data.filter(r => r.status === t.id).length;
  });

  const displayData = activeTab === 'all' ? data : data.filter(r => r.status === activeTab);

  return (
    <div style={{ padding: 'var(--page-pad)', maxWidth: 1100, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 20, fontWeight: 700 }}>{(window.appT||(s=>s))('Tasks')}</h1>
          <p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--text-3)' }}>
            {(window.appT||(s=>s))('Tasks parsed from standup check-ins — blocked, stalled, repeated, completed, and auto-closed items. A task you stop listing closes itself on your next standup.')}
          </p>
        </div>

        {/* Period picker */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 12, color: 'var(--text-3)' }}>{(window.appT||(s=>s))('Period:')}</span>
          {[
            { label: '1d',  value: 1  },
            { label: '7d',  value: 7  },
            { label: '30d', value: 30 },
          ].map(opt => (
            <button
              key={opt.value}
              className={`btn ${days === opt.value ? 'btn-primary' : 'btn-ghost'}`}
              style={{ padding: '4px 10px', fontSize: 12 }}
              onClick={() => setDays(opt.value)}
              title={(window.appLang&&window.appLang()==='ar') ? `عرض المهام من آخر ${opt.value} ${opt.value === 1 ? 'يوم' : 'أيام'}` : `Show tasks from the last ${opt.value} day${opt.value === 1 ? '' : 's'}`}
            >
              {opt.label}
            </button>
          ))}
        </div>
      </div>

      {/* Status tabs */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 16, borderBottom: '1px solid var(--line)', paddingBottom: 0 }}>
        {STATUS_TABS.map(tab => {
          const cnt = tab.id === 'all' ? data.length : counts[tab.id];
          const isActive = activeTab === tab.id;
          return (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              title={{
                all:       (window.appT||(s=>s))('All tasks regardless of status'),
                active:    (window.appT||(s=>s))('Single-occurrence tasks in progress'),
                blocked:   (window.appT||(s=>s))('Tasks marked blocked by the user'),
                stalled:   (window.appT||(s=>s))('Same task on 2+ days, not completed'),
                repeated:  (window.appT||(s=>s))('Same task on 3+ days in the window'),
                completed: (window.appT||(s=>s))('Tasks marked complete'),
                dropped:   (window.appT||(s=>s))('Auto-closed — omitted from a later standup without being marked done'),
              }[tab.id] || (window.appT||(s=>s))(tab.label)}
              style={{
                background: 'none',
                border: 'none',
                borderBottom: isActive ? '2px solid var(--brand)' : '2px solid transparent',
                padding: '8px 14px',
                cursor: 'pointer',
                fontSize: 13,
                fontWeight: isActive ? 600 : 400,
                color: isActive ? 'var(--text-1)' : 'var(--text-3)',
                display: 'flex',
                alignItems: 'center',
                gap: 6,
                transition: 'color 0.1s',
                marginBottom: -1,
              }}
            >
              {(window.appT||(s=>s))(tab.label)}
              {cnt > 0 && (
                <span style={{
                  fontSize: 11,
                  fontWeight: 600,
                  padding: '1px 6px',
                  borderRadius: 999,
                  background: isActive ? 'var(--brand)' : 'var(--bg-elev-2)',
                  color: isActive ? '#fff' : 'var(--text-2)',
                }}>
                  {cnt}
                </span>
              )}
            </button>
          );
        })}
      </div>

      {/* Table */}
      {loading ? (
        <div style={{ textAlign: 'center', padding: '60px 0', color: 'var(--text-3)', fontSize: 14 }}>
          {(window.appT||(s=>s))('Loading tasks…')}
        </div>
      ) : error ? (
        <div style={{ textAlign: 'center', padding: '60px 0', color: 'var(--err)', fontSize: 14 }}>
          {error}
        </div>
      ) : displayData.length === 0 ? (
        <div style={{
          textAlign: 'center',
          padding: '60px 0',
          color: 'var(--text-3)',
          fontSize: 14,
        }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>✓</div>
          {(window.appLang&&window.appLang()==='ar')
            ? `لا توجد مهام ${activeTab === 'all' ? '' : (window.appT||(s=>s))(activeTab) + ' '}في آخر ${days} ${days !== 1 ? 'أيام' : 'يوم'}.`
            : `No ${activeTab === 'all' ? '' : activeTab + ' '}tasks found in the last ${days} day${days !== 1 ? 's' : ''}.`}
        </div>
      ) : (
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--line)' }}>
                {['User', 'Task', 'Status', 'First seen', 'Last seen', 'Occurrences'].map(col => (
                  <th key={col} style={{
                    padding: '8px 12px',
                    textAlign: 'left',
                    fontSize: 11,
                    fontWeight: 600,
                    color: 'var(--text-3)',
                    textTransform: 'uppercase',
                    letterSpacing: '0.05em',
                    whiteSpace: 'nowrap',
                  }}>
                    {(window.appT||(s=>s))(col)}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {displayData.map((row, i) => /* eslint-disable react/no-array-index-key */ (
                <tr
                  key={i}
                  style={{
                    borderBottom: '1px solid var(--line)',
                    background: i % 2 === 0 ? 'transparent' : 'var(--bg-elev-1)',
                  }}
                >
                  <td style={{ padding: '10px 12px', fontWeight: 500, whiteSpace: 'nowrap', color: 'var(--text-1)' }}>
                    {row.display_name}
                  </td>
                  <td style={{ padding: '10px 12px', color: 'var(--text-1)', maxWidth: 400 }}>
                    {row.task_text}
                    {row.is_stale && (
                      <span
                        title={(window.appT||(s=>s))('Open 2+ days and still being listed — may need help')}
                        style={{
                          marginLeft: 8, padding: '1px 6px', borderRadius: 999,
                          fontSize: 10, fontWeight: 700, letterSpacing: '0.04em',
                          background: 'var(--warn)', color: '#000',
                          verticalAlign: 'middle',
                        }}
                      >
                        {(window.appT||(s=>s))('STALE')}
                      </span>
                    )}
                  </td>
                  <td style={{ padding: '10px 12px', whiteSpace: 'nowrap' }}>
                    <StatusPillTask s={row.status} />
                  </td>
                  <td style={{ padding: '10px 12px', color: 'var(--text-2)', whiteSpace: 'nowrap', fontFamily: 'var(--font-mono)', fontSize: 12 }}>
                    {row.first_seen}
                  </td>
                  <td style={{ padding: '10px 12px', color: 'var(--text-2)', whiteSpace: 'nowrap', fontFamily: 'var(--font-mono)', fontSize: 12 }}>
                    {row.last_seen}
                  </td>
                  <td style={{ padding: '10px 12px', textAlign: 'center', color: (row.occurrences ?? row.days_seen) > 1 ? 'var(--brand)' : 'var(--text-3)', fontWeight: (row.occurrences ?? row.days_seen) > 1 ? 600 : 400 }}>
                    {row.occurrences ?? row.days_seen ?? '—'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

window.TasksPage = TasksPage;
