/* ui.jsx — ส่วนประกอบที่ใช้ซ้ำ */
const { useEffect: uiUseEffect, useRef: uiUseRef } = React;

/* ---------- thumbnail ของสินค้า (ตัวอักษรย่อบนพื้นสีหมวด) ---------- */
function ItemThumb({ sku, size = 40 }) {
  const s = useStore();
  const cat = catOf(sku);
  const it = itemOf(sku);
  const img = s && s.images ? s.images[sku] : null;
  if (img) {
    return <img src={img} alt={it ? it.name : sku} className="item-thumb" style={{ width: size, height: size, objectFit: "cover" }} />;
  }
  const initials = (it ? it.name : sku).replace(/[^ก-๙A-Za-z0-9]/g, "").slice(0, 2);
  return (
    <div className="item-thumb" style={{ width: size, height: size, background: cat.color, fontSize: size * 0.34, fontWeight: 600 }}>
      {initials || "?"}
    </div>
  );
}

/* ---------- Badge สถานะคงเหลือ ---------- */
function StockBadge({ qty, reorder }) {
  if (qty <= 0) return <span className="badge badge-red"><span className="b-dot" style={{ background: "#dc3545" }}></span>หมดสต๊อก</span>;
  if (qty <= reorder) return <span className="badge badge-amber"><span className="b-dot" style={{ background: "#d98a04" }}></span>ต่ำกว่าจุดสั่ง</span>;
  return <span className="badge badge-green"><span className="b-dot" style={{ background: "#0f9d58" }}></span>ปกติ</span>;
}

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

function SectionHead({ title, sub, right }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 14, gap: 12, flexWrap: "wrap" }}>
      <div>
        <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: "-.01em" }}>{title}</div>
        {sub && <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 2 }}>{sub}</div>}
      </div>
      {right}
    </div>
  );
}

/* ---------- Drawer ---------- */
function Drawer({ title, sub, onClose, children, footer, headIcon }) {
  uiUseEffect(() => {
    const h = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);
  return (
    <React.Fragment>
      <div className="scrim" onClick={onClose}></div>
      <aside className="drawer" role="dialog" aria-modal="true">
        <div className="drawer-head">
          {headIcon}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 17, fontWeight: 600, letterSpacing: "-.01em" }}>{title}</div>
            {sub && <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 2 }}>{sub}</div>}
          </div>
          <button className="icon-btn" style={{ width: 36, height: 36 }} onClick={onClose} aria-label="ปิด"><Icons.close size={18} /></button>
        </div>
        <div className="drawer-body">{children}</div>
        {footer && <div className="drawer-foot">{footer}</div>}
      </aside>
    </React.Fragment>
  );
}

/* ---------- Modal ---------- */
function Modal({ title, onClose, children, footer, width }) {
  uiUseEffect(() => {
    const h = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);
  return (
    <React.Fragment>
      <div className="scrim" onClick={onClose}></div>
      <div className="modal" style={width ? { width } : null} role="dialog" aria-modal="true">
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "18px 22px", borderBottom: "1px solid var(--line)" }}>
          <div style={{ fontSize: 17, fontWeight: 600 }}>{title}</div>
          <button className="icon-btn" style={{ width: 34, height: 34 }} onClick={onClose}><Icons.close size={17} /></button>
        </div>
        <div style={{ padding: 22 }}>{children}</div>
        {footer && <div style={{ padding: "16px 22px", borderTop: "1px solid var(--line)", display: "flex", gap: 10, justifyContent: "flex-end" }}>{footer}</div>}
      </div>
    </React.Fragment>
  );
}

/* ---------- Empty state ---------- */
function Empty({ icon, title, sub }) {
  return (
    <div style={{ textAlign: "center", padding: "48px 20px", color: "var(--muted)" }}>
      <div style={{ width: 56, height: 56, borderRadius: 16, background: "var(--bg-2)", display: "grid", placeItems: "center", margin: "0 auto 14px", color: "var(--muted-2)" }}>{icon}</div>
      <div style={{ fontWeight: 600, color: "var(--ink-2)", fontSize: 15 }}>{title}</div>
      {sub && <div style={{ fontSize: 13, marginTop: 4 }}>{sub}</div>}
    </div>
  );
}

/* ---------- Toasts ---------- */
function Toasts() {
  const { toasts } = useStore();
  return (
    <div className="toast-wrap">
      {toasts.map(t => (
        <div className="toast" key={t.id}>
          <span className="t-ic" style={{ background: t.kind === "warn" ? "var(--amber)" : "var(--green)" }}>
            {t.kind === "warn" ? <Icons.alert size={14} /> : <Icons.check size={14} />}
          </span>
          {t.msg}
        </div>
      ))}
    </div>
  );
}

/* ---------- Mini sparkline / donut (simple svg, primitives only) ---------- */
function Donut({ segments, size = 132, thickness = 16, center }) {
  const r = (size - thickness) / 2;
  const C = 2 * Math.PI * r;
  const total = segments.reduce((s, x) => s + x.value, 0) || 1;
  let offset = 0;
  return (
    <div style={{ position: "relative", width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--bg-2)" strokeWidth={thickness} />
        {segments.map((s, i) => {
          const len = (s.value / total) * C;
          const el = (
            <circle key={i} cx={size/2} cy={size/2} r={r} fill="none" stroke={s.color}
              strokeWidth={thickness} strokeDasharray={`${len} ${C - len}`} strokeDashoffset={-offset}
              strokeLinecap="round" style={{ transition: "stroke-dasharray .6s var(--ease-out)" }} />
          );
          offset += len;
          return el;
        })}
      </svg>
      {center && <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", textAlign: "center" }}>{center}</div>}
    </div>
  );
}

Object.assign(window, { ItemThumb, StockBadge, Card, SectionHead, Drawer, Modal, Empty, Toasts, Donut });
