// Shared UI components: StatusBadge, PlatformChip, Avatar, Card, Modal, Empty,
// Toast notification system, ConfirmDialog — used across all screens.

const { useState, useEffect, useRef, useCallback, createContext, useContext } = React;

// ─── Status badge — maps backend status values to UI colors ────────────
const STATUS_MAP = {
  active:           { cls: "green",  label: "Active" },
  pending:          { cls: "yellow", label: "Pending" },
  live:             { cls: "green",  label: "Live" },
  ok:               { cls: "green",  label: "OK" },
  authenticated:    { cls: "green",  label: "Authenticated" },
  paused:           { cls: "yellow", label: "Paused" },
  warning:          { cls: "yellow", label: "Warning" },
  expiring:         { cls: "yellow", label: "Expiring" },
  auth_required:    { cls: "yellow", label: "Auth Required" },
  auth_in_progress: { cls: "yellow", label: "Authing…" },
  awaiting_code:    { cls: "yellow", label: "Awaiting Code" },
  awaiting_password:{ cls: "yellow", label: "Awaiting 2FA" },
  error:            { cls: "red",    label: "Error" },
  failed:           { cls: "red",    label: "Failed" },
  offline:          { cls: "red",    label: "Offline" },
  expired:          { cls: "red",    label: "Expired" },
  idle:             { cls: "",       label: "Idle" },
  disabled:         { cls: "",       label: "Disabled" },
};

const StatusBadge = ({ status }) => {
  const m = STATUS_MAP[status] || { cls: "", label: status || "Unknown" };
  return (
    <span className={`badge ${m.cls}`}>
      <span className="dot"></span>
      {m.label}
    </span>
  );
};

// ─── Platform chip ──────────────────────────────────────────────────────
const PlatformChip = ({ platform }) => {
  const isTg = platform === "telegram";
  return (
    <span className={`platform-chip ${platform || ""}`}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: isTg ? "#4ea4f6" : "#5b9aff" }}></span>
      {isTg ? "Telegram" : "Zalo"}
    </span>
  );
};

// ─── Platform filter chips ──────────────────────────────────────────────
const PlatformFilter = ({ value, onChange }) => (
  <div className="chip-group">
    {[
      { id: "all", label: "All" },
      { id: "telegram", label: "Telegram", color: "#4ea4f6" },
      { id: "zalo", label: "Zalo", color: "#5b9aff" },
    ].map(({ id, label, color }) => (
      <button key={id} className={`chip ${value === id ? "active" : ""}`} onClick={() => onChange(id)}>
        {color && <span style={{ width: 6, height: 6, borderRadius: "50%", background: color }}></span>}
        {label}
      </button>
    ))}
  </div>
);

// ─── Avatar (initials) ──────────────────────────────────────────────────
const Avatar = ({ name, size = "" }) => {
  const initials = (name || "?")
    .split(/\s+/)
    .slice(0, 2)
    .map((s) => s[0]?.toUpperCase())
    .join("");
  return <span className={`avatar ${size}`}>{initials}</span>;
};

// ─── KPI Card ───────────────────────────────────────────────────────────
const Kpi = ({ label, value, sub }) => (
  <div className="kpi">
    <div className="kpi-label">{label}</div>
    <div className="kpi-value">{value ?? "—"}</div>
    {sub && <div className="kpi-delta">{sub}</div>}
  </div>
);

// ─── Card heading helper ────────────────────────────────────────────────
const Card = ({ title, subtitle, action, children, flush }) => (
  <div className={`card ${flush ? "flush" : ""}`}>
    {(title || action) && (
      <div className="card-head">
        <div>
          {title && <h3>{title}</h3>}
          {subtitle && <div className="sub">{subtitle}</div>}
        </div>
        {action}
      </div>
    )}
    <div className="card-body">{children}</div>
  </div>
);

// ─── Empty state ────────────────────────────────────────────────────────
const Empty = ({ icon: IconC = I.Info, title, sub, action }) => (
  <div className="empty">
    <IconC className="icon" size={32} />
    <h4>{title}</h4>
    {sub && <div>{sub}</div>}
    {action && <div style={{ marginTop: 12 }}>{action}</div>}
  </div>
);

// ─── Modal ──────────────────────────────────────────────────────────────
const Modal = ({ open, onClose, title, subtitle, children, footer, width = 480 }) => {
  useEffect(() => {
    if (!open) return;
    const handler = (e) => { if (e.key === "Escape") onClose?.(); };
    document.addEventListener("keydown", handler);
    return () => document.removeEventListener("keydown", handler);
  }, [open, onClose]);

  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{ width }} onClick={(e) => e.stopPropagation()}>
        {(title || subtitle) && (
          <div className="modal-head">
            {title && <h3 className="modal-title">{title}</h3>}
            {subtitle && <div className="modal-sub">{subtitle}</div>}
          </div>
        )}
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-foot">{footer}</div>}
      </div>
    </div>
  );
};

// ─── Loading skeleton row ───────────────────────────────────────────────
const SkeletonRows = ({ cols = 5, rows = 4 }) => (
  <>
    {Array.from({ length: rows }).map((_, i) => (
      <tr key={i}>
        {Array.from({ length: cols }).map((_, j) => (
          <td key={j}><div className="skeleton" style={{ height: 14, width: "80%", borderRadius: 4 }}></div></td>
        ))}
      </tr>
    ))}
  </>
);

// ─── Toast context + provider ────────────────────────────────────────────
const ToastContext = createContext(null);

let _toastIdCounter = 0;

const ToastProvider = ({ children }) => {
  const [toasts, setToasts] = useState([]);

  const addToast = useCallback((type, message) => {
    const id = ++_toastIdCounter;
    setToasts((prev) => [...prev, { id, type, message }]);
    setTimeout(() => {
      setToasts((prev) => prev.filter((t) => t.id !== id));
    }, 3500);
  }, []);

  const toast = {
    success: (msg) => addToast("success", msg),
    error: (msg) => addToast("error", msg),
    info: (msg) => addToast("info", msg),
  };

  const iconMap = { success: I.Check, error: I.AlertTriangle, info: I.Info };
  const colorMap = { success: "var(--green)", error: "var(--red)", info: "var(--accent)" };

  return (
    <ToastContext.Provider value={toast}>
      {children}
      <div className="toast-container">
        {toasts.map((t) => {
          const IconC = iconMap[t.type] || I.Info;
          return (
            <div key={t.id} className={`toast ${t.type}`}>
              <IconC size={14} style={{ color: colorMap[t.type], flexShrink: 0 }} />
              <span>{t.message}</span>
            </div>
          );
        })}
      </div>
    </ToastContext.Provider>
  );
};

const useToast = () => useContext(ToastContext);

// ─── Confirm dialog context + provider ──────────────────────────────────
const ConfirmContext = createContext(null);

const ConfirmProvider = ({ children }) => {
  const [state, setState] = useState(null); // { title, message, resolve }

  const confirm = useCallback((title, message) => {
    return new Promise((resolve) => {
      setState({ title, message, resolve });
    });
  }, []);

  const handleClose = (result) => {
    state?.resolve(result);
    setState(null);
  };

  return (
    <ConfirmContext.Provider value={confirm}>
      {children}
      {state && (
        <div className="modal-backdrop" onClick={() => handleClose(false)}>
          <div className="modal" style={{ width: 400 }} onClick={(e) => e.stopPropagation()}>
            <div className="modal-head">
              <h3 className="modal-title">{state.title}</h3>
              {state.message && <div className="modal-sub">{state.message}</div>}
            </div>
            <div className="modal-foot">
              <button className="btn ghost" onClick={() => handleClose(false)}>Cancel</button>
              <button className="btn danger" onClick={() => handleClose(true)}>Confirm</button>
            </div>
          </div>
        </div>
      )}
    </ConfirmContext.Provider>
  );
};

const useConfirm = () => useContext(ConfirmContext);

// ─── Relative time helper ────────────────────────────────────────────────
const relativeTime = (dateStr) => {
  if (!dateStr) return "—";
  const diff = Date.now() - new Date(dateStr).getTime();
  const m = Math.floor(diff / 60000);
  if (m < 1) return "just now";
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
};

Object.assign(window, {
  StatusBadge, PlatformChip, PlatformFilter, Avatar,
  Kpi, Card, Empty, Modal, SkeletonRows,
  ToastProvider, useToast,
  ConfirmProvider, useConfirm,
  relativeTime,
});
