// AMOMS · Admin Web — System / status screens (SYS-01…06).
// Standalone screens (no admin shell). Each HTML sets window.SYS_KIND and this
// file renders the matching state. Reuses window.Icons + <Button>/<ToastProvider>
// from the shared design system. Missing glyphs are merged in below.

(function () {
  const I = ({ children, size = 16, ...rest }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
         stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"
         {...rest}>{children}</svg>
  );
  Object.assign(window.Icons, {
    WifiOff: window.Icons.WifiOff || ((p)=> <I {...p}><path d="M2 2l20 20"/><path d="M8.5 16.5a5 5 0 0 1 7 0"/><path d="M5 12.5a10 10 0 0 1 4-2.6"/><path d="M19 12.5a10 10 0 0 0-4.5-2.8"/><path d="M2 8.8A15 15 0 0 1 6 6.3M22 8.8a15 15 0 0 0-7-3.6"/><path d="M12 20h.01"/></I>),
    Refresh: window.Icons.Refresh || ((p)=> <I {...p}><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/><path d="M3 21v-5h5"/></I>),
    Compass: (p)=> <I {...p}><circle cx="12" cy="12" r="9"/><path d="M15.5 8.5l-2 5-5 2 2-5z"/></I>,
  });
})();

const Ic = window.Icons;
const HOME = "../procurement/ADM-PROC-01.html";
const LOGIN = "../core/CORE-01.html";

const SYS = {
  notFound: {
    tone: "neutral", icon: Ic.Compass, code: "404", title: "We can't find that page",
    desc: "The screen you're looking for may have been moved, renamed, or never existed. Check the address or head back to your dashboard.",
    actions: (
      <>
        <Button variant="primary" onClick={()=> { window.location.href = HOME; }}><Ic.Home size={15}/>Back to dashboard</Button>
        <Button variant="outline" onClick={()=> history.back()}><Ic.ArrowLeft size={15}/>Go back</Button>
      </>
    ),
    support: <>Still stuck? Contact <b>it@amoms.co.ke</b> with the URL you were trying to reach.</>,
  },
  sessionExpired: {
    tone: "warn", icon: Ic.Lock, code: "401", title: "Your session has expired",
    desc: "For your security, you were signed out after a period of inactivity. Sign in again to pick up where you left off.",
    actions: (
      <>
        <Button variant="primary" onClick={()=> { window.location.href = LOGIN; }}><Ic.ArrowRight size={15}/>Sign in again</Button>
      </>
    ),
    support: <>Sessions time out after 30 minutes of inactivity. Unsaved changes may not have been kept.</>,
  },
  forbidden: {
    tone: "danger", icon: Ic.Shield, code: "403", title: "You don't have access to this",
    desc: "Your role doesn't include permission for this area. If you believe this is a mistake, ask your administrator to review your access.",
    actions: (
      <>
        <Button variant="primary" onClick={()=> { window.location.href = HOME; }}><Ic.Home size={15}/>Back to dashboard</Button>
        <Button variant="outline" onClick={()=> { window.location.href = "mailto:admin@amoms.co.ke?subject=Access%20request"; }}><Ic.Mail size={15}/>Request access</Button>
      </>
    ),
    support: <>Signed in as <b>Caroline Wanjala</b> · Plant Manager. Access is managed in Settings → Users & roles.</>,
  },
  serverError: {
    tone: "danger", icon: Ic.Warning, code: "500", title: "Something went wrong on our end",
    desc: "An unexpected error stopped this page from loading. The issue has been logged — try again in a moment.",
    actions: (
      <>
        <Button variant="primary" onClick={()=> window.location.reload()}><Ic.Refresh size={15}/>Try again</Button>
        <Button variant="outline" onClick={()=> { window.location.href = HOME; }}><Ic.Home size={15}/>Back to dashboard</Button>
      </>
    ),
    refId: "ERR-7F3A2C91",
  },
  offline: {
    tone: "neutral", pulse: true, icon: Ic.WifiOff, eyebrow: "No connection",
    title: "You're offline", 
    desc: "AMOMS can't reach the server right now. Check your network — this page will reconnect automatically when the connection returns.",
    actions: (
      <>
        <Button variant="primary" onClick={()=> window.location.reload()}><Ic.Refresh size={15}/>Retry now</Button>
      </>
    ),
    support: <>Any changes you make while offline are not saved to the server.</>,
  },
  maintenance: {
    tone: "info", icon: Ic.Maintenance, eyebrow: "Scheduled maintenance",
    title: "AMOMS is being upgraded",
    desc: "We're performing scheduled maintenance to improve the platform. Everything will be back automatically — no action needed.",
    note: [
      ["Started", "26 Jul 2026, 01:00"],
      ["Expected back", "26 Jul 2026, 03:00 EAT"],
      ["Affected", "All web modules"],
    ],
    actions: (
      <>
        <Button variant="outline" onClick={()=> window.location.reload()}><Ic.Refresh size={15}/>Check again</Button>
      </>
    ),
    support: <>Urgent? Reach the operations desk at <b>ops@amoms.co.ke</b>.</>,
  },
};

const SystemScreen = () => {
  const kind = window.SYS_KIND || "notFound";
  const s = SYS[kind] || SYS.notFound;
  const Glyph = s.icon;
  return (
    <div className="sys-stage">
      <div className="sys-wrap">
        <div className="sys-card">
          <div className="sys-brand"><span className="m"><Ic.Leaf size={15}/></span> AMOMS · Admin</div>
          <span className={`sys-badge ${s.tone} ${s.pulse ? "pulse" : ""}`}><Glyph size={38}/></span>
          {s.code && <div className="sys-code">{s.code}</div>}
          {s.eyebrow && <div className="sys-eyebrow">{s.eyebrow}</div>}
          <div className="sys-title">{s.title}</div>
          <div className="sys-desc">{s.desc}</div>
          {s.note && (
            <div className="sys-note">
              {s.note.map(([k, v]) => (
                <div className="sys-note-row" key={k}><span className="k">{k}</span><span className="v">{v}</span></div>
              ))}
            </div>
          )}
          <div className={`sys-actions ${s.code ? "" : "stack"}`}>{s.actions}</div>
          {s.refId && <div className="sys-ref"><Ic.File size={13}/> Reference <b>{s.refId}</b></div>}
          {s.support && <div className="sys-support">{s.support}</div>}
        </div>
      </div>
    </div>
  );
};

const SysApp = () => {
  const [t, setTweak] = window.useTweaks
    ? window.useTweaks({ dark: false, bgPattern: "two", palette: "grove" })
    : [{ dark: false, bgPattern: "two", palette: "grove" }, () => {}];
  useEffect(() => { document.documentElement.classList.toggle("dark", !!t.dark); }, [t.dark]);
  useEffect(() => { document.documentElement.setAttribute("data-pattern", t.bgPattern || "two"); }, [t.bgPattern]);
  useEffect(() => { document.documentElement.setAttribute("data-palette", t.palette || "grove"); }, [t.palette]);
  return (
    <>
      <SystemScreen/>
      {window.TweaksPanel && (
        <window.TweaksPanel title="Tweaks">
          <window.TweakSection label="Appearance">
            <window.TweakToggle label="Dark mode" value={t.dark} onChange={(v)=> setTweak("dark", v)}/>
            <window.TweakSelect label="Colour palette" value={t.palette || "grove"} onChange={(v)=> setTweak("palette", v)}
              options={[{value:"grove", label:"Grove (avocado · default)"},{value:"harvest", label:"Harvest (olive · pumpkin)"},{value:"orchard", label:"Orchard (teal · plum)"}]}/>
            <window.TweakSelect label="Background pattern" value={t.bgPattern || "two"} onChange={(v)=> setTweak("bgPattern", v)}
              options={[{value:"two", label:"Fields"},{value:"mosaic", label:"Mosaic"},{value:"botanical", label:"Botanical"},{value:"none", label:"None"}]}/>
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </>
  );
};

const sysRoot = ReactDOM.createRoot(document.getElementById("root"));
sysRoot.render(<ToastProvider><SysApp/></ToastProvider>);
