/* App shell — sidebar + topbar + page router */

const { useState: useStateApp, useEffect: useEffectApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "violet",
  "density": "comfortable",
  "showAIChips": true
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = {
  violet: { accent: "oklch(0.52 0.16 282)", soft: "oklch(0.94 0.04 282)", ink: "oklch(0.36 0.18 282)" },
  indigo: { accent: "oklch(0.52 0.18 262)", soft: "oklch(0.94 0.04 262)", ink: "oklch(0.36 0.18 262)" },
  ember:  { accent: "oklch(0.58 0.18 35)",  soft: "oklch(0.95 0.045 40)", ink: "oklch(0.42 0.16 35)"  },
  jade:   { accent: "oklch(0.55 0.13 168)", soft: "oklch(0.94 0.04 168)", ink: "oklch(0.36 0.13 168)" },
};

function App() {
  const [page, setPage] = useStateApp("dashboard");
  const [pageState, setPageState] = useStateApp({});
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  /* Live-API boot — fetches /companies + /contacts in parallel and polls
     /health. Returns a data-version counter that bumps whenever live
     data merges into the in-memory stores; we use it as a render key on
     the page wrapper so child screens re-derive their filtered lists. */
  const apiDataVersion = window.useApiBoot ? window.useApiBoot() : 0;

  /* apply accent to CSS vars */
  useEffectApp(() => {
    const root = document.documentElement;
    const c = ACCENT_OPTIONS[tweaks.accent] || ACCENT_OPTIONS.violet;
    root.style.setProperty("--accent",      c.accent);
    root.style.setProperty("--accent-soft", c.soft);
    root.style.setProperty("--accent-ink",  c.ink);
  }, [tweaks.accent]);

  useEffectApp(() => {
    document.body.style.fontSize = tweaks.density === "compact" ? "12.5px" : "13px";
  }, [tweaks.density]);

  const navigate = (target, state = {}) => {
    setPage(target);
    setPageState(state);
  };

  const breadcrumb = buildBreadcrumb(page, pageState, navigate);
  const pageIcon = (window.NAV || []).find(n => n.id === topLevel(page))?.icon;

  return (
    <div className="app" data-page={page}>
      <Sidebar current={topLevel(page)} onNavigate={navigate} />
      <div className="main-col">
        <Topbar breadcrumb={breadcrumb} pageIcon={pageIcon} />
        <div className="page-scroll" key={page + JSON.stringify(pageState)}
          style={{ animation: "fadein 200ms ease-out" }}>
          <PageRouter page={page} pageState={pageState} onNavigate={navigate} />
        </div>
      </div>

      {/* Tweaks panel */}
      <window.TweaksPanel title="Tweaks">
        <window.TweakSection label="Theme">
          <window.TweakRadio
            label="Accent"
            value={tweaks.accent}
            onChange={(v) => setTweak("accent", v)}
            options={[
              { value: "violet", label: "Violet" },
              { value: "indigo", label: "Indigo" },
              { value: "ember",  label: "Ember" },
              { value: "jade",   label: "Jade" },
            ]}
          />
        </window.TweakSection>
        <window.TweakSection label="Density">
          <window.TweakRadio
            label="Compactness"
            value={tweaks.density}
            onChange={(v) => setTweak("density", v)}
            options={[
              { value: "compact",     label: "Compact" },
              { value: "comfortable", label: "Comfortable" },
            ]}
          />
        </window.TweakSection>
        <window.TweakSection label="AI">
          <window.TweakToggle
            label="Show 'AI' chips"
            value={tweaks.showAIChips}
            onChange={(v) => setTweak("showAIChips", v)}
          />
        </window.TweakSection>
      </window.TweaksPanel>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────
   Floating AI Ask bar — bottom-centered. ⌘J / Ctrl+J to focus.
   Pill-shaped, surfaces suggestions above when focused.
   ───────────────────────────────────────────────────────────────────── */
function AIInputBar() {
  const [focused, setFocused] = useStateApp(false);
  const [text, setText] = useStateApp("");
  const inputRef = React.useRef(null);

  useEffectApp(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "j") {
        e.preventDefault();
        inputRef.current?.focus();
      } else if (e.key === "Escape" && document.activeElement === inputRef.current) {
        inputRef.current?.blur();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const suggestions = [
    { icon: "edit",        label: "Draft a follow-up to Pilar at Majestic" },
    { icon: "lightbulb",   label: "Summarize today's pipeline movement" },
    { icon: "target",      label: "Find net-new HR leaders at retail accounts" },
    { icon: "trending-up", label: "What's the next best action on Mango?" },
  ];

  const handleSubmit = (e) => {
    e?.preventDefault();
    if (!text.trim()) return;
    setText("");
    inputRef.current?.blur();
  };

  return (
    <div className="ai-input-bar" style={{
      position: "relative",
      width: focused ? 546 : 338,
      maxWidth: "100%",
      minWidth: 0,
      transition: "width 240ms cubic-bezier(0.2, 0.7, 0.2, 1)",
      flexShrink: 1,
    }}>
      {/* Suggestions panel — drops DOWN from the bar */}
      {focused && (
        <div style={{
          position: "absolute", top: "calc(100% + 8px)", left: 0, right: 0,
          background: "var(--surface)",
          border: "1px solid var(--line-strong)",
          borderRadius: 12,
          boxShadow: "0 16px 48px oklch(0.2 0 0 / 0.14), 0 4px 12px oklch(0.2 0 0 / 0.08)",
          padding: 5,
          zIndex: 120,
          opacity: 0,
          animation: "fadein 180ms ease forwards",
        }}>
          <div style={{ padding: "7px 10px 3px", fontSize: 10, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.05em", display: "flex", alignItems: "center", gap: 6 }}>
            <Icon name="sparkles" size={10} style={{ color: "var(--accent)" }} />
            Try
          </div>
          {suggestions.map((s, i) => (
            <button key={i}
              onMouseDown={(e) => { e.preventDefault(); setText(s.label); inputRef.current?.focus(); }}
              style={{
                display: "flex", alignItems: "center", gap: 9,
                width: "100%", padding: "7px 10px", borderRadius: 7,
                fontSize: 12.5, color: "var(--ink-2)", textAlign: "left",
                transition: "background 100ms",
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface-2)"}
              onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
            >
              <div style={{
                width: 20, height: 20, borderRadius: 5,
                background: "var(--accent-soft)", color: "var(--accent-ink)",
                display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
              }}>
                <Icon name={s.icon} size={10} />
              </div>
              <span style={{ flex: 1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.label}</span>
              <Icon name="arrow-up-right" size={10} style={{ color: "var(--ink-4)", flexShrink: 0 }} />
            </button>
          ))}
        </div>
      )}

      <form onSubmit={handleSubmit} style={{
        display: "flex", alignItems: "center", gap: 6,
        padding: "3px 4px 3px 10px",
        height: 32,
        background: "var(--surface)",
        border: "1px solid var(--line-strong)",
        borderRadius: 999,
        boxShadow: focused
          ? "0 8px 24px oklch(0.2 0 0 / 0.10), 0 2px 6px oklch(0.2 0 0 / 0.05)"
          : "inset 0 1px 0 oklch(1 0 0 / 0.6), 0 1px 0 oklch(0.85 0.005 80 / 0.4)",
        transition: "box-shadow 200ms, border-color 200ms",
      }}>
        <Icon name="sparkles" size={13} style={{ color: "var(--accent)", flexShrink: 0 }} />
        <input
          ref={inputRef}
          value={text}
          onChange={(e) => setText(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setTimeout(() => setFocused(false), 150)}
          placeholder="Ask anything…"
          style={{
            flex: 1, minWidth: 0, border: "none", outline: "none", background: "transparent",
            fontSize: 12.5, color: "var(--ink)", height: 22,
          }}
        />
        {!text && !focused && <Kbd>⌘J</Kbd>}
        {(text || focused) && (
          <button type="submit" style={{
            background: text ? "var(--accent)" : "var(--inset)",
            color: text ? "#fff" : "var(--ink-4)",
            padding: "0 10px", height: 24, borderRadius: 999,
            fontSize: 11.5, fontWeight: 600,
            display: "inline-flex", alignItems: "center", gap: 4,
            transition: "background 120ms, color 120ms",
            cursor: text ? "pointer" : "default",
            flexShrink: 0,
          }} disabled={!text}>
            Ask
            <Icon name="arrow-right" size={10} />
          </button>
        )}
      </form>
    </div>
  );
}

window.AIInputBar = AIInputBar;

function topLevel(page) {
  if (page === "account-detail") return "accounts";
  if (page === "contact-detail") return "contacts";
  return page;
}

function buildBreadcrumb(page, pageState, navigate) {
  if (page === "dashboard") return [{ label: "Dashboard", icon: "layout-dashboard" }];
  if (page === "accounts")  return [{ label: "Accounts", icon: "building" }];
  if (page === "account-detail") {
    const company = window.getCompany(pageState.companyId);
    return [
      { label: "Accounts", icon: "building", onClick: () => navigate("accounts") },
      { label: company?.name || "Account" },
    ];
  }
  if (page === "contacts")     return [{ label: "Contacts", icon: "users" }];
  if (page === "contact-detail") {
    const c = window.getContact(pageState.contactId);
    return [
      { label: "Contacts", icon: "users", onClick: () => navigate("contacts") },
      { label: c ? `${c.firstName} ${c.lastName}` : "Contact" },
    ];
  }
  if (page === "conversations")return [{ label: "Conversations", icon: "messages" }];
  if (page === "opportunities")return [{ label: "Pipeline", icon: "kanban" }];
  if (page === "calendar")     return [{ label: "Calendar", icon: "calendar" }];
  if (page === "tasks")        return [{ label: "Tasks", icon: "check-square" }];
  if (page === "content")      return [{ label: "Content Library", icon: "library" }];
  if (page === "knowledge")    return [{ label: "Product Knowledge", icon: "book" }];
  if (page === "automation")   return [{ label: "Automation", icon: "send" }];
  if (page === "admin")        return [{ label: "Administration", icon: "settings" }];
  return [];
}

function PageRouter({ page, pageState, onNavigate }) {
  switch (page) {
    case "dashboard":      return <window.PageDashboard onNavigate={onNavigate} />;
    case "accounts":       return <window.PageAccounts onNavigate={onNavigate} />;
    case "account-detail": return <window.PageAccountDetail companyId={pageState.companyId} onNavigate={onNavigate} />;
    case "contacts":       return <window.PageContacts onNavigate={onNavigate} />;
    case "contact-detail": return <window.PageContactDetail contactId={pageState.contactId} onNavigate={onNavigate} />;
    case "conversations":  return <window.PageConversations initialConversationId={pageState.conversationId} onNavigate={onNavigate} />;
    case "opportunities":  return <window.PagePipeline onNavigate={onNavigate} />;
    case "calendar":       return <window.PageCalendar onNavigate={onNavigate} />;
    case "tasks":          return <window.PageTasks onNavigate={onNavigate} />;
    case "content":        return <window.PageContent />;
    case "knowledge":      return <window.PageKnowledge />;
    case "automation":     return <window.PageAutomation />;
    case "admin":          return <window.PageAdmin />;
    default: return null;
  }
}

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