/* global React, ReactDOM, Ic, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakSelect, TweakToggle */
/* global LoadBoard, CheckCalls, CarrierMatch, RateDesk, Dispatch, ShipperPortal, DocumentAI, Analytics, Onboarding, Inbox */
/* global AIConsole, FraudShield, RFPEngine, Accounting, Claims, CRM, Appointments, Compliance, Integrations */

const { useState, useEffect } = React;

const NAV = [
  { group: "Ops" },
  { id: "loads",    label: "Load Board",       icon: Ic.load,    badge: 47 },
  { id: "calls",    label: "AI Check Calls",   icon: Ic.phone,   badge: 12, live: true },
  { id: "dispatch", label: "Dispatch & Track", icon: Ic.map },
  { id: "appts",    label: "Appointments",     icon: Ic.portal,  badge: 42 },
  { id: "inbox",    label: "Agent Inbox",      icon: Ic.inbox,   badge: 8 },

  { group: "Commerce" },
  { id: "rates",    label: "Rate Desk",        icon: Ic.cash },
  { id: "rfp",      label: "RFP Engine",       icon: Ic.spark,   badge: 2, live: true },
  { id: "carriers", label: "Carrier Match",    icon: Ic.truck },
  { id: "onboard",  label: "Carrier Onboarding", icon: Ic.shield, badge: 3 },
  { id: "crm",      label: "CRM",              icon: Ic.chart },
  { id: "portal",   label: "Shipper Portal",   icon: Ic.portal },

  { group: "Finance" },
  { id: "accounting", label: "Accounting",     icon: Ic.cash,    badge: 8 },
  { id: "claims",     label: "Claims",         icon: Ic.shield,  badge: 4 },

  { group: "Intelligence" },
  { id: "aiconsole", label: "AI Console",      icon: Ic.bot,     live: true },
  { id: "fraud",     label: "Fraud Shield",    icon: Ic.shield,  badge: 2, live: true },
  { id: "docs",      label: "Document AI",     icon: Ic.doc,     badge: 21 },
  { id: "compliance",label: "Compliance",      icon: Ic.check },
  { id: "analytics", label: "Analytics",       icon: Ic.chart },

  { group: "System" },
  { id: "integrations", label: "Integrations", icon: Ic.spark,   badge: 28 },
];

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "density": "medium",
  "theme": "light",
  "palette": "brass",
  "aiPersonality": "balanced",
  "callVariant": "live"
}/*EDITMODE-END*/;

// Plays the broker-flow demo video in a full-screen overlay.
// "broker" is the canonical demo per the BMS page brief; "ai" is the legacy
// AI-first cut, kept available for completeness.
function DemoOverlay({ mode, setMode }) {
  const src = mode === "ai" ? "demo-ai.html" : "demo-broker-flow.html";
  return (
    <div
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 10000,
        background: "rgba(20, 18, 16, 0.92)",
        backdropFilter: "blur(8px)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 24,
      }}
      onClick={() => setMode(null)}
    >
      <div
        style={{
          position: "relative",
          width: "100%",
          maxWidth: 1600,
          aspectRatio: "16 / 9",
          background: "#2a2724",
          borderRadius: 8,
          overflow: "hidden",
          boxShadow: "0 30px 80px rgba(0,0,0,0.6)",
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <iframe
          src={src}
          title="Keelway demo video"
          style={{ width: "100%", height: "100%", border: 0, display: "block" }}
          allow="autoplay"
        />
        <button
          onClick={() => setMode(null)}
          aria-label="Close demo"
          style={{
            position: "absolute",
            top: 12,
            right: 12,
            width: 32,
            height: 32,
            borderRadius: 16,
            background: "rgba(0,0,0,0.5)",
            color: "#fff",
            border: "1px solid rgba(255,255,255,0.2)",
            cursor: "pointer",
            fontFamily: "IBM Plex Mono, monospace",
            fontSize: 14,
            lineHeight: "30px",
            padding: 0,
          }}
        >
          ✕
        </button>
      </div>
    </div>
  );
}

function App() {
  const [route, setRoute] = useState("loads");
  const [navCollapsed, setNavCollapsed] = useState(false);
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [demoMode, setDemoMode] = useState(null); // null | "broker" | "ai"

  // URL params: ?demo=broker | ai — for website click-through
  useEffect(() => {
    const p = new URLSearchParams(window.location.search).get("demo");
    if (p === "broker" || p === "ai") setDemoMode(p);
  }, []);

  // ESC closes demo
  useEffect(() => {
    if (!demoMode) return;
    const h = (e) => { if (e.key === "Escape") setDemoMode(null); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [demoMode]);

  // sync theme/density/palette to body attributes
  useEffect(() => {
    document.body.dataset.theme = t.theme;
    document.body.dataset.density = t.density;
    document.body.dataset.palette = t.palette;
    document.body.dataset.navCollapsed = navCollapsed;
  }, [t.theme, t.density, t.palette, navCollapsed]);

  const renderRoute = () => {
    const ctx = { aiPersonality: t.aiPersonality, callVariant: t.callVariant, setTweak };
    switch (route) {
      case "loads":     return <LoadBoard ctx={ctx} />;
      case "calls":     return <CheckCalls ctx={ctx} />;
      case "carriers":  return <CarrierMatch ctx={ctx} />;
      case "rates":     return <RateDesk ctx={ctx} />;
      case "dispatch":  return <Dispatch ctx={ctx} />;
      case "portal":    return <ShipperPortal ctx={ctx} />;
      case "docs":      return <DocumentAI ctx={ctx} />;
      case "analytics": return <Analytics ctx={ctx} />;
      case "onboard":   return <Onboarding ctx={ctx} />;
      case "inbox":     return <Inbox ctx={ctx} />;
      case "aiconsole": return <AIConsole ctx={ctx} />;
      case "fraud":     return <FraudShield ctx={ctx} />;
      case "rfp":       return <RFPEngine ctx={ctx} />;
      case "accounting":return <Accounting ctx={ctx} />;
      case "claims":    return <Claims ctx={ctx} />;
      case "crm":       return <CRM ctx={ctx} />;
      case "appts":     return <Appointments ctx={ctx} />;
      case "compliance":return <Compliance ctx={ctx} />;
      case "integrations": return <Integrations ctx={ctx} />;
      default: return null;
    }
  };

  const currentNav = NAV.find(n => n.id === route);
  const groupOfCurrent = (() => {
    let g = "";
    for (const n of NAV) {
      if (n.group) g = n.group;
      if (n.id === route) return g;
    }
    return "";
  })();

  return (
    <>
      <div className="app">
        {/* Logo */}
        <div className="logo">
          <div className="logo-mark">K</div>
          {!navCollapsed && <>
            <div className="logo-text">Keelway</div>
            <div className="logo-sub">v2.4</div>
          </>}
        </div>

        {/* Topbar */}
        <div className="topbar">
          <div className="crumbs">
            <span>{groupOfCurrent}</span>
            <span className="sep">/</span>
            <span className="leaf">{currentNav?.label}</span>
          </div>

          <div className="cmdk">
            <Ic.search style={{ width: 12, height: 12 }} />
            <span>Search loads, carriers, orders…</span>
            <span className="kbd">⌘K</span>
          </div>

          <div className="topbar-right">
            <div className="tb-stat">
              <span className="tb-stat-label">Open Loads</span>
              <span className="tb-stat-val">147</span>
            </div>
            <div className="tb-stat">
              <span className="tb-stat-label">Today GM</span>
              <span className="tb-stat-val up">$48,210</span>
            </div>
            <div className="tb-stat">
              <span className="tb-stat-label">Margin</span>
              <span className="tb-stat-val">17.3%</span>
            </div>
            <div className="tb-stat">
              <span className="tb-stat-label">AI Actions</span>
              <span className="tb-stat-val">312</span>
            </div>
            <button
              className="btn sm"
              title="Watch demo"
              onClick={() => setDemoMode("broker")}
              style={{
                background: "var(--accent)",
                color: "#FFFFFF",
                border: "1px solid var(--accent)",
                fontWeight: 500,
              }}
            >
              <span style={{ fontSize: 9 }}>▶</span> Watch Demo
            </button>
            <button className="btn ghost sm" title="New">
              <Ic.plus style={{ width: 12, height: 12 }} />
              New
            </button>
            <div className="avatar" title="Maya Ortiz">MO</div>
          </div>
        </div>

        {/* Nav */}
        <nav className="nav">
          {NAV.map((n, i) => {
            if (n.group) return <div className="nav-group" key={i}>{n.group}</div>;
            const I = n.icon;
            return (
              <div
                key={n.id}
                className={`nav-item ${route === n.id ? "active" : ""}`}
                onClick={() => setRoute(n.id)}
                title={n.label}
              >
                <I className="ico" />
                <span className="lbl">{n.label}</span>
                {n.badge != null && (
                  <span className={`badge ${n.live ? "live" : ""}`}>{n.badge}</span>
                )}
              </div>
            );
          })}
          <div className="nav-foot">
            <span className="chip ok"><span className="dot pulse" /> AGENT LIVE</span>
            <span style={{ marginLeft: "auto", cursor: "pointer" }} onClick={() => setNavCollapsed(v => !v)}>
              {navCollapsed ? "›" : "‹"}
            </span>
          </div>
        </nav>

        {/* Main */}
        <main className="main">{renderRoute()}</main>

        {/* Status bar */}
        <div className="statusbar">
          <span><span className="dot" style={{ background: "var(--ok)" }} /> CONNECTED</span>
          <span>EDI 204/214 SYNC OK</span>
          <span>DAT · TRUCKSTOP · LOADBOARD · SAFER</span>
          <div className="right">
            <span>AGENT · MAYA ORTIZ</span>
            <span>NASHVILLE OPS</span>
            <span>{new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })} CT</span>
          </div>
        </div>
      </div>

      {demoMode && <DemoOverlay mode={demoMode} setMode={setDemoMode} />}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Theme">
          <TweakRadio
            label="Mode"
            value={t.theme}
            options={[{ value: "dark", label: "Dark" }, { value: "light", label: "Light" }]}
            onChange={(v) => setTweak("theme", v)}
          />
          <TweakSelect
            label="Palette"
            value={t.palette}
            options={[
              { value: "brass", label: "Brass (Keelway)" },
              { value: "teal", label: "Teal" },
              { value: "indigo", label: "Indigo" },
              { value: "emerald", label: "Emerald" },
              { value: "amber", label: "Amber" },
            ]}
            onChange={(v) => setTweak("palette", v)}
          />
          <TweakSelect
            label="Density"
            value={t.density}
            options={[
              { value: "compact", label: "Compact" },
              { value: "medium", label: "Medium" },
              { value: "comfortable", label: "Comfortable" },
            ]}
            onChange={(v) => setTweak("density", v)}
          />
        </TweakSection>
        <TweakSection label="AI Behavior">
          <TweakRadio
            label="Personality"
            value={t.aiPersonality}
            options={[
              { value: "terse", label: "Terse" },
              { value: "balanced", label: "Balanced" },
              { value: "warm", label: "Warm" },
            ]}
            onChange={(v) => setTweak("aiPersonality", v)}
          />
        </TweakSection>
        <TweakSection label="Check Calls layout">
          <TweakSelect
            label="Variant"
            value={t.callVariant}
            options={[
              { value: "live", label: "Live monitor + transcript" },
              { value: "queue", label: "Post-call summary queue" },
              { value: "map", label: "Map-centric, calls pinned" },
              { value: "thread", label: "Inbox / thread style" },
            ]}
            onChange={(v) => setTweak("callVariant", v)}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
