/* Where you are in a sequence: a vertical rail with a point for every step —
 * behind (filled), here (ringed, with its content expanded in place), ahead
 * (hollow) — and every point jumps.
 *
 * Points, not numbers. A numbered rail reads as a ranking, or a form to be
 * filled in order, and the count is already in the header ("Step 2 of 5");
 * a point is a place on a line, which is what a step in a tour is. `numbered`
 * remains for a sequence whose ordinals carry meaning (a ranked list, a
 * numbered procedure).
 *
 * A walkthrough is one use: the current beat's words, approval and
 * conversation hang off the rail as children. Any tool with a sequence —
 * onboarding, a signoff, a punchlist flow — reads the same way. */

import type { CSSProperties, ReactNode } from "react";

export type TimelineItem = {
  id: string | number;
  title: string;
  state: "done" | "current" | "todo";
  /** Trailing badge(s): "Approval needed", "2 comments". */
  badges?: { label: string; tone?: string }[];
};

export function Timeline({
  items, onSelect, children, ariaLabel, numbered,
}: {
  items: TimelineItem[];
  onSelect?: (id: TimelineItem["id"]) => void;
  /** Content for the current item, rendered under its row. */
  children?: ReactNode;
  ariaLabel?: string;
  /** Ordinals in the nodes instead of points. */
  numbered?: boolean;
}) {
  return (
    <ol className={`cu-timeline ${numbered ? "is-numbered" : ""}`} aria-label={ariaLabel}>
      {items.map((it, i) => (
        <li key={it.id} className={`cu-tl-item is-${it.state}`}
            aria-current={it.state === "current" ? "step" : undefined}>
          <button type="button" className="cu-tl-row"
                  onClick={() => onSelect?.(it.id)} disabled={!onSelect}>
            <span className="cu-tl-node" aria-hidden="true">
              {numbered ? (it.state === "done" ? "✓" : i + 1) : ""}
            </span>
            <span className="cu-tl-title">{it.title}</span>
            {it.badges && it.badges.length > 0 && (
              <span className="cu-tl-badges">
                {it.badges.map((b, j) => (
                  <span key={j} className="cu-tl-badge"
                        style={b.tone
                          ? ({ ["--chip-tone" as string]: b.tone } as CSSProperties)
                          : undefined}>
                    {b.label}
                  </span>
                ))}
              </span>
            )}
          </button>
          {it.state === "current" && children && (
            <div className="cu-tl-body">{children}</div>
          )}
        </li>
      ))}
    </ol>
  );
}
