// ============ DASHBOARD · CROSS-SECTION HELPERS ============
// Visual primitives used by more than one section
// (Sparkline + RatingStars appear in Agents tab and Agent Detail).

// ---- BRAND BOOTSTRAP ----
// Read the brand color out of localStorage and apply it as a CSS variable on
// :root so any component can pick it up via var(--brand). Re-applies on
// the "citrus-brand" event that Settings dispatches.
function applyBrand() {
  try {
    const p = JSON.parse(localStorage.getItem("citrus_profile") || "{}");
    const c = p.color || "#E85D1A";
    document.documentElement.style.setProperty("--brand", c);
    document.documentElement.style.setProperty("--brand-soft", c + "33");
  } catch { /* ignore */ }
}
applyBrand();
window.addEventListener("citrus-brand", applyBrand);

function Sparkline({ data, label, color }) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const w = 240, h = 44;
  const step = w / (data.length - 1);
  const pts = data.map((v, i) => {
    const x = i * step;
    const y = h - ((v - min) / Math.max(1, max - min)) * (h - 6) - 3;
    return `${x},${y}`;
  }).join(" ");
  const areaPath = `M0,${h} L${pts.split(" ").join(" L")} L${w},${h} Z`;
  return (
    <div className="spark">
      <div className="spark-label">{label}</div>
      <svg viewBox={`0 0 ${w} ${h}`} className="spark-svg" preserveAspectRatio="none">
        <path d={areaPath} fill={color} opacity="0.12" />
        <polyline points={pts} fill="none" stroke={color} strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round" />
        <circle cx={w} cy={h - ((data[data.length - 1] - min) / Math.max(1, max - min)) * (h - 6) - 3} r="3" fill={color} />
      </svg>
    </div>
  );
}

function RatingStars({ value, onChange, size = "sm" }) {
  const [hover, setHover] = useState(0);
  return (
    <div className={`stars stars-${size}`} onMouseLeave={() => setHover(0)}>
      {[1, 2, 3, 4, 5].map((n) => {
        const filled = (hover || value) >= n;
        return (
          <button
            key={n}
            type="button"
            className={`star ${filled ? "is-on" : ""}`}
            onMouseEnter={() => setHover(n)}
            onClick={() => onChange(n)}
            aria-label={`Rate ${n} stars`}
          >
            ★
          </button>
        );
      })}
      <span className="stars-v">{value}.0</span>
    </div>
  );
}

// ============ TOAST · global lightweight notifier ============
// Any code can call window.toast("Saved") to flash a confirmation in the
// bottom-right. ToastHost is mounted once by the Dashboard root.
const _toastListeners = new Set();
window.toast = (msg, kind) => {
  const t = { id: Math.random().toString(36).slice(2), msg, kind: kind || "info" };
  _toastListeners.forEach((fn) => fn(t));
};

function ToastHost() {
  const [items, setItems] = useState([]);
  useEffect(() => {
    const fn = (t) => {
      setItems((prev) => [...prev, t]);
      setTimeout(() => setItems((prev) => prev.filter((x) => x.id !== t.id)), 2600);
    };
    _toastListeners.add(fn);
    return () => _toastListeners.delete(fn);
  }, []);
  if (items.length === 0) return null;
  return (
    <div className="toast-host">
      {items.map((t) => (
        <div key={t.id} className={`toast toast-${t.kind}`}>{t.msg}</div>
      ))}
    </div>
  );
}

Object.assign(window, { Sparkline, RatingStars, ToastHost });
