let timelineData = [];

// Function 1: Render from timelineData
function renderTimelineFromJson() {
  const el = document.getElementById("timeline-body");
  if (!el) return;

  el.innerHTML = "";
  el.className = "timeline vertical";

  timelineData.forEach((item) => {
    const div = document.createElement("div");
    div.className = "milestone " + (item.status || "");

    const dot = document.createElement("div");
    dot.className = "dot";

    const label = document.createElement("label");
    label.textContent = item.label;

    div.appendChild(dot);
    div.appendChild(label);
    el.appendChild(div);
  });
}

// Function 2: Render from textarea JSON
function renderTimelineFromTextarea() {
  const ta = document.getElementById("timeline-editor");
  if (!ta) return;
  try {
    const data = JSON.parse(ta.value);
    timelineData = data;
    renderTimelineFromJson();
  } catch (e) {
    alert("Invalid JSON!");
  }
}

// Function 3: Set a single milestone
function setTimeline(key, label, status) {
  timelineData = [{ key, label, status }];
  document.getElementById("timeline-editor").value = JSON.stringify(
    timelineData,
    null,
    2,
  );
  renderTimelineFromJson();
}

// Function 4: Append milestone
function addTimeline(key, label, status) {
  timelineData.push({ key, label, status });
  document.getElementById("timeline-editor").value = JSON.stringify(
    timelineData,
    null,
    2,
  );
  renderTimelineFromJson();
}

// Create the panel
createPanel("timelinePanel", "CC", "ctc", 600, 450, {
  title: "Simple Timeline Panel",
  overflow: true,
  radius: "10px",
  footerCloseBtn: true,
  bodyContent: `
    <div class="timeline-panel">
      <div class="controls">
        <button onclick="renderTimelineFromJson()">Render from JSON</button>
        <button onclick="renderTimelineFromTextarea()">Render from Textarea</button>
        <button onclick="setTimeline('step1','Start','done')">Set 1 Timeline</button>
        <button onclick="addTimeline('stepX','Another Step','ongoing')">Add Timeline</button>
      </div>
      <textarea id="timeline-editor">[]</textarea>
      <div id="timeline-body" class="timeline vertical"></div>
    </div>
  `,
});
