/* eslint-disable */
// ============================================================
// DEVTOOLS — bottom drawer with two tabs:
//   1) Network log (live feed of mockApi calls)
//   2) Theme (dark/light, density, primary colour, simulated latency)
//
// The dev button lives bottom-left; the panel slides up.
// ============================================================

const { useState: useDV_S, useEffect: useDV_E, useRef: useDV_R, useMemo: useDV_M } = React;

// ---- Apply theme to :root ----
function hexToRgb(hex) {
  const h = hex.replace("#", "");
  const n = parseInt(h.length === 3 ? h.split("").map((c) => c + c).join("") : h, 16);
  return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255 };
}
// hex -> OKLCH (we only need the hue, but L/C are handy for derived shades)
function hexToOklch(hex) {
  const { r, g, b } = hexToRgb(hex);
  const lin = (c) => { const cs = c / 255; return cs <= 0.04045 ? cs / 12.92 : Math.pow((cs + 0.055) / 1.055, 2.4); };
  const rl = lin(r), gl = lin(g), bl = lin(b);
  const L_ = 0.4122214708 * rl + 0.5363325363 * gl + 0.0514459929 * bl;
  const M_ = 0.2119034982 * rl + 0.6806995451 * gl + 0.1073969566 * bl;
  const S_ = 0.0883024619 * rl + 0.2817188376 * gl + 0.6299787005 * bl;
  const l_ = Math.cbrt(L_), m_ = Math.cbrt(M_), s_ = Math.cbrt(S_);
  const L = 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_;
  const A = 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_;
  const B = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_;
  let H = Math.atan2(B, A) * 180 / Math.PI; if (H < 0) H += 360;
  return { L, C: Math.sqrt(A * A + B * B), H };
}
function applyTheme(theme) {
  const r = document.documentElement;
  const mode = theme.mode || "light";
  r.setAttribute("data-theme", mode);

  if (theme.primary) {
    r.style.setProperty("--primary", theme.primary);
    const { r: rd, g: gn, b: bl } = hexToRgb(theme.primary);
    const { H } = hexToOklch(theme.primary);
    // accent = analogous hue offset; gives the secondary color family a related-but-distinct feel
    const Ha = (H + 150) % 360;

    if (mode === "light") {
      // Tinted neutrals — extremely low chroma at the primary hue
      r.style.setProperty("--bg",        `oklch(0.975 0.012 ${H})`);
      r.style.setProperty("--surface",   `oklch(1 0 0)`);
      r.style.setProperty("--surface-2", `oklch(0.968 0.014 ${H})`);
      r.style.setProperty("--surface-3", `oklch(0.93 0.028 ${H})`);
      r.style.setProperty("--border",    `oklch(0.905 0.030 ${H})`);
      r.style.setProperty("--border-2",  `oklch(0.82 0.045 ${H})`);
      r.style.setProperty("--ink",       `oklch(0.20 0.020 ${H})`);
      r.style.setProperty("--ink-2",     `oklch(0.30 0.020 ${H})`);
      r.style.setProperty("--muted",     `oklch(0.50 0.018 ${H})`);
      r.style.setProperty("--subtle",    `oklch(0.62 0.018 ${H})`);
      r.style.setProperty("--faint",     `oklch(0.80 0.018 ${H})`);

      r.style.setProperty("--primary-2",   `oklch(0.45 0.16 ${H})`);
      r.style.setProperty("--primary-bg",  `rgba(${rd},${gn},${bl},0.10)`);
      r.style.setProperty("--primary-ring",`rgba(${rd},${gn},${bl},0.38)`);

      r.style.setProperty("--accent",      `oklch(0.55 0.13 ${Ha})`);
      r.style.setProperty("--accent-bg",   `oklch(0.95 0.04 ${Ha})`);
      r.style.setProperty("--accent-ring", `oklch(0.78 0.10 ${Ha})`);

      r.style.setProperty("--row-zebra",   `rgba(${rd},${gn},${bl},0.05)`);
      r.style.setProperty("--row-hover",   `rgba(${rd},${gn},${bl},0.06)`);

      // Sidebar surface — deep tinted neutral so the chrome carries the brand hue
      r.style.setProperty("--sidebar-bg",        `oklch(0.18 0.025 ${H})`);
      r.style.setProperty("--sidebar-bg-2",      `oklch(0.22 0.030 ${H})`);
      r.style.setProperty("--sidebar-border",    `rgba(255,255,255,0.05)`);
      r.style.setProperty("--sidebar-text",      `oklch(0.86 0.015 ${H})`);
      r.style.setProperty("--sidebar-muted",     `oklch(0.62 0.020 ${H})`);
      r.style.setProperty("--sidebar-faint",     `oklch(0.45 0.020 ${H})`);
      r.style.setProperty("--sidebar-active-bg", `rgba(${rd},${gn},${bl},0.18)`);
      r.style.setProperty("--sidebar-active-bd", `rgba(${rd},${gn},${bl},0.34)`);
      r.style.setProperty("--sidebar-active-fg", `oklch(0.80 0.16 ${H})`);
    } else {
      // Tinted dark neutrals
      r.style.setProperty("--bg",        `oklch(0.175 0.018 ${H})`);
      r.style.setProperty("--surface",   `oklch(0.215 0.020 ${H})`);
      r.style.setProperty("--surface-2", `oklch(0.245 0.022 ${H})`);
      r.style.setProperty("--surface-3", `oklch(0.285 0.025 ${H})`);
      r.style.setProperty("--border",    `oklch(0.335 0.025 ${H})`);
      r.style.setProperty("--border-2",  `oklch(0.42 0.030 ${H})`);
      r.style.setProperty("--ink",       `oklch(0.96 0.012 ${H})`);
      r.style.setProperty("--ink-2",     `oklch(0.86 0.015 ${H})`);
      r.style.setProperty("--muted",     `oklch(0.68 0.020 ${H})`);
      r.style.setProperty("--subtle",    `oklch(0.55 0.020 ${H})`);
      r.style.setProperty("--faint",     `oklch(0.40 0.020 ${H})`);

      r.style.setProperty("--primary-2",   `oklch(0.78 0.16 ${H})`);
      r.style.setProperty("--primary-bg",  `rgba(${rd},${gn},${bl},0.16)`);
      r.style.setProperty("--primary-ring",`rgba(${rd},${gn},${bl},0.42)`);

      r.style.setProperty("--accent",      `oklch(0.78 0.14 ${Ha})`);
      r.style.setProperty("--accent-bg",   `oklch(0.30 0.06 ${Ha})`);
      r.style.setProperty("--accent-ring", `oklch(0.55 0.10 ${Ha})`);

      r.style.setProperty("--row-zebra",   `rgba(255,255,255,0.025)`);
      r.style.setProperty("--row-hover",   `rgba(${rd},${gn},${bl},0.09)`);

      // Sidebar surface — even darker tint in dark mode
      r.style.setProperty("--sidebar-bg",        `oklch(0.14 0.025 ${H})`);
      r.style.setProperty("--sidebar-bg-2",      `oklch(0.18 0.030 ${H})`);
      r.style.setProperty("--sidebar-border",    `rgba(255,255,255,0.06)`);
      r.style.setProperty("--sidebar-text",      `oklch(0.86 0.015 ${H})`);
      r.style.setProperty("--sidebar-muted",     `oklch(0.62 0.020 ${H})`);
      r.style.setProperty("--sidebar-faint",     `oklch(0.45 0.020 ${H})`);
      r.style.setProperty("--sidebar-active-bg", `rgba(${rd},${gn},${bl},0.20)`);
      r.style.setProperty("--sidebar-active-bd", `rgba(${rd},${gn},${bl},0.38)`);
      r.style.setProperty("--sidebar-active-fg", `oklch(0.82 0.16 ${H})`);
    }
  }

  if (theme.density != null) {
    // density is a multiplier for "comfortable" spacing
    r.style.setProperty("--density", String(theme.density));
  }
}

const PRIMARY_OPTIONS = [
  { name: "Terracotta", value: "#ad4a1a", swatch: "#ad4a1a" },
  { name: "Saffron",    value: "#c2660d", swatch: "#c2660d" },
  { name: "Greenhouse", value: "#10b981", swatch: "#10b981" },
  { name: "Indigo",     value: "#4338ca", swatch: "#4338ca" },
  { name: "Teal",       value: "#0a6e6e", swatch: "#0a6e6e" },
  { name: "Plum",       value: "#7c2d6f", swatch: "#7c2d6f" },
  { name: "Slate",      value: "#334155", swatch: "#334155" },
];

const DENSITIES = [
  { id: "compact",  label: "Compact",  value: 0.85 },
  { id: "cozy",     label: "Cozy",     value: 1.0 },
  { id: "comfortable", label: "Comfy", value: 1.15 },
];

// ============================================================
// Network log
// ============================================================
const NetworkLog = () => {
  const [log, setLog] = useDV_S(() => mockApi.apiLogSnapshot());
  const [calls, setCalls] = useDV_S({}); // id → { start, end? }
  const [expanded, setExpanded] = useDV_S({});

  useDV_E(() => {
    // Hydrate from snapshot
    const initial = mockApi.apiLogSnapshot();
    const cMap = {};
    initial.forEach((evt) => {
      if (evt.type === "call/start") cMap[evt.id] = { start: evt };
      else if (evt.type === "call/end") cMap[evt.id] = { ...cMap[evt.id], end: evt };
    });
    setCalls(cMap);
    setLog(initial);

    const unsub = mockApi.apiSubscribe((evt) => {
      if (evt.type === "log/clear") { setCalls({}); setLog([]); return; }
      setLog((arr) => [...arr.slice(-79), evt]);
      if (evt.type === "call/start") setCalls((m) => ({ ...m, [evt.id]: { start: evt } }));
      if (evt.type === "call/end")   setCalls((m) => ({ ...m, [evt.id]: { ...m[evt.id], end: evt } }));
    });
    return () => unsub();
  }, []);

  // Order: latest first
  const ordered = useDV_M(() => {
    const ids = [];
    const seen = new Set();
    for (let i = log.length - 1; i >= 0; i--) {
      const e = log[i];
      if (!e.id || seen.has(e.id)) continue;
      seen.add(e.id);
      ids.push(e.id);
    }
    return ids.map((id) => calls[id]).filter(Boolean);
  }, [log, calls]);

  const methodColor = (m) => ({
    GET: "var(--info)",
    POST: "var(--success)",
    PUT: "var(--warning)",
    PATCH: "var(--accent)",
    DELETE: "var(--danger)",
  }[m] || "var(--muted)");

  return (
    <div className="flex flex-col h-full min-h-0">
      <div className="flex items-center gap-2 px-4 py-2 border-b text-[11.5px]" style={{ borderColor: "var(--border)", color: "var(--muted)" }}>
        <span className="dot-live" />
        Live · <span className="font-mono">{ordered.length}</span> call{ordered.length === 1 ? "" : "s"} captured
        <div className="flex-1" />
        <button onClick={() => mockApi.apiClearLog()} className="inline-flex items-center gap-1 h-7 px-2 rounded hover:bg-[var(--surface-2)]" style={{ color: "var(--muted)" }}>
          <Icon name="trash" size={11} /> Clear
        </button>
      </div>
      <div className="flex-1 overflow-y-auto scrollbar-thin">
        {ordered.length === 0 && (
          <div className="px-4 py-8 text-center text-[12px]" style={{ color: "var(--subtle)" }}>
            No calls yet — click around to see /api requests light up here.
          </div>
        )}
        <table className="w-full">
          <thead>
            <tr className="text-[10.5px] uppercase tracking-wider" style={{ color: "var(--muted)" }}>
              <th className="text-left font-semibold px-4 py-1.5 w-16">Method</th>
              <th className="text-left font-semibold px-2 py-1.5">URL</th>
              <th className="text-right font-semibold px-2 py-1.5 w-16">Status</th>
              <th className="text-right font-semibold px-3 py-1.5 w-20">Time</th>
            </tr>
          </thead>
          <tbody>
            {ordered.map((c) => {
              const m = c.start.method;
              const url = c.start.url;
              const status = c.end?.status;
              const isPending = !c.end;
              const isErr = status >= 400;
              const isExpanded = expanded[c.start.id];
              return (
                <React.Fragment key={c.start.id}>
                  <tr
                    onClick={() => setExpanded((s) => ({ ...s, [c.start.id]: !s[c.start.id] }))}
                    className="hover:bg-[var(--surface-2)] cursor-pointer"
                    style={{ borderBottom: "1px solid var(--border)" }}
                  >
                    <td className="px-4 py-1.5">
                      <span className="font-mono text-[10.5px] font-semibold px-1.5 py-0.5 rounded" style={{ color: methodColor(m), background: "transparent", border: `1px solid ${methodColor(m)}` }}>
                        {m}
                      </span>
                    </td>
                    <td className="px-2 py-1.5 font-mono text-[12px] truncate max-w-0" style={{ color: "var(--ink-2)" }}>
                      <div className="truncate">{url}</div>
                    </td>
                    <td className="px-2 py-1.5 text-right font-mono text-[11px]" style={{ color: isPending ? "var(--warning)" : isErr ? "var(--danger)" : "var(--success)" }}>
                      {isPending ? <span className="inline-flex items-center gap-1"><span className="w-2 h-2 rounded-full pulse-dot" style={{ background: "var(--warning)" }} /></span> : status}
                    </td>
                    <td className="px-3 py-1.5 text-right font-mono text-[11px] tabular-nums" style={{ color: "var(--muted)" }}>
                      {c.end ? `${c.end.durationMs}ms` : "…"}
                    </td>
                  </tr>
                  {isExpanded && (
                    <tr style={{ borderBottom: "1px solid var(--border)" }}>
                      <td colSpan={4} className="px-4 py-2 text-[11px] font-mono" style={{ background: "var(--surface-2)", color: "var(--ink-2)" }}>
                        {c.start.params && Object.keys(c.start.params).length > 0 && (
                          <div className="mb-1"><span className="text-[var(--muted)]">params</span> {JSON.stringify(c.start.params)}</div>
                        )}
                        {c.start.body && (
                          <div className="mb-1"><span className="text-[var(--muted)]">body</span> {typeof c.start.body === "string" ? c.start.body : JSON.stringify(c.start.body).slice(0, 200)}</div>
                        )}
                        {c.end?.responsePreview && (
                          <div className=""><span className="text-[var(--muted)]">resp</span> {c.end.responsePreview}</div>
                        )}
                        {c.end?.error && (
                          <div className="text-[var(--danger)]">{c.end.error}</div>
                        )}
                      </td>
                    </tr>
                  )}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// ============================================================
// Theme pane
// ============================================================
const ThemePane = ({ theme, setTheme }) => {
  const lat = mockApi.getLatency();
  return (
    <div className="p-4 space-y-5">
      <div>
        <div className="text-[11px] uppercase tracking-wider font-semibold mb-2" style={{ color: "var(--muted)" }}>Appearance</div>
        <div className="flex gap-2">
          {["light", "dark"].map((m) => {
            const active = theme.mode === m;
            return (
              <button
                key={m}
                onClick={() => setTheme({ ...theme, mode: m })}
                className="flex-1 flex items-center gap-2 px-3 py-2.5 rounded-md text-[13px] font-medium transition-all"
                style={{
                  background: active ? "var(--primary-bg)" : "var(--surface-2)",
                  color: active ? "var(--primary)" : "var(--ink-2)",
                  border: `1px solid ${active ? "var(--primary-ring)" : "var(--border)"}`,
                }}
              >
                <Icon name={m === "light" ? "sun" : "moon"} size={14} />
                <span className="capitalize">{m}</span>
                {active && <Icon name="check" size={12} className="ml-auto" />}
              </button>
            );
          })}
        </div>
      </div>

      <div>
        <div className="text-[11px] uppercase tracking-wider font-semibold mb-2" style={{ color: "var(--muted)" }}>Brand colour</div>
        <div className="grid grid-cols-6 gap-2">
          {PRIMARY_OPTIONS.map((p) => {
            const active = theme.primary === p.value;
            return (
              <button
                key={p.value}
                onClick={() => setTheme({ ...theme, primary: p.value })}
                title={p.name}
                className="aspect-square rounded-md relative ring-offset-1 transition-transform hover:scale-105"
                style={{
                  background: p.swatch,
                  boxShadow: active ? `0 0 0 2px var(--surface), 0 0 0 4px ${p.value}` : "var(--shadow-sm)",
                }}
              >
                {active && <Icon name="check" size={14} className="absolute inset-0 m-auto text-white" />}
              </button>
            );
          })}
        </div>
      </div>

      <div>
        <div className="text-[11px] uppercase tracking-wider font-semibold mb-2" style={{ color: "var(--muted)" }}>Density</div>
        <div className="flex gap-1.5 p-0.5 rounded-md" style={{ background: "var(--surface-2)", border: "1px solid var(--border)" }}>
          {DENSITIES.map((d) => {
            const active = Math.abs((theme.density || 1) - d.value) < 0.01;
            return (
              <button
                key={d.id}
                onClick={() => setTheme({ ...theme, density: d.value })}
                className="flex-1 h-8 rounded text-[12px] font-medium transition-colors"
                style={{
                  background: active ? "var(--surface)" : "transparent",
                  color: active ? "var(--ink)" : "var(--muted)",
                  boxShadow: active ? "var(--shadow-sm)" : "none",
                }}
              >
                {d.label}
              </button>
            );
          })}
        </div>
      </div>

      <div>
        <div className="text-[11px] uppercase tracking-wider font-semibold mb-2" style={{ color: "var(--muted)" }}>Simulated latency</div>
        <div className="flex items-center gap-2 mb-2">
          <input
            type="range" min={0} max={1500} step={50}
            value={lat.max}
            onChange={(e) => mockApi.setLatency(Math.min(lat.min, Number(e.target.value)), Number(e.target.value), lat.errorRate)}
            className="flex-1"
            style={{ accentColor: "var(--primary)" }}
          />
          <span className="font-mono text-[12px] tabular-nums w-12 text-right" style={{ color: "var(--ink-2)" }}>{lat.max}ms</span>
        </div>
        <div className="flex items-center gap-2">
          <span className="text-[11px]" style={{ color: "var(--muted)" }}>Error rate</span>
          <input
            type="range" min={0} max={50} step={5}
            value={lat.errorRate * 100}
            onChange={(e) => mockApi.setLatency(lat.min, lat.max, Number(e.target.value) / 100)}
            className="flex-1"
            style={{ accentColor: "var(--danger)" }}
          />
          <span className="font-mono text-[12px] tabular-nums w-10 text-right" style={{ color: "var(--ink-2)" }}>{Math.round(lat.errorRate * 100)}%</span>
        </div>
        <div className="text-[10.5px] mt-2" style={{ color: "var(--subtle)" }}>
          Click these to feel what your users feel on a slow network.
        </div>
      </div>

      <div className="rounded-md p-3 text-[11.5px] leading-relaxed" style={{ background: "var(--surface-2)", border: "1px solid var(--border)", color: "var(--muted)" }}>
        <div className="font-semibold mb-0.5" style={{ color: "var(--ink-2)" }}>How this works</div>
        The whole UI reads from CSS custom properties (<span className="font-mono">--primary</span>, <span className="font-mono">--bg</span>, etc).
        In production the chosen tokens would be persisted per workspace and shipped down with the page bootstrap — every grid, card and detail picks them up without rebuilding.
      </div>
    </div>
  );
};

// ============================================================
// The devtools panel itself
// ============================================================
const Devtools = ({ open, onClose, theme, setTheme }) => {
  const [tab, setTab] = useDV_S("network");
  if (!open) return null;

  return (
    <div
      className="fixed left-0 right-0 bottom-0 z-40"
      style={{
        background: "var(--surface)",
        borderTop: "1px solid var(--border)",
        boxShadow: "var(--shadow-lg)",
        height: 360,
        animation: "fade .2s ease-out both",
      }}
    >
      <div className="flex items-center px-4 h-10 border-b" style={{ borderColor: "var(--border)" }}>
        <div className="flex items-center gap-2 text-[12px] font-semibold" style={{ color: "var(--ink)" }}>
          <Icon name="terminal" size={13} style={{ color: "var(--primary)" }} />
          Devtools
        </div>
        <div className="ml-4 inline-flex items-center gap-0.5 p-0.5 rounded" style={{ background: "var(--surface-2)", border: "1px solid var(--border)" }}>
          {[{id:"network", label:"Network", icon:"network"}, {id:"theme", label:"Theme", icon:"sun"}].map((t) => {
            const active = tab === t.id;
            return (
              <button
                key={t.id}
                onClick={() => setTab(t.id)}
                className="inline-flex items-center gap-1.5 h-7 px-2.5 rounded text-[12px] font-medium transition-colors"
                style={{
                  background: active ? "var(--surface)" : "transparent",
                  color: active ? "var(--ink)" : "var(--muted)",
                  boxShadow: active ? "var(--shadow-sm)" : "none",
                }}
              >
                <Icon name={t.icon} size={12} /> {t.label}
              </button>
            );
          })}
        </div>
        <div className="flex-1" />
        <button onClick={onClose} className="h-8 w-8 inline-flex items-center justify-center rounded hover:bg-[var(--surface-2)]" style={{ color: "var(--muted)" }}>
          <Icon name="x" size={14} />
        </button>
      </div>
      <div className="h-[calc(100%-40px)] min-h-0">
        {tab === "network" && <NetworkLog />}
        {tab === "theme" && <ThemePane theme={theme} setTheme={setTheme} />}
      </div>
    </div>
  );
};

// ============================================================
// Floating dev FAB (bottom-left)
// ============================================================
const DevtoolsFab = ({ open, setOpen }) => {
  const [pending, setPending] = useDV_S(0);
  useDV_E(() => {
    const unsub = mockApi.apiSubscribe((evt) => {
      if (evt.type === "call/start") setPending((n) => n + 1);
      if (evt.type === "call/end")   setPending((n) => Math.max(0, n - 1));
    });
    return () => unsub();
  }, []);

  return (
    <button
      onClick={() => setOpen(!open)}
      className="fixed bottom-4 left-4 z-40 flex items-center gap-2 pl-1.5 pr-3 h-9 rounded-full transition-colors"
      style={{
        background: "#171b22",
        color: "#f3efe5",
        boxShadow: "var(--shadow-md)",
        border: "1px solid rgba(255,255,255,0.06)",
      }}
      title="Toggle devtools"
    >
      <span className="h-6 w-6 inline-flex items-center justify-center rounded-full" style={{ background: pending > 0 ? "var(--primary)" : "rgba(255,255,255,0.08)" }}>
        <Icon name="terminal" size={12} />
      </span>
      <span className="text-[11.5px] font-medium">
        {pending > 0 ? <span className="inline-flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full pulse-dot" style={{ background: "var(--primary)" }} /> {pending} in flight</span> : "devtools"}
      </span>
    </button>
  );
};

Object.assign(window, { Devtools, DevtoolsFab, applyTheme });
