/* Timeline (Gantt) view — 6-week horizontal scheduling visualisation */

function TimelineView({ tasks, onSelect, selectedId }) {
  // Start of view: Monday of current week
  const start = React.useMemo(() => {
    const d = new Date(TODAY); d.setHours(0,0,0,0);
    d.setDate(d.getDate() - ((d.getDay() + 6) % 7));
    return d;
  }, []);

  const totalDays = 42;
  const dayWidth = 30;
  const labelWidth = 240;

  // Group rows by space
  const spacesUsed = React.useMemo(() => {
    const used = new Set(tasks.map(t => t.spaceId));
    return D.spaces.filter(s => used.has(s.id));
  }, [tasks]);

  const dates = Array.from({ length: totalDays }, (_, i) => {
    const d = new Date(start); d.setDate(start.getDate() + i);
    return d;
  });

  // Place each task as a bar based on dueDate. We assume duration = ceil(estimateMins / 480) days, min 1.
  const placeTask = (t) => {
    if (!t.dueDate) return null;
    const d = new Date(t.dueDate + 'T00:00:00');
    const diff = Math.round((d - start) / 86400000);
    if (diff < 0 || diff >= totalDays) return null;
    const days = Math.max(1, Math.ceil((t.estimateMins || 480) / 480));
    return { startDay: Math.max(0, diff - (days - 1)), days };
  };

  // For each space, group tasks
  const rows = spacesUsed.map(sp => ({
    space: sp,
    tasks: tasks.filter(t => t.spaceId === sp.id),
  }));

  const headerTotalWidth = totalDays * dayWidth;

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: 'rgb(var(--bg))', overflow: 'hidden', padding: '14px 20px 20px' }}>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12, paddingInline: 4 }}>
        <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, letterSpacing: '-0.02em' }}>Timeline</h2>
        <span style={{ fontSize: 12, color: 'rgb(var(--muted))' }}>6 weeks · today highlighted · est. duration as bar length</span>
        <span style={{ flex: 1 }} />
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'rgb(var(--muted))' }}>
          <span style={{ width: 8, height: 8, background: 'rgb(var(--accent))', borderRadius: 2 }} /> In progress
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'rgb(var(--muted))' }}>
          <span style={{ width: 8, height: 8, background: 'rgb(var(--brick))', borderRadius: 2 }} /> Blocked
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'rgb(var(--muted))' }}>
          <span style={{ width: 8, height: 8, background: 'rgb(var(--forest))', borderRadius: 2 }} /> Done
        </span>
      </div>

      <div style={{
        flex: 1, background: 'rgb(var(--surface))',
        border: '1px solid rgb(var(--rule))', borderRadius: 12,
        boxShadow: 'var(--sh-sm)',
        overflow: 'auto',
        position: 'relative',
      }}>
        {/* Header */}
        <div style={{
          display: 'grid', gridTemplateColumns: `${labelWidth}px ${headerTotalWidth}px`,
          position: 'sticky', top: 0, zIndex: 5,
          background: 'rgb(var(--surface))', borderBottom: '1px solid rgb(var(--rule))',
        }}>
          <div style={{
            padding: '10px 14px',
            fontSize: 11, fontWeight: 600, color: 'rgb(var(--muted))', textTransform: 'uppercase', letterSpacing: '0.06em',
            borderRight: '1px solid rgb(var(--rule))',
          }}>Space / Task</div>
          <div>
            {/* Week labels */}
            <div style={{
              display: 'grid', gridTemplateColumns: `repeat(${totalDays / 7}, 1fr)`,
              borderBottom: '1px solid rgb(var(--rule) / 0.6)',
            }}>
              {Array.from({ length: totalDays / 7 }, (_, w) => {
                const d = new Date(start); d.setDate(start.getDate() + w * 7);
                return (
                  <div key={w} style={{
                    padding: '6px 10px', fontSize: 11, fontWeight: 600,
                    color: 'rgb(var(--ink-2))',
                    borderRight: w < (totalDays / 7) - 1 ? '1px solid rgb(var(--rule))' : 'none',
                  }}>w/c {d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })}</div>
                );
              })}
            </div>
            {/* Day labels */}
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${totalDays}, ${dayWidth}px)` }}>
              {dates.map((d, i) => {
                const isToday = d.toDateString() === TODAY.toDateString();
                const isWeekend = d.getDay() === 0 || d.getDay() === 6;
                return (
                  <div key={i} style={{
                    fontSize: 10, padding: '4px 0', textAlign: 'center',
                    color: isToday ? 'rgb(var(--accent))' : isWeekend ? 'rgb(var(--muted-2))' : 'rgb(var(--muted))',
                    fontWeight: isToday ? 700 : 500,
                    background: isWeekend ? 'rgb(var(--paper-2) / 0.4)' : 'transparent',
                    borderRight: '1px solid rgb(var(--rule) / 0.4)',
                  }}>{d.getDate()}</div>
                );
              })}
            </div>
          </div>
        </div>

        {/* Body rows */}
        {rows.map(row => (
          <React.Fragment key={row.space.id}>
            {/* Space group header */}
            <div style={{
              display: 'grid', gridTemplateColumns: `${labelWidth}px ${headerTotalWidth}px`,
              background: 'rgb(var(--paper-2) / 0.4)',
              borderBottom: '1px solid rgb(var(--rule))',
            }}>
              <div style={{
                padding: '7px 14px',
                display: 'flex', alignItems: 'center', gap: 8,
                fontSize: 12.5, fontWeight: 700,
                borderRight: '1px solid rgb(var(--rule))',
              }}>
                <span style={{ width: 8, height: 8, background: row.space.colour, borderRadius: 2 }} />
                {row.space.name}
                <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'rgb(var(--muted))', fontWeight: 500 }}>{row.space.prefix}</span>
                <span className="num" style={{ marginLeft: 'auto', fontSize: 11, color: 'rgb(var(--muted))' }}>{row.tasks.length}</span>
              </div>
              <div />
            </div>
            {row.tasks.map(t => {
              const place = placeTask(t);
              const st = statusById(t.statusId);
              return (
                <div key={t.id} style={{
                  display: 'grid', gridTemplateColumns: `${labelWidth}px ${headerTotalWidth}px`,
                  borderBottom: '1px solid rgb(var(--rule) / 0.5)',
                  background: selectedId === t.id ? 'rgb(var(--accent-soft) / 0.3)' : 'transparent',
                  cursor: 'pointer',
                }}
                  onClick={() => onSelect(t.id)}
                  onMouseEnter={e => { if (selectedId !== t.id) e.currentTarget.style.background = 'rgb(var(--paper-2) / 0.4)'; }}
                  onMouseLeave={e => { if (selectedId !== t.id) e.currentTarget.style.background = 'transparent'; }}
                >
                  <div style={{
                    padding: '8px 14px 8px 24px',
                    display: 'flex', alignItems: 'center', gap: 8, minWidth: 0,
                    borderRight: '1px solid rgb(var(--rule))',
                  }}>
                    <PriorityDot p={t.priority} />
                    <span style={{ fontSize: 12.5, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.title}</span>
                    {t.assignees.length > 0 && <AvatarStack ids={t.assignees} size={18} max={2} />}
                  </div>
                  <div style={{ position: 'relative', height: 32 }}>
                    {/* Grid lines */}
                    {dates.map((d, i) => {
                      const isToday = d.toDateString() === TODAY.toDateString();
                      const isWeekend = d.getDay() === 0 || d.getDay() === 6;
                      return (
                        <span key={i} style={{
                          position: 'absolute',
                          left: i * dayWidth, top: 0, bottom: 0, width: dayWidth,
                          background: isToday ? 'rgb(var(--accent) / 0.06)' : isWeekend ? 'rgb(var(--paper-2) / 0.35)' : 'transparent',
                          borderRight: '1px solid rgb(var(--rule) / 0.4)',
                        }} />
                      );
                    })}
                    {/* Today line */}
                    {(() => {
                      const idx = Math.round((TODAY - start) / 86400000);
                      if (idx < 0 || idx >= totalDays) return null;
                      return <span style={{
                        position: 'absolute', top: 0, bottom: 0,
                        left: idx * dayWidth + dayWidth / 2,
                        width: 1, background: 'rgb(var(--accent))',
                      }} />;
                    })()}
                    {place && (
                      <div style={{
                        position: 'absolute',
                        left: place.startDay * dayWidth + 2,
                        top: 5, bottom: 5,
                        width: place.days * dayWidth - 4,
                        background: st.colour + '22',
                        borderLeft: `3px solid ${st.colour}`,
                        borderRadius: 6,
                        padding: '0 8px',
                        display: 'flex', alignItems: 'center', gap: 6,
                        fontSize: 11, fontWeight: 500,
                        color: st.colour,
                        overflow: 'hidden',
                      }}>
                        <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.title}</span>
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </React.Fragment>
        ))}
        {rows.length === 0 && (
          <div style={{ padding: 50, textAlign: 'center', color: 'rgb(var(--muted))' }}>
            No dated tasks in view.
          </div>
        )}
      </div>
    </div>
  );
}

window.TimelineView = TimelineView;
