// ui.jsx — shared interface primitives. Read theme via CSS vars (--accent, --radius…).

function AppButton({ children, onClick, variant = "primary", full, disabled, icon, style = {}, ...rest }) {
  const base = {
    display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 9,
    font: "inherit", fontWeight: 650, fontSize: 16, letterSpacing: -0.1,
    border: "none", cursor: disabled ? "not-allowed" : "pointer",
    borderRadius: "var(--radius)", padding: "0 18px", height: 52,
    width: full ? "100%" : undefined, transition: "transform .12s ease, filter .12s ease, background .15s ease",
    WebkitTapHighlightColor: "transparent", opacity: disabled ? 0.45 : 1,
  };
  const variants = {
    primary: { background: "var(--accent)", color: "var(--on-accent)" },
    secondary: { background: "var(--surface-2)", color: "var(--text)" },
    ghost: { background: "transparent", color: "var(--accent)", boxShadow: "inset 0 0 0 1.5px var(--border-strong)" },
    danger: { background: "var(--danger-bg)", color: "var(--danger)" },
  };
  return (
    <button className="wmc-btn" onClick={disabled ? undefined : onClick} disabled={disabled}
      style={{ ...base, ...variants[variant], ...style }} {...rest}>
      {icon}{children}
    </button>
  );
}

function IconButton({ children, onClick, label, active, style = {}, size = 40 }) {
  return (
    <button className="wmc-btn" aria-label={label} onClick={onClick} style={{
      width: size, height: size, borderRadius: "var(--radius-sm)", border: "none",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      background: active ? "var(--accent)" : "var(--surface-2)",
      color: active ? "var(--on-accent)" : "var(--text)",
      cursor: "pointer", WebkitTapHighlightColor: "transparent", flexShrink: 0,
      transition: "background .15s ease, transform .12s ease", ...style,
    }}>{children}</button>
  );
}

function Card({ children, style = {}, onClick, pad = 16 }) {
  return (
    <div onClick={onClick} className={onClick ? "wmc-press" : ""} style={{
      background: "var(--surface)", borderRadius: "var(--radius)", padding: pad,
      boxShadow: "var(--card-shadow)", border: "1px solid var(--hairline)",
      cursor: onClick ? "pointer" : "default", ...style,
    }}>{children}</div>
  );
}

function ColorDot({ color, size = 14 }) {
  return <span style={{
    width: size, height: size, borderRadius: 999, background: color, flexShrink: 0,
    boxShadow: "inset 0 0 0 1px rgba(255,255,255,.18), 0 1px 2px rgba(0,0,0,.3)",
    display: "inline-block",
  }} />;
}

// ── Bottom sheet ─────────────────────────────────────────────
function Sheet({ open, onClose, title, children, footer }) {
  const [mounted, setMounted] = React.useState(open);
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    if (open) {
      setMounted(true);
      const t = requestAnimationFrame(() => setShown(true));
      return () => cancelAnimationFrame(t);
    } else {
      setShown(false);
      const t = setTimeout(() => setMounted(false), 260);
      return () => clearTimeout(t);
    }
  }, [open]);
  if (!mounted) return null;
  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 200, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>
      <div onClick={onClose} style={{
        position: "absolute", inset: 0, background: "rgba(0,0,0,.5)",
        opacity: shown ? 1 : 0, transition: "opacity .26s ease", backdropFilter: "blur(2px)",
      }} />
      <div style={{
        position: "relative", background: "var(--surface)", borderTopLeftRadius: 28, borderTopRightRadius: 28,
        padding: "10px 20px calc(20px + var(--safe-bottom))", maxHeight: "86%", overflow: "auto",
        transform: shown ? "translateY(0)" : "translateY(102%)",
        transition: "transform .3s cubic-bezier(.32,.72,0,1)",
        boxShadow: "0 -10px 40px rgba(0,0,0,.4)", borderTop: "1px solid var(--hairline)",
      }}>
        <div style={{ width: 38, height: 5, borderRadius: 999, background: "var(--border-strong)", margin: "0 auto 14px" }} />
        {title && <div style={{ fontSize: 21, fontWeight: 750, letterSpacing: -0.3, marginBottom: 16, color: "var(--text)" }}>{title}</div>}
        {children}
        {footer && <div style={{ marginTop: 18 }}>{footer}</div>}
      </div>
    </div>
  );
}

// ── Form fields ──────────────────────────────────────────────
function Field({ label, children, hint }) {
  return (
    <label style={{ display: "block", marginBottom: 16 }}>
      <div style={{ fontSize: 13, fontWeight: 650, color: "var(--text-2)", marginBottom: 7, letterSpacing: 0.1 }}>{label}</div>
      {children}
      {hint && <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 6 }}>{hint}</div>}
    </label>
  );
}

const inputStyle = {
  width: "100%", boxSizing: "border-box", font: "inherit", fontSize: 16,
  padding: "13px 14px", borderRadius: "var(--radius-sm)", color: "var(--text)",
  background: "var(--surface-2)", border: "1.5px solid var(--hairline)", outline: "none",
  transition: "border-color .15s ease",
};
function TextInput(props) {
  return <input {...props} className="wmc-input" style={{ ...inputStyle, ...(props.style || {}) }} />;
}
function TextArea(props) {
  return <textarea {...props} className="wmc-input" style={{ ...inputStyle, resize: "none", minHeight: 76, ...(props.style || {}) }} />;
}

// ── Segmented control ────────────────────────────────────────
function Segmented({ options, value, onChange, style = {} }) {
  return (
    <div style={{
      display: "grid", gridAutoFlow: "column", gridAutoColumns: "1fr", gap: 3,
      background: "var(--surface-2)", padding: 3, borderRadius: "var(--radius-sm)", ...style,
    }}>
      {options.map((o) => {
        const v = typeof o === "string" ? o : o.value;
        const lab = typeof o === "string" ? o : o.label;
        const on = v === value;
        return (
          <button key={v} className="wmc-btn" onClick={() => onChange(v)} style={{
            border: "none", cursor: "pointer", fontWeight: 600, fontSize: 14, font: "inherit",
            padding: "9px 6px", borderRadius: "calc(var(--radius-sm) - 3px)",
            background: on ? "var(--surface-raise)" : "transparent",
            color: on ? "var(--text)" : "var(--text-2)",
            boxShadow: on ? "0 1px 3px rgba(0,0,0,.25)" : "none",
            transition: "background .15s ease, color .15s ease",
          }}>{lab}</button>
        );
      })}
    </div>
  );
}

// ── Horizontal car selector ──────────────────────────────────
function CarSelector({ cars, selectedId, onSelect }) {
  return (
    <div style={{ display: "flex", gap: 9, overflowX: "auto", padding: "2px 0 4px", margin: "0 -2px" }} className="wmc-noscroll">
      {cars.map((c) => {
        const Glyph = carGlyph(c.emoji);
        const on = c.id === selectedId;
        return (
          <button key={c.id} className="wmc-btn" onClick={() => onSelect(c.id)} style={{
            display: "flex", alignItems: "center", gap: 9, flexShrink: 0, cursor: "pointer",
            padding: "9px 15px 9px 11px", borderRadius: 999, font: "inherit", fontSize: 15, fontWeight: 650,
            border: on ? "1.5px solid var(--accent)" : "1.5px solid var(--hairline)",
            background: on ? "var(--accent-soft)" : "var(--surface)",
            color: on ? "var(--accent-ink)" : "var(--text-2)",
            transition: "all .15s ease",
          }}>
            <span style={{
              width: 28, height: 28, borderRadius: 8, display: "grid", placeItems: "center",
              background: c.color, color: pickInk(c.color), flexShrink: 0,
            }}><Glyph size={17} sw={2} /></span>
            {c.name}
          </button>
        );
      })}
    </div>
  );
}

// pick black/white ink for a colored chip
function pickInk(hex) {
  const h = hex.replace("#", "");
  if (h.length < 6) return "#fff";
  const r = parseInt(h.slice(0, 2), 16), g = parseInt(h.slice(2, 4), 16), b = parseInt(h.slice(4, 6), 16);
  const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
  return lum > 0.62 ? "#1a1a1a" : "#ffffff";
}

function EmptyState({ icon, title, body, action }) {
  return (
    <div style={{ textAlign: "center", padding: "44px 26px", color: "var(--text-2)" }}>
      <div style={{
        width: 66, height: 66, borderRadius: 20, margin: "0 auto 16px", display: "grid", placeItems: "center",
        background: "var(--surface-2)", color: "var(--text-3)",
      }}>{icon}</div>
      <div style={{ fontSize: 18, fontWeight: 700, color: "var(--text)", marginBottom: 6 }}>{title}</div>
      <div style={{ fontSize: 14.5, lineHeight: 1.5, maxWidth: 260, margin: "0 auto", color: "var(--text-2)" }}>{body}</div>
      {action && <div style={{ marginTop: 20 }}>{action}</div>}
    </div>
  );
}

function SectionLabel({ children, style = {} }) {
  return <div style={{
    fontSize: 12.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.7,
    color: "var(--text-3)", margin: "4px 2px 10px", ...style,
  }}>{children}</div>;
}

// ── Toast ────────────────────────────────────────────────────
function toast(message, opts = {}) {
  window.dispatchEvent(new CustomEvent("wmc-toast", { detail: { message, ...opts } }));
}
function ToastHost() {
  const [items, setItems] = React.useState([]);
  React.useEffect(() => {
    const h = (e) => {
      const id = Math.random().toString(36).slice(2);
      setItems((s) => [...s, { id, ...e.detail }]);
      setTimeout(() => setItems((s) => s.filter((i) => i.id !== id)), e.detail.duration || 2400);
    };
    window.addEventListener("wmc-toast", h);
    return () => window.removeEventListener("wmc-toast", h);
  }, []);
  return (
    <div style={{
      position: "absolute", left: 0, right: 0, bottom: "calc(96px + var(--safe-bottom))", zIndex: 300,
      display: "flex", flexDirection: "column", alignItems: "center", gap: 8, pointerEvents: "none",
    }}>
      {items.map((i) => (
        <div key={i.id} className="wmc-toast" style={{
          background: "var(--toast-bg)", color: "var(--toast-ink)", borderRadius: 999,
          padding: "11px 18px", fontSize: 14.5, fontWeight: 600, maxWidth: "82%",
          boxShadow: "0 8px 24px rgba(0,0,0,.35)", display: "flex", alignItems: "center", gap: 8,
        }}>{i.icon}{i.message}</div>
      ))}
    </div>
  );
}

Object.assign(window, {
  AppButton, IconButton, Card, ColorDot, Sheet, Field, TextInput, TextArea,
  Segmented, CarSelector, pickInk, EmptyState, SectionLabel, toast, ToastHost, inputStyle,
});
