// Shared atoms — avatars, badges, sparkline, popover, etc.
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ── Avatar with platform badge ─────────────────────────────
function Avatar({ creator, size = 30 }) {
  const [c1, c2] = creator.avatarColor;
  const PlatIcon = PLATFORM_ICON[creator.platform];
  const fontSize = Math.round(size * 0.36);
  return (
    <div
      className="avatar"
      style={{
        width: size, height: size,
        background: `linear-gradient(135deg, ${c1}, ${c2})`,
        fontSize,
      }}
    >
      {creator.initials}
      <span className={`pbadge ${creator.platform}`} style={{ background: PLATFORM_META[creator.platform].color }}>
        <PlatIcon />
      </span>
    </div>
  );
}

// ── Status pill ────────────────────────────────────────────
function StatusPill({ status }) {
  const meta = STATUS_META[status];
  return (
    <span className={`pill ${meta.cls}`}>
      <span className="dot" style={{ background: meta.color }}></span>
      {meta.ru}
    </span>
  );
}

// ── Platform icon ─────────────────────────────────────────
function PlatformBadge({ platform, size = 18 }) {
  const PlatIcon = PLATFORM_ICON[platform];
  const meta = PLATFORM_META[platform];
  return (
    <span className={`platform-icon ${platform}`} style={{ width: size, height: size, background: meta.color }}>
      <PlatIcon />
    </span>
  );
}

// ── Sparkline ─────────────────────────────────────────────
function Sparkline({ data, width = 64, height = 18, stroke = "var(--accent-500)" }) {
  if (!data || data.length === 0) return null;
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const stepX = width / (data.length - 1);
  const points = data
    .map((v, i) => `${i * stepX},${height - ((v - min) / range) * (height - 2) - 1}`)
    .join(" ");
  const last = data[data.length - 1];
  const lastX = (data.length - 1) * stepX;
  const lastY = height - ((last - min) / range) * (height - 2) - 1;
  return (
    <svg className="sparkline" width={width} height={height}>
      <polyline
        fill="none"
        stroke={stroke}
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
        points={points}
      />
      <circle cx={lastX} cy={lastY} r="1.8" fill={stroke} />
    </svg>
  );
}

// ── Popover (uncontrolled close on outside click) ─────────
function Popover({ anchor, onClose, children, align = "start", offset = 6 }) {
  const ref = useRef(null);
  const [pos, setPos] = useState(null);

  useEffect(() => {
    if (!anchor) return;
    const rect = anchor.getBoundingClientRect();
    const left = align === "end" ? rect.right : rect.left;
    setPos({ top: rect.bottom + offset, left, align });
  }, [anchor, align, offset]);

  useEffect(() => {
    const onClick = (e) => {
      if (ref.current && !ref.current.contains(e.target) && !anchor.contains(e.target)) {
        onClose();
      }
    };
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("mousedown", onClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [anchor, onClose]);

  if (!pos) return null;
  return (
    <div
      ref={ref}
      className="popover"
      style={{
        top: pos.top,
        left: align === "end" ? "auto" : pos.left,
        right: align === "end" ? (window.innerWidth - pos.left) : "auto",
      }}
    >
      {children}
    </div>
  );
}

// ── Contacts stack (for table cell) ───────────────────────
function ContactsStack({ contacts, max = 3 }) {
  const visible = contacts.slice(0, max);
  const extra = contacts.length - max;
  return (
    <div className="contacts-stack">
      {visible.map((c) => (
        <div
          key={c.id}
          className="avatar"
          style={{ background: `linear-gradient(135deg, ${c.avatarColor[0]}, ${c.avatarColor[1]})` }}
          title={`${c.name} (${c.role === "creator" ? "Creator" : "Manager"})`}
        >
          {c.initials}
        </div>
      ))}
      {extra > 0 && <div className="more">+{extra}</div>}
    </div>
  );
}

// ── Bar list (geo / demographics) ─────────────────────────
function BarList({ data, max = 5 }) {
  const entries = Object.entries(data).sort((a, b) => b[1] - a[1]).slice(0, max);
  const top = entries[0]?.[1] || 1;
  return (
    <div>
      {entries.map(([k, v]) => (
        <div className="bar-row" key={k}>
          <span className="bar-label">{k}</span>
          <span className="bar-track"><span className="bar-fill" style={{ width: `${(v / top) * 100}%` }}></span></span>
          <span className="bar-val">{v}%</span>
        </div>
      ))}
    </div>
  );
}

// ── Metric tile ───────────────────────────────────────────
function MetricTile({ label, value, trend, trendDir }) {
  return (
    <div className="metric">
      <div className="label">{label}</div>
      <div className="value">{value}</div>
      {trend && <div className={`trend ${trendDir || ""}`}>{trend}</div>}
    </div>
  );
}

Object.assign(window, {
  Avatar, StatusPill, PlatformBadge, Sparkline, Popover, ContactsStack, BarList, MetricTile,
});
