import type { ChartSingleData } from "@gnommo/slide-contracts";
import type { SlideRuntimeProps } from "../types/lecture";

interface ChartPoint {
  label: string;
  value: number;
  color?: string;
}

function normalizePoints(value: unknown): ChartPoint[] {
  if (!Array.isArray(value) || value.length === 0) {
    return [
      { label: "Security", value: 72, color: "#111" },
      { label: "Trust", value: 58, color: "rgba(17, 17, 17, 0.72)" },
      { label: "Growth", value: 44, color: "rgba(17, 17, 17, 0.52)" }
    ];
  }

  const normalizedPoints: ChartPoint[] = [];

  value.forEach((item, index) => {
      if (!item || typeof item !== "object") {
        return;
      }

      const candidate = item as Record<string, unknown>;
      const rawValue = Number(candidate.value);

      normalizedPoints.push({
        label: String(candidate.label ?? `Series ${index + 1}`),
        value: Number.isFinite(rawValue) ? Math.max(0, rawValue) : 0,
        color:
          typeof candidate.color === "string" ? candidate.color : undefined
      });
    });

  return normalizedPoints.length > 0
    ? normalizedPoints
    : [
        { label: "Security", value: 72, color: "#111" },
        { label: "Trust", value: 58, color: "rgba(17, 17, 17, 0.72)" },
        { label: "Growth", value: 44, color: "rgba(17, 17, 17, 0.52)" }
      ];
}

export default function ChartSingle({ props, paused }: SlideRuntimeProps) {
  const data = props as ChartSingleData;
  const header = String(data.header ?? data.eyebrow ?? "Chart single");
  const title = String(data.title ?? "One chart, one comparison");
  const body = String(data.body ?? "Use one chart for one contrast.");
  const points = normalizePoints(data.points);
  const maxValue = Math.max(...points.map((point) => point.value), 1);

  return (
    <article className={`chart-single ${paused ? "chart-single--paused" : ""}`}>
      <div className="chart-single__content">
        <div className="chart-single__copy">
          <p className="chart-single__eyebrow">{header}</p>
          <h2 className="chart-single__title">{title}</h2>
          <p className="chart-single__body">{body}</p>
        </div>
        <div className="chart-single__plot" role="img" aria-label={title}>
          {points.map((point) => (
            <div key={point.label} className="chart-single__row">
              <span className="chart-single__label">{point.label}</span>
              <div className="chart-single__bar-track">
                <div
                  className="chart-single__bar-fill"
                  style={{
                    width: `${(point.value / maxValue) * 100}%`,
                    background: point.color ?? "#111"
                  }}
                />
              </div>
              <span className="chart-single__value">{point.value}</span>
            </div>
          ))}
        </div>
      </div>
    </article>
  );
}
