/* B28 HospeX — hand-built SVG charts */

// Smooth-ish area line chart
function LineChart({ data, w = 680, h = 200, pad = 28, color = "var(--primary)", min, max, suffix = "" }) {
  const vals = data.map(d => d.v);
  const lo = min !== undefined ? min : Math.min(...vals) - 6;
  const hi = max !== undefined ? max : Math.max(...vals) + 6;
  const X = i => pad + (i * (w - pad * 2)) / (data.length - 1);
  const Y = v => h - pad - ((v - lo) / (hi - lo)) * (h - pad * 2);
  const pts = data.map((d, i) => [X(i), Y(d.v)]);
  const line = pts.map((p, i) => (i === 0 ? "M" : "L") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ");
  const area = line + ` L ${X(data.length - 1)} ${h - pad} L ${X(0)} ${h - pad} Z`;
  const gid = "lg" + Math.random().toString(36).slice(2, 7);
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: "auto", display: "block" }}>
      <defs>
        <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--primary)" stopOpacity="0.18" />
          <stop offset="100%" stopColor="var(--primary)" stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0, 0.5, 1].map((t, i) => {
        const y = pad + t * (h - pad * 2);
        return <line key={i} x1={pad} y1={y} x2={w - pad} y2={y} stroke="var(--outline-variant)" strokeOpacity="0.5" strokeDasharray="2 5" />;
      })}
      <path d={area} fill={`url(#${gid})`} />
      <path d={line} fill="none" stroke={color} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" />
      {pts.map((p, i) => (
        <g key={i}>
          {i === pts.length - 1 && <circle cx={p[0]} cy={p[1]} r="9" fill={color} fillOpacity="0.16" />}
          <circle cx={p[0]} cy={p[1]} r={i === pts.length - 1 ? 4.5 : 2.6} fill={i === pts.length - 1 ? color : "var(--surface-container-lowest)"} stroke={color} strokeWidth="2" />
        </g>
      ))}
      {data.map((d, i) => (
        <text key={i} x={X(i)} y={h - 6} textAnchor="middle" fontSize="11" fontWeight="600" fill="var(--on-surface-variant)" fontFamily="Inter">{d.m}</text>
      ))}
      <text x={X(pts.length - 1)} y={Y(vals[vals.length - 1]) - 14} textAnchor="middle" fontSize="13" fontWeight="800" fill={color} fontFamily="Plus Jakarta Sans">{vals[vals.length - 1]}{suffix}</text>
    </svg>
  );
}

// NPS composition bar (promoters / passives / detractors)
function NpsBar({ promoters, passives, detractors, height = 16 }) {
  const seg = [
    { v: promoters, c: "var(--primary)", l: "Promotores" },
    { v: passives, c: "#e3c46a", l: "Passivos" },
    { v: detractors, c: "var(--error)", l: "Detratores" },
  ];
  return (
    <div>
      <div style={{ display: "flex", height, borderRadius: 999, overflow: "hidden", gap: 2 }}>
        {seg.map((s, i) => (
          <div key={i} style={{ width: s.v + "%", background: s.c }} title={`${s.l}: ${s.v}%`}></div>
        ))}
      </div>
      <div style={{ display: "flex", gap: 18, marginTop: 12 }}>
        {seg.map((s, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 7 }}>
            <span style={{ width: 9, height: 9, borderRadius: 3, background: s.c }}></span>
            <span style={{ fontSize: 12.5, color: "var(--on-surface-variant)", fontWeight: 600 }}>{s.l}</span>
            <span style={{ fontSize: 12.5, color: "var(--on-surface)", fontWeight: 800 }}>{s.v}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// Donut chart
function Donut({ data, size = 160, thickness = 26, centerLabel, centerSub }) {
  const total = data.reduce((a, d) => a + d.pct, 0);
  const r = (size - thickness) / 2;
  const c = 2 * Math.PI * r;
  let off = 0;
  return (
    <div style={{ position: "relative", width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
        {data.map((d, i) => {
          const len = (d.pct / total) * c;
          const el = (
            <circle key={i} cx={size / 2} cy={size / 2} r={r} fill="none" stroke={d.color} strokeWidth={thickness}
              strokeDasharray={`${len} ${c - len}`} strokeDashoffset={-off} strokeLinecap="butt" />
          );
          off += len;
          return el;
        })}
      </svg>
      {centerLabel !== undefined && (
        <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", textAlign: "center" }}>
          <div>
            <div className="font-headline" style={{ fontSize: 30, fontWeight: 800, letterSpacing: "-0.02em", lineHeight: 1 }}>{centerLabel}</div>
            {centerSub && <div style={{ fontSize: 11, color: "var(--on-surface-variant)", marginTop: 3, fontWeight: 600 }}>{centerSub}</div>}
          </div>
        </div>
      )}
    </div>
  );
}

// Horizontal bar list (areas / scores)
function HBars({ items, max = 100, accentAt }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {items.map((it, i) => {
        const score = it.score;
        const color = score >= 70 ? "var(--primary)" : score >= 55 ? "#caa53a" : "var(--error)";
        return (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "168px 1fr 86px", alignItems: "center", gap: 14 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9, minWidth: 0 }}>
              {it.icon && <Icon name={it.icon} size={18} style={{ color: "var(--on-surface-variant)" }} />}
              <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--on-surface)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.area}</span>
            </div>
            <div style={{ height: 10, borderRadius: 999, background: "var(--surface-container-high)", overflow: "hidden" }}>
              <div style={{ width: (score / max * 100) + "%", height: "100%", background: color, borderRadius: 999 }}></div>
            </div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 8 }}>
              <span className="font-headline" style={{ fontSize: 15, fontWeight: 800 }}>{score}</span>
              <Delta value={it.delta} size={11} />
            </div>
          </div>
        );
      })}
    </div>
  );
}

// Vertical mini bars (compare)
function VBars({ items, max, h = 150, fmt = v => v }) {
  const hi = max || Math.max(...items.map(i => i.v));
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 14, height: h }}>
      {items.map((it, i) => (
        <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", height: "100%", justifyContent: "flex-end", gap: 8 }}>
          <div className="font-headline" style={{ fontSize: 14, fontWeight: 800, color: it.me ? "var(--primary)" : "var(--on-surface)" }}>{fmt(it.v)}</div>
          <div style={{ width: "100%", maxWidth: 54, height: (it.v / hi * (h - 50)) + "px", background: it.me ? "var(--primary)" : "var(--surface-container-high)", borderRadius: "8px 8px 0 0" }}></div>
          <div style={{ fontSize: 11.5, fontWeight: it.me ? 700 : 600, color: it.me ? "var(--on-surface)" : "var(--on-surface-variant)", textAlign: "center", lineHeight: 1.25 }}>{it.label}</div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { LineChart, NpsBar, Donut, HBars, VBars });
