// ===== Common components =====

const Avatar = ({ person, size = 36, photo }) => {
  const [c1, c2] = person?.tone || ["#7c5cff", "#5a3eff"];
  return (
    <div className="avatar"
      style={{
        width: size, height: size, fontSize: Math.round(size * 0.36),
        "--c1": c1, "--c2": c2,
        backgroundImage: photo ? `url(${photo})` : undefined,
      }}>
      {!photo && (person?.initials || "?")}
    </div>
  );
};

// ----- Toast system -----
const ToastContext = React.createContext({ push: () => {} });
const useToast = () => React.useContext(ToastContext);

const ToastProvider = ({ children }) => {
  const [list, setList] = React.useState([]);
  const idRef = React.useRef(0);
  const push = React.useCallback((msg, opts = {}) => {
    const id = ++idRef.current;
    const t = { id, msg, kind: opts.kind || "info", duration: opts.duration || 3200 };
    setList(prev => [...prev, t]);
    setTimeout(() => setList(prev => prev.filter(x => x.id !== id)), t.duration);
  }, []);
  return (
    <ToastContext.Provider value={{ push }}>
      {children}
      <div className="toast-stack">
        {list.map(t => (
          <div key={t.id} className="toast" style={{
            borderLeftColor: {
              success: "var(--teal)", error: "var(--pink)",
              warn: "var(--yellow)", info: "var(--blue)"
            }[t.kind] || "var(--teal)"
          }}>
            <span style={{
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              width: 22, height: 22, borderRadius: "50%",
              background: {
                success: "rgba(0,212,168,0.18)", error: "rgba(255,93,143,0.18)",
                warn: "rgba(255,201,77,0.18)", info: "rgba(78,195,255,0.18)"
              }[t.kind] || "rgba(0,212,168,0.18)",
              color: {
                success: "var(--teal)", error: "var(--pink)",
                warn: "var(--yellow)", info: "var(--blue)"
              }[t.kind] || "var(--teal)"
            }}>
              {t.kind === "success" ? <Icon name="check" size={14} />
                : t.kind === "error" ? <Icon name="close" size={14} />
                : <Icon name="sparkle" size={12} />}
            </span>
            {t.msg}
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  );
};

// ----- Drawer -----
const Drawer = ({ open, onClose, children, width = 480 }) => {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open]);
  if (!open) return null;
  return (
    <>
      <div className="drawer-backdrop" onClick={onClose} />
      <div className="drawer" style={{ width }}>{children}</div>
    </>
  );
};

// ----- Modal -----
const Modal = ({ open, onClose, children, maxWidth = 1080 }) => {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open]);
  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{ maxWidth }} onClick={(e) => e.stopPropagation()}>
        {children}
      </div>
    </div>
  );
};

// ----- Dept Pill -----
const DeptPill = ({ dept, small }) => {
  if (!dept) return null;
  return (
    <span className="chip" style={{
      background: `${dept.color}1a`,
      borderColor: `${dept.color}44`,
      color: dept.color,
      fontSize: small ? 11 : 12,
      padding: small ? "3px 8px" : "4px 10px"
    }}>
      <span className="dot" style={{ background: dept.color }} /> {dept.name}
    </span>
  );
};

// ----- Status pill -----
const StatusPill = ({ status }) => {
  if (status === "active") return <span className="chip chip-teal"><span className="live-dot" /> Active</span>;
  return <span className="chip chip-red">ลาออก</span>;
};

// ----- Glass background scenery panels -----
const GlowBlob = ({ color, x, y, size = 400, opacity = 0.18 }) => (
  <div style={{
    position: "fixed",
    left: x, top: y,
    width: size, height: size,
    background: `radial-gradient(circle, ${color}, transparent 60%)`,
    opacity, filter: "blur(60px)",
    pointerEvents: "none", zIndex: 0
  }} />
);

// ----- Checkbox -----
const CheckBox = ({ checked, onChange }) => (
  <div className={`checkbox ${checked ? "checked" : ""}`}
    onClick={(e) => { e.stopPropagation(); onChange && onChange(!checked); }} />
);

// ----- Helper format -----
const fmtThaiDate = (iso) => {
  if (!iso) return "—";
  const d = new Date(iso);
  const months = ["ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค."];
  return `${d.getDate()} ${months[d.getMonth()]} ${d.getFullYear() + 543}`;
};
const fmtTenure = (iso, endIso) => {
  if (!iso) return "—";
  const s = new Date(iso);
  const e = endIso ? new Date(endIso) : new Date(2026, 4, 14);
  const months = (e.getFullYear() - s.getFullYear()) * 12 + (e.getMonth() - s.getMonth());
  const y = Math.floor(months / 12);
  const m = months % 12;
  if (y === 0) return `${m} เดือน`;
  if (m === 0) return `${y} ปี`;
  return `${y} ปี ${m} เดือน`;
};
const fmtMoney = (n) => n.toLocaleString("en-US");

Object.assign(window, {
  Avatar, ToastProvider, useToast, Drawer, Modal,
  DeptPill, StatusPill, GlowBlob, CheckBox,
  fmtThaiDate, fmtTenure, fmtMoney,
});
