// CareerTimeline — horizontal timeline of roles, replaces the HAL eye.
// Data sources: window.RESUME.history (older roles) + window.RESUME.experience (current).
// Props:
//   mode          - "compact" | "expanded"  density of cards (default "compact")
//   activeCompany - string | null            currently emphasized node (pulse target)
//   accentHue     - number                   forwarded for color sync, but most colors
//                                            come from CSS vars via :root[data-theme]
//
// Behavior:
//   - One node per role, oldest left → newest right on the spine.
//   - Default selection = newest role (HealthStream).
//   - Hover/focus selects a node; selected node's full card replaces the
//     summary on the right.
//   - activeCompany prop briefly pulses the matching node (chat-driven).

function CareerTimeline({ mode, activeCompany }) {
  const { useState, useMemo, useEffect } = React;

  const roles = useMemo(() => {
    const r = window.RESUME || {};
    return [
      ...(r.history || []),
      ...(r.experience || []).map((e) => ({
        role: e.role,
        company: e.company,
        period: e.period,
        summary: e.bullets && e.bullets[0] ? e.bullets[0] : "",
        tags: deriveTags(e),
        bullets: e.bullets || [],
      })),
    ];
  }, []);

  const [selectedIdx, setSelectedIdx] = useState(Math.max(0, roles.length - 1));

  // When a chat reply mentions a company, jump selection to that role too,
  // so the spotlight pulse + the card you read line up.
  useEffect(() => {
    if (!activeCompany) return;
    const idx = roles.findIndex(
      (r) => r.company && activeCompany.toLowerCase().includes(r.company.toLowerCase())
    );
    if (idx >= 0) setSelectedIdx(idx);
  }, [activeCompany, roles]);

  if (!roles.length) return null;

  const selected = roles[selectedIdx] || roles[roles.length - 1];

  return (
    <div className={"timeline " + (mode === "expanded" ? "is-expanded" : "is-compact")}>
      <div className="timeline-rail" role="list">
        <div className="timeline-spine" aria-hidden="true" />
        {roles.map((r, i) => {
          const isActive = i === selectedIdx;
          const isPulsing = activeCompany &&
            r.company &&
            activeCompany.toLowerCase().includes(r.company.toLowerCase());
          return (
            <button
              key={i}
              role="listitem"
              className={
                "timeline-node" +
                (isActive ? " is-active" : "") +
                (isPulsing ? " is-pulsing" : "")
              }
              style={{ left: `${(i / Math.max(1, roles.length - 1)) * 100}%` }}
              onClick={() => setSelectedIdx(i)}
              onMouseEnter={() => setSelectedIdx(i)}
              onFocus={() => setSelectedIdx(i)}
              aria-label={`${r.company} — ${r.period}`}
              title={`${r.company} — ${r.period}`}
            >
              <span className="timeline-dot" />
              <span className="timeline-label">
                <span className="timeline-label-company">{r.company}</span>
                <span className="timeline-label-period">{r.period}</span>
              </span>
            </button>
          );
        })}
      </div>

      <div className="timeline-card" key={selectedIdx}>
        <div className="timeline-card-head">
          <span className="timeline-card-period">{selected.period}</span>
          <span className="timeline-card-divider">·</span>
          <span className="timeline-card-company">{selected.company}</span>
        </div>
        <h3 className="timeline-card-role">{selected.role}</h3>
        {selected.summary && (
          <p className="timeline-card-summary">{selected.summary}</p>
        )}
        {mode === "expanded" && selected.bullets && selected.bullets.length > 1 && (
          <ul className="timeline-card-bullets">
            {selected.bullets.slice(1, 5).map((b, i) => (
              <li key={i}>{b}</li>
            ))}
          </ul>
        )}
        {selected.tags && selected.tags.length > 0 && (
          <div className="timeline-card-tags">
            {selected.tags.map((t) => (
              <span key={t} className="timeline-tag">{t}</span>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// Derive a small set of tech tags from an experience bullet list.
// Best effort: looks for common tech names in the text. Falls back to empty.
function deriveTags(exp) {
  const text = [exp.role || "", ...(exp.bullets || [])].join(" ");
  const candidates = [
    "Go", "Python", "TypeScript", "React",
    "Azure OpenAI", "OpenAI", "RAG", "Semantic Search",
    "Embedding", "WebSocket", "Cloudflare", "Postgres",
  ];
  const hits = [];
  for (const c of candidates) {
    const re = new RegExp("(?<![A-Za-z])" + c.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "(?![A-Za-z])", "i");
    if (re.test(text)) hits.push(c);
    if (hits.length >= 4) break;
  }
  return hits;
}
