/* My Work — a personal dashboard for the current user
   Combines My Day briefing, mentions, assigned tasks, schedule, and quick actions */

function MyWorkView({ allTasks, currentUserId = 1, onView, onSelectTask, onOpenModal, onStatusChange }) {
  const me = userById(currentUserId);
  const mine = allTasks.filter(t => t.assignees.includes(currentUserId));
  const open = mine.filter(t => t.statusId !== 6);

  const today    = open.filter(t => t.dueDate && dayDelta(t.dueDate) === 0);
  const overdue  = open.filter(t => t.dueDate && dayDelta(t.dueDate) < 0);
  const week     = open.filter(t => t.dueDate && dayDelta(t.dueDate) >= 0 && dayDelta(t.dueDate) <= 7);
  const myDay    = open.filter(t => t.myDay);
  const urgent   = open.filter(t => t.priority === 'urgent');
  const watching = allTasks.filter(t => t.watchers?.includes(currentUserId));
  const doneRecently = mine.filter(t => t.statusId === 6).slice(0, 5);

  const totalEstWeek = week.reduce((s, t) => s + (t.estimateMins || 0), 0);
  const totalLog     = mine.reduce((s, t) => s + (t.actualMins || 0), 0);

  const [tab, setTab] = React.useState('today');
  const rank = { urgent: 0, high: 1, medium: 2, low: 3 };
  const sortQ = (arr) => [...arr].sort((a, b) =>
    rank[a.priority] - rank[b.priority] ||
    (a.dueDate || '9999').localeCompare(b.dueDate || '9999')
  );

  const buckets = {
    today:    sortQ(today),
    upcoming: sortQ(week.filter(t => dayDelta(t.dueDate) > 0)),
    overdue:  sortQ(overdue),
    later:    sortQ(open.filter(t => !t.dueDate || dayDelta(t.dueDate) > 7)),
    mention:  watching,
    done:     doneRecently,
  };
  const tabs = [
    ['today',    'Today',      buckets.today.length,    'rgb(var(--accent))'],
    ['upcoming', 'This week',  buckets.upcoming.length, 'rgb(var(--forest))'],
    ['overdue',  'Overdue',    buckets.overdue.length,  'rgb(var(--brick))'],
    ['later',    'Later',      buckets.later.length,    'rgb(var(--muted))'],
    ['mention',  'Watching',   buckets.mention.length,  'rgb(var(--navy))'],
    ['done',     'Done',       buckets.done.length,     'rgb(var(--muted))'],
  ];

  // 7-day schedule
  const days = Array.from({ length: 7 }, (_, i) => {
    const d = new Date(TODAY); d.setDate(d.getDate() + i);
    const iso = d.toISOString().slice(0, 10);
    return { d, iso, tasks: open.filter(t => t.dueDate === iso) };
  });

  return (
    <div style={{ flex: 1, overflowY: 'auto', background: 'rgb(var(--bg))' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '24px 32px 60px' }}>

        {/* Hero */}
        <div style={{
          padding: '24px 26px', marginBottom: 22,
          background: 'linear-gradient(135deg, rgb(var(--accent-soft)) 0%, rgb(var(--surface)) 60%)',
          border: '1px solid rgb(var(--rule))', borderRadius: 16,
          boxShadow: 'var(--sh-sm)', position: 'relative', overflow: 'hidden',
        }}>
          <span aria-hidden style={{
            position: 'absolute', top: -60, right: -60,
            width: 220, height: 220, borderRadius: '50%',
            background: 'rgb(var(--accent) / 0.12)',
            filter: 'blur(20px)', pointerEvents: 'none',
          }} />
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 18, position: 'relative' }}>
            <Avatar user={me} size={60} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <p style={{ margin: 0, fontSize: 12, fontWeight: 600, color: 'rgb(var(--accent-2))', letterSpacing: '0.04em', textTransform: 'uppercase' }}>{TODAY.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' })}</p>
              <h1 style={{ margin: '4px 0 0', fontSize: 28, fontWeight: 700, letterSpacing: '-0.025em' }}>Good morning, {me.name.split(' ')[0]}.</h1>
              <p style={{ margin: '6px 0 0', fontSize: 14, color: 'rgb(var(--ink-2))', maxWidth: 600 }}>
                You have <strong>{open.length} open task{open.length === 1 ? '' : 's'}</strong>
                {urgent.length > 0 && <>, <strong style={{ color: 'rgb(var(--brick))' }}>{urgent.length} urgent</strong></>}
                {overdue.length > 0 && <>, <strong style={{ color: 'rgb(var(--brick))' }}>{overdue.length} overdue</strong></>}.
                {' '}About <strong>{fmtMins(totalEstWeek) || '0m'}</strong> of estimated work this week.
              </p>
              <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
                <button onClick={() => onView?.('my-day')} className="btn btn-accent" style={{ fontSize: 13 }}>☀ Open My Day</button>
                <button onClick={() => onView?.('mentions')} className="btn btn-secondary" style={{ fontSize: 13 }}>@ Mentions</button>
                <button onClick={() => setTab('today')} className="btn btn-secondary" style={{ fontSize: 13 }}>Plan today →</button>
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10, minWidth: 280 }}>
              <MWStat n={today.length}    l="Today"    c="rgb(var(--accent))" soft="rgb(var(--accent-soft))" />
              <MWStat n={overdue.length}  l="Overdue"  c="rgb(var(--brick))"  soft="rgb(var(--brick-soft))" />
              <MWStat n={urgent.length}   l="Urgent"   c="rgb(var(--warm))"   soft="rgb(var(--warm-soft))" />
              <MWStat n={fmtMins(totalLog) || '0m'} l="Logged" c="rgb(var(--forest))" soft="rgb(var(--forest-soft))" isText />
            </div>
          </div>
        </div>

        {/* Schedule strip */}
        <section style={{ marginBottom: 22 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 10 }}>
            <h2 style={{ margin: 0, fontSize: 15, fontWeight: 700, letterSpacing: '-0.01em' }}>Your week ahead</h2>
            <span style={{ flex: 1 }} />
            <button onClick={() => onView?.('planned')} className="btn btn-ghost" style={{ fontSize: 11.5 }}>Open calendar →</button>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 8 }}>
            {days.map(({ d, iso, tasks }) => {
              const isToday = d.toDateString() === TODAY.toDateString();
              return (
                <div key={iso} style={{
                  background: isToday ? 'rgb(var(--accent-soft) / 0.45)' : 'rgb(var(--surface))',
                  border: '1px solid ' + (isToday ? 'rgb(var(--accent) / 0.4)' : 'rgb(var(--rule))'),
                  borderRadius: 10, padding: 10, minHeight: 110,
                  boxShadow: 'var(--sh-sm)',
                }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 8 }}>
                    <span style={{ fontSize: 10.5, fontWeight: 700, color: isToday ? 'rgb(var(--accent-2))' : 'rgb(var(--muted))', letterSpacing: '0.04em', textTransform: 'uppercase' }}>{d.toLocaleDateString('en-GB', { weekday: 'short' })}</span>
                    <span style={{ fontSize: 13, fontWeight: 700, fontFamily: 'JetBrains Mono, monospace', color: isToday ? 'rgb(var(--accent))' : 'rgb(var(--ink-2))' }}>{d.getDate()}</span>
                  </div>
                  {tasks.length === 0 && <span style={{ fontSize: 11, color: 'rgb(var(--rule-2))', fontStyle: 'italic' }}>nothing</span>}
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
                    {tasks.slice(0, 3).map(t => (
                      <button key={t.id} onClick={() => onSelectTask?.(t.id)} style={{
                        textAlign: 'left', display: 'flex', alignItems: 'center', gap: 5,
                        fontSize: 10.5, padding: '3px 6px', borderRadius: 5,
                        background: 'rgb(var(--paper-2) / 0.6)',
                        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                      }}>
                        <PriorityDot p={t.priority} />
                        <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.title}</span>
                      </button>
                    ))}
                    {tasks.length > 3 && <span style={{ fontSize: 10, color: 'rgb(var(--muted))' }}>+{tasks.length - 3} more</span>}
                  </div>
                </div>
              );
            })}
          </div>
        </section>

        {/* Tabs + ticket list */}
        <section>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4, padding: 4, background: 'rgb(var(--paper-2))', borderRadius: 10, marginBottom: 14, overflowX: 'auto' }}>
            {tabs.map(([k, lbl, n, c]) => (
              <button key={k} onClick={() => setTab(k)} style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                padding: '6px 12px', fontSize: 12.5, fontWeight: 600,
                background: tab === k ? 'rgb(var(--surface))' : 'transparent',
                color: tab === k ? 'rgb(var(--ink))' : 'rgb(var(--muted))',
                borderRadius: 7, boxShadow: tab === k ? 'var(--sh-sm)' : 'none',
                whiteSpace: 'nowrap',
              }}>
                {lbl}
                <span className="num" style={{
                  fontSize: 10, fontWeight: 700, padding: '1px 6px', borderRadius: 999,
                  background: tab === k ? c + '14' : 'rgb(var(--paper-3))',
                  color: tab === k ? c : 'rgb(var(--muted))',
                }}>{n}</span>
              </button>
            ))}
          </div>

          <div style={{
            background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
            borderRadius: 12, overflow: 'hidden', boxShadow: 'var(--sh-sm)',
          }}>
            {(buckets[tab] || []).length === 0 && (
              <div style={{ padding: '50px 20px', textAlign: 'center', color: 'rgb(var(--muted))' }}>
                <div style={{ fontSize: 28, marginBottom: 8 }}>🍵</div>
                <p style={{ margin: 0, fontSize: 14, fontWeight: 600, color: 'rgb(var(--ink))' }}>Nothing here.</p>
                <p style={{ margin: '4px 0 0', fontSize: 12.5 }}>Switch tabs or take a breath.</p>
              </div>
            )}
            {(buckets[tab] || []).map((t, i, arr) => (
              <MyWorkRow key={t.id} task={t} last={i === arr.length - 1}
                onClick={() => onSelectTask?.(t.id)}
                onOpen={() => onOpenModal?.(t.id)}
                onComplete={() => onStatusChange?.(t.id, 6)}
              />
            ))}
          </div>
        </section>

      </div>
    </div>
  );
}

function MWStat({ n, l, c, soft, isText }) {
  return (
    <div style={{ padding: '10px 14px', background: soft, borderRadius: 10 }}>
      <div className="num" style={{ fontSize: isText ? 18 : 22, fontWeight: 700, color: c, letterSpacing: '-0.025em', lineHeight: 1 }}>{n}</div>
      <div style={{ fontSize: 10.5, fontWeight: 600, color: c, marginTop: 4, opacity: 0.8, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{l}</div>
    </div>
  );
}

function MyWorkRow({ task, last, onClick, onOpen, onComplete }) {
  const sp = spaceById(task.spaceId);
  const st = statusById(task.statusId);
  const done = task.statusId === 6;
  return (
    <article onClick={onClick} onDoubleClick={(e) => { e.stopPropagation(); onOpen(); }} style={{
      display: 'grid', gridTemplateColumns: '24px 18px 1fr auto auto auto',
      gap: 12, alignItems: 'center', padding: '11px 16px',
      borderBottom: last ? 'none' : '1px solid rgb(var(--rule) / 0.6)',
      cursor: 'pointer', transition: 'background-color .12s',
    }}
      onMouseEnter={e => e.currentTarget.style.background = 'rgb(var(--paper-2) / 0.4)'}
      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
      <Checkbox checked={done} onClick={(e) => { e.stopPropagation(); onComplete(); }} />
      <PriorityDot p={task.priority} />
      <div style={{ minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 3 }}>
          <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10.5, color: 'rgb(var(--muted))' }}>{task.ticket}</span>
          <span style={{ width: 3, height: 3, background: 'rgb(var(--rule-2))', borderRadius: '50%' }} />
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11, color: sp.colour, fontWeight: 600 }}>
            <span style={{ width: 5, height: 5, background: sp.colour, borderRadius: 2 }} />{sp.name}
          </span>
        </div>
        <div style={{
          fontSize: 13.5, fontWeight: 600,
          color: done ? 'rgb(var(--muted))' : 'rgb(var(--ink))',
          textDecoration: done ? 'line-through' : 'none',
          letterSpacing: '-0.005em',
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>{task.title}</div>
      </div>
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 5,
        padding: '2px 9px', background: st.colour + '14', color: st.colour,
        fontSize: 10.5, fontWeight: 700, borderRadius: 999,
      }}>
        <span style={{ width: 5, height: 5, background: st.colour, borderRadius: '50%' }} />{st.title}
      </span>
      {task.dueDate ? <DueChip iso={task.dueDate} /> : <span style={{ fontSize: 11, color: 'rgb(var(--muted-2))', fontFamily: 'JetBrains Mono, monospace' }}>—</span>}
      {task.estimateMins > 0 ? <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10.5, color: 'rgb(var(--muted))' }}>{fmtMins(task.estimateMins)}</span> : <span />}
    </article>
  );
}

window.MyWorkView = MyWorkView;
