/* ============================================================
   Carebridge Portal — shared UI primitives (React + Babel)
   Exports to window. Icons render via Lucide (<i data-lucide>).
   ============================================================ */
const { useState, useEffect, useRef, useMemo } = React;

/* Refresh Lucide icons after every commit. */
function useIcons() {
  useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  });
}

function Icon({ name, size, style, className }) {
  return <i data-lucide={name} className={className} style={{ width: size || 18, height: size || 18, ...(style || {}) }} aria-hidden="true" />;
}

function Avatar({ initials, color, size }) {
  const cls = size === "sm" ? "cb-av cb-av--sm" : size === "lg" ? "cb-av cb-av--lg" : "cb-av";
  return <div className={cls} style={{ background: color || "var(--navy-600)" }}>{initials}</div>;
}

function Card({ children, className, pad0, style }) {
  return <div className={"cb-card" + (pad0 ? " cb-card--pad0" : "") + (className ? " " + className : "")} style={style}>{children}</div>;
}

function CardHead({ title, sub, action, onAction, icon }) {
  return (
    <div className="cb-card__head">
      <div>
        <h3>{title}</h3>
        {sub ? <div className="cb-sub">{sub}</div> : null}
      </div>
      {action ? (
        <button className="cb-link" onClick={onAction}>{action}{icon !== false ? <Icon name="arrow-right" size={15} /> : null}</button>
      ) : null}
    </div>
  );
}

function StatCard({ icon, chip, value, label, delta, deltaDir }) {
  const dCls = deltaDir === "down" ? "cb-delta cb-delta--down" : deltaDir === "flat" ? "cb-delta cb-delta--flat" : "cb-delta cb-delta--up";
  const dIcon = deltaDir === "down" ? "trending-down" : deltaDir === "flat" ? "minus" : "trending-up";
  return (
    <Card>
      <div className="cb-stat">
        <div className="cb-stat__top">
          <div className={"cb-chip" + (chip ? " cb-chip--" + chip : "")}><Icon name={icon} size={22} /></div>
          {delta ? <span className={dCls}><Icon name={dIcon} size={13} />{delta}</span> : null}
        </div>
        <div>
          <div className="cb-stat__val">{value}</div>
          <div className="cb-stat__label">{label}</div>
        </div>
      </div>
    </Card>
  );
}

function Pill({ children, tone, dot, icon }) {
  return (
    <span className={"cb-pill cb-pill--" + (tone || "muted") + (dot ? " cb-pill--dot" : "")}>
      {icon ? <Icon name={icon} size={13} /> : null}{children}
    </span>
  );
}

/* Map a status / state string to an on-brand tone */
function statusTone(s) {
  const t = (s || "").toLowerCase();
  if (/(paid|approved|completed|active|recommendation ready|follow-up|done)/.test(t)) return "teal";
  if (/(treatment|in country|recovery|in coordination|under review|ai organized)/.test(t)) return "navy";
  if (/(process|pending|held|partial|awaiting|needs review|reports under review|pre-departure)/.test(t)) return "warn";
  if (/(not started|new inquiry|planning|—)/.test(t)) return "muted";
  if (/(overdue|cancelled|urgent)/.test(t)) return "danger";
  return "sky";
}

function ProgressBar({ value, navy }) {
  return (
    <div className={"cb-prog" + (navy ? " cb-prog--navy" : "")}>
      <div className="cb-prog__fill" style={{ width: Math.max(3, value) + "%" }} />
    </div>
  );
}

/* Treatment journey stage track */
function StageTrack({ current, stages, compact }) {
  const list = stages || window.CB_DATA.STAGES;
  const icons = ["clipboard-list", "microscope", "stethoscope", "heart-pulse", "calendar-check"];
  return (
    <div className="cb-stages">
      {list.map((s, i) => {
        const state = i < current ? "is-done" : i === current ? "is-current" : "";
        return (
          <div key={s} className={"cb-stage " + state}>
            <div className="cb-stage__line" />
            <div className="cb-stage__dot">
              {i < current ? <Icon name="check" size={15} /> : <Icon name={icons[i] || "circle"} size={15} />}
            </div>
            {!compact ? <div className="cb-stage__name">{s}</div> : null}
          </div>
        );
      })}
    </div>
  );
}

/* Stacked bars chart — data: [{label, a, b}] with maxBy */
function BarsChart({ data, keys, colors, max }) {
  const m = max || Math.max(...data.map((d) => keys.reduce((s, k) => s + d[k], 0)));
  return (
    <div className="cb-bars">
      {data.map((d, i) => {
        const total = keys.reduce((s, k) => s + d[k], 0);
        return (
          <div className="cb-bar" key={i} title={d.label + ": " + total}>
            <div className="cb-bar__stack">
              {keys.map((k, ki) => (
                <div key={k} className="cb-bar__seg" style={{ height: ((d[k] / m) * 100) + "%", background: colors[ki], minHeight: d[k] > 0 ? 4 : 0 }} />
              ))}
            </div>
            <div className="cb-bar__lbl">{d.label}</div>
          </div>
        );
      })}
    </div>
  );
}

/* SVG donut. segments: [{label,value,color}] */
function Donut({ segments, size, thickness, centerTop, centerBottom }) {
  const sz = size || 168, th = thickness || 26, r = (sz - th) / 2, c = 2 * Math.PI * r;
  const total = segments.reduce((s, x) => s + x.value, 0) || 1;
  let offset = 0;
  return (
    <div className="cb-donut-wrap">
      <div style={{ position: "relative", width: sz, height: sz, flex: "none" }}>
        <svg width={sz} height={sz} viewBox={`0 0 ${sz} ${sz}`} style={{ transform: "rotate(-90deg)" }}>
          <circle cx={sz / 2} cy={sz / 2} r={r} fill="none" stroke="var(--sky-200)" strokeWidth={th} />
          {segments.map((s, i) => {
            const len = (s.value / total) * c;
            const el = (
              <circle key={i} cx={sz / 2} cy={sz / 2} r={r} fill="none" stroke={s.color} strokeWidth={th}
                strokeDasharray={`${len} ${c - len}`} strokeDashoffset={-offset} strokeLinecap="butt" />
            );
            offset += len;
            return el;
          })}
        </svg>
        <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", textAlign: "center" }}>
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 26, color: "var(--text-strong)", lineHeight: 1 }}>{centerTop}</div>
            <div style={{ fontSize: 12, color: "var(--text-muted)", fontWeight: 600, marginTop: 4 }}>{centerBottom}</div>
          </div>
        </div>
      </div>
      <div className="cb-legend">
        {segments.map((s, i) => (
          <div className="cb-legend__row" key={i}>
            <span className="cb-legend__sw" style={{ background: s.color }} />
            <span>{s.label}</span>
            <b>{s.value}{s.suffix || ""}</b>
          </div>
        ))}
      </div>
    </div>
  );
}

/* Area/line spark for revenue */
function AreaChart({ data, height }) {
  const h = height || 200, w = 640, pad = 8;
  const vals = data.map((d) => d.revenue);
  const max = Math.max(...vals) * 1.12, min = Math.min(...vals) * 0.82;
  const x = (i) => pad + (i / (data.length - 1)) * (w - pad * 2);
  const y = (v) => h - pad - ((v - min) / (max - min)) * (h - pad * 2 - 22);
  const line = data.map((d, i) => `${i === 0 ? "M" : "L"} ${x(i)} ${y(d.revenue)}`).join(" ");
  const area = `${line} L ${x(data.length - 1)} ${h} L ${x(0)} ${h} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} preserveAspectRatio="none" style={{ display: "block" }}>
      <defs>
        <linearGradient id="cbArea" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="rgba(28,168,156,0.28)" />
          <stop offset="100%" stopColor="rgba(28,168,156,0)" />
        </linearGradient>
      </defs>
      <path d={area} fill="url(#cbArea)" />
      <path d={line} fill="none" stroke="var(--teal-500)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
      {data.map((d, i) => (
        <g key={i}>
          <circle cx={x(i)} cy={y(d.revenue)} r="3.5" fill="#fff" stroke="var(--teal-500)" strokeWidth="2" />
          <text x={x(i)} y={h - 4} textAnchor="middle" fontSize="11" fontWeight="600" fill="var(--text-muted)" fontFamily="var(--font-body)">{d.m}</text>
        </g>
      ))}
    </svg>
  );
}

function SectionTitle({ eyebrow, title, children }) {
  return (
    <div className="cb-between" style={{ marginBottom: "var(--space-5)", flexWrap: "wrap", gap: 16 }}>
      <div>
        {eyebrow ? <div className="cb-eyebrow" style={{ marginBottom: 8 }}>{eyebrow}</div> : null}
        <h2 style={{ fontSize: 24, fontWeight: 800 }}>{title}</h2>
      </div>
      {children}
    </div>
  );
}

Object.assign(window, {
  useIcons, Icon, Avatar, Card, CardHead, StatCard, Pill, statusTone,
  ProgressBar, StageTrack, BarsChart, Donut, AreaChart, SectionTitle,
});
