/* ui.jsx — shared UI primitives. Exports to window. */
const { useState, useEffect, useRef } = React;

/* ---------- Avatar ---------- */
function Avatar({ name, size = 36, state }) {
  const palette = ["#2f5fe0", "#1f9d6b", "#c97a12", "#8b5cf6", "#0e8f9e", "#d6453c", "#5a6b8c"];
  let h = 0;
  for (const c of name || "?") h = (h * 31 + c.charCodeAt(0)) % palette.length;
  const bg = palette[h];
  return (
    <div className="avatar" style={{ width: size, height: size, background: bg, fontSize: size * 0.4 }}>
      {window.LP.fmt.initials(name)}
      {state && state !== "ok" && state !== "none" && (
        <span className={"avatar-dot " + (state === "over" ? "is-red" : "is-amber")} />
      )}
    </div>
  );
}

/* ---------- Badge ---------- */
function Badge({ tone = "neutral", children, soft = true, dot = false }) {
  return (
    <span className={`badge tone-${tone} ${soft ? "soft" : "solid"}`}>
      {dot && <span className="badge-dot" />}
      {children}
    </span>
  );
}

/* ---------- Button ---------- */
function Button({ variant = "secondary", size = "md", icon, children, ...rest }) {
  return (
    <button className={`btn btn-${variant} btn-${size}`} {...rest}>
      {icon ? <span className="btn-ic">{icon}</span> : null}
      {children}
    </button>
  );
}
function IconButton({ label, icon, active, danger, ...rest }) {
  return (
    <button className={`iconbtn ${active ? "is-active" : ""} ${danger ? "is-danger" : ""}`} aria-label={label} title={label} {...rest}>
      {icon}
    </button>
  );
}

/* ---------- Card ---------- */
function Card({ children, className = "", pad = true, ...rest }) {
  return (
    <div className={`card ${pad ? "card-pad" : ""} ${className}`} {...rest}>
      {children}
    </div>
  );
}

/* ---------- ProgressBar ---------- */
function ProgressBar({ value, max, state = "ok" }) {
  const pct = max > 0 ? Math.max(0, Math.min(100, (value / max) * 100)) : 0;
  const over = value < 0;
  return (
    <div className="progress">
      <div className={`progress-fill st-${over ? "over" : state}`} style={{ width: (over ? 100 : pct) + "%" }} />
    </div>
  );
}

/* ---------- Modal ---------- */
function Modal({ title, subtitle, onClose, children, footer, wide = false }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [onClose]);
  return (
    <div className="modal-scrim" onMouseDown={onClose}>
      <div className={`modal ${wide ? "modal-wide" : ""}`} onMouseDown={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <h3>{title}</h3>
            {subtitle && <p className="modal-sub">{subtitle}</p>}
          </div>
          <IconButton label="关闭" icon={<Icon.close size={18} />} onClick={onClose} />
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-foot">{footer}</div>}
      </div>
    </div>
  );
}

/* ---------- Form fields ---------- */
function Field({ label, hint, children, span }) {
  return (
    <label className="field" style={span ? { gridColumn: "1 / -1" } : undefined}>
      <span className="field-label">{label}{hint && <em className="field-hint">{hint}</em>}</span>
      {children}
    </label>
  );
}
function Input(props) { return <input className="input" {...props} />; }
function Textarea(props) { return <textarea className="input textarea" {...props} />; }
function Select({ children, ...props }) {
  return <div className="select-wrap"><select className="input select" {...props}>{children}</select><Icon.chevR size={14} className="select-caret" /></div>;
}

/* ---------- Confirm ---------- */
function Confirm({ title, message, confirmLabel = "删除", onConfirm, onClose }) {
  return (
    <Modal title={title} onClose={onClose} footer={
      <>
        <Button variant="ghost" onClick={onClose}>取消</Button>
        <Button variant="danger" onClick={() => { onConfirm(); onClose(); }}>{confirmLabel}</Button>
      </>
    }>
      <p className="confirm-msg">{message}</p>
    </Modal>
  );
}

/* ---------- EmptyState ---------- */
function EmptyState({ icon, title, hint, action }) {
  return (
    <div className="empty">
      <div className="empty-ic">{icon}</div>
      <h4>{title}</h4>
      {hint && <p>{hint}</p>}
      {action}
    </div>
  );
}

/* ---------- StatCard ---------- */
function StatCard({ label, value, sub, icon, tone = "neutral", onClick }) {
  return (
    <div className={`stat ${onClick ? "stat-click" : ""}`} onClick={onClick}>
      <div className={`stat-ic tone-${tone}`}>{icon}</div>
      <div className="stat-body">
        <div className="stat-label">{label}</div>
        <div className="stat-value">{value}</div>
        {sub && <div className="stat-sub">{sub}</div>}
      </div>
    </div>
  );
}

/* ---------- SectionHead ---------- */
function SectionHead({ title, count, action }) {
  return (
    <div className="section-head">
      <h2>{title}{count != null && <span className="section-count">{count}</span>}</h2>
      {action}
    </div>
  );
}

Object.assign(window, {
  Avatar, Badge, Button, IconButton, Card, ProgressBar, Modal,
  Field, Input, Textarea, Select, Confirm, EmptyState, StatCard, SectionHead,
});
