// Main App — VaultOS operator cockpit
const { useState, useEffect, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "accent": "indigo",
  "density": "comfortable",
  "sidebar": "expanded"
}/*EDITMODE-END*/;

// Map accent name -> hex for TweakColor swatches
const ACCENT_HEX = { indigo: "#4f46e5", cyan: "#06b6d4", emerald: "#10b981", amber: "#f59e0b" };
const HEX_TO_ACCENT = Object.fromEntries(Object.entries(ACCENT_HEX).map(([k,v]) => [v.toLowerCase(), k]));

const App = () => {
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = useState("dashboard");
  const [pickedUnit, setPickedUnit] = useState(null);

  // Apply tweaks to root
  useEffect(() => {
    const r = document.documentElement;
    r.dataset.theme = t.theme;
    r.dataset.accent = t.accent;
    r.dataset.density = t.density;
  }, [t.theme, t.accent, t.density]);

  const handlePickUnit = (uOrId) => {
    if (typeof uOrId === "string") {
      const u = window.VAULT_DATA.UNITS.find(x => x.id === uOrId);
      if (u) setPickedUnit(u);
    } else {
      setPickedUnit(uOrId);
    }
  };

  const Panel = window.Views.UnitPanel;

  // Routing
  let view;
  if (route === "dashboard")  view = <window.Dashboard onSelectUnit={handlePickUnit} onGoTo={setRoute} />;
  else if (route === "map" || route === "units") view = <window.FacilityMap onPickUnit={handlePickUnit} />;
  else if (route === "customers") view = <window.Views.Customers onPickUnit={handlePickUnit} />;
  else if (route === "billing")   view = <window.Views.Billing onPickUnit={handlePickUnit} />;
  else if (route === "automation")view = <window.Views.Automation />;
  else if (route === "access")    view = <window.Views.Access />;
  else if (route === "portfolio") view = <window.Views.Portfolio />;
  else if (route === "analytics") view = <window.Views.Analytics />;
  else if (route === "bookings")  view = <window.Views.Placeholder name="Bookings" icon="bookings" />;
  else if (route === "comms")     view = <window.Views.Placeholder name="Communications" icon="comms" />;
  else if (route === "auctions")  view = <window.Views.Placeholder name="Auctions" icon="auctions" />;
  else view = <window.Views.Placeholder name="Settings" icon="settings" />;

  const accentHex = ACCENT_HEX[t.accent] || ACCENT_HEX.indigo;

  return (
    <div className="app" data-sidebar={t.sidebar === "collapsed" ? "collapsed" : "expanded"}>
      <window.AppChrome.Sidebar
        active={route}
        onNav={setRoute}
        collapsed={t.sidebar === "collapsed"}
      />
      <div className="main">
        <window.AppChrome.Topbar
          active={route}
          theme={t.theme}
          onTheme={() => setTweak("theme", t.theme === "dark" ? "light" : "dark")}
          onSidebar={() => setTweak("sidebar", t.sidebar === "collapsed" ? "expanded" : "collapsed")}
        />
        <div className="content" style={{ position: "relative" }}>
          {view}
          {pickedUnit && <Panel unit={pickedUnit} onClose={() => setPickedUnit(null)} />}
        </div>
      </div>

      {/* Tweaks panel */}
      <window.TweaksPanel title="Tweaks">
        <window.TweakSection label="Appearance">
          <window.TweakRadio
            label="Theme"
            value={t.theme}
            options={[
              { value: "dark",  label: "Dark" },
              { value: "light", label: "Light" },
            ]}
            onChange={(v) => setTweak("theme", v)}
          />
          <window.TweakColor
            label="Accent"
            value={accentHex}
            options={["#4f46e5", "#06b6d4", "#10b981", "#f59e0b"]}
            onChange={(hex) => setTweak("accent", HEX_TO_ACCENT[hex.toLowerCase()] || "indigo")}
          />
        </window.TweakSection>

        <window.TweakSection label="Layout">
          <window.TweakRadio
            label="Density"
            value={t.density}
            options={[
              { value: "compact",     label: "Compact" },
              { value: "comfortable", label: "Default" },
              { value: "roomy",       label: "Roomy" },
            ]}
            onChange={(v) => setTweak("density", v)}
          />
          <window.TweakRadio
            label="Sidebar"
            value={t.sidebar}
            options={[
              { value: "expanded",  label: "Expanded" },
              { value: "collapsed", label: "Collapsed" },
            ]}
            onChange={(v) => setTweak("sidebar", v)}
          />
        </window.TweakSection>

        <window.TweakSection label="Navigate">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
            {[
              ["dashboard","Dashboard"],
              ["map","Facility"],
              ["customers","Customers"],
              ["billing","Billing"],
              ["automation","Automation"],
              ["access","Access"],
              ["portfolio","Portfolio"],
              ["analytics","Analytics"],
            ].map(([id, lbl]) => (
              <button key={id}
                onClick={() => setRoute(id)}
                style={{
                  background: route === id ? accentHex : "rgba(0,0,0,0.05)",
                  color: route === id ? "white" : "#29261b",
                  border: "1px solid rgba(0,0,0,0.08)",
                  borderRadius: 6, padding: "6px 8px",
                  fontSize: 11, fontWeight: 500,
                  cursor: "pointer",
                  fontFamily: "inherit",
                }}
              >{lbl}</button>
            ))}
          </div>
        </window.TweakSection>
      </window.TweaksPanel>
    </div>
  );
};

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