import React, { useMemo } from "react";

function sectionStatus(index, activeIndex, cachedIds, sectionId) {
  if (index < activeIndex) return "complete";
  if (index === activeIndex) return "active";
  if (cachedIds.has(String(sectionId))) return "cached";
  return "pending";
}

function statusLabel(status) {
  if (status === "complete") return "ACK";
  if (status === "active") return "LIVE";
  if (status === "cached") return "BUF";
  return "WAIT";
}

export default function PtwSectionProgress({
  sections = [],
  activeIndex = 0,
  cachedSectionIds = [],
  percent = 0,
  jobTypeName = "",
  permitNumber = "",
}) {
  const cachedSet = useMemo(
    () => new Set(cachedSectionIds.map((id) => String(id))),
    [cachedSectionIds]
  );

  const cachedCount = useMemo(
    () =>
      sections.filter((section) => cachedSet.has(String(section.id))).length,
    [sections, cachedSet]
  );

  const remaining = Math.max(sections.length - (activeIndex + 1), 0);
  const activeSection = sections[activeIndex];

  if (!sections.length || !activeSection) return null;

  const segmentMarkers = sections.map((_, index) =>
    sections.length > 1 ? (index / (sections.length - 1)) * 100 : 0
  );

  return (
    <section className="ptw-tech-progress" aria-label="Section workflow telemetry">
      <div className="ptw-tech-progress__grid" aria-hidden />

      <header className="ptw-tech-progress__header">
        <div className="ptw-tech-progress__header-left">
          <span className="ptw-tech-progress__pulse" aria-hidden />
          <div>
            <p className="ptw-tech-progress__kicker">Workflow telemetry</p>
            <p className="ptw-tech-progress__route">
              <span>{jobTypeName || "PTW"}</span>
              <span className="ptw-tech-progress__sep">/</span>
              <span className="ptw-tech-progress__mono">
                {permitNumber ? `PTW-${permitNumber}` : "DRAFT-SESSION"}
              </span>
            </p>
          </div>
        </div>
        <div className="ptw-tech-progress__header-right">
          <span className="ptw-tech-progress__badge ptw-tech-progress__badge--live">
            LIVE
          </span>
          <span className="ptw-tech-progress__clock ptw-tech-progress__mono">
            SEC-{String(activeIndex + 1).padStart(2, "0")}
          </span>
        </div>
      </header>

      <ol className="ptw-tech-progress__steps" aria-label="Section sequence">
        {sections.map((section, index) => {
          const status = sectionStatus(index, activeIndex, cachedSet, section.id);
          const isActive = status === "active";

          return (
            <li
              key={section.id}
              className={`ptw-tech-progress__step ptw-tech-progress__step--${status}${isActive ? " is-active" : ""}`}
              aria-current={isActive ? "step" : undefined}
            >
              <span className="ptw-tech-progress__step-index ptw-tech-progress__mono">
                {String(index + 1).padStart(2, "0")}
              </span>
              <span className="ptw-tech-progress__step-body">
                <span className="ptw-tech-progress__step-title">
                  {section.title || `Section ${index + 1}`}
                </span>
                <span className="ptw-tech-progress__step-state ptw-tech-progress__mono">
                  {statusLabel(status)}
                </span>
              </span>
              <span className="ptw-tech-progress__step-node" aria-hidden>
                {status === "complete" ? (
                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                    <path
                      d="M2.5 6.2 4.8 8.5 9.5 3.5"
                      stroke="currentColor"
                      strokeWidth="1.6"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>
                ) : null}
              </span>
            </li>
          );
        })}
      </ol>

      <div className="ptw-tech-progress__rail-wrap">
        <div className="ptw-tech-progress__rail-meta">
          <span className="ptw-tech-progress__mono">
            COMPLETION {String(percent).padStart(3, " ")}%
          </span>
          <span className="ptw-tech-progress__mono">
            BUF {cachedCount}/{sections.length}
          </span>
        </div>

        <div
          className="ptw-tech-progress__rail"
          role="progressbar"
          aria-valuenow={percent}
          aria-valuemin={0}
          aria-valuemax={100}
          aria-label={`Section ${activeIndex + 1} of ${sections.length}`}
        >
          <div className="ptw-tech-progress__rail-track" aria-hidden>
            {segmentMarkers.map((left, index) => (
              <span
                key={`marker-${index}`}
                className="ptw-tech-progress__rail-tick"
                style={{ left: `${left}%` }}
              />
            ))}
          </div>
          <div
            className="ptw-tech-progress__rail-fill"
            style={{ width: `${percent}%` }}
          >
            <span className="ptw-tech-progress__rail-scan" aria-hidden />
          </div>
          <span
            className="ptw-tech-progress__rail-head"
            style={{ left: `calc(${percent}% - 6px)` }}
            aria-hidden
          />
        </div>

        <footer className="ptw-tech-progress__footer">
          <p className="ptw-tech-progress__active-label">
            <span className="ptw-tech-progress__mono">ACTIVE NODE</span>
            <strong>{activeSection.title || `Section ${activeIndex + 1}`}</strong>
          </p>
          <p className="ptw-tech-progress__metrics ptw-tech-progress__mono">
            <span>
              IDX {activeIndex + 1}/{sections.length}
            </span>
            <span className="ptw-tech-progress__sep">·</span>
            <span>REM {remaining}</span>
            <span className="ptw-tech-progress__sep">·</span>
            <span>ID {activeSection.id}</span>
          </p>
        </footer>
      </div>
    </section>
  );
}
