// Pill button component
const Button = ({ kind = "secondary", size = "md", icon, iconRight, children, onClick, style = {}, disabled }) => {
  const sizes = {
    sm: { height: 28, fontSize: 13, padding: "0 12px" },
    md: { height: 32, fontSize: 14, padding: "0 14px" },
    lg: { height: 36, fontSize: 14, padding: "0 18px" },
  };
  const kinds = {
    primary: { background: "var(--mw-brand-500)", color: "#fff", border: "0", boxShadow: "var(--mw-shadow-button)" },
    secondary: { background: "#fff", color: "var(--mw-text-secondary)", border: "1px solid var(--mw-border-strong)" },
    ghost: { background: "transparent", color: "var(--mw-text-secondary)", border: "0" },
    destructive: { background: "var(--mw-danger)", color: "#fff", border: "0", boxShadow: "var(--mw-shadow-button)" },
    brand: { background: "#fff", color: "var(--mw-brand-500)", border: "1px solid var(--mw-brand-500)" },
  };
  return (
    <button onClick={disabled ? undefined : onClick} disabled={disabled} style={{
      ...sizes[size], ...kinds[kind], ...style,
      borderRadius: 9999, fontFamily: "inherit", fontWeight: 500, cursor: disabled ? "not-allowed" : "pointer",
      display: "inline-flex", alignItems: "center", gap: 6, lineHeight: 1, transition: "all 120ms",
      opacity: disabled ? 0.5 : 1, whiteSpace: "nowrap"
    }}>
      {icon && <img src={`assets/icons/${icon}.svg`} style={{ width: 14, height: 14, filter: kind === "primary" || kind === "destructive" ? "brightness(0) invert(1)" : "none" }} />}
      {children}
      {iconRight && <img src={`assets/icons/${iconRight}.svg`} style={{ width: 14, height: 14, filter: kind === "primary" || kind === "destructive" ? "brightness(0) invert(1)" : "none" }} />}
    </button>
  );
};

const Chip = ({ tone = "neutral", children, dot, style = {}, size = "md" }) => {
  const tones = {
    success: { bg: "#DAF0E0", fg: "#22863A" },
    warning: { bg: "#FFF9E0", fg: "#B2791A" },
    danger:  { bg: "#FCE2E2", fg: "#C02F32" },
    info:    { bg: "#E8E9F6", fg: "#534AFF" },
    purple:  { bg: "#F0E8FF", fg: "#7B3DCC" },
    neutral: { bg: "#F1F2F4", fg: "#6A7383" },
    indigoSoft: { bg: "rgba(232,233,246,.7)", fg: "#534AFF" },
  };
  const t = tones[tone] || tones.neutral;
  const sizes = {
    sm: { padding: "1px 6px", fontSize: 11 },
    md: { padding: "2px 8px", fontSize: 12 },
  };
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 4,
      borderRadius: 6, fontWeight: 500,
      background: t.bg, color: t.fg, lineHeight: 1.4,
      ...sizes[size], ...style
    }}>
      {dot && <span style={{ width: 6, height: 6, borderRadius: "50%", background: t.fg }} />}
      {children}
    </span>
  );
};

const Avatar = ({ initials = "NM", color = "#76ADFF", size = 32, image }) => (
  <div style={{
    width: size, height: size, borderRadius: "50%", background: image ? `center/cover url(${image})` : color,
    color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center",
    fontSize: size * 0.36, fontWeight: 600, flexShrink: 0,
  }}>
    {!image && initials}
  </div>
);

// Form atoms ---------------------------------------------------------------

const Label = ({ children, required, hint, htmlFor }) => (
  <label htmlFor={htmlFor} style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 12, fontWeight: 500, color: "var(--mw-text-secondary)", marginBottom: 6 }}>
    <span>{children}{required && <span style={{ color: "var(--mw-danger)", marginLeft: 2 }}>*</span>}</span>
    {hint && (
      <span title={hint} style={{ display: "inline-flex" }}>
        <img src="assets/icons/infoCircle.svg" style={{ width: 12, height: 12, opacity: 0.5 }} />
      </span>
    )}
  </label>
);

const Input = ({ value, onChange, placeholder, prefix, suffix, type = "text", style = {}, id, error, disabled }) => (
  <div style={{
    display: "flex", alignItems: "center", height: 32, padding: "0 10px",
    border: `1px solid ${error ? "var(--mw-danger)" : "var(--mw-border-strong)"}`, borderRadius: 8,
    background: disabled ? "var(--mw-bg)" : "#fff", fontSize: 14, opacity: disabled ? 0.6 : 1, ...style
  }} className="mw-input-wrap">
    {prefix && <span style={{ color: "var(--mw-text-tertiary)", marginRight: 6, fontSize: 13 }}>{prefix}</span>}
    <input id={id} value={value ?? ""} onChange={onChange} placeholder={placeholder} type={type} disabled={disabled}
      style={{ flex: 1, border: 0, outline: 0, background: "transparent", fontFamily: "inherit", fontSize: 14, color: "var(--mw-text-primary)", minWidth: 0, cursor: disabled ? "not-allowed" : "text" }} />
    {suffix && <span style={{ color: "var(--mw-text-tertiary)", marginLeft: 6, fontSize: 13 }}>{suffix}</span>}
  </div>
);

const Textarea = ({ value, onChange, placeholder, rows = 3, style = {} }) => (
  <textarea value={value ?? ""} onChange={onChange} placeholder={placeholder} rows={rows}
    style={{
      width: "100%", padding: "8px 10px", border: "1px solid var(--mw-border-strong)", borderRadius: 8,
      background: "#fff", fontSize: 14, fontFamily: "inherit", outline: 0, resize: "vertical",
      color: "var(--mw-text-primary)", lineHeight: 1.5, ...style
    }} />
);

const Select = ({ value, onChange, options, placeholder = "Select…", style = {}, disabled }) => (
  <div style={{ position: "relative", opacity: disabled ? 0.6 : 1, ...style }}>
    <select value={value ?? ""} onChange={onChange} disabled={disabled}
      style={{
        appearance: "none", width: "100%", height: 32, padding: "0 32px 0 10px",
        border: "1px solid var(--mw-border-strong)", borderRadius: 8, background: disabled ? "var(--mw-bg)" : "#fff",
        fontSize: 14, fontFamily: "inherit", color: value ? "var(--mw-text-primary)" : "var(--mw-text-tertiary)",
        cursor: disabled ? "not-allowed" : "pointer", outline: 0
      }}>
      {!value && <option value="" disabled>{placeholder}</option>}
      {options.map(o => typeof o === "string"
        ? <option key={o} value={o}>{o}</option>
        : <option key={o.value} value={o.value}>{o.label}</option>)}
    </select>
    <img src="assets/icons/expandDown.svg" style={{ position: "absolute", right: 10, top: 10, width: 12, height: 12, opacity: 0.5, pointerEvents: "none" }} />
  </div>
);

const Toggle = ({ checked, onChange, size = "md", disabled }) => {
  const w = size === "sm" ? 28 : 32, h = size === "sm" ? 16 : 18, k = size === "sm" ? 12 : 14;
  return (
    <button onClick={() => !disabled && onChange && onChange(!checked)} role="switch" aria-checked={checked} disabled={disabled}
      style={{
        width: w, height: h, borderRadius: 9999, border: 0, padding: 0, position: "relative",
        background: checked ? "var(--mw-brand-500)" : "rgb(213,219,225)",
        cursor: disabled ? "not-allowed" : "pointer", transition: "background 120ms", flexShrink: 0,
        opacity: disabled ? 0.5 : 1
      }}>
      <span style={{
        position: "absolute", top: 2, left: checked ? w - k - 2 : 2, width: k, height: k,
        borderRadius: "50%", background: "#fff", boxShadow: "0 1px 2px rgba(0,0,0,.2)",
        transition: "left 140ms cubic-bezier(0.2,0.6,0.2,1)"
      }} />
    </button>
  );
};

// Field row in a form: label + control + helper
const FormRow = ({ label, required, hint, children, helper, style = {} }) => (
  <div style={{ display: "flex", flexDirection: "column", ...style }}>
    {label && <Label required={required} hint={hint}>{label}</Label>}
    {children}
    {helper && <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", marginTop: 4 }}>{helper}</div>}
  </div>
);

// Inline toggle row (label left, helper below, toggle right)
const ToggleRow = ({ title, description, checked, onChange, disabled }) => (
  <div style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: "12px 0", opacity: disabled ? 0.55 : 1 }}>
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 14, fontWeight: 500, color: "var(--mw-text-primary)" }}>{title}</div>
      {description && <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", marginTop: 2, lineHeight: 1.5 }}>{description}</div>}
    </div>
    <Toggle checked={checked} onChange={onChange} disabled={disabled} />
  </div>
);

// Read-only field (record detail)
const Field = ({ label, value, placeholder = "Click to Add", icon, iconBefore }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
    <span style={{ fontSize: 12, color: "var(--mw-text-tertiary)", display: "inline-flex", alignItems: "center", gap: 4 }}>
      {label}
      {icon && <img src={`assets/icons/${icon}.svg`} style={{ width: 12, height: 12, opacity: 0.6 }} />}
    </span>
    <div style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 14, color: value ? "var(--mw-text-primary)" : "var(--mw-text-quaternary)" }}>
      {iconBefore}
      {value || placeholder}
    </div>
  </div>
);

// Shipping-type icon (drawn inline so we don't depend on a missing asset)
const ShippingTypeIcon = ({ type, size = 20, color }) => {
  const c = color || "currentColor";
  const s = { width: size, height: size, fill: "none", stroke: c, strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" };
  const icons = {
    Parcel: <svg viewBox="0 0 24 24" style={s}><path d="M3 7.5 12 3l9 4.5v9L12 21 3 16.5z"/><path d="M3 7.5 12 12l9-4.5"/><path d="M12 12v9"/><path d="m7.5 5.25 9 4.5"/></svg>,
    "LTL Freight": <svg viewBox="0 0 24 24" style={s}><rect x="2" y="7" width="11" height="9" rx="1"/><path d="M13 10h5l3 3v3h-8z"/><circle cx="7" cy="18" r="1.6"/><circle cx="17" cy="18" r="1.6"/></svg>,
    "FTL Freight": <svg viewBox="0 0 24 24" style={s}><rect x="2" y="6" width="12" height="10" rx="1"/><path d="M14 9h4l3 3v4h-7z"/><circle cx="7" cy="18" r="1.6"/><circle cx="17" cy="18" r="1.6"/></svg>,
    "Ocean Freight": <svg viewBox="0 0 24 24" style={s}><path d="M3 17c2 1.5 4 1.5 6 0s4-1.5 6 0 4 1.5 6 0"/><path d="M4 14h16l-2 3H6z"/><path d="M12 4v10"/><path d="M9 7h6"/></svg>,
    "Air Freight": <svg viewBox="0 0 24 24" style={s}><path d="M21 12 3 19l4-7-4-7z"/><path d="m7 12 14 0"/></svg>,
    "Local Delivery": <svg viewBox="0 0 24 24" style={s}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>,
    "Customer Pickup": <svg viewBox="0 0 24 24" style={s}><path d="M3 10h18l-1.5 9a2 2 0 0 1-2 2h-11a2 2 0 0 1-2-2z"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/></svg>,
    "Digital / No Shipment": <svg viewBox="0 0 24 24" style={s}><rect x="3" y="5" width="18" height="12" rx="1.5"/><path d="M3 9h18"/><path d="M8 21h8"/><path d="M12 17v4"/></svg>,
    Other: <svg viewBox="0 0 24 24" style={s}><circle cx="12" cy="12" r="9"/><path d="M9.5 9a2.5 2.5 0 1 1 3.5 2.3c-.7.3-1 .8-1 1.7"/><path d="M12 16.5h.01"/></svg>,
  };
  return icons[type] || icons.Other;
};

const TypeEmblem = ({ type, size = 36 }) => {
  const palette = {
    Parcel:                { bg: "#FFF4EC", fg: "#FF8A3D" },
    "LTL Freight":         { bg: "#EEF1FF", fg: "#534AFF" },
    "FTL Freight":         { bg: "#E7EEFF", fg: "#3B7FFF" },
    "Ocean Freight":       { bg: "#E5F4FB", fg: "#0E94CC" },
    "Air Freight":         { bg: "#F4ECFF", fg: "#7B3DCC" },
    "Local Delivery":      { bg: "#E7F6EC", fg: "#22863A" },
    "Customer Pickup":     { bg: "#FFF6E0", fg: "#B2791A" },
    "Digital / No Shipment":{ bg: "#F1F2F4", fg: "#6A7383" },
    Other:                 { bg: "#F1F2F4", fg: "#6A7383" },
  };
  const p = palette[type] || palette.Other;
  return (
    <div style={{
      width: size, height: size, borderRadius: 8, background: p.bg,
      display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0
    }}>
      <ShippingTypeIcon type={type} color={p.fg} size={Math.round(size * 0.55)} />
    </div>
  );
};

window.Button = Button;
window.Chip = Chip;
window.Avatar = Avatar;
window.Label = Label;
window.Input = Input;
window.Textarea = Textarea;
window.Select = Select;
window.Toggle = Toggle;
window.FormRow = FormRow;
window.ToggleRow = ToggleRow;
window.Field = Field;
window.ShippingTypeIcon = ShippingTypeIcon;
window.TypeEmblem = TypeEmblem;
