/* App root — auth, routing, role/theme context, toasts */
const { useState: useStateApp, useEffect: useEffectApp, useMemo: useMemoApp, useCallback: useCallbackApp } = React;

const ROLE_USER = { admin: "u1", fulfillment: "u2", finance: "u4", support: "u5" };
const ROLE_VIEWS = {
  admin: ["overview", "orders", "activation", "shipping", "inventory", "audit", "settings"],
  fulfillment: ["overview", "activation", "shipping"],
};
const firstView = (r) => (ROLE_VIEWS[r] || ROLE_VIEWS.admin)[0];

function ToastStack({ toasts, dismiss }) {
  return React.createElement("div", { style: { position: "fixed", bottom: 0, right: 0, zIndex: 200, display: "flex", flexDirection: "column-reverse", gap: 10, padding: 24 } },
    toasts.map((t) => React.createElement("div", { key: t.id, className: "co-toast" + (t.task ? " task" : "") },
      React.createElement("div", { className: "co-toast-icon" + (t.task ? " task" : "") }, React.createElement(window.Icon, { name: t.icon || "bell" })),
      React.createElement("div", { style: { flex: 1, minWidth: 0 } },
        React.createElement("div", { style: { fontWeight: 700, fontSize: t.task ? 15 : 13.5 } }, t.title),
        t.body && React.createElement("div", { style: { fontSize: 12.5, color: "var(--co-text-2)", marginTop: 3 } }, t.body),
        t.action && React.createElement("button", { className: "co-btn " + (t.task ? "co-btn-primary" : "co-btn-secondary") + " co-btn-sm", style: { marginTop: 11 }, onClick: () => { t.action.fn(); dismiss(t.id); } }, t.action.label)),
      React.createElement("button", { className: "co-icon-btn", style: { width: 28, height: 28, background: "none", border: "none" }, onClick: () => dismiss(t.id) },
        React.createElement(window.Icon, { name: "x", size: 15 })))));
}

function App() {
  const [authed, setAuthed] = useStateApp(false);
  const [role, setRole] = useStateApp("fulfillment");
  const [theme, setTheme] = useStateApp("light");
  const [view, setView] = useStateApp("overview");
  const [viewFilter, setViewFilter] = useStateApp(null);
  const [product, setProduct] = useStateApp("All");
  const [country, setCountry] = useStateApp("all");
  const [selectedOrder, setSelectedOrder] = useStateApp(null);
  const [wizardOpen, setWizardOpen] = useStateApp(false);
  const [wizardPre, setWizardPre] = useStateApp(null);
  const [shipOpen, setShipOpen] = useStateApp(false);
  const [shipPre, setShipPre] = useStateApp(null);
  const [bump, setBump] = useStateApp(0);
  const [aiForce, setAiForce] = useStateApp("auto");
  const [toasts, setToasts] = useStateApp([]);
  const [sidebarOpen, setSidebarOpen] = useStateApp(false);
  const [loading, setLoading] = useStateApp(false);

  useEffectApp(() => { document.documentElement.dataset.theme = theme; }, [theme]);

  const user = useMemoApp(() => {
    const base = window.CardOps.USERS.find((u) => u.id === ROLE_USER[role]) || window.CardOps.USERS[1];
    return { ...base, role };
  }, [role]);

  const addToast = useCallbackApp((t) => {
    const id = Math.random().toString(36).slice(2);
    setToasts((cur) => [...cur, { ...t, id }]);
    setTimeout(() => setToasts((cur) => cur.filter((x) => x.id !== id)), t.sticky ? 12000 : 6500);
  }, []);
  const dismiss = useCallbackApp((id) => setToasts((cur) => cur.filter((x) => x.id !== id)), []);

  // simulate per-view load
  const go = useCallbackApp((v, filter) => {
    setView(v); setViewFilter(filter || null); setSidebarOpen(false);
    setLoading(true);
    setTimeout(() => setLoading(false), 420);
  }, []);
  const canView = useCallbackApp((v) => (ROLE_VIEWS[role] || ROLE_VIEWS.admin).includes(v), [role]);

  // land on the right home view for the role after login
  useEffectApp(() => { if (authed) go(firstView(role)); }, [authed]);

  // task popups on login — the operator's main jobs, front and centre
  useEffectApp(() => {
    if (!authed) return;
    const acts = window.CardOps.ORDERS.filter((o) => ["fee_paid", "activating"].includes(o.status)).length;
    const ships = window.CardOps.ORDERS.filter((o) => o.deliver && o.status === "activated").length;
    const t = setTimeout(() => {
      addToast({ icon: "activate", task: true, sticky: true, title: acts + " new cards to activate", body: "Paid premium orders waiting in your queue.", action: { label: "Go to Activation", fn: () => go("activation") } });
      addToast({ icon: "truck", task: true, sticky: true, title: ships + " shipments to send", body: "Activated cards ready to ship out.", action: { label: "Go to Shipping", fn: () => go("shipping") } });
    }, 850);
    return () => clearTimeout(t);
  }, [authed]);

  const openOrder = useCallbackApp((o) => setSelectedOrder(o), []);
  const startActivation = useCallbackApp((o) => { setWizardPre(o); setWizardOpen(true); }, []);
  const startShipping = useCallbackApp((o) => { setShipPre(o); setShipOpen(true); }, []);

  const onAction = useCallbackApp((kind, o) => {
    const me = (window.CardOps.USERS.find((u) => u.role === role) || {}).name || "you";
    const stamp = (title) => { o.timeline = o.timeline.concat([{ title, who: me, source: null, time: "Jun 22 · now" }]); };
    if (kind === "block") {
      o.status = "blocked"; stamp("Card blocked");
      addToast({ icon: "ban", title: "Card blocked", body: o.ref + " · " + o.holder + " — blocked and logged." });
      setBump((b) => b + 1); return;
    }
    if (kind === "unblock") {
      o.status = !o.deliver ? "live_virtual" : "activated"; stamp("Card unblocked");
      addToast({ icon: "shieldcheck", title: "Card unblocked", body: o.ref + " is active again." });
      setBump((b) => b + 1); return;
    }
    if (kind === "assign_new") {
      stamp("New card assigned — activation required"); o.status = "activating";
      addToast({ icon: "card", title: "New card assigned", body: o.ref + " moved into the activation flow." });
      setSelectedOrder(null); startActivation(o); return;
    }
    if (kind === "lost") {
      stamp("Reported lost — old card blocked, new card to be issued"); o.status = "activating";
      addToast({ icon: "rotate", title: "Card reported lost", body: o.ref + " — old card blocked; assign a new card to re-activate." });
      setSelectedOrder(null); startActivation(o); return;
    }
    if (kind === "details_saved") {
      addToast({ icon: "note", title: "Cardholder details updated", body: o.ref + " — name, contact & address saved and logged." });
      setBump((b) => b + 1); return;
    }
    const map = {
      ship: { icon: "truck", title: "Marked shipped", body: o.ref + " · " + o.holder + " — shipping label created." },
      remind: { icon: "send", title: "Reminder sent", body: "Payment/renewal reminder sent to " + o.holder + "." },
    };
    addToast(map[kind]);
    setSelectedOrder(null);
  }, [addToast, role, startActivation]);

  if (!authed) return React.createElement(window.Login, { onLogin: (r) => { if (r) setRole(r); setAuthed(true); } });

  const counts = {
    orders: window.CardOps.ORDERS.length,
    activation: window.CardOps.ORDERS.filter((o) => ["fee_paid", "activating"].includes(o.status)).length,
    shipping: window.CardOps.ORDERS.filter((o) => o.deliver && o.status === "activated").length,
  };

  let page;
  if (view === "overview") page = React.createElement(window.Overview, { onOpenOrder: openOrder, onNav: go, loading, role });
  else if (view === "orders") page = React.createElement(window.Orders, { globalProduct: product, setProduct, globalCountry: country, setCountry, role, selectedOrder, onOpenOrder: openOrder, onCloseOrder: () => setSelectedOrder(null), onStartActivation: startActivation, initialFilter: viewFilter, onAction, loading });
  else if (view === "activation") page = React.createElement(window.ActivationView, { role, onStartActivation: startActivation, aiForce, setAiForce, loading });
  else if (view === "shipping") page = React.createElement(window.ShippingView, { role, onStartShipping: startShipping, loading });
  else if (view === "inventory") page = React.createElement(window.Inventory, { globalCountry: country, setCountry, role, loading });
  else if (view === "audit") page = React.createElement(window.AuditLog, { role, globalCountry: country, loading, addToast });
  else if (view === "settings") page = React.createElement(window.Settings, { role });

  return React.createElement("div", { className: "co-app" },
    React.createElement(window.Sidebar, { view, setView: go, counts, open: sidebarOpen, onClose: () => setSidebarOpen(false), canView }),
    React.createElement("div", { className: "co-main" },
      React.createElement(window.Topbar, {
        user, theme, setTheme,
        onSwitchRole: (r) => { setRole(r); if (!(ROLE_VIEWS[r] || []).includes(view)) go(firstView(r)); addToast({ icon: "user", title: "Viewing as " + window.CardOps.ROLES[r].label, body: "Navigation and actions update across the app." }); },
        onLogout: () => { setAuthed(false); setView("overview"); },
        product, setProduct, country, setCountry,
        onOpenOrder: (o) => { if (canView("orders")) { go("orders"); setTimeout(() => openOrder(o), 50); } else { openOrder(o); } },
        onBurger: () => setSidebarOpen(true),
      }),
      React.createElement("div", { className: "co-scroll" }, page)),

    wizardOpen && React.createElement(window.ActivationWizard, {
      role, preselect: wizardPre, aiForce, setAiForce,
      onClose: () => setWizardOpen(false),
      onComplete: () => {}, addToast,
    }),

    shipOpen && React.createElement(window.ShippingWizard, {
      role, preselect: shipPre, addToast,
      onClose: () => setShipOpen(false),
      onShipped: () => setBump((b) => b + 1),
    }),

    (view !== "orders" && selectedOrder) && React.createElement(window.OrderDrawer, { order: selectedOrder, role, onClose: () => setSelectedOrder(null), onStartActivation: startActivation, onAction }),

    React.createElement(ToastStack, { toasts, dismiss }));
}

ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(App));
