/* ============ CORE primitives (tenant-agnostic) ============
   These never reference a brand or a district. Brand-bearing chrome lives in chrome.jsx. */

/* ============ Icons ============ */
function Icon({ name, size = 20, stroke = 2, style }) {
  const p = {
    parent: <><circle cx="9" cy="7" r="3.2"/><path d="M3.5 20c0-3.3 2.5-5.5 5.5-5.5s5.5 2.2 5.5 5.5"/><circle cx="17" cy="9" r="2.4"/><path d="M15 20c0-2.4 1.2-4 3.5-4 1 0 1.8.3 2.4.8"/></>,
    student: <><path d="M12 4 2.5 8.5 12 13l9.5-4.5L12 4Z"/><path d="M6 10.5V15c0 1.4 2.7 2.8 6 2.8s6-1.4 6-2.8v-4.5"/><path d="M21.5 8.5v5"/></>,
    teacher: <><path d="M4 5.5A1.5 1.5 0 0 1 5.5 4H19a1 1 0 0 1 1 1v11H5.5A1.5 1.5 0 0 0 4 17.5Z"/><path d="M4 17.5A1.5 1.5 0 0 1 5.5 16H20v3a1 1 0 0 1-1 1H5.5A1.5 1.5 0 0 1 4 18.5Z"/><path d="M9 8.5h7M9 11.5h5"/></>,
    official: <><path d="M3 21h18"/><path d="M5 21V9.5L12 5l7 4.5V21"/><path d="M9.5 21v-5h5v5"/><path d="M12 3v2"/></>,
    campus: <><path d="M3 21h18"/><path d="M5 21V7l7-3 7 3v14"/><path d="M9 11h2M13 11h2M9 15h2M13 15h2"/></>,
    teacherP: <><circle cx="12" cy="8" r="3.4"/><path d="M5.5 20c0-3.6 2.9-6 6.5-6s6.5 2.4 6.5 6"/></>,
    link: <><path d="M9.5 14.5 14.5 9.5"/><path d="M8 12 6 14a3.5 3.5 0 0 0 5 5l2-2"/><path d="M16 12l2-2a3.5 3.5 0 0 0-5-5l-2 2"/></>,
    mail: <><rect x="3" y="5" width="18" height="14" rx="2.5"/><path d="m4 7 8 5.5L20 7"/></>,
    key: <><circle cx="8" cy="14" r="4"/><path d="m11 11 8-8"/><path d="m16 6 2 2M14 8l2 2"/></>,
    check: <path d="M5 12.5 10 17.5 19.5 7"/>,
    plus: <><path d="M12 5v14M5 12h14"/></>,
    chevDown: <path d="m6 9 6 6 6-6"/>,
    chevRight: <path d="m9 6 6 6-6 6"/>,
    chevLeft: <path d="m15 6-6 6 6 6"/>,
    pin: <><path d="M12 21c4.5-4.3 7-7.6 7-11a7 7 0 1 0-14 0c0 3.4 2.5 6.7 7 11Z"/><circle cx="12" cy="10" r="2.5"/></>,
    phone: <path d="M6.5 3.5h3l1.5 4-2 1.5a11 11 0 0 0 5 5l1.5-2 4 1.5v3a2 2 0 0 1-2.2 2A16.5 16.5 0 0 1 4.5 5.7 2 2 0 0 1 6.5 3.5Z"/>,
    cart: <><circle cx="9.5" cy="20" r="1.4"/><circle cx="17.5" cy="20" r="1.4"/><path d="M3 4h2l2.2 11.2a1.5 1.5 0 0 0 1.5 1.2h8.4a1.5 1.5 0 0 0 1.5-1.2L20.5 8H6"/></>,
    login: <><path d="M14 4h4a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-4"/><path d="M10 8l4 4-4 4M4 12h10"/></>,
    user: <><circle cx="12" cy="8" r="3.6"/><path d="M5 20c0-3.7 3-6.3 7-6.3s7 2.6 7 6.3"/></>,
    edit: <><path d="M4 20h4l10-10-4-4L4 16Z"/><path d="m13.5 6.5 4 4"/></>,
    trash: <><path d="M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"/></>,
    send: <path d="M21 3 3 10.5l6.5 2.5L12 20l3-7 6-10Z"/>,
    info: <><circle cx="12" cy="12" r="9"/><path d="M12 11v5M12 7.5v.5"/></>,
    search: <><circle cx="11" cy="11" r="6.5"/><path d="m20 20-3.5-3.5"/></>,
    sparkle: <path d="M12 3.5 13.7 9l5.5 1.7-5.5 1.7L12 18l-1.7-5.6L4.8 10.7 10.3 9 12 3.5Z"/>,
    shop: <><path d="M5 8h14l-1 12H6L5 8Z"/><path d="M8.5 8V6a3.5 3.5 0 0 1 7 0v2"/></>,
    arrowR: <path d="M5 12h14M13 6l6 6-6 6"/>,
    clock: <><circle cx="12" cy="12" r="9"/><path d="M12 7.5V12l3 2"/></>,
    grid: <><rect x="4" y="4" width="6.5" height="6.5" rx="1.4"/><rect x="13.5" y="4" width="6.5" height="6.5" rx="1.4"/><rect x="4" y="13.5" width="6.5" height="6.5" rx="1.4"/><rect x="13.5" y="13.5" width="6.5" height="6.5" rx="1.4"/></>,
    grad: <><path d="M12 4 2.5 8.5 12 13l9.5-4.5L12 4Z"/><path d="M6 10.5V15c0 1.4 2.7 2.8 6 2.8s6-1.4 6-2.8v-4.5"/></>,
  }[name];
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" style={style}>{p}</svg>
  );
}

/* ============ Logo star mark (colors come from the active district branding) ============ */
function StarMark({ size = 22, primary = "#E8821E", secondary = "#0A3A75" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
      <path d="M16 2.5c1.6 4.2 3 6 6.8 6.6-3.4 1.7-4.8 3.3-5.2 7.2-1-3.6-2.3-5.2-5.7-6.2 3.2-1.3 3.4-3.6 4.1-7.6Z" fill={primary}/>
      <path d="M11 14c1.1 2.9 2 4.2 4.7 4.6-2.4 1.2-3.3 2.3-3.6 5-0.7-2.5-1.6-3.6-4-4.3 2.2-0.9 2.4-2.5 2.9-5.3Z" fill={secondary}/>
      <g fill={secondary}><circle cx="6" cy="9" r="1"/><circle cx="25" cy="20" r="1"/><circle cx="22" cy="26" r="1"/><circle cx="8" cy="25" r="1"/></g>
    </svg>
  );
}

/* ============ Stepper ============ */
function Stepper({ steps, current }) {
  return (
    <div className="stepper">
      {steps.map((s, i) => {
        const cls = i < current ? "done" : i === current ? "active" : "";
        return (
          <div className={"step " + cls} key={s}>
            <div className="step-dot">{i < current ? <Icon name="check" size={15} stroke={2.6} /> : i + 1}</div>
            <div className="step-label">{s}</div>
            {i < steps.length - 1 && <div className="step-line" />}
          </div>
        );
      })}
    </div>
  );
}

/* ============ Buttons / primitives ============ */
function Btn({ kind = "primary", size, block, icon, iconR, children, ...rest }) {
  const cls = ["btn", "btn-" + kind, size === "sm" ? "btn-sm" : "", block ? "btn-block" : ""].join(" ");
  return (
    <button className={cls} {...rest}>
      {icon && <Icon name={icon} size={size === "sm" ? 16 : 18} />}
      {children}
      {iconR && <Icon name={iconR} size={size === "sm" ? 16 : 18} />}
    </button>
  );
}

const DEFAULT_AVATAR_PALETTE = ["#1C6FE0", "#E8821E", "#1E9E62", "#7A4FD0", "#D0457A", "#0E8FA8"];
function Avatar({ name = "", size = 40, seed = 0, palette }) {
  const pal = palette && palette.length ? palette : DEFAULT_AVATAR_PALETTE;
  const bg = pal[(seed + name.length) % pal.length];
  const initials = name.split(" ").filter(Boolean).slice(0, 2).map((w) => w[0]).join("").toUpperCase() || "?";
  return <div className="avatar" style={{ width: size, height: size, background: bg, fontSize: size * 0.4 }}>{initials}</div>;
}

function Chip({ kind = "neutral", icon, children }) {
  return <span className={"chip " + kind}>{icon && <Icon name={icon} size={13} stroke={2.4} />}{children}</span>;
}

function Field({ label, required, optional, hint, children }) {
  return (
    <div className="field">
      {label && (
        <label className="field-label">
          {label}
          {required && <span className="req">*</span>}
          {optional && <span className="opt">Optional</span>}
        </label>
      )}
      {children}
      {hint && <div className="field-hint">{hint}</div>}
    </div>
  );
}

function Callout({ icon = "info", warm, children }) {
  return (
    <div className={"callout" + (warm ? " warm" : "")}>
      <span className="c-ic"><Icon name={icon} size={19} /></span>
      <div className="c-tx">{children}</div>
    </div>
  );
}

/* ============ Combobox (searchable select) ============ */
function Combo({ value, onChange, options, placeholder = "Select…", groups, filled, renderTrigger }) {
  const [open, setOpen] = React.useState(false);
  const [q, setQ] = React.useState("");
  const ref = React.useRef(null);
  React.useEffect(() => {
    function h(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  const sel = options.find((o) => String(o.value) === String(value));
  const filtered = options.filter((o) => (o.label + " " + (o.sub || "")).toLowerCase().includes(q.toLowerCase()));
  let grouped;
  if (groups) {
    const groupIds = groups.map((g) => g.id);
    grouped = groups.map((g) => ({ ...g, items: filtered.filter((o) => o.group === g.id) })).filter((g) => g.items.length);
    const orphans = filtered.filter((o) => !groupIds.includes(o.group)); // region-less campuses, etc.
    if (orphans.length) grouped.push({ id: "_other", label: "Other", items: orphans });
  } else {
    grouped = [{ id: "_", label: null, items: filtered }];
  }
  return (
    <div className="combo" ref={ref}>
      <div className={"control combo-trigger" + (filled && sel ? " filled" : "")} onClick={() => setOpen((v) => !v)} tabIndex={0}>
        <div style={{ minWidth: 0 }}>
          {sel ? (renderTrigger ? renderTrigger(sel) : <><div className="ct-main">{sel.label}</div>{sel.sub && <div className="ct-sub">{sel.sub}</div>}</>)
               : <span className="ct-placeholder">{placeholder}</span>}
        </div>
        <Icon name="chevDown" size={18} style={{ color: "var(--muted)", flex: "none" }} />
      </div>
      {open && (
        <div className="combo-pop">
          <div className="combo-search">
            <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="Type to search…" />
          </div>
          <div className="combo-list">
            {grouped.length === 0 && <div className="combo-empty">No matches</div>}
            {grouped.map((g) => (
              <div key={g.id}>
                {g.label && <div className="combo-group">{g.label}</div>}
                {g.items.map((o) => (
                  <div key={o.value} className={"combo-opt" + (String(o.value) === String(value) ? " sel" : "")}
                    onClick={() => { onChange(o.value); setOpen(false); setQ(""); }}>
                    {o.icon && <span style={{ color: "var(--blue-600)" }}><Icon name={o.icon} size={18} /></span>}
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div className="co-main">{o.label}</div>
                      {o.sub && <div className="co-sub">{o.sub}</div>}
                    </div>
                    {String(o.value) === String(value) && <Icon name="check" size={17} stroke={2.6} style={{ color: "var(--blue-600)" }} />}
                  </div>
                ))}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

/* ============ Toast host ============ */
function Toasts({ items }) {
  return (
    <div className="toast-wrap">
      {items.map((t) => (
        <div className="toast" key={t.id}>
          <span className="ti"><Icon name={t.icon || "check"} size={18} stroke={2.6} /></span>{t.msg}
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { Icon, StarMark, Stepper, Btn, Avatar, DEFAULT_AVATAR_PALETTE, Chip, Field, Callout, Combo, Toasts });
