/* eslint-disable no-undef */
// Agrobotic — top-level shell, sidebar, mode switcher, hash routing, Tweaks integration.

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

// ------- Route parser (hash-based) -------
function parseHash() {
  const h = (window.location.hash || "#iot/pulse").replace(/^#/, "");
  const [mode, ...rest] = h.split("/");
  return { mode: mode || "iot", route: rest.join("/") || "pulse" };
}
function setHash(mode, route) { window.location.hash = `${mode}/${route}`; }

// ------- Sidebar groups -------
const IOT_NAV = [
  { group: "Operations", items: [
    { id: "pulse",     label: "Pulse",          icon: "pulse" },
    { id: "farms",     label: "Farms",          icon: "tractor" },
    { id: "satellite", label: "Satellite & soil", icon: "map" },
    { id: "alerts",    label: "Alerts",         icon: "alert" },
  ]},
  { group: "Network", items: [
    { id: "network", label: "LoRaWAN mesh",   icon: "network" },
  ]},
  { group: "Sensor families", items: [
    { id: "family/NitroSense",     label: "NitroSense",     icon: "leaf",    accent: "var(--green)"  },
    { id: "family/EcoSense",       label: "EcoSense",       icon: "cloud",   accent: "var(--cyan)"   },
    { id: "family/AquaSentinel",   label: "AquaSentinel",   icon: "droplet", accent: "var(--violet)" },
    { id: "family/AirWatch",       label: "AirWatch",       icon: "wifi",    accent: "var(--pink)"   },
    { id: "family/ForestSentinel", label: "ForestSentinel", icon: "flame",   accent: "var(--amber)"  },
    { id: "family/EcoNitro",       label: "EcoNitro ⚡",    icon: "cpu",     accent: "oklch(0.78 0.16 320)" },
  ]},
  { group: "Conditions", items: [
    { id: "conditions", label: "Soil · Water · Weather", icon: "layers" },
  ]},
];

const FT_NAV = [
  { group: "Capital", items: [
    { id: "portfolio", label: "Portfolio",        icon: "chart" },
    { id: "roi",       label: "Sensor ROI",       icon: "target" },
    { id: "markets",   label: "Markets",          icon: "market" },
  ]},
  { group: "Climate", items: [
    { id: "ghg",       label: "GHG tax",          icon: "gauge" },
    { id: "carbon",    label: "Carbon credits",   icon: "coin" },
  ]},
  { group: "Risk & ops", items: [
    { id: "water",     label: "Water · inputs",   icon: "droplet" },
    { id: "lending",   label: "Lending",          icon: "bank" },
    { id: "insurance", label: "Insurance",        icon: "shield" },
    { id: "reports",   label: "Reports",          icon: "file" },
  ]},
];

// ------- Logo -------
function Logo({ mode }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
        <path d="M5 21c0-8 5-15 16-15 0 11-7 16-15 16-1 0-1 0-1-1z" fill="var(--primary)" opacity="0.85" />
        <path d="M5 21l8-8" stroke="var(--bg)" strokeWidth="1.5" strokeLinecap="round" />
      </svg>
      <div style={{ display: "flex", alignItems: "baseline" }}>
        <span style={{ fontWeight: 700, fontSize: 15, letterSpacing: "-0.01em" }}>Agro</span>
        <span style={{ fontWeight: 700, fontSize: 15, color: "var(--primary)", letterSpacing: "-0.01em" }}>botic</span>
      </div>
    </div>
  );
}

// ------- Top bar -------
function TopBar({ mode, setMode, navigate }) {
  return (
    <div style={{
      height: "var(--topbar-h)", borderBottom: "1px solid var(--border)",
      display: "flex", alignItems: "center", padding: "0 16px 0 20px",
      background: "var(--bg-elev)", position: "sticky", top: 0, zIndex: 10,
    }}>
      <Logo mode={mode} />
      <div style={{ width: 1, height: 24, background: "var(--border)", margin: "0 16px" }} />
      {/* Mode switcher */}
      <div style={{ display: "inline-flex", padding: 3, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 8, gap: 2 }}>
        {[
          { id: "iot",     label: "IoT Platform",     icon: "sensor" },
          { id: "fintech", label: "Fintech Platform", icon: "coin" },
        ].map((m) => (
          <button key={m.id} onClick={() => setMode(m.id)}
            style={{
              border: 0, font: "inherit", fontSize: 13, fontWeight: 500,
              padding: "6px 14px", borderRadius: 6, cursor: "pointer",
              background: mode === m.id ? (m.id === "iot" ? "color-mix(in oklch, var(--green) 18%, var(--bg))" : "color-mix(in oklch, var(--cyan) 18%, var(--bg))") : "transparent",
              color: mode === m.id ? (m.id === "iot" ? "var(--green)" : "var(--cyan)") : "var(--text-dim)",
              display: "inline-flex", alignItems: "center", gap: 8,
              transition: "all .15s",
            }}>
            <Icon name={m.icon} size={14} />
            {m.label}
          </button>
        ))}
      </div>

      {/* Search */}
      <div style={{ marginLeft: 16, flex: 1, maxWidth: 420, display: "flex", alignItems: "center", gap: 8, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 8, padding: "6px 12px" }}>
        <Icon name="search" size={14} color="var(--text-faint)" />
        <input placeholder={`Search ${mode === "iot" ? "sensors, farms, alerts" : "farms, scenarios, reports"}…`}
               style={{ background: "transparent", border: 0, outline: 0, font: "inherit", color: "var(--text)", flex: 1, fontSize: 13 }} />
        <span className="kbd">⌘K</span>
      </div>

      <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 8 }}>
        <span className="tag ok" style={{ fontSize: 10 }}>
          <span className="pulse-dot" style={{ width: 6, height: 6 }} /> Live
        </span>

        {/* Notifications */}
        <Dropdown width={340} trigger={
          <button className="btn ghost" style={{ position: "relative" }}>
            <Icon name="bell" size={16} />
            <span style={{ position: "absolute", top: 5, right: 6, width: 7, height: 7, borderRadius: 999, background: "var(--rose)", border: "1.5px solid var(--bg-elev)" }} />
          </button>
        }>
          {(close) => <NotificationsMenu close={close} setMode={setMode} navigate={navigate} />}
        </Dropdown>

        {/* Settings */}
        <Dropdown width={260} trigger={<button className="btn ghost"><Icon name="settings" size={16} /></button>}>
          {(close) => <SettingsMenu close={close} navigate={navigate} setMode={setMode} />}
        </Dropdown>

        {/* Profile */}
        <Dropdown width={250} trigger={
          <button style={{ border: 0, background: "transparent", cursor: "pointer", padding: 0 }}>
            <div style={{ width: 30, height: 30, borderRadius: 999, background: "linear-gradient(135deg, var(--green), var(--cyan))", display: "grid", placeItems: "center", fontSize: 12, fontWeight: 600, color: "var(--bg)" }}>IE</div>
          </button>
        }>
          {(close) => <ProfileMenu close={close} />}
        </Dropdown>
      </div>
    </div>
  );
}

// ------- Topbar menus -------
function NotificationsMenu({ close, setMode, navigate }) {
  const { ALERTS, FARMS } = window.AGB_DATA;
  return (
    <div>
      <div style={{ padding: "12px 14px", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span style={{ fontWeight: 600, fontSize: 13 }}>Notifications</span>
        <span className="tag bad" style={{ fontSize: 10 }}>{ALERTS.filter((a) => a.severity === "high").length} high</span>
      </div>
      <div style={{ maxHeight: 320, overflowY: "auto" }}>
        {ALERTS.slice(0, 5).map((a) => (
          <div key={a.id} onClick={() => { close(); setMode("iot"); setTimeout(() => navigate("alerts"), 30); }}
            style={{ padding: "10px 14px", borderBottom: "1px solid var(--border-faint)", cursor: "pointer", display: "flex", gap: 10 }}
            onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface)"}
            onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
            <Severity level={a.severity} />
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 500 }}>{a.title}</div>
              <div className="dim" style={{ fontSize: 11, marginTop: 2 }}>{FARMS.find((f) => f.id === a.farm_id)?.name} · {a.t}</div>
            </div>
          </div>
        ))}
      </div>
      <button className="btn ghost" style={{ width: "100%", borderRadius: 0, padding: 12, justifyContent: "center" }}
        onClick={() => { close(); setMode("iot"); setTimeout(() => navigate("alerts"), 30); }}>View all alerts →</button>
    </div>
  );
}

function SettingsMenu({ close, navigate, setMode }) {
  const items = [
    { label: "Open Tweaks panel", icon: "settings", action: () => AGB_UI.toast("Toggle Tweaks from the toolbar to theme the app", { type: "info" }) },
    { label: "Preferences", icon: "cpu", action: () => AGB_UI.form({ eyebrow: "Settings", title: "Preferences", isForm: true, submitLabel: "Save preferences", fields: [
      { key: "units", label: "Units", type: "select", options: ["Metric (°C, ha, mm)", "Imperial (°F, ac, in)"] },
      { key: "tz", label: "Time zone", type: "select", options: ["Auto (farm-local)", "UTC", "America/Vancouver", "America/Chicago"] },
      { key: "refresh", label: "Live refresh interval", type: "range", min: 2, max: 60, step: 2, value: 4, suffix: "s" },
      { key: "alertEmail", label: "Send high-severity alerts to email", type: "checkbox", value: true },
    ], onSubmit: () => {} }) },
    { label: "Notification rules", icon: "bell", action: () => AGB_UI.form({ eyebrow: "Settings", title: "Notification rules", isForm: true, submitLabel: "Save rules", fields: [
      { key: "high", label: "High severity", type: "select", options: ["Push + Email + SMS", "Push + Email", "Push only"] },
      { key: "calib", label: "Calibration reminders", type: "select", options: ["7 days before due", "On due date", "Off"] },
      { key: "digest", label: "Daily digest", type: "checkbox", value: true },
    ], onSubmit: () => {} }) },
    { label: "API & integrations", icon: "network", action: () => AGB_UI.modal({ eyebrow: "Settings", title: "API & integrations", body: (
      <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        <KV k="CDSE / Sentinel Hub" v={<span className="tag warn">configure backend</span>} />
        <KV k="Open-Meteo" v={<span className="tag ok">connected</span>} />
        <KV k="OpenWeather" v={<span className="tag ok">connected</span>} />
        <KV k="Ambee" v={<span className="tag ok">connected</span>} />
        <KV k="LoRaWAN network server" v={<span className="tag ok">connected</span>} mono />
        <div className="dim" style={{ fontSize: 12, marginTop: 8 }}>Manage credentials in <span className="mono">secrets.txt</span>.</div>
      </div>
    ) }) },
  ];
  return (
    <div style={{ padding: 6 }}>
      {items.map((it) => (
        <button key={it.label} onClick={() => { close(); it.action(); }} className="menu-item">
          <Icon name={it.icon} size={15} color="var(--text-dim)" /> {it.label}
        </button>
      ))}
    </div>
  );
}

function ProfileMenu({ close }) {
  return (
    <div>
      <div style={{ padding: "14px", borderBottom: "1px solid var(--border)", display: "flex", gap: 10, alignItems: "center" }}>
        <div style={{ width: 36, height: 36, borderRadius: 999, background: "linear-gradient(135deg, var(--green), var(--cyan))", display: "grid", placeItems: "center", fontSize: 14, fontWeight: 600, color: "var(--bg)" }}>IE</div>
        <div>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Imran El-Chami</div>
          <div className="dim" style={{ fontSize: 11 }}>Operations · Agrobotic</div>
        </div>
      </div>
      <div style={{ padding: 6 }}>
        {[
          { label: "Account", icon: "users" },
          { label: "Billing & plan", icon: "coin" },
          { label: "Team members", icon: "users" },
          { label: "Help & docs", icon: "book" },
        ].map((it) => (
          <button key={it.label} className="menu-item" onClick={() => { close(); AGB_UI.toast(`${it.label} — coming soon`, { type: "info" }); }}>
            <Icon name={it.icon} size={15} color="var(--text-dim)" /> {it.label}
          </button>
        ))}
        <div className="h-rule" style={{ margin: "6px 0" }} />
        <button className="menu-item" onClick={() => { close(); AGB_UI.toast("Signed out", { type: "info" }); }}>
          <Icon name="close" size={15} color="var(--rose)" /> <span style={{ color: "var(--rose)" }}>Sign out</span>
        </button>
      </div>
    </div>
  );
}

// ------- Sidebar -------
function Sidebar({ mode, route, navigate, density }) {
  const groups = mode === "iot" ? IOT_NAV : FT_NAV;
  return (
    <aside style={{
      width: "var(--sidebar-w)", borderRight: "1px solid var(--border)",
      background: "var(--bg-elev)", padding: "16px 12px",
      overflowY: "auto", display: "flex", flexDirection: "column", gap: 18,
      position: "sticky", top: "var(--topbar-h)", height: "calc(100vh - var(--topbar-h))",
    }}>
      {groups.map((g) => (
        <div key={g.group}>
          <div className="section-title" style={{ padding: "0 8px", margin: "0 0 8px" }}>{g.group}</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 1 }}>
            {g.items.map((item) => {
              const isActive = route === item.id || (item.id.includes("/") && route.startsWith(item.id.split("/")[0] + "/" + item.id.split("/")[1]));
              return (
                <button key={item.id} onClick={() => navigate(item.id)}
                  style={{
                    border: 0, background: isActive ? "var(--surface-2)" : "transparent",
                    color: isActive ? "var(--text)" : "var(--text-dim)",
                    padding: "7px 10px", borderRadius: 6, fontSize: 13, fontWeight: 500,
                    cursor: "pointer", display: "flex", alignItems: "center", gap: 10,
                    textAlign: "left", font: "inherit",
                    position: "relative",
                  }}
                  onMouseEnter={(e) => { if (!isActive) e.currentTarget.style.background = "var(--surface)"; }}
                  onMouseLeave={(e) => { if (!isActive) e.currentTarget.style.background = "transparent"; }}>
                  {isActive && <span style={{ position: "absolute", left: -12, top: 8, bottom: 8, width: 2, background: item.accent || "var(--primary)", borderRadius: 2 }} />}
                  <Icon name={item.icon} size={15} color={isActive ? (item.accent || "var(--primary)") : "var(--text-faint)"} />
                  <span style={{ flex: 1 }}>{item.label}</span>
                </button>
              );
            })}
          </div>
        </div>
      ))}
      {/* Footer of sidebar */}
      <div style={{ marginTop: "auto", padding: "12px 8px 4px", borderTop: "1px solid var(--border-faint)", fontSize: 11 }}>
        <div className="dim" style={{ marginBottom: 6 }}>System</div>
        <div style={{ display: "flex", justifyContent: "space-between" }}><span className="faint">Build</span><span className="mono">v2.4.1</span></div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 4 }}><span className="faint">Region</span><span className="mono">CA-BC</span></div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 4 }}><span className="faint">Sync</span><span style={{ color: "var(--green)" }}>● live</span></div>
      </div>
    </aside>
  );
}

// ------- Router-aware page renderer -------
function PageRouter({ mode, route, navigate }) {
  // IoT routes
  if (mode === "iot") {
    if (route === "pulse") return <IoTPulse navigate={navigate} />;
    if (route === "farms") return <IoTFarms navigate={navigate} />;
    if (route.startsWith("farm/")) return <IoTFarmDetail farmId={route.split("/")[1]} navigate={navigate} />;
    if (route === "network") return <IoTNetwork navigate={navigate} />;
    if (route === "satellite") return <LiveSatellite navigate={navigate} />;
    if (route.startsWith("family/")) return <IoTFamily family={route.split("/")[1]} navigate={navigate} />;
    if (route === "conditions") return <IoTConditions navigate={navigate} />;
    if (route === "alerts") return <IoTAlerts navigate={navigate} />;
    return <Empty title="Page not found" body={`No route '${route}' in IoT mode.`} />;
  }
  // Fintech routes
  if (route === "portfolio") return <FtPortfolio navigate={navigate} />;
  if (route === "ghg")       return <FtGhgTax />;
  if (route === "carbon")    return <FtCarbon />;
  if (route === "roi")       return <FtRoi />;
  if (route === "markets")   return <FtMarkets />;
  if (route === "water")     return <FtWater />;
  if (route === "lending")   return <FtLending />;
  if (route === "insurance") return <FtInsurance />;
  if (route === "reports")   return <FtReports />;
  return <Empty title="Page not found" body={`No route '${route}' in Fintech mode.`} />;
}

// ------- Tweaks defaults -------
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "primaryHue": 148,
  "accentPalette": "default",
  "density": 1,
  "showSidebar": true,
  "showCanvasBg": true,
  "displayFont": "Geist"
}/*EDITMODE-END*/;

// ------- App -------
function App() {
  const [{ mode, route }, setLoc] = useState(parseHash());
  const [tweaks, setTweaks] = useTweaks(TWEAK_DEFAULTS);

  useEffect(() => {
    const onHash = () => setLoc(parseHash());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Apply mode to document
  useEffect(() => {
    document.documentElement.setAttribute("data-mode", mode);
  }, [mode]);

  // Apply tweaks live
  useEffect(() => {
    const root = document.documentElement;
    // Primary hue: shift green/cyan together via custom prop
    if (tweaks.primaryHue != null) {
      root.style.setProperty("--green", `oklch(0.82 0.17 ${tweaks.primaryHue})`);
      root.style.setProperty("--green-dim", `oklch(0.55 0.12 ${tweaks.primaryHue})`);
      root.style.setProperty("--green-glow", `oklch(0.82 0.17 ${tweaks.primaryHue} / 0.22)`);
    }
    root.style.setProperty("--density", String(tweaks.density || 1));
    if (tweaks.displayFont === "Geist") {
      root.style.setProperty("--font-ui", `"Geist", ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`);
    } else if (tweaks.displayFont === "Instrument Sans") {
      root.style.setProperty("--font-ui", `"Instrument Sans", ui-sans-serif, sans-serif`);
    } else if (tweaks.displayFont === "Space Grotesk") {
      root.style.setProperty("--font-ui", `"Space Grotesk", ui-sans-serif, sans-serif`);
    }
  }, [tweaks]);

  const setMode = (m) => {
    const def = m === "iot" ? "pulse" : "portfolio";
    setHash(m, def);
  };
  const navigate = (r) => setHash(mode, r);

  return (
    <div>
      <TopBar mode={mode} setMode={setMode} navigate={navigate} />
      <div style={{ display: "flex", minHeight: "calc(100vh - var(--topbar-h))" }}>
        {tweaks.showSidebar && <Sidebar mode={mode} route={route} navigate={navigate} />}
        <main style={{ flex: 1, minWidth: 0, background: tweaks.showCanvasBg ? "linear-gradient(180deg, var(--bg) 0%, color-mix(in oklch, var(--primary) 1.5%, var(--bg)) 100%)" : "var(--bg)" }}>
          <PageRouter mode={mode} route={route} navigate={navigate} />
        </main>
      </div>

      {/* Tweaks panel */}
      <TweaksPanel title="Tweaks" defaultPos={{ right: 20, bottom: 20 }}>        <TweakSection title="Theme">
          <TweakSlider label="Primary hue" value={tweaks.primaryHue} min={100} max={220} step={2}
                       onChange={(v) => setTweaks({ primaryHue: v })} suffix="°" />
          <TweakSelect label="Display font" value={tweaks.displayFont}
                       onChange={(v) => setTweaks({ displayFont: v })}
                       options={["Geist", "Instrument Sans", "Space Grotesk"]} />
        </TweakSection>
        <TweakSection title="Layout">
          <TweakSlider label="Density" value={tweaks.density} min={0.85} max={1.2} step={0.05}
                       onChange={(v) => setTweaks({ density: v })} suffix="×" />
          <TweakToggle label="Sidebar" value={tweaks.showSidebar} onChange={(v) => setTweaks({ showSidebar: v })} />
          <TweakToggle label="Tinted backdrop" value={tweaks.showCanvasBg} onChange={(v) => setTweaks({ showCanvasBg: v })} />
        </TweakSection>
        <TweakSection title="Quick jump">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
            <button className="btn" onClick={() => setMode("iot")}>IoT mode</button>
            <button className="btn" onClick={() => setMode("fintech")}>Fintech</button>
            <button className="btn ghost" onClick={() => navigate("pulse")}>Pulse</button>
            <button className="btn ghost" onClick={() => navigate("portfolio")}>Portfolio</button>
            <button className="btn ghost" onClick={() => navigate("ghg")}>GHG tax</button>
            <button className="btn ghost" onClick={() => navigate("carbon")}>Carbon</button>
          </div>
        </TweakSection>
      </TweaksPanel>

      <UIHost />
    </div>
  );
}

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