// Timeline — the draft-plan gantt (Slice 3). Composite, pure render: it turns the
// output of lib/plan-to-gantt.js (planToGantt) into a CSS-grid gantt — a week-number
// header, one bar row per scheduled feature (bar spans startWeek..endWeek, colored
// by phase), and a compact list of unscheduled features underneath. It NEVER
// fetches and has no interactions beyond `title=` tooltips; the page maps the draft
// plan.json through planToGantt and feeds the result in as `gantt`.
//
// Props:
//   gantt — planToGantt(plan) output:
//     { weeks: [{ week, holiday }], rows: [{ feature, title, phase, startWeek, endWeek }],
//       unscheduled: [{ feature, title, phase }] }

// Bar colors are decided per phase in lib/plan-to-gantt.js and ride along on each
// row, so this view and the canvas TimelineSection color the same phase the same way.
const barColor = (row) => row.color || window.TimelineFormat.phaseColorAt(0);

// Consecutive rows sharing a phase form one labelled group. Grouping by RUNS rather
// than by collecting all rows of a phase keeps the bars in plan order — the timeline
// reads top-to-bottom in the order the plan schedules the work.
function groupRowsByPhase(rows) {
  const groups = [];
  for (const row of rows) {
    const last = groups[groups.length - 1];
    if (last && last.phase === row.phase) last.rows.push(row);
    else groups.push({ phase: row.phase, label: row.phaseLabel, color: row.color, rows: [row] });
  }
  return groups;
}

const Timeline = ({ gantt }) => {
  const { weeks = [], rows = [], unscheduled = [] } = gantt || {};
  const n = weeks.length;
  const minWeek = n ? weeks[0].week : 0;
  // A fixed label column + one equal track per week. gridColumn on each bar (below)
  // is 1-based over these tracks, offset by 1 for the leading label column.
  // Week tracks are wide enough for the "10–16 Aug" date label under the number.
  const gridTemplateColumns = `minmax(7rem, 12rem) repeat(${n}, minmax(5.5rem, 1fr))`;

  return (
    <div className="text-sm">
      {n > 0 ? (
        <div className="overflow-x-auto">
          <div className="grid items-center gap-y-1" style={{ gridTemplateColumns }}>
            {/* Header: phase-column label + one week cell per week. */}
            <div className="px-2 py-1 text-[10px] font-bold uppercase tracking-widest text-neutral-400">
              Phase
            </div>
            {weeks.map((w) => (
              <div
                key={w.week}
                title={w.holiday ? `Week ${w.week} · ${w.dateLabel} — holiday` : `Week ${w.week} · ${w.dateLabel}`}
                className={
                  'text-center py-1 rounded leading-tight ' +
                  (w.holiday ? 'bg-neutral-200 text-neutral-400' : 'text-neutral-500')
                }
              >
                <div className="text-[11px] font-semibold">Week {w.week}</div>
                <div className="text-[10px] text-neutral-400 whitespace-nowrap">{w.dateLabel}</div>
                {w.holiday && (
                  <div className="text-[9px] uppercase font-bold tracking-widest text-amber-600">Holiday</div>
                )}
              </div>
            ))}

            {/* Rows grouped by phase: the phase label is written ONCE per group and
                spans its rows; the bars carry the feature names. Every cell carries
                an explicit gridRow — without it, sparse auto-placement fills a bar's
                leftover week columns with the next row's content instead of starting
                a new line. Line 1 is the week header; `line` walks down from 2 and
                also budgets one line per between-group separator. */}
            {(() => {
              const cells = [];
              let line = 2;
              groupRowsByPhase(rows).forEach((group, gi) => {
                if (gi > 0) {
                  cells.push(
                    <div
                      key={`sep-${gi}`}
                      className="border-t border-neutral-200"
                      style={{ gridColumn: '1 / -1', gridRow: line }}
                    />
                  );
                  line += 1;
                }
                const first = line;
                cells.push(
                  <div
                    key={`phase-${gi}`}
                    className="px-2 py-1 self-center flex items-center gap-2 text-xs font-semibold text-neutral-600"
                    title={group.phase || 'No phase'}
                    style={{ gridColumn: 1, gridRow: `${first} / ${first + group.rows.length}` }}
                  >
                    <span className={'inline-block h-2 w-2 shrink-0 rounded-full ' + barColor(group)} />
                    <span className="truncate">{group.label}</span>
                  </div>
                );
                group.rows.forEach((r) => {
                  cells.push(
                    <div
                      key={r.feature}
                      className="min-w-0"
                      style={{ gridColumn: `${2 + (r.startWeek - minWeek)} / ${3 + (r.endWeek - minWeek)}`, gridRow: line }}
                    >
                      <div
                        title={`${r.title} — ${r.phase} (weeks ${r.startWeek}–${r.endWeek})`}
                        className={'truncate rounded-lg px-3 py-1 text-xs font-semibold text-white shadow-sm ' + barColor(r)}
                      >
                        {r.title}
                      </div>
                    </div>
                  );
                  line += 1;
                });
              });
              return cells;
            })()}
          </div>
        </div>
      ) : (
        <div className="px-2 py-3 text-xs text-neutral-400">No scheduled work yet.</div>
      )}

      {unscheduled.length > 0 && (
        <div className="mt-3 border-t border-neutral-200 pt-2">
          <div className="mb-1 px-2 text-[10px] font-bold uppercase tracking-widest text-neutral-400">
            Unscheduled
          </div>
          <ul className="flex flex-wrap gap-1.5 px-2">
            {unscheduled.map((u) => (
              <li
                key={u.feature}
                title={`${u.title} — ${u.phase}`}
                className="flex items-center gap-1.5 rounded-full border border-neutral-200 bg-neutral-50 px-2 py-0.5 text-xs text-neutral-600"
              >
                <span className={'inline-block h-2 w-2 rounded-full ' + barColor(u)} />
                {u.title}
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
};

if (typeof window !== 'undefined') {
  window.Timeline = Timeline;
}
