// ───────────────────────────────────────────────────────────────
// Busco Ops — shared components (v2)
// Top-nav shell, no emoji, larger logo, denser primitives.
// ───────────────────────────────────────────────────────────────

const { useState, useEffect, useRef, useMemo } = React;

// ── Icon set (Lucide-style) ───────────────────────────────────
function Icon({ name, size = 14, color = "currentColor", className = "", strokeWidth }) {
  const props = {
    width: size, height: size, viewBox: "0 0 24 24",
    fill: "none", stroke: color, strokeWidth: strokeWidth || 1.75,
    strokeLinecap: "round", strokeLinejoin: "round",
    className
  };
  switch (name) {
    case "layout":return <svg {...props}><rect x="3" y="3" width="7" height="9" rx="1.5" /><rect x="14" y="3" width="7" height="5" rx="1.5" /><rect x="14" y="12" width="7" height="9" rx="1.5" /><rect x="3" y="16" width="7" height="5" rx="1.5" /></svg>;
    case "clipboard":return <svg {...props}><rect x="8" y="3" width="8" height="4" rx="1" /><path d="M8 5H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-3" /><path d="M7 11h10M7 15h7" /></svg>;
    case "building":return <svg {...props}><rect x="4" y="2" width="16" height="20" rx="1.5" /><path d="M8 6h2M14 6h2M8 10h2M14 10h2M8 14h2M14 14h2M10 22v-4h4v4" /></svg>;
    case "truck":return <svg {...props}><path d="M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2" /><path d="M15 18H9" /><path d="M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14" /><circle cx="7" cy="18" r="2" /><circle cx="17" cy="18" r="2" /></svg>;
    case "bell":return <svg {...props}><path d="M6 8a6 6 0 1 1 12 0c0 7 3 9 3 9H3s3-2 3-9" /><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" /></svg>;
    case "wallet":return <svg {...props}><path d="M19 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-2" /><path d="M3 5v14" /><path d="M22 12h-6a2 2 0 0 0 0 4h6V12z" /></svg>;
    case "users":return <svg {...props}><circle cx="9" cy="8" r="3.5" /><path d="M3 21a6 6 0 0 1 12 0" /><circle cx="17" cy="7" r="2.5" /><path d="M16 13a4 4 0 0 1 5 4" /></svg>;
    case "upload":return <svg {...props}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><path d="M17 8l-5-5-5 5" /><path d="M12 3v12" /></svg>;
    case "check":return <svg {...props}><polyline points="20 6 9 17 4 12" /></svg>;
    case "check-circle":return <svg {...props}><circle cx="12" cy="12" r="10" /><path d="m8 12 3 3 5-6" /></svg>;
    case "package":return <svg {...props}><path d="M16.5 9.4 7.55 4.24" /><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" /><path d="m3.27 6.96 8.73 5.05 8.73-5.05M12 22.08V12" /></svg>;
    case "trend":return <svg {...props}><path d="m3 17 6-6 4 4 8-8" /><path d="M14 7h7v7" /></svg>;
    case "trend-down":return <svg {...props}><path d="m3 7 6 6 4-4 8 8" /><path d="M14 17h7v-7" /></svg>;
    case "alert":return <svg {...props}><path d="m12 3 10 18H2L12 3z" /><path d="M12 9v5M12 17h.01" /></svg>;
    case "alert-circle":return <svg {...props}><circle cx="12" cy="12" r="10" /><path d="M12 8v4M12 16h.01" /></svg>;
    case "file":return <svg {...props}><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><path d="M14 2v6h6" /></svg>;
    case "search":return <svg {...props}><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></svg>;
    case "x":return <svg {...props}><path d="M18 6 6 18M6 6l12 12" /></svg>;
    case "lock":return <svg {...props}><rect x="4" y="11" width="16" height="10" rx="2" /><path d="M8 11V8a4 4 0 0 1 8 0v3" /></svg>;
    case "unlock":return <svg {...props}><rect x="4" y="11" width="16" height="10" rx="2" /><path d="M8 11V8a4 4 0 0 1 7.5-2" /></svg>;
    case "plus":return <svg {...props}><path d="M12 5v14M5 12h14" /></svg>;
    case "minus":return <svg {...props}><path d="M5 12h14" /></svg>;
    case "edit":return <svg {...props}><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" /><path d="m18.5 2.5 3 3L12 15l-4 1 1-4 9.5-9.5z" /></svg>;
    case "trash":return <svg {...props}><path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M5 6l1 14a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2l1-14" /></svg>;
    case "send":return <svg {...props}><path d="m22 2-7 20-4-9-9-4 20-7z" /><path d="M22 2 11 13" /></svg>;
    case "arrow-right":return <svg {...props}><path d="M5 12h14M13 5l7 7-7 7" /></svg>;
    case "trophy":return <svg {...props}><path d="M8 21h8M12 17v4M7 4h10v5a5 5 0 0 1-10 0V4z" /><path d="M17 4h3v3a3 3 0 0 1-3 3M7 4H4v3a3 3 0 0 0 3 3" /></svg>;
    case "flag":return <svg {...props}><path d="M4 22V4M4 4h13l-2 4 2 4H4" /></svg>;
    case "filter":return <svg {...props}><path d="M22 3H2l8 9.46V19l4 2v-8.54L22 3z" /></svg>;
    case "calendar":return <svg {...props}><rect x="3" y="5" width="18" height="16" rx="2" /><path d="M16 3v4M8 3v4M3 11h18" /></svg>;
    case "mail":return <svg {...props}><rect x="2" y="5" width="20" height="14" rx="2" /><path d="m2 7 10 7 10-7" /></svg>;
    case "phone":return <svg {...props}><path d="M22 16.92v3a2 2 0 0 1-2.18 2A19.79 19.79 0 0 1 2 4.18 2 2 0 0 1 4 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8 10a16 16 0 0 0 6 6l1.36-1.36a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z" /></svg>;
    case "down":return <svg {...props}><path d="m6 9 6 6 6-6" /></svg>;
    case "up":return <svg {...props}><path d="m6 15 6-6 6 6" /></svg>;
    case "chevron-right":return <svg {...props}><path d="m9 6 6 6-6 6" /></svg>;
    case "chevron-down":return <svg {...props}><path d="m6 9 6 6 6-6" /></svg>;
    case "more":return <svg {...props}><circle cx="5" cy="12" r="1.5" /><circle cx="12" cy="12" r="1.5" /><circle cx="19" cy="12" r="1.5" /></svg>;
    case "info":return <svg {...props}><circle cx="12" cy="12" r="10" /><path d="M12 16v-4M12 8h.01" /></svg>;
    case "briefcase":return <svg {...props}><rect x="2" y="7" width="20" height="14" rx="2" /><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16" /></svg>;
    case "tool":return <svg {...props}><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z" /></svg>;
    case "settings":return <svg {...props}><circle cx="12" cy="12" r="3" /><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" /></svg>;
    case "export":return <svg {...props}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><path d="M7 10l5 5 5-5" /><path d="M12 15V3" /></svg>;
    case "kanban":return <svg {...props}><rect x="3" y="3" width="18" height="18" rx="2" /><path d="M8 7v10M16 7v6" /></svg>;
    case "refresh":return <svg {...props}><path d="M21 12a9 9 0 0 1-15 6.7l-3-2.7M3 12a9 9 0 0 1 15-6.7l3 2.7" /><path d="M21 3v6h-6M3 21v-6h6" /></svg>;
    case "list":return <svg {...props}><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01" /></svg>;
    case "grid":return <svg {...props}><rect x="3" y="3" width="7" height="7" /><rect x="14" y="3" width="7" height="7" /><rect x="3" y="14" width="7" height="7" /><rect x="14" y="14" width="7" height="7" /></svg>;
    case "office":return <svg {...props}><path d="M3 21h18M5 21V7l8-4v18M19 21V11l-6-4" /><path d="M9 9v.01M9 13v.01M9 17v.01" /></svg>;
    default:return null;
  }
}

// ── Section nav config ────────────────────────────────────────
const SECTIONS = [
{ id: "hub", label: "Overview", icon: "layout" },
{ id: "log", label: "Operations", icon: "clipboard" },
{ id: "clients", label: "Clients", icon: "office" },
{ id: "couriers", label: "Couriers", icon: "truck" },
{ id: "alerts", label: "Alerts", icon: "bell" },
{ id: "users", label: "Users", icon: "users" },
{ id: "financial", label: "Financial", icon: "wallet", pin: true }];


// ── Header ────────────────────────────────────────────────────
function Header({ user, workspace, onWorkspaceChange, onRequestSignIn, onSignOut }) {
  return (
    <div className="header" data-comment-anchor="6e7904fb47-div-80-5">
      <div className="brand">
        <div className="brand-logo">
          <img src="assets/busco-logo.png" alt="Busco Shipping Company" data-comment-anchor="a140f1f8ff-img-82-11" />
        </div>
      </div>

      <WorkspaceChip workspace={workspace} onChange={onWorkspaceChange} />

      <div style={{ flex: 1 }} />

      <UserMenu user={user} workspace={workspace} onRequestSignIn={onRequestSignIn} onSignOut={onSignOut} />
    </div>);

}

// ── Workspace chip (header dropdown) ─────────────────────────
function WorkspaceChip({ workspace, onChange }) {
  const [open, setOpen] = useState(false);
  const wrapRef = useRef(null);
  const active = workspace || WORKSPACES[0];
  return (
    <div className="dropdown-wrap" ref={wrapRef} data-tour="workspace">
      <button
        className={"workspace-chip" + (open ? " open" : "")}
        onClick={() => setOpen((o) => !o)}
        aria-haspopup="menu"
        aria-expanded={open}>
        <span className="ws-dot" />
        <span>{t(active.label)}</span>
        <Icon name="down" size={12} color="currentColor" />
      </button>
      <Popover open={open} onClose={() => setOpen(false)} anchor={wrapRef} align="left" width={264}>
        <div className="mp-label">Switch workspace</div>
        {buscoAllWorkspaces().map((w) =>
          <button
            key={w.id}
            className={"mp-item compact" + (w.id === active.id ? " on" : "")}
            onClick={() => { onChange && onChange(w); setOpen(false); }}>
            <span className="mp-l">
              <span className="mp-t">{w.label}</span>
              <span className="mp-s">{w.sub}</span>
            </span>
            {w.id === active.id && <Icon name="check" size={13} color="var(--b600)" />}
          </button>
        )}
        <div className="mp-divider" />
        <button className="mp-item compact" onClick={() => { setOpen(false); opsAccount("workspace"); }}>
          <span className="mp-l"><span className="mp-t">Manage workspaces…</span></span>
          <Icon name="chevron-right" size={13} color="var(--muted-2)" />
        </button>
      </Popover>
    </div>);

}

// ── User menu (dropdown) ─────────────────────────────────────
function UserMenu({ user, workspace, onRequestSignIn, onSignOut }) {
  const [open, setOpen] = useState(false);
  const wrapRef = useRef(null);

  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    };
    const onEsc = (e) => e.key === "Escape" && setOpen(false);
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onEsc);
    return () => {
      document.removeEventListener("mousedown", onDoc);
      document.removeEventListener("keydown", onEsc);
    };
  }, [open]);

  const signedIn = !!user;
  const initials = user?.initials || "OM";
  const name = user?.name || "Ops Manager";
  const role = t(user?.role || "Team access");
  const email = user?.email || "ops.manager@busco.sa";
  const wsLabel = workspace?.label || "KSA · Multi-city";

  const go = (view) => { setOpen(false); opsAccount(view); };

  return (
    <div className="user-chip-wrap" ref={wrapRef}>
      <button
        className={"user-chip" + (open ? " open" : "")}
        onClick={() => setOpen((o) => !o)}
        aria-haspopup="menu"
        aria-expanded={open}>
        <span className="av">{initials}</span>
        <span className="um">
          <span className="un">{name}</span>
          <span className="ur">{role}</span>
        </span>
        <Icon name="down" size={11} className="uc-caret" />
      </button>
      {open &&
      <div className="user-menu" role="menu">
          <div className="um-head">
            <span className="av">{initials}</span>
            <div style={{ minWidth: 0 }}>
              <div className="um-name">{name}</div>
              <div className="um-email">{email}</div>
            </div>
          </div>
          <div className="um-sec">
            <button className="um-item" onClick={() => go("settings")}>
              <Icon name="users" size={13} color="var(--muted)" />
              <span>{t("Account settings")}</span>
            </button>
            <button className="um-item" onClick={() => go("workspace")}>
              <Icon name="building" size={13} color="var(--muted)" />
              <span>{t("Switch workspace")}</span>
              <span className="um-meta">{wsLabel}</span>
            </button>
            <button className="um-item" onClick={() => go("preferences")}>
              <Icon name="settings" size={13} color="var(--muted)" />
              <span>{t("Preferences")}</span>
            </button>
            <button className="um-item" onClick={() => { setOpen(false); window.dispatchEvent(new CustomEvent("busco:tour")); }}>
              <Icon name="flag" size={13} color="var(--muted)" />
              <span>{t("Take the tour")}</span>
            </button>
          </div>
          <div className="um-divider" />
          <div className="um-sec">
            {signedIn ?
          <button className="um-item danger" onClick={() => {setOpen(false);onSignOut && onSignOut();}}>
                <Icon name="lock" size={13} color="var(--crit-700)" />
                <span>{t("Sign out")}</span>
              </button> :
          <button className="um-item" onClick={() => {setOpen(false);onRequestSignIn && onRequestSignIn();}}>
                <Icon name="unlock" size={13} color="var(--b700)" />
                <span>{t("Sign in")}</span>
              </button>
          }
          </div>
        </div>
      }
    </div>);

}

// ── Sign-in window ───────────────────────────────────────────
function SignInModal({ onClose, onSignIn, required }) {
  const [email, setEmail] = useState("");
  const [pw, setPw] = useState("");
  const [busy, setBusy] = useState(false);
  const [mode, setMode] = useState("signin"); // "signin" or "signup"
  const [error, setError] = useState(null);
  // Note: "keep me signed in" removed — Supabase persists sessions by default,
  // and the checkbox was decorative. Sessions live in localStorage until you sign out.

  useEffect(() => {
    if (required) return;
    const esc = (e) => e.key === "Escape" && onClose && onClose();
    document.addEventListener("keydown", esc);
    return () => document.removeEventListener("keydown", esc);
  }, [onClose, required]);

  const submit = async (e) => {
    e.preventDefault();
    if (!email || !pw) return;
    setBusy(true); setError(null);
    try {
      const authUser = mode === "signin"
        ? await window.buscoSignIn(email, pw)
        : await window.buscoSignUp(email, pw);
      const buscoUser = window.buscoUserFromAuth(authUser);
      onSignIn(buscoUser);
    } catch (err) {
      let msg = err?.message || "Sign-in failed. Check your credentials.";
      if (/email not confirmed/i.test(msg)) msg = "Confirm your email first (or disable email confirmation in Supabase Auth settings).";
      if (/invalid login/i.test(msg))      msg = "Wrong email or password.";
      if (/already registered/i.test(msg)) msg = "Account already exists — switch to Sign in.";
      setError(msg);
      setBusy(false);
    }
  };

  const handleOverlayClick = required ? undefined : onClose;
  const switchMode = (e, target) => { e.preventDefault(); setMode(target); setError(null); };

  return (
    <div className="modal-overlay" onClick={handleOverlayClick}>
      <div className="signin-card" onClick={(e) => e.stopPropagation()}>
        {!required && (
          <button className="signin-x" onClick={onClose} aria-label="Close"><Icon name="x" size={14} /></button>
        )}
        <div className="signin-brand">
          <img src="assets/busco-logo-alt.png" alt="Busco Shipping Company" />
        </div>
        <div className="signin-title">
          {mode === "signin" ? t("Sign in to Busco Ops") : t("Create your account")}
        </div>
        <div className="signin-sub">
          {mode === "signin"
            ? t("Use your work email to access the operations centre.")
            : t("First-time setup — pick a strong password (6+ characters).")}
        </div>
        <form className="signin-form" onSubmit={submit}>
          <div className="field">
            <label>{t("Work email")}</label>
            <input type="email" autoFocus value={email} onChange={(e) => setEmail(e.target.value)} placeholder="name@busco.sa" />
          </div>
          <div className="field">
            <label>
              <span>{t("Password")}</span>
              {mode === "signin" &&
                <a className="signin-link" href="#" onClick={async (e) => {
                  e.preventDefault();
                  if (!email) { setError("Enter your email above first, then click Forgot?"); return; }
                  setError(null); setBusy(true);
                  try {
                    await window.buscoResetPassword(email);
                    setError("Reset link sent — check your email."); // Re-uses the error slot as info
                  } catch (err) {
                    setError(err?.message || "Couldn't send reset email");
                  } finally {
                    setBusy(false);
                  }
                }}>{t("Forgot?")}</a>
              }
            </label>
            <input type="password" value={pw} onChange={(e) => setPw(e.target.value)} placeholder={mode === "signin" ? "••••••••" : "At least 6 characters"} />
          </div>
          {error &&
            <div style={{ background: "var(--crit-50)", border: "1px solid var(--crit-100)", color: "var(--crit-700)", padding: "9px 11px", borderRadius: "var(--r-sm)", fontSize: 12 }}>
              <Icon name="alert-circle" size={12} color="var(--crit-700)" /> {error}
            </div>
          }
          <button type="submit" className="btn primary lg signin-submit" disabled={busy || !email || !pw}>
            {busy ? <span className="spinner" /> : <Icon name="unlock" size={13} color="#fff" />}
            {busy ? (mode === "signin" ? t("Signing in…") : t("Creating account…")) : (mode === "signin" ? t("Sign in") : t("Create account"))}
          </button>
          <div className="signin-foot">
            {mode === "signin"
              ? <>{t("New here?")} <a href="#" className="signin-link" onClick={(e) => switchMode(e, "signup")}>{t("Create an account")}</a></>
              : <>{t("Already have an account?")} <a href="#" className="signin-link" onClick={(e) => switchMode(e, "signin")}>{t("Sign in")}</a></>
            }
          </div>
        </form>
      </div>
    </div>);

}

// ── Section nav ───────────────────────────────────────────────
function SectionNav({ active, onChange, sections }) {
  const list = sections && sections.length ? sections : SECTIONS;
  // Single-section users (e.g. warehouse staff) — skip the nav entirely
  if (list.length <= 1) return null;
  return (
    <div className="subnav">
      {list.map((s) =>
      <button
        key={s.id}
        className={active === s.id ? "on" : ""}
        onClick={() => onChange(s.id)}>

          <Icon name={s.icon} size={14} />
          {t(s.label)}
          {s.pin && <span className="pin-tag">PIN</span>}
        </button>
      )}
    </div>);

}

// ── Page subbar (title + breadcrumbs + actions) ──────────────
function PageBar({ title, crumbs, actions }) {
  return (
    <div className="subbar">
      <div className="title-block">
        <h1>{title}</h1>
        {crumbs && crumbs.length > 0 &&
        <div className="crumbs">
            {crumbs.map((c, i) =>
          <React.Fragment key={i}>
                {i > 0 && <span className="sep">/</span>}
                <span>{c}</span>
              </React.Fragment>
          )}
          </div>
        }
      </div>
      <div className="actions">{actions}</div>
    </div>);

}

// ── Badges ────────────────────────────────────────────────────
function RateBadge({ r, size }) {
  const cls = r >= 75 ? "rate-good" : r >= 50 ? "rate-warn" : "rate-bad";
  return <span className={"badge rate-pill " + cls + (size === "lg" ? " lg" : "")}>{r}%</span>;
}

function TierBadge({ tier }) {
  return (
    <span className={"tier " + tier.cls}>
      <span className="tdot" />
      {tier.label}
    </span>);

}

function SourceBadge({ s }) {
  if (s === "manual") return <span className="src s-manual" title="Manual entry">M</span>;
  if (s === "upload") return <span className="src s-upload" title="File upload">U</span>;
  return null;
}

function ContractBadge({ type }) {
  return (
    <span className={"ctype " + type}>
      <Icon name={type === "salary" ? "briefcase" : "tool"} size={11} />
      {type === "salary" ? "Salaried" : "Freelancer"}
    </span>);

}

// ── KPI ───────────────────────────────────────────────────────
function KPI({ label, value, sub, icon, tint, accent, tone, delta }) {
  return (
    <div className="kpi">
      {icon &&
      <div className="icon-spot" style={{ background: tint, color: accent }}>
          <Icon name={icon} size={14} color={accent} />
        </div>
      }
      <div className="lbl">{label}</div>
      <div className={"val mono " + (tone || "")}>{value}</div>
      <div className="sub">
        {delta !== undefined &&
        <span className={"delta " + (delta >= 0 ? "up" : "dn")}>
            {delta >= 0 ? "▲" : "▼"} {Math.abs(delta)}%
          </span>
        }
        <span>{sub}</span>
      </div>
    </div>);

}

// ── Sparkline ─────────────────────────────────────────────────
function Sparkline({ values }) {
  const max = Math.max(...values, 100);
  return (
    <div className="spark" title={values.join(" · ") + " %"}>
      {values.map((v, i) => {
        const cls = v < 70 ? "lo" : v >= 88 ? "hi" : v >= 75 ? "ok" : "";
        return <i key={i} className={cls} style={{ height: `${v / max * 100}%` }} />;
      })}
    </div>);

}

// ── Segmented ─────────────────────────────────────────────────
function Segmented({ options, value, onChange }) {
  return (
    <div className="segmented">
      {options.map((o) =>
      <button key={o} className={value === o ? "on" : ""} onClick={() => onChange(o)}>{o}</button>
      )}
    </div>);

}

// ── Pill picker ───────────────────────────────────────────────
function PillRow({ options, value, onChange, multi }) {
  const isOn = (o) => multi ? value.includes(o) : value === o;
  const toggle = (o) => multi ?
  onChange(value.includes(o) ? value.filter((x) => x !== o) : [...value, o]) :
  onChange(o);
  return (
    <div className="pill-row">
      {options.map((o) =>
      <button key={o} className={"pill " + (isOn(o) ? "on" : "")} onClick={() => toggle(o)}>
          {multi && isOn(o) && <Icon name="check" size={10} color="var(--b700)" strokeWidth={2.5} />} {o}
        </button>
      )}
    </div>);

}

// ── Multi-select dropdown ─────────────────────────────────────
// value = array of selected strings. Renders a select-like trigger that
// opens a checklist popover. Used for courier Client + Zone pickers.
function MultiSelect({ options, value = [], onChange, placeholder = "Select…" }) {
  const [open, setOpen] = useState(false);
  const anchor = useRef(null);
  const toggle = (o) => onChange(value.includes(o) ? value.filter((x) => x !== o) : [...value, o]);
  const label = value.length === 0 ? placeholder
    : value.length <= 2 ? value.join(", ")
    : `${value.length} selected`;
  return (
    <div style={{ position: "relative" }} ref={anchor}>
      <button type="button" className="ms-trigger" onClick={() => setOpen((o) => !o)}
        style={{ width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8,
                 border: "1px solid var(--border)", background: "var(--surface)", borderRadius: "var(--r-sm)",
                 padding: "8px 11px", fontSize: 12.5, cursor: "pointer", color: value.length ? "var(--text)" : "var(--muted-2)" }}>
        <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{label}</span>
        <Icon name="chevron-down" size={13} color="var(--muted)" />
      </button>
      <Popover open={open} onClose={() => setOpen(false)} anchor={anchor} align="left" width="100%">
        <div style={{ maxHeight: 220, overflowY: "auto", padding: 4 }}>
          {options.length === 0 && <div style={{ padding: "8px 10px", fontSize: 11.5, color: "var(--muted)" }}>No options</div>}
          {options.map((o) => (
            <button key={o} type="button" className={"mp-item compact" + (value.includes(o) ? " on" : "")} onClick={() => toggle(o)}>
              <span style={{ width: 14, height: 14, borderRadius: 4, flexShrink: 0,
                             border: "1px solid " + (value.includes(o) ? "var(--b600)" : "var(--border)"),
                             background: value.includes(o) ? "var(--b600)" : "transparent",
                             display: "flex", alignItems: "center", justifyContent: "center" }}>
                {value.includes(o) && <Icon name="check" size={10} color="#fff" strokeWidth={3} />}
              </span>
              {o}
            </button>
          ))}
        </div>
      </Popover>
    </div>
  );
}

// ── Modal shell ───────────────────────────────────────────────
function Modal({ title, onClose, children, maxWidth }) {
  useEffect(() => {
    const esc = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", esc);
    return () => document.removeEventListener("keydown", esc);
  }, [onClose]);
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" style={{ maxWidth: maxWidth || 1140 }} onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          {title}
          <button className="close-x" onClick={onClose} aria-label="Close"><Icon name="x" size={14} /></button>
        </div>
        <div className="modal-body">{children}</div>
      </div>
    </div>);

}

// ── Toast ─────────────────────────────────────────────────────
function Toast({ msg, kind, onDone }) {
  useEffect(() => {
    if (!msg) return;
    const t = setTimeout(onDone, 2400);
    return () => clearTimeout(t);
  }, [msg, onDone]);
  if (!msg) return null;
  return (
    <div className={"toast " + (kind || "success")}>
      <Icon name="check" size={13} color="#fff" /> {msg}
    </div>);

}

// ── Rate cell with mini bar ──────────────────────────────────
function RateCell({ r }) {
  const color = r >= 75 ? "var(--good)" : r >= 50 ? "var(--warn)" : "var(--crit)";
  return (
    <div className="rate-cell">
      <span className="mono" style={{ fontSize: 12, fontWeight: 600, minWidth: 32, color }}>{r}%</span>
      <span className="rate-bar"><i style={{ width: Math.min(100, r) + "%", background: color }} /></span>
    </div>);

}

// ── Navigation helper (cross-screen) ─────────────────────────
const opsNav = (page) => window.dispatchEvent(new CustomEvent("ops:nav", { detail: page }));

// ── Account helper (opens account-level modals from anywhere) ─
const opsAccount = (view) => window.dispatchEvent(new CustomEvent("ops:account", { detail: view }));

// ── Workspaces (shared list) ─────────────────────────────────
// Built-in workspaces (country logic lives in busco-lib). Custom workspaces
// are user-defined city lists, stored in localStorage and editable from the
// Workspaces modal.
const WORKSPACES = [
  { id: "all",     label: "All cities", sub: "KSA & Bahrain" },
  { id: "ksa",     label: "KSA",        sub: "All Saudi cities" },
  { id: "bahrain", label: "Bahrain",    sub: "Manama · Riffa · Muharraq" },
];
function buscoCustomWorkspaces() {
  try { return JSON.parse(localStorage.getItem("busco-workspaces") || "[]"); } catch { return []; }
}
function buscoSaveCustomWorkspaces(list) {
  try { localStorage.setItem("busco-workspaces", JSON.stringify(list)); } catch {}
  window.dispatchEvent(new CustomEvent("busco:workspaces"));
}
function buscoAllWorkspaces() {
  return [...WORKSPACES, ...buscoCustomWorkspaces().map((w) => ({ ...w, sub: (w.cities || []).join(" · "), custom: true }))];
}
// Quick-pick KSA areas for the workspace editor
const BUSCO_KSA_AREAS = {
  "Capital":  ["Riyadh", "Qassim", "Kharj"],
  "Western":  ["Jeddah", "Mecca", "Madinah", "Taif"],
  "Eastern":  ["Dammam", "Khobar", "Dhahran", "Jubail", "Ahsa"],
  "Southern": ["Abha", "Khamis Mushait", "Jazan", "Najran"],
  "Northern": ["Tabuk", "Hail", "Sakaka", "Arar"],
};
Object.assign(window, { buscoCustomWorkspaces, buscoSaveCustomWorkspaces, buscoAllWorkspaces });

// ── Generic popover wrapper (handles outside-click + escape) ─
function Popover({ open, onClose, anchor, align = "right", children, width }) {
  const popRef = useRef(null);
  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (popRef.current && !popRef.current.contains(e.target) && !anchor?.current?.contains?.(e.target)) {
        onClose();
      }
    };
    const onEsc = (e) => e.key === "Escape" && onClose();
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onEsc);
    return () => {
      document.removeEventListener("mousedown", onDoc);
      document.removeEventListener("keydown", onEsc);
    };
  }, [open, onClose, anchor]);

  if (!open) return null;
  // RTL: flip the alignment so a popover anchored "right" in LTR sticks to
  // the visual right edge in RTL (i.e. mirror it). Anchored "left" similarly
  // flips to the visual left.
  const isRtl = (typeof document !== "undefined") &&
                document.documentElement.getAttribute("dir") === "rtl";
  const eff = isRtl ? (align === "right" ? "left" : "right") : align;
  const style = { [eff]: 0, width };
  return (
    <div ref={popRef} className="menu-pop" style={style}>
      {children}
    </div>);

}

// ── Export menu ──────────────────────────────────────────────
// getRows() → { rows, filename } built from the screen's CURRENT (filtered)
// view, so the export always matches what's on screen. `formats` lists which
// file types make sense here (data lists = xlsx/csv; no print-table PDF).
function ExportMenu({ getRows, formats = ["xlsx", "csv"], onToast, includeBrief = false, label = "Export", size = "sm", primary = false }) {
  const [open, setOpen] = useState(false);
  const [briefOpen, setBriefOpen] = useState(false);
  const btnRef = useRef(null);

  const run = async (fmt) => {
    setOpen(false);
    if (fmt === "brief") { setBriefOpen(true); return; }
    try {
      const { rows, filename } = getRows();
      const n = window.buscoExportData(fmt, rows, filename);
      onToast && onToast(`Downloaded ${n} row${n === 1 ? "" : "s"} as ${fmt.toUpperCase()}`);
    } catch (e) {
      onToast && onToast(e?.message || "Export failed", "danger");
    }
  };

  return (
    <div className="dropdown-wrap">
      <button
        ref={btnRef}
        className={"btn " + (primary ? "primary " : "") + size + (open ? " on" : "")}
        onClick={() => setOpen((o) => !o)}
        aria-haspopup="menu"
        aria-expanded={open}>
        <Icon name="export" size={12} color={primary ? "#fff" : undefined} />
        {label}
        <Icon name="down" size={10} color={primary ? "#fff" : "currentColor"} />
      </button>
      <Popover open={open} onClose={() => setOpen(false)} anchor={btnRef} width={240}>
        <div className="mp-label">{t("Export format")}</div>
        {formats.includes("xlsx") &&
        <button className="mp-item" onClick={() => run("xlsx")}>
          <span className="mp-glyph mp-glyph-xls">XLS</span>
          <span className="mp-l">
            <span className="mp-t">{t("Excel")}</span>
            <span className="mp-s">.xlsx · {t("opens in Excel/Sheets")}</span>
          </span>
        </button>}
        {formats.includes("csv") &&
        <button className="mp-item" onClick={() => run("csv")}>
          <span className="mp-glyph mp-glyph-csv">CSV</span>
          <span className="mp-l">
            <span className="mp-t">CSV</span>
            <span className="mp-s">.csv · {t("raw rows")}</span>
          </span>
        </button>}
        {includeBrief &&
        <>
            <div className="mp-divider" />
            <button className="mp-item" onClick={() => run("brief")}>
              <span className="mp-glyph mp-glyph-brief">M/E</span>
              <span className="mp-l">
                <span className="mp-t">{t("Brief report")}</span>
                <span className="mp-s">{t("Morning + evening text")}</span>
              </span>
            </button>
          </>
        }
      </Popover>
      {briefOpen && <BriefReportModal onClose={() => setBriefOpen(false)} onToast={onToast} />}
    </div>);

}

// ── Brief report (morning/evening text export) ───────────────
function buildBriefReport(date) {
  const today = ENTRIES.filter((e) => e.date === date);
  const map = {};
  for (const e of today) {
    const k = e.client;
    if (!map[k]) map[k] = { off: 0, del: 0, courierCount: 0, courierSet: new Set() };
    map[k].off += e.offloaded;
    map[k].del += e.delivered;
    if (e.courierCount) map[k].courierCount += e.courierCount;
    if (e.courier && e.courier !== "—") map[k].courierSet.add(e.courier);
  }
  const rows = Object.entries(map).map(([name, v]) => ({
    name, off: v.off, del: v.del,
    couriers: v.courierCount > 0 ? v.courierCount : v.courierSet.size,
  })).sort((a, b) => b.off - a.off);

  const totalOff = rows.reduce((a, r) => a + r.off, 0);
  const totalDel = rows.reduce((a, r) => a + r.del, 0);
  const tillOff = CLIENT_ROWS.reduce((a, c) => a + c.offloaded, 0);
  const tillDel = CLIENT_ROWS.reduce((a, c) => a + c.delivered, 0);

  const d = new Date(date + "T00:00:00");
  const monthName = d.toLocaleString("en-US", { month: "long", year: "numeric" });
  const dateName  = d.toLocaleString("en-US", { month: "long", day: "numeric", year: "numeric" });

  let txt = `Month - ${monthName}\nDate - ${dateName}\n\n*Morning Report*\n`;
  rows.forEach((r, i) => {
    txt += `${i + 1}. ${r.name} - ${r.couriers} courier${r.couriers === 1 ? "" : "s"} took ${r.off} deliveries\n`;
  });
  txt += `\nTotal Collected Today - ${totalOff} deliveries\nTotal Collected Till Date - ${tillOff} deliveries\n\n`;
  txt += `*Evening Report*\n`;
  rows.forEach((r, i) => {
    txt += `${i + 1}. ${r.name} - ${r.del} Delivered\n`;
  });
  txt += `\nTotal Delivered Today - ${totalDel}\nTotal Delivered Till Date - ${tillDel}\n`;
  return { text: txt, rows, totalOff, totalDel, tillOff, tillDel, monthName, dateName };
}

function BriefReportModal({ onClose, onToast }) {
  const [date, setDate] = useState(new Date().toISOString().slice(0, 10));
  const [copied, setCopied] = useState(false);
  const data = useMemo(() => buildBriefReport(date), [date]);

  useEffect(() => {
    const esc = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", esc);
    return () => document.removeEventListener("keydown", esc);
  }, [onClose]);

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(data.text);
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
      onToast && onToast("Brief copied to clipboard");
    } catch {
      onToast && onToast("Copy failed — select & copy manually", "danger");
    }
  };

  const download = () => {
    const blob = new Blob([data.text], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `busco-brief-${date}.txt`;
    a.click();
    URL.revokeObjectURL(url);
    onToast && onToast("Brief downloaded");
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="brief-card" onClick={(e) => e.stopPropagation()}>
        <div className="brief-head">
          <div>
            <div className="brief-title">{t("Brief report")}</div>
            <div className="brief-sub">{t("Morning + evening client summary — plain text for chat sharing")}</div>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div className="field" style={{ width: 160 }}>
              <input type="date" value={date} onChange={(e) => setDate(e.target.value)} />
            </div>
            <button className="close-x" onClick={onClose}><Icon name="x" size={14} /></button>
          </div>
        </div>

        <div className="brief-body">
          <div className="brief-stats">
            <div className="brief-stat">
              <div className="label-tiny">{t("Clients reporting")}</div>
              <div className="brief-stat-v">{data.rows.length}</div>
            </div>
            <div className="brief-stat">
              <div className="label-tiny">{t("Collected today")}</div>
              <div className="brief-stat-v" style={{ color: "var(--warn-700)" }}>{fmtNum(data.totalOff)}</div>
            </div>
            <div className="brief-stat">
              <div className="label-tiny">{t("Delivered today")}</div>
              <div className="brief-stat-v" style={{ color: "var(--good-700)" }}>{fmtNum(data.totalDel)}</div>
            </div>
            <div className="brief-stat">
              <div className="label-tiny">Rate</div>
              <div className="brief-stat-v">{data.totalOff > 0 ? Math.round(data.totalDel / data.totalOff * 100) : 0}%</div>
            </div>
          </div>

          {data.rows.length === 0 ?
          <div className="brief-empty">
              No entries on {data.dateName}. Pick a different date.
            </div> :

          <pre className="brief-pre">{data.text}</pre>
          }
        </div>

        <div className="brief-foot">
          <span className="muted" style={{ fontSize: 11.5 }}>
            <Icon name="info" size={11} /> Ready to paste into WhatsApp, Slack, or email
          </span>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="btn sm" onClick={download} disabled={data.rows.length === 0}>
              <Icon name="export" size={12} /> Download .txt
            </button>
            <button className="btn primary sm" onClick={copy} disabled={data.rows.length === 0}>
              <Icon name={copied ? "check" : "file"} size={12} color="#fff" />
              {copied ? "Copied" : "Copy to clipboard"}
            </button>
          </div>
        </div>
      </div>
    </div>);

}

// ── Filter popover ───────────────────────────────────────────
function FilterPopover({ groups, value, onChange, onClear, label = "Filter", size = "sm" }) {
  const [open, setOpen] = useState(false);
  const btnRef = useRef(null);
  const active = Object.values(value || {}).reduce((a, v) => a + (Array.isArray(v) ? v.length : v ? 1 : 0), 0);

  return (
    <div className="dropdown-wrap">
      <button ref={btnRef} className={"btn " + size + (open ? " on" : "")} onClick={() => setOpen((o) => !o)}>
        <Icon name="filter" size={12} />
        {label}{active > 0 && <span className="filter-count">{active}</span>}
        <Icon name="down" size={10} />
      </button>
      <Popover open={open} onClose={() => setOpen(false)} anchor={btnRef} width={260}>
        <div className="mp-label" style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span>{t("Filters")}</span>
          {active > 0 && <button className="mp-clear" onClick={() => onClear && onClear()}>{t("Clear all")}</button>}
        </div>
        {groups.map((g) =>
        <div key={g.key} className="mp-group">
            <div className="mp-group-label">{g.label}</div>
            <div className="mp-checks">
              {g.options.map((o) => {
              const checked = (value[g.key] || []).includes(o);
              return (
                <label key={o} className="mp-check">
                    <input type="checkbox" checked={checked} onChange={(e) => {
                    const cur = value[g.key] || [];
                    onChange({ ...value, [g.key]: e.target.checked ? [...cur, o] : cur.filter((x) => x !== o) });
                  }} />
                    <span>{o}</span>
                  </label>);

            })}
            </div>
          </div>
        )}
      </Popover>
    </div>);

}

// ── Date popover ─────────────────────────────────────────────
function DatePopover({ value, onChange, label = "Today", size = "sm" }) {
  const [open, setOpen] = useState(false);
  const btnRef = useRef(null);
  const presets = [
  { k: "today", l: "Today" },
  { k: "yesterday", l: "Yesterday" },
  { k: "7d", l: "Last 7 days" },
  { k: "30d", l: "Last 30 days" },
  { k: "mtd", l: "Month to date" },
  { k: "qtd", l: "Quarter to date" }];

  return (
    <div className="dropdown-wrap">
      <button ref={btnRef} className={"btn " + size + (open ? " on" : "")} onClick={() => setOpen((o) => !o)}>
        <Icon name="calendar" size={12} />
        {presets.find((p) => p.k === value)?.l || label}
        <Icon name="down" size={10} />
      </button>
      <Popover open={open} onClose={() => setOpen(false)} anchor={btnRef} width={200}>
        <div className="mp-label">{t("Date range")}</div>
        {presets.map((p) =>
        <button key={p.k}
        className={"mp-item compact" + (value === p.k ? " on" : "")}
        onClick={() => { onChange(p.k); setOpen(false); }}>
            <span className="mp-l"><span className="mp-t">{p.l}</span></span>
            {value === p.k && <Icon name="check" size={12} color="var(--b600)" />}
          </button>
        )}
      </Popover>
    </div>);

}

// ── Confirm dialog ───────────────────────────────────────────
function ConfirmModal({ title, body, confirmLabel = "Confirm", cancelLabel = "Cancel", tone = "primary", onConfirm, onClose }) {
  useEffect(() => {
    const esc = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", esc);
    return () => document.removeEventListener("keydown", esc);
  }, [onClose]);
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="confirm-card" onClick={(e) => e.stopPropagation()}>
        <div className="confirm-title">{title}</div>
        <div className="confirm-body">{body}</div>
        <div className="confirm-foot">
          <button className="btn" onClick={onClose}>{cancelLabel}</button>
          <button className={"btn " + (tone === "danger" ? "danger" : "primary")} onClick={() => { onConfirm(); onClose(); }}>
            {confirmLabel}
          </button>
        </div>
      </div>
    </div>);

}

// ── Paste-report modal (WhatsApp morning/evening format) ────
function PasteReportModal({ onClose, onToast }) {
  const [text, setText] = useState("");
  const [busy, setBusy] = useState(false);
  const parsed = useMemo(() => {
    if (!text.trim()) return null;
    try { return window.buscoParseTextReport(text); } catch { return null; }
  }, [text]);

  useEffect(() => {
    const esc = (e) => e.key === "Escape" && !busy && onClose();
    document.addEventListener("keydown", esc);
    return () => document.removeEventListener("keydown", esc);
  }, [onClose, busy]);

  const submit = async () => {
    if (busy || !parsed) return;
    setBusy(true);
    try {
      const r = await window.buscoImportTextReport(text);
      const msg = `${r.inserted} new · ${r.updated} updated`;
      onToast(`Report imported: ${msg}`);
      onClose();
    } catch (e) {
      onToast(e?.message || "Import failed", "danger");
      setBusy(false);
    }
  };

  const hasData = parsed && (parsed.morning.length || parsed.evening.length);
  const placeholderText =
    "Month - May 2026\n" +
    "Date - May 27, 2026\n\n" +
    "*Morning Report*\n" +
    "1. Ajex BH - 9 couriers took 375 deliveries\n" +
    "2. SMSA BH - 7 couriers took 280 deliveries\n\n" +
    "Total Collected Today - 655\n" +
    "Total Collected Till Date - 16034\n\n" +
    "*Evening Report*\n" +
    "1. Ajex BH - 313 Delivered\n" +
    "2. SMSA BH - 240 Delivered\n\n" +
    "Total Delivered Today - 553\n" +
    "Total Delivered Till Date - 11790";

  return (
    <div className="modal-overlay" onClick={busy ? undefined : onClose}>
      <div className="modal" style={{ maxWidth: 760 }} onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            <span style={{ fontSize: 14, fontWeight: 600 }}>Paste daily report</span>
            <span style={{ fontSize: 11.5, color: "var(--muted)" }}>WhatsApp format — morning + evening sections both supported</span>
          </div>
          {!busy && <button className="close-x" onClick={onClose}><Icon name="x" size={14} /></button>}
        </div>
        <div className="modal-body">
          <textarea
            value={text}
            onChange={(e) => setText(e.target.value)}
            placeholder={placeholderText}
            spellCheck={false}
            style={{
              width: "100%", minHeight: 320,
              fontFamily: "IBM Plex Mono, ui-monospace, monospace",
              fontSize: 12, lineHeight: 1.55,
              padding: "12px 14px",
              border: "1px solid var(--border)",
              borderRadius: "var(--r-sm)",
              background: "var(--surface-2)",
              resize: "vertical",
            }}
          />
          {parsed &&
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10, marginTop: 14 }}>
              <div className="tile">
                <div className="tl">Date</div>
                <div className="tv mono" style={{ fontSize: 14 }}>{parsed.date ? fmtDate(parsed.date) : "—"}</div>
              </div>
              <div className="tile">
                <div className="tl">Morning lines</div>
                <div className="tv mono" style={{ fontSize: 14, color: "var(--warn-700)" }}>{parsed.morning.length}</div>
              </div>
              <div className="tile">
                <div className="tl">Evening lines</div>
                <div className="tv mono" style={{ fontSize: 14, color: "var(--good-700)" }}>{parsed.evening.length}</div>
              </div>
              <div className="tile">
                <div className="tl">{t("Stated total")}</div>
                <div className="tv mono" style={{ fontSize: 14 }}>
                  {parsed.totalCollectedToday ?? "—"} / {parsed.totalDeliveredToday ?? "—"}
                </div>
              </div>
            </div>
          }
          {parsed && hasData &&
            <div style={{ marginTop: 14, padding: "10px 12px", background: "var(--b50)", border: "1px solid var(--b100)", borderRadius: "var(--r-sm)", fontSize: 11.5, color: "var(--b800)" }}>
              <Icon name="info" size={11} /> Each client becomes one row per date. Morning sets offloaded; evening updates delivered.
            </div>
          }
        </div>
        <div className="brief-foot">
          <span className="muted" style={{ fontSize: 11.5 }}>
            <Icon name="info" size={11} /> Lines with "xxx" placeholders are skipped automatically.
          </span>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="btn sm" onClick={onClose} disabled={busy}>{t("Cancel")}</button>
            <button className="btn primary sm" onClick={submit} disabled={busy || !hasData}>
              {busy ? <span className="spinner" /> : <Icon name="check" size={12} color="#fff" />}
              {busy ? "Importing…" : "Import to database"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Account settings modal ───────────────────────────────────
function AccountSettingsModal({ user, onClose, onToast, onSave }) {
  const [name, setName] = useState(user?.name || "Ops Manager");
  const [email] = useState(user?.email || "ops.manager@busco.sa"); // read-only — auth-owned
  const [phone, setPhone] = useState(user?.phone || "");
  const [lang, setLang] = useState(user?.lang || "English");
  const [tz, setTz] = useState(user?.tz || "Arabia Standard Time (GMT+3)");
  const [busy, setBusy] = useState(false);
  const initials = (name.trim().split(/\s+/).map((p) => p[0]).join("").slice(0, 2) || "OM").toUpperCase();

  const save = async () => {
    if (busy) return;
    setBusy(true);
    try {
      await (onSave && onSave({ name, phone, lang, tz, initials }));
      onToast && onToast("Account settings saved");
      onClose();
    } catch (e) {
      onToast && onToast(e?.message || "Failed to save", "danger");
      setBusy(false);
    }
  };

  return (
    <Modal title={t("Account settings")} onClose={onClose} maxWidth={560}>
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 18 }}>
        <span className="av" style={{ width: 52, height: 52, fontSize: 18, borderRadius: "var(--r-md)" }}>{initials}</span>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 14 }}>{name}</div>
          <div style={{ fontSize: 11.5, color: "var(--muted)" }}>{t(user?.role || "Team access")} · {t("member since")} 2024</div>
        </div>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <div className="field-row c2">
          <div className="field"><label>{t("Full name")}</label><input value={name} onChange={(e) => setName(e.target.value)} /></div>
          <div className="field">
            <label>{t("Work email")} <span className="muted" style={{ textTransform: "none", fontWeight: 400, fontSize: 10 }}>{t("read-only")}</span></label>
            <input type="email" value={email} disabled style={{ background: "var(--surface-2)", color: "var(--muted)" }} />
          </div>
        </div>
        <div className="field-row c2">
          <div className="field"><label>{t("Phone")}</label><input className="mono" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+966 50 000 0000" /></div>
          <div className="field">
            <label>{t("Language")}</label>
            <select value={lang} onChange={(e) => setLang(e.target.value)}>
              <option>English</option><option>العربية (Arabic)</option>
            </select>
          </div>
        </div>
        <div className="field">
          <label>{t("Timezone")}</label>
          <select value={tz} onChange={(e) => setTz(e.target.value)}>
            <option>Arabia Standard Time (GMT+3)</option>
            <option>Gulf Standard Time (GMT+4)</option>
            <option>Coordinated Universal Time (GMT+0)</option>
          </select>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8, paddingTop: 6 }}>
          <button className="btn" onClick={() => opsAccount("preferences")} disabled={busy}><Icon name="settings" size={12} /> {t("Preferences")}</button>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="btn" onClick={onClose} disabled={busy}>{t("Cancel")}</button>
            <button className="btn primary" onClick={save} disabled={busy}>
              {busy ? <span className="spinner" /> : <Icon name="check" size={12} color="#fff" />}
              {busy ? t("Saving…") : t("Save changes")}
            </button>
          </div>
        </div>
      </div>
    </Modal>);

}

// ── Preferences modal ────────────────────────────────────────
const PREF_DEFAULTS = { emailDigest: false, criticalAlerts: false, weeklySummary: false, landing: "Overview", numberFmt: "1,234.5", reduceMotion: false };
function loadPrefs() {
  // Display prefs come from localStorage; notification prefs are overlaid from
  // the signed-in user's profile (so they persist server-side, cross-device).
  const base = (() => {
    try { return { ...PREF_DEFAULTS, ...(window.BUSCO_PREFS || {}) }; }
    catch { return { ...PREF_DEFAULTS }; }
  })();
  const u = window.buscoUser || {};
  if (u.notify_daily_digest    !== undefined) base.emailDigest    = !!u.notify_daily_digest;
  if (u.notify_critical_alerts !== undefined) base.criticalAlerts = !!u.notify_critical_alerts;
  if (u.notify_weekly_summary  !== undefined) base.weeklySummary  = !!u.notify_weekly_summary;
  return base;
}
function PreferencesModal({ onClose, onToast }) {
  const [p, setP] = useState(loadPrefs);
  const set = (k, v) => setP((cur) => ({ ...cur, [k]: v }));
  const Toggle = ({ k, label, sub }) =>
    <button className="pref-row" onClick={() => set(k, !p[k])}>
      <div style={{ textAlign: "left" }}>
        <div style={{ fontSize: 12.5, fontWeight: 600 }}>{label}</div>
        {sub && <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>{sub}</div>}
      </div>
      <span className={"pref-switch" + (p[k] ? " on" : "")}><span className="knob" /></span>
    </button>;

  return (
    <Modal title={window.t("Preferences")} onClose={onClose} maxWidth={520}>
      <div className="pref-group-label">{window.t("Notifications")}</div>
      <div className="pref-list">
        <Toggle k="emailDigest"   label={window.t("Daily email digest")} sub={window.t("Morning summary at 07:00 AST")} />
        <Toggle k="criticalAlerts" label={window.t("Critical alerts")}    sub={window.t("Push when a client drops below 70%")} />
        <Toggle k="weeklySummary" label={window.t("Weekly summary")}      sub={window.t("Sunday performance recap")} />
      </div>
      <div style={{ fontSize: 10.5, color: "var(--muted-2)", marginTop: 6, display: "flex", gap: 5, alignItems: "flex-start" }}>
        <Icon name="info" size={11} color="var(--muted-2)" /> {window.t("Your choices are saved. Email/push delivery is enabled once the mail service is connected.")}
      </div>

      <div className="pref-group-label" style={{ marginTop: 16 }}>{window.t("Display")}</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <div className="field">
          <label>{window.t("Default landing screen")}</label>
          <select value={p.landing} onChange={(e) => set("landing", e.target.value)}>
            {SECTIONS.map((s) => <option key={s.id} value={s.label}>{window.t(s.label)}</option>)}
          </select>
        </div>
        <div className="field">
          <label>{window.t("Number format")}</label>
          <select value={p.numberFmt} onChange={(e) => set("numberFmt", e.target.value)}>
            <option>1,234.5</option><option>1.234,5</option><option>1 234.5</option>
          </select>
        </div>
        <div className="pref-list">
          <Toggle k="reduceMotion" label={window.t("Reduce motion")} sub={window.t("Minimise chart and panel animations")} />
        </div>
      </div>

      <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, paddingTop: 16 }}>
        <button className="btn" onClick={onClose}>{t("Cancel")}</button>
        <button className="btn primary" onClick={async () => {
          window.buscoApplyPrefs(p);                  // display prefs → localStorage (instant)
          try {
            await window.buscoUpdateMyProfile({       // notification prefs → profile (server)
              notify_daily_digest:    !!p.emailDigest,
              notify_critical_alerts: !!p.criticalAlerts,
              notify_weekly_summary:  !!p.weeklySummary,
            });
            if (window.buscoUser) Object.assign(window.buscoUser, {
              notify_daily_digest: !!p.emailDigest, notify_critical_alerts: !!p.criticalAlerts, notify_weekly_summary: !!p.weeklySummary,
            });
          } catch (e) { console.warn("Could not save notification prefs:", e?.message); }
          onToast && onToast("Preferences saved");
          onClose();
        }}>
          <Icon name="check" size={12} color="#fff" /> {window.t("Save preferences")}
        </button>
      </div>
    </Modal>);

}

// ── Workspace modal (switch / add / edit / delete) ───────────
function WorkspaceModal({ workspace, onChange, onClose, onToast }) {
  const active = workspace || WORKSPACES[0];
  const [, force] = useState(0);
  const [editing, setEditing] = useState(null);   // null | { id?, label, cities: "a, b" }
  const refresh = () => force((x) => x + 1);

  const startAdd = () => setEditing({ label: "", cities: "" });
  const startEdit = (w) => setEditing({ id: w.id, label: w.label, cities: (w.cities || []).join(", ") });
  const addArea = (area) => setEditing((e) => ({
    ...e,
    label: e.label || area,
    cities: [...new Set([...(e.cities || "").split(",").map((s) => s.trim()).filter(Boolean), ...BUSCO_KSA_AREAS[area]])].join(", "),
  }));
  const saveEditing = () => {
    const cities = editing.cities.split(",").map((s) => s.trim()).filter(Boolean);
    if (!editing.label.trim() || !cities.length) { onToast && onToast(t("Give the workspace a name and at least one city"), "danger"); return; }
    const list = buscoCustomWorkspaces();
    if (editing.id) {
      const i = list.findIndex((w) => w.id === editing.id);
      if (i >= 0) list[i] = { ...list[i], label: editing.label.trim(), cities };
    } else {
      list.push({ id: "ws-" + Date.now(), label: editing.label.trim(), cities });
    }
    buscoSaveCustomWorkspaces(list);
    setEditing(null); refresh();
    onToast && onToast(t("Workspace saved"));
  };
  const removeWs = (w) => {
    buscoSaveCustomWorkspaces(buscoCustomWorkspaces().filter((x) => x.id !== w.id));
    if (active.id === w.id && onChange) onChange(WORKSPACES[0]);
    refresh();
  };

  return (
    <Modal title={t("Workspaces")} onClose={onClose} maxWidth={520}>
      <div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 14 }}>
        {t("Switch the active region — or create your own (e.g. Eastern province only). Custom workspaces match entries by city name.")}
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {buscoAllWorkspaces().map((w) =>
          <div key={w.id} className={"ws-row" + (w.id === active.id ? " on" : "")} style={{ cursor: "default" }}>
            <span className="ws-row-dot" />
            <span style={{ flex: 1, textAlign: "start", cursor: "pointer" }}
              onClick={() => { onChange && onChange(w); onClose(); }}>
              <span style={{ display: "block", fontSize: 13, fontWeight: 600 }}>{t(w.label)}</span>
              <span style={{ display: "block", fontSize: 11, color: "var(--muted)", marginTop: 1 }}>{t(w.sub)}</span>
            </span>
            {w.custom &&
              <>
                <button className="btn ghost sm" title={t("Edit")} onClick={() => startEdit(w)}><Icon name="edit" size={12} /></button>
                <button className="btn ghost sm" title={t("Delete")} onClick={() => removeWs(w)}><Icon name="trash" size={12} color="var(--crit)" /></button>
              </>
            }
            {w.id === active.id
              ? <span className="badge badge-brand" style={{ fontSize: 10 }}>{t("Active")}</span>
              : <span className="badge badge-slate" style={{ fontSize: 10, cursor: "pointer" }} onClick={() => { onChange && onChange(w); onClose(); }}>{t("Switch")}</span>}
          </div>
        )}
      </div>

      {editing ? (
        <div style={{ marginTop: 14, border: "1px solid var(--b100)", background: "var(--b50)", borderRadius: "var(--r-md)", padding: 14, display: "flex", flexDirection: "column", gap: 10 }}>
          <div className="field">
            <label>{t("Workspace name")}</label>
            <input value={editing.label} onChange={(e) => setEditing({ ...editing, label: e.target.value })} placeholder={t("e.g. Eastern province")} />
          </div>
          <div className="field">
            <label>{t("Cities / areas it covers")}</label>
            <input value={editing.cities} onChange={(e) => setEditing({ ...editing, cities: e.target.value })} placeholder={t("Dammam, Khobar, Jubail — comma-separated")} />
            <div style={{ fontSize: 10.5, color: "var(--muted)", marginTop: 4 }}>{t("Matching is by city name — \"Riyadh\" also catches \"Riyadh North Hub\".")}</div>
          </div>
          <div>
            <div className="label-tiny" style={{ marginBottom: 6 }}>{t("Quick add — KSA areas")}</div>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              {Object.keys(BUSCO_KSA_AREAS).map((a) => (
                <button key={a} className="btn sm" onClick={() => addArea(a)}>{t(a)}</button>
              ))}
            </div>
          </div>
          <div style={{ display: "flex", justifyContent: "flex-end", gap: 8 }}>
            <button className="btn sm" onClick={() => setEditing(null)}>{t("Cancel")}</button>
            <button className="btn primary sm" onClick={saveEditing}><Icon name="check" size={12} color="#fff" /> {t("Save workspace")}</button>
          </div>
        </div>
      ) : (
        <button className="btn sm" style={{ marginTop: 14 }} onClick={startAdd}>
          <Icon name="plus" size={12} /> {t("Add workspace")}
        </button>
      )}
    </Modal>);

}

Object.assign(window, {
  Icon, Header, UserMenu, WorkspaceChip, SignInModal, SectionNav, PageBar, SECTIONS, WORKSPACES,
  RateBadge, TierBadge, SourceBadge, ContractBadge,
  KPI, Sparkline, Segmented, PillRow, MultiSelect, Modal, Toast, RateCell,
  Popover, ExportMenu, BriefReportModal, PasteReportModal,
  FilterPopover, DatePopover, ConfirmModal,
  AccountSettingsModal, PreferencesModal, WorkspaceModal,
  opsNav, opsAccount, buildBriefReport
});