/* ============================================================
   FacilityOS — Charts (hand-built SVG/CSS)
   ============================================================ */

/* ---------- Donut ---------- */
function Donut({ data, size = 168, thickness = 22, centerLabel, centerValue }) {
  const total = data.reduce((s, d) => s + d.value, 0);
  const r = (size - thickness) / 2;
  const c = 2 * Math.PI * r;
  let offset = 0;
  return (
    <div style={{ position: "relative", width: size, height: size }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: "rotate(-90deg)" }}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--surface-3)" strokeWidth={thickness} />
        {data.map((d, i) => {
          const frac = d.value / total;
          const len = frac * c;
          const seg = (
            <circle key={i} cx={size/2} cy={size/2} r={r} fill="none"
              stroke={`var(${d.token})`} strokeWidth={thickness}
              strokeDasharray={`${len} ${c - len}`} strokeDashoffset={-offset}
              strokeLinecap="butt" style={{ transition: "stroke-dasharray .6s ease" }} />
          );
          offset += len;
          return seg;
        })}
      </svg>
      <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
        <span className="tnum" style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-.02em" }}>{centerValue}</span>
        <span style={{ fontSize: 11.5, color: "var(--text-faint)", fontWeight: 500 }}>{centerLabel}</span>
      </div>
    </div>
  );
}

/* ---------- Legend ---------- */
function Legend({ data, total, vertical }) {
  const tot = total || data.reduce((s, d) => s + d.value, 0);
  return (
    <div style={{ display: "flex", flexDirection: vertical ? "column" : "row", gap: vertical ? 11 : 18, flexWrap: "wrap" }}>
      {data.map((d, i) => (
        <div key={i} style={{ display: "flex", alignItems: "center", gap: 9, minWidth: 0 }}>
          <span style={{ width: 9, height: 9, borderRadius: 3, background: `var(${d.token})`, flex: "0 0 auto" }} />
          <span style={{ flex: 1, minWidth: 0, fontSize: 13, color: "var(--text-muted)", fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{d.label}</span>
          <span className="tnum" style={{ fontSize: 13, fontWeight: 700, flex: "0 0 auto" }}>{d.value}</span>
          {vertical && <span className="tnum" style={{ fontSize: 11.5, color: "var(--text-faint)", width: 40, textAlign: "right", flex: "0 0 auto" }}>{Math.round((d.value/tot)*100)}%</span>}
        </div>
      ))}
    </div>
  );
}

/* ---------- Horizontal bars ---------- */
function HBars({ data, unit = "", max }) {
  const mx = max || Math.max(...data.map((d) => d.value));
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {data.map((d, i) => (
        <div key={i} style={{ display: "grid", gridTemplateColumns: "120px 1fr auto", alignItems: "center", gap: 12 }}>
          <span style={{ fontSize: 13, color: "var(--text-muted)", fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{d.label}</span>
          <span style={{ height: 12, borderRadius: 99, background: "var(--surface-3)", overflow: "hidden", display: "block" }}>
            <span style={{ display: "block", height: "100%", width: `${(d.value/mx)*100}%`, background: `var(${d.token})`, borderRadius: 99 }} />
          </span>
          <span className="tnum" style={{ fontSize: 13, fontWeight: 700, minWidth: 44, textAlign: "right" }}>{d.value}{unit}</span>
        </div>
      ))}
    </div>
  );
}

/* ---------- Column + line combo ---------- */
function ColumnLine({ labels, bars, line, barToken = "--accent", lineToken = "--c-violet", h = 200, barLabel, lineLabel, lineUnit = "" }) {
  const w = 460, padL = 8, padR = 8, padT = 16, padB = 26;
  const iw = w - padL - padR, ih = h - padT - padB;
  const maxBar = Math.max(...bars) * 1.15;
  const lmin = Math.min(...line), lmax = Math.max(...line);
  const bw = (iw / labels.length) * 0.52;
  const x = (i) => padL + (iw / labels.length) * (i + 0.5);
  const ly = (v) => padT + ih - ((v - lmin) / (lmax - lmin || 1)) * (ih * 0.8) - ih * 0.1;
  const linePath = line.map((v, i) => (i ? "L" : "M") + x(i).toFixed(1) + " " + ly(v).toFixed(1)).join(" ");
  return (
    <div>
      <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: "auto", display: "block" }}>
        {[0, 0.25, 0.5, 0.75, 1].map((g, i) => (
          <line key={i} x1={padL} x2={w - padR} y1={padT + ih * g} y2={padT + ih * g} stroke="var(--border)" strokeWidth="1" strokeDasharray={i === 4 ? "0" : "3 4"} opacity={i===4?1:0.6} />
        ))}
        {bars.map((v, i) => {
          const bh = (v / maxBar) * ih;
          return <rect key={i} x={x(i) - bw/2} y={padT + ih - bh} width={bw} height={bh} rx="5"
            fill={`var(${barToken})`} opacity="0.85" />;
        })}
        <path d={linePath} fill="none" stroke={`var(${lineToken})`} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
        {line.map((v, i) => <circle key={i} cx={x(i)} cy={ly(v)} r="3.5" fill="var(--surface)" stroke={`var(${lineToken})`} strokeWidth="2.5" />)}
        {labels.map((l, i) => <text key={i} x={x(i)} y={h - 8} textAnchor="middle" fontSize="11" fill="var(--text-faint)" fontFamily="var(--font-sans)">{l}</text>)}
      </svg>
      {(barLabel || lineLabel) && (
        <div style={{ display: "flex", gap: 18, marginTop: 6, justifyContent: "center" }}>
          {barLabel && <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 12.5, color: "var(--text-muted)", fontWeight: 500 }}><span style={{ width: 11, height: 11, borderRadius: 3, background: `var(${barToken})`, opacity: .85 }} />{barLabel}</span>}
          {lineLabel && <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 12.5, color: "var(--text-muted)", fontWeight: 500 }}><span style={{ width: 14, height: 3, borderRadius: 99, background: `var(${lineToken})` }} />{lineLabel}</span>}
        </div>
      )}
    </div>
  );
}

/* ---------- Stacked bar (single row) ---------- */
function StackedBar({ data, height = 14 }) {
  const total = data.reduce((s, d) => s + d.value, 0);
  return (
    <div style={{ display: "flex", height, borderRadius: 99, overflow: "hidden", background: "var(--surface-3)" }}>
      {data.map((d, i) => (
        <div key={i} title={`${d.label}: ${d.value}`} style={{ width: `${(d.value/total)*100}%`, background: `var(${d.token})`, transition: "width .6s ease" }} />
      ))}
    </div>
  );
}

/* ---------- Gauge (compliance %) ---------- */
function Gauge({ value, size = 150, token = "--c-done", label }) {
  const r = size / 2 - 12, c = Math.PI * r; // half circle
  const frac = value / 100;
  return (
    <div style={{ position: "relative", width: size, height: size * 0.62 }}>
      <svg width={size} height={size * 0.62} viewBox={`0 0 ${size} ${size*0.62}`}>
        <path d={`M 12 ${size*0.6} A ${r} ${r} 0 0 1 ${size-12} ${size*0.6}`} fill="none" stroke="var(--surface-3)" strokeWidth="13" strokeLinecap="round" />
        <path d={`M 12 ${size*0.6} A ${r} ${r} 0 0 1 ${size-12} ${size*0.6}`} fill="none" stroke={`var(${token})`} strokeWidth="13" strokeLinecap="round"
          strokeDasharray={`${frac * c} ${c}`} style={{ transition: "stroke-dasharray .8s ease" }} />
      </svg>
      <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, textAlign: "center" }}>
        <div className="tnum" style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-.02em" }}>{value}<span style={{ fontSize: 15 }}>%</span></div>
        {label && <div style={{ fontSize: 11.5, color: "var(--text-faint)", fontWeight: 500 }}>{label}</div>}
      </div>
    </div>
  );
}

/* ---------- Heatmap ---------- */
function Heatmap({ days, rows, token = "--accent" }) {
  return (
    <div>
      <div style={{ display: "grid", gridTemplateColumns: `48px repeat(${days.length}, 1fr)`, gap: 6 }}>
        <span />
        {days.map((d) => <span key={d} style={{ fontSize: 11, color: "var(--text-faint)", textAlign: "center", fontWeight: 500 }}>{d}</span>)}
        {rows.map((row, ri) => (
          <React.Fragment key={ri}>
            <span style={{ fontSize: 11, color: "var(--text-faint)", display: "flex", alignItems: "center", fontWeight: 500 }}>W{ri + 1}</span>
            {row.map((v, ci) => (
              <div key={ci} title={`${days[ci]} · W${ri+1}`} style={{
                aspectRatio: "1.6 / 1", borderRadius: 6,
                background: `color-mix(in oklch, var(${token}) ${Math.round(v*90+6)}%, var(--surface-3))`,
              }} />
            ))}
          </React.Fragment>
        ))}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 12, justifyContent: "flex-end" }}>
        <span style={{ fontSize: 11, color: "var(--text-faint)" }}>Less</span>
        {[0.15, 0.4, 0.65, 0.9].map((v) => <span key={v} style={{ width: 13, height: 13, borderRadius: 4, background: `color-mix(in oklch, var(${token}) ${Math.round(v*90+6)}%, var(--surface-3))` }} />)}
        <span style={{ fontSize: 11, color: "var(--text-faint)" }}>More</span>
      </div>
    </div>
  );
}

window.Charts = { Donut, Legend, HBars, ColumnLine, StackedBar, Gauge, Heatmap };
