import React, { useMemo, useState, useId, useRef, useEffect } from "react";
import { createRoot } from "react-dom/client";
/* CSS is loaded globally via css/main.css → components/pipeline-chart.css */

/**
 * PipelineChart
 * ─────────────────────────────────────────────────────────────────────────────
 * Pure React + SVG. No external chart libraries.
 * All copy, data, and toggles are props — nothing is hard-coded inside the SVG.
 *
 * Default export:
 *   export default function PipelineChart({ data, ...props })
 *
 * Expected `data` shape (cumulative years per stage):
 *   [
 *     { stage: "START",         label: "Pipeline start",         traditional: 0,  drugrepai: 0 },
 *     { stage: "DISCOVERY",     label: "Discovery (R&D)",        traditional: 6,  drugrepai: 1 },
 *     { stage: "TRIALS",        label: "Clinical trials",        traditional: 8,  drugrepai: 3 },
 *     { stage: "EFFECTIVENESS", label: "Confirmed effectiveness", traditional: 12, drugrepai: 7 },
 *     { stage: "APPROVAL",      label: "Repurpose approval",     traditional: 13, drugrepai: 8 },
 *   ]
 */

const DEFAULT_DATA = [
  { stage: "DISCOVERY",     label: "Discovery (R&D)",         traditional: 6,  drugrepai: 1 },
  { stage: "TRIALS",        label: "Clinical trials",         traditional: 8,  drugrepai: 3 },
  { stage: "EFFECTIVENESS", label: "Confirmed effectiveness", traditional: 12, drugrepai: 7 },
  { stage: "APPROVAL",      label: "Repurpose approval",      traditional: 13, drugrepai: 8 },
];

const DEFAULT_METRICS = [
  { name: "Traditional pipeline", value: 13, unit: "yrs", change: "Baseline", positive: false },
  { name: "With DrugRepAI",       value: 8,  unit: "yrs", change: "−38%",     positive: true  },
];

function PipelineChart({
  // Content
  title = "Pipeline Duration",
  heroValue = "5 years saved",
  heroBadge = "−38%",
  heroSubtitle = "Accelerated development cycle",
  heroDescription = "AI-driven drug repurposing reduces early-stage research bottlenecks, shortening the path from discovery to clinical validation and market readiness.",
  data = DEFAULT_DATA,
  metrics = DEFAULT_METRICS,
  axisLabels, // optional [string, string, ...] — falls back to data.stage values

  // Toggles
  showHeader = true,
  showDetailsButton = true,
  showBadge = true,
  showMetrics = true,
  showTooltip = true,
  showAxisLabels = true,

  // Behaviour
  onDetailsClick,

  // Misc
  className = "",
  style,
}) {
  // Y-domain has a small headroom above the largest value so the curve never
  // touches the top edge of the plot.
  const maxValue = useMemo(() => {
    const all = data.flatMap((d) => [d.traditional, d.drugrepai]);
    return Math.max(...all, 1);
  }, [data]);
  const yMax = Math.ceil(maxValue * 1.08);

  return (
    <div
      className={`pipeline-chart ${className}`.trim()}
      style={style}
      role="figure"
      aria-label={`${title}: ${heroValue}`}
    >
      {showHeader && (
        <div className="pipeline-chart__header">
          <div className="pipeline-chart__title">{title}</div>
          {showDetailsButton && (
            <button
              type="button"
              className="pipeline-chart__details-btn"
              onClick={onDetailsClick}
            >
              Details
            </button>
          )}
        </div>
      )}

      <div className="pipeline-chart__hero">
        <div className="pipeline-chart__hero-top">
          <span className="pipeline-chart__hero-value">{heroValue}</span>
          {showBadge && heroBadge && (
            <span className="pipeline-chart__hero-badge">{heroBadge}</span>
          )}
        </div>
        {heroSubtitle && (
          <div className="pipeline-chart__hero-subtitle">{heroSubtitle}</div>
        )}
        {heroDescription && (
          <p className="pipeline-chart__hero-description">{heroDescription}</p>
        )}
      </div>

      {showMetrics && metrics?.length > 0 && (
        <ul className="pipeline-chart__metrics">
          {metrics.map((m, i) => (
            <li key={i} className="pipeline-chart__metric">
              <span className="pipeline-chart__metric-name">{m.name}</span>
              <span className="pipeline-chart__metric-right">
                <span className="pipeline-chart__metric-value">
                  {m.value} {m.unit}
                </span>
                <span
                  className={
                    "pipeline-chart__metric-change" +
                    (m.positive ? " pipeline-chart__metric-change--positive" : "")
                  }
                >
                  {m.positive && (
                    <svg
                      viewBox="0 0 24 24"
                      width="12"
                      height="12"
                      aria-hidden="true"
                    >
                      <path
                        fill="currentColor"
                        d="M11 4v12.175l-4.9-4.9a1 1 0 0 0-1.414 1.414l6.6 6.6a1 1 0 0 0 1.414 0l6.6-6.6a1 1 0 0 0-1.414-1.414L13 16.175V4a1 1 0 1 0-2 0Z"
                      />
                    </svg>
                  )}
                  {m.change}
                </span>
              </span>
            </li>
          ))}
        </ul>
      )}

      <ChartSVG
        data={data}
        yMax={yMax}
        showTooltip={showTooltip}
      />

      {showAxisLabels && (
        <div className="pipeline-chart__axis">
          {(axisLabels || data.map((d) => d.stage)).map((label, i) => (
            <span key={i} className="pipeline-chart__axis-label">
              {label}
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

/* ────────────────────────────────────────────────────────────────────────── */
/*  Chart                                                                     */
/* ────────────────────────────────────────────────────────────────────────── */

function ChartSVG({ data, yMax, showTooltip }) {
  // Internal SVG coordinate space — the SVG itself scales responsively
  // through preserveAspectRatio="none" + CSS width/height.
  const W = 400;
  const H = 112;
  const PAD_X = 2;
  const PAD_TOP = 6;
  const PAD_BOTTOM = 2;

  const plotW = W - PAD_X * 2;
  const plotH = H - PAD_TOP - PAD_BOTTOM;

  const xFor = (i) =>
    data.length === 1 ? PAD_X : PAD_X + (i / (data.length - 1)) * plotW;
  const yFor = (v) => PAD_TOP + plotH - (v / yMax) * plotH;

  const tradPath = useMemo(() => buildAreaPath(data, "traditional", xFor, yFor, H - PAD_BOTTOM), [data, yMax]);
  const drugPath = useMemo(() => buildAreaPath(data, "drugrepai",   xFor, yFor, H - PAD_BOTTOM), [data, yMax]);

  // Stable id for clip-paths and gradients (works with SSR via useId)
  const uid = useId().replace(/:/g, "");

  // Hover state
  const [hoverIdx, setHoverIdx] = useState(null);

  // Reveal-on-scroll: clip-path animates left → right when 30% visible
  const plotRef = useRef(null);
  const [revealed, setRevealed] = useState(false);
  useEffect(() => {
    const el = plotRef.current;
    if (!el || revealed) return;
    if (!('IntersectionObserver' in window)) { setRevealed(true); return; }
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        setRevealed(true);
        io.unobserve(el);
      }
    }, { threshold: 0.3 });
    io.observe(el);
    return () => io.disconnect();
  }, [revealed]);

  return (
    <div
      ref={plotRef}
      className={`pipeline-chart__plot${revealed ? ' is-revealed' : ''}`}>
      <svg
        className="pipeline-chart__svg"
        viewBox={`0 0 ${W} ${H}`}
        preserveAspectRatio="none"
        role="img"
        aria-label="Cumulative years per stage, Traditional vs With DrugRepAI"
        onMouseLeave={() => setHoverIdx(null)}
      >
        {/* Grid — 4 vertical, 4 horizontal cells */}
        <g className="pipeline-chart__grid" aria-hidden="true">
          {[1, 2, 3].map((i) => {
            const x = PAD_X + (i / 4) * plotW;
            return <line key={`v${i}`} x1={x} x2={x} y1={0} y2={H} />;
          })}
          {[1, 2, 3].map((i) => {
            const y = PAD_TOP + (i / 4) * plotH;
            return <line key={`h${i}`} x1={0} x2={W} y1={y} y2={y} />;
          })}
        </g>

        {/* Traditional area — sits behind */}
        <path
          d={tradPath}
          className="pipeline-chart__area pipeline-chart__area--traditional"
        />

        {/* DrugRepAI area — overlays on top */}
        <path
          d={drugPath}
          className="pipeline-chart__area pipeline-chart__area--drugrepai"
        />

        {/* Vertical hover guide */}
        {hoverIdx !== null && (
          <line
            x1={xFor(hoverIdx)}
            x2={xFor(hoverIdx)}
            y1={0}
            y2={H}
            className="pipeline-chart__cursor"
          />
        )}

        {/* Hover hit-zones — invisible vertical bands, one per data point */}
        {data.map((_, i) => {
          const bandStart = i === 0 ? 0 : (xFor(i - 1) + xFor(i)) / 2;
          const bandEnd =
            i === data.length - 1 ? W : (xFor(i) + xFor(i + 1)) / 2;
          return (
            <rect
              key={`hit-${i}`}
              x={bandStart}
              y={0}
              width={bandEnd - bandStart}
              height={H}
              fill="transparent"
              onMouseEnter={() => setHoverIdx(i)}
              onMouseMove={() => setHoverIdx(i)}
              style={{ cursor: "pointer" }}
            />
          );
        })}

      </svg>

      {/* Hover dots — HTML overlay so they stay circular regardless of
          preserveAspectRatio="none" stretching the SVG. */}
      {hoverIdx !== null && (
        <>
          <span
            className="pipeline-chart__dot pipeline-chart__dot--traditional"
            style={{
              left: `${((xFor(hoverIdx) - PAD_X) / plotW) * 100}%`,
              top: `${(yFor(data[hoverIdx].traditional) / H) * 100}%`,
            }}
          />
          <span
            className="pipeline-chart__dot pipeline-chart__dot--drugrepai"
            style={{
              left: `${((xFor(hoverIdx) - PAD_X) / plotW) * 100}%`,
              top: `${(yFor(data[hoverIdx].drugrepai) / H) * 100}%`,
            }}
          />
        </>
      )}

      {/* HTML tooltip — positioned via % of plot width, lives outside the SVG
          so font sizing and shadows don't have to fight the viewBox. */}
      {showTooltip && hoverIdx !== null && (
        <Tooltip
          datum={data[hoverIdx]}
          xPercent={((xFor(hoverIdx) - PAD_X) / plotW) * 100}
        />
      )}

      {/* Suppress unused var warning for uid in environments that lint strictly */}
      <span hidden>{uid}</span>
    </div>
  );
}

function Tooltip({ datum, xPercent }) {
  // Flip the tooltip horizontally when it gets close to either edge
  const align =
    xPercent < 18 ? "left" : xPercent > 82 ? "right" : "center";

  return (
    <div
      className={`pipeline-chart__tooltip pipeline-chart__tooltip--${align}`}
      style={{ left: `${xPercent}%` }}
      role="tooltip"
    >
      <div className="pipeline-chart__tooltip-label">
        {datum.label || datum.stage}
      </div>
      <div className="pipeline-chart__tooltip-row">
        <span className="pipeline-chart__tooltip-key">
          <span className="pipeline-chart__tooltip-swatch pipeline-chart__tooltip-swatch--traditional" />
          Traditional
        </span>
        <span className="pipeline-chart__tooltip-value">
          {datum.traditional} yrs
        </span>
      </div>
      <div className="pipeline-chart__tooltip-row">
        <span className="pipeline-chart__tooltip-key">
          <span className="pipeline-chart__tooltip-swatch pipeline-chart__tooltip-swatch--drugrepai" />
          With DrugRepAI
        </span>
        <span className="pipeline-chart__tooltip-value pipeline-chart__tooltip-value--accent">
          {datum.drugrepai} yrs
        </span>
      </div>
    </div>
  );
}

/* ────────────────────────────────────────────────────────────────────────── */
/*  Helpers                                                                   */
/* ────────────────────────────────────────────────────────────────────────── */

function buildAreaPath(data, key, xFor, yFor, baselineY) {
  if (!data.length) return "";
  const top = data
    .map((d, i) => `${i === 0 ? "M" : "L"} ${xFor(i).toFixed(2)} ${yFor(d[key]).toFixed(2)}`)
    .join(" ");
  const close = ` L ${xFor(data.length - 1).toFixed(2)} ${baselineY} L ${xFor(0).toFixed(2)} ${baselineY} Z`;
  return top + close;
}


/* ─────────────────────────────────────────────────────────────────────────
   MOUNT — render into #pipeline-chart in the impact section
───────────────────────────────────────────────────────────────────────── */
const container = document.getElementById("pipeline-chart");
if (container) {
  createRoot(container).render(
    <PipelineChart
      showHeader={false}
      showDetailsButton={false}
      showMetrics={false}
      showBadge={false}
      axisLabels={[
        "Discovery (R&D)",
        "Clinical trials",
        "Confirmed effectiveness",
        "Repurpose approval",
      ]}
    />,
  );
} else {
  console.warn("[pipeline-mount] #pipeline-chart not found");
}
