/* Sidebar — collapsed-rail by default, expands on hover. Floats over content. */

const { useState: useStateSB } = React;
const COLLAPSED_W = 56;
const EXPANDED_W  = 240;

function Sidebar({ current, onNavigate }) {
  const [hover, setHover] = useStateSB(false);
  /* Live /health → workspace status dot tone. */
  const health = window.useApiHealth ? window.useApiHealth() : { state: "unknown" };
  const liveStats = window.useApiLiveStats ? window.useApiLiveStats() : null;
  const totals    = window.useApiTotals    ? window.useApiTotals()    : null;
  const healthTone = health.state === "ok" ? "green"
                  : health.state === "error" ? "red"
                  : "neutral";
  /* Prefer the discovered DB totals (binary-search probe) over the
     in-memory live counts — they reflect the actual record count even
     though we only load one page on boot. */
  const companyN = totals?.companies ?? liveStats?.companies;
  const contactN = totals?.contacts  ?? liveStats?.contacts;
  const healthLabel = health.state === "ok"
    ? (companyN != null && contactN != null
        ? `Live · ${companyN.toLocaleString()} companies · ${contactN.toLocaleString()} contacts`
        : "Demo Workspace")
    : health.state === "error" ? "API offline"
    : "Connecting…";
  const healthTitle = health.state === "ok"
    ? `API healthy${health.runtime ? " · " + health.runtime : ""}${liveStats?.syncedAt ? " · synced " + window.fmtRelative(liveStats.syncedAt) : ""}`
    : health.state === "error"
      ? `API unreachable${health.error ? " · " + health.error : ""}`
      : "Probing api.businessteam.app…";

  return (
    <aside
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position: "absolute",
        top: 0, left: 0, bottom: 0,
        width: hover ? EXPANDED_W : COLLAPSED_W,
        background: "var(--bg-tint)",
        borderRight: "1px solid var(--line)",
        display: "flex", flexDirection: "column",
        padding: hover ? "12px 10px" : "12px 8px",
        gap: 12,
        zIndex: 50,
        boxShadow: hover ? "0 12px 40px oklch(0.2 0 0 / 0.10), 0 2px 8px oklch(0.2 0 0 / 0.06)" : "none",
        transition: "width 200ms cubic-bezier(0.2, 0.7, 0.2, 1), box-shadow 200ms ease, padding 200ms ease",
        overflow: "hidden",
        whiteSpace: "nowrap",
      }}
    >
      {/* Workspace switcher */}
      <button
        onClick={() => onNavigate("dashboard")}
        style={{
          display: "flex", alignItems: "center", gap: 10,
          height: 44,
          padding: "0 8px",
          borderRadius: 8,
          textAlign: "left",
          transition: "background 120ms",
          width: "100%", minWidth: 0,
          justifyContent: hover ? "flex-start" : "center",
        }}
        onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface)"}
        onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
      >
        <BrandMark />
        {hover && (
          <>
            <div style={{ flex: 1, minWidth: 0, opacity: 0, animation: "fadein 200ms ease 60ms forwards" }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)", letterSpacing: "-0.01em" }}>BusinessTeam</div>
              <div style={{ fontSize: 11, color: "var(--ink-3)", display: "flex", alignItems: "center", gap: 4 }} title={healthTitle}>
                <StatusDot tone={healthTone} size={6} />
                {healthLabel}
              </div>
            </div>
            <Icon name="chevron-down" size={13} style={{ color: "var(--ink-4)" }} />
          </>
        )}
      </button>

      {/* Search */}
      {hover ? (
        <RevealSlot show={hover} style={{ padding: "0 2px" }}>
          <SidebarSearch onNavigate={onNavigate} />
        </RevealSlot>
      ) : (
        <button
          onClick={() => onNavigate("dashboard")}
          title="Search"
          style={{
            width: 40, height: 28,
            margin: "0 auto",
            borderRadius: 6,
            display: "flex", alignItems: "center", justifyContent: "center",
            color: "var(--ink-3)",
            transition: "background 120ms, color 120ms",
          }}
          onMouseEnter={(e) => { e.currentTarget.style.background = "var(--surface)"; e.currentTarget.style.color = "var(--ink)"; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--ink-3)"; }}
        >
          <Icon name="search" size={15} />
        </button>
      )}

      {/* Primary nav */}
      <nav style={{ display: "flex", flexDirection: "column", gap: 1, marginTop: 4 }}>
        <RailGroup hover={hover} label="Workspace">
          {NAV.slice(0, 4).map(item => (
            <NavItem key={item.id} item={item} active={current === item.id} expanded={hover} onClick={() => onNavigate(item.id)} />
          ))}
        </RailGroup>

        <RailGroup hover={hover} label="Execution">
          {NAV.slice(4, 7).map(item => (
            <NavItem key={item.id} item={item} active={current === item.id} expanded={hover} onClick={() => onNavigate(item.id)} />
          ))}
        </RailGroup>

        <RailGroup hover={hover} label="Library">
          {NAV.slice(7, 10).map(item => (
            <NavItem key={item.id} item={item} active={current === item.id} expanded={hover} onClick={() => onNavigate(item.id)} />
          ))}
        </RailGroup>
      </nav>

      <div style={{ flex: 1 }} />

      <NavItem
        item={{ id: "admin", label: "Admin", icon: "settings" }}
        active={current === "admin"} expanded={hover} onClick={() => onNavigate("admin")}
      />

      {/* User strip */}
      <div style={{
        display: "flex", alignItems: "center", gap: 8,
        height: 40,
        padding: hover ? "0 8px" : 0,
        borderRadius: 8,
        background: hover ? "var(--surface)" : "transparent",
        border: hover ? "1px solid var(--line)" : "1px solid transparent",
        justifyContent: hover ? "flex-start" : "center",
        transition: "padding 200ms, background 200ms, border-color 200ms",
      }}>
        <Avatar name={CURRENT_USER.name} size={26} />
        {hover && (
          <>
            <div style={{ minWidth: 0, flex: 1, opacity: 0, animation: "fadein 200ms ease 60ms forwards" }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: "var(--ink)" }}>{CURRENT_USER.name}</div>
              <div style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{CURRENT_USER.email}</div>
            </div>
            <IconButton icon="more-horizontal" size={24} title="Account" />
          </>
        )}
      </div>
    </aside>
  );
}

/* Helper: a slot whose contents fade in/out with the sidebar's expand state.
   Visibility: hidden + opacity:0 when collapsed so it doesn't take a click. */
function RevealSlot({ show, children, style = {} }) {
  return (
    <div style={{
      opacity: show ? 1 : 0,
      visibility: show ? "visible" : "hidden",
      transition: "opacity 160ms ease",
      transitionDelay: show ? "60ms" : "0ms",
      ...style,
    }}>
      {children}
    </div>
  );
}

function RailGroup({ hover, label, children }) {
  /* Fixed-height group header — text visible only when expanded.
     Keeps nav items at identical vertical positions across both states. */
  return (
    <>
      <div style={{
        height: 26,
        padding: "10px 10px 2px",
        fontSize: 10, fontWeight: 600, letterSpacing: "0.08em",
        color: "var(--ink-4)", textTransform: "uppercase",
        opacity: hover ? 1 : 0,
        transition: "opacity 160ms",
        whiteSpace: "nowrap",
      }}>{label}</div>
      {children}
    </>
  );
}

function BrandMark() {
  return (
    <div style={{
      width: 28, height: 28, borderRadius: 7,
      background: "var(--ink)",
      display: "flex", alignItems: "center", justifyContent: "center",
      color: "#fff", fontWeight: 700, fontSize: 12, letterSpacing: "-0.02em",
      position: "relative", overflow: "hidden",
      boxShadow: "inset 0 1px 0 rgba(255,255,255,0.08)",
      flexShrink: 0,
    }}>
      <div style={{
        position: "absolute", top: 0, right: 0,
        width: 8, height: 8,
        background: "var(--accent)",
        borderBottomLeftRadius: 6,
      }} />
      B
    </div>
  );
}

function NavLabel({ children }) {
  return (
    <div style={{
      fontSize: 10, fontWeight: 600, letterSpacing: "0.08em",
      color: "var(--ink-4)", textTransform: "uppercase",
      padding: "10px 10px 4px",
    }}>{children}</div>
  );
}

function NavItem({ item, active, onClick, expanded }) {
  const [hover, setHover] = useStateSB(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      title={!expanded ? item.label : undefined}
      style={{
        display: "flex", alignItems: "center",
        gap: 9,
        height: 32,
        padding: expanded ? "0 10px" : "0 10px",
        justifyContent: expanded ? "flex-start" : "center",
        borderRadius: 7,
        fontSize: 13, fontWeight: 500,
        color: active ? "var(--ink)" : "var(--ink-2)",
        background: active ? "var(--surface)" : (hover ? "var(--surface)" : "transparent"),
        boxShadow: active ? "var(--shadow-1)" : "none",
        textAlign: "left",
        transition: "background 120ms, color 120ms",
        position: "relative",
        width: "100%",
      }}
    >
      {!expanded && active && (
        <span style={{
          position: "absolute", left: -8, top: "50%",
          transform: "translateY(-50%)",
          width: 3, height: 18, borderRadius: 2,
          background: "var(--ink)",
        }} />
      )}
      <Icon name={item.icon} size={16} style={{ color: active ? "var(--ink)" : "var(--ink-3)", flexShrink: 0 }} />
      {expanded && (
        <span style={{ flex: 1, opacity: 0, animation: "fadein 200ms ease 60ms forwards" }}>{item.label}</span>
      )}
    </button>
  );
}

/* AI Copilot pocket card — adapts content but keeps a stable height in both states */
function AIPocketCard({ expanded, onClick }) {
  return (
    <button onClick={onClick} style={{
      textAlign: "left",
      display: "flex",
      flexDirection: expanded ? "column" : "row",
      gap: 6,
      padding: expanded ? 10 : 0,
      height: 62,
      width: "100%",
      borderRadius: 10,
      alignItems: expanded ? "stretch" : "center",
      justifyContent: expanded ? "flex-start" : "center",
      background: expanded
        ? "linear-gradient(180deg, color-mix(in oklch, var(--accent) 8%, var(--surface)) 0%, var(--surface) 100%)"
        : "var(--accent-soft)",
      border: expanded
        ? "1px solid color-mix(in oklch, var(--accent) 18%, var(--line))"
        : "1px solid color-mix(in oklch, var(--accent) 14%, transparent)",
      transition: "transform 120ms",
    }}
    onMouseEnter={(e) => e.currentTarget.style.transform = "translateY(-1px)"}
    onMouseLeave={(e) => e.currentTarget.style.transform = ""}
    title={expanded ? undefined : "Today's brief"}
    >
      {expanded ? (
        <>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <Icon name="sparkles" size={13} style={{ color: "var(--accent)" }} />
            <span style={{ fontSize: 11.5, fontWeight: 600, color: "var(--ink)", letterSpacing: "-0.01em" }}>Today's brief</span>
            <span style={{ flex: 1 }} />
            <Icon name="arrow-right" size={11} style={{ color: "var(--ink-3)" }} />
          </div>
          <div style={{ fontSize: 11.5, color: "var(--ink-2)", lineHeight: 1.45, whiteSpace: "normal" }}>
            <span style={{ fontWeight: 600, color: "var(--ink)" }}>3 accounts</span> need follow-up · Mango ready for proposal
          </div>
        </>
      ) : (
        <div style={{ position: "relative", display: "inline-flex" }}>
          <Icon name="sparkles" size={16} style={{ color: "var(--accent-ink)" }} />
          <span style={{
            position: "absolute", top: -2, right: -4,
            minWidth: 10, height: 10, padding: "0 2px",
            borderRadius: 5, background: "var(--accent)", color: "#fff",
            fontSize: 8, fontWeight: 700,
            display: "flex", alignItems: "center", justifyContent: "center",
            boxShadow: "0 0 0 1.5px var(--bg-tint)",
          }} className="mono num">3</span>
        </div>
      )}
    </button>
  );
}

window.Sidebar = Sidebar;

/* ─────────────────────────────────────────────────────────────────────
   Sidebar search — input with popover results, arrow-key navigable.
   ───────────────────────────────────────────────────────────────────── */
function SidebarSearch({ onNavigate }) {
  const [q, setQ]         = useStateSB("");
  const [focused, setFocused] = useStateSB(false);
  const [active, setActive] = useStateSB(0);
  const inputRef = React.useRef(null);
  const popRef   = React.useRef(null);

  /* ⌘K / Ctrl+K to focus */
  React.useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        inputRef.current?.focus();
        inputRef.current?.select();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const lower = q.toLowerCase().trim();

  /* Build result groups. Always show pages when typing. */
  const groups = React.useMemo(() => {
    const matches = (s) => !lower || (s || "").toLowerCase().includes(lower);
    const accounts = window.COMPANIES
      .filter(c => matches(c.name) || matches(c.industry) || matches(c.hqCity))
      .slice(0, 6)
      .map(c => ({
        kind: "account",
        id: c.id,
        primary: c.name,
        secondary: `${c.industry} · ${c.hqCity}`,
        icon: "building",
        company: c,
        onPick: () => onNavigate("account-detail", { companyId: c.id }),
      }));
    const contacts = window.CONTACTS
      .filter(c => {
        const name = `${c.firstName} ${c.lastName}`;
        return matches(name) || matches(c.headline) || matches(c.position);
      })
      .slice(0, 6)
      .map(c => ({
        kind: "contact",
        id: c.id,
        primary: `${c.firstName} ${c.lastName}`,
        secondary: c.position + (c.companyName ? ` · ${c.companyName}` : ""),
        icon: "user",
        contact: c,
        onPick: () => {
          const conv = window.CONVERSATIONS.find(cv => cv.contactId === c.id);
          if (conv) onNavigate("conversations", { conversationId: conv.id });
          else onNavigate("contacts");
        },
      }));
    const pages = window.NAV
      .filter(n => matches(n.label))
      .slice(0, 5)
      .map(n => ({
        kind: "page",
        id: n.id,
        primary: n.label,
        secondary: "Workspace · " + n.label,
        icon: n.icon,
        onPick: () => onNavigate(n.id),
      }));

    const out = [];
    if (accounts.length) out.push({ heading: "Accounts", items: accounts });
    if (contacts.length) out.push({ heading: "Contacts", items: contacts });
    if (lower && pages.length) out.push({ heading: "Navigate", items: pages });
    if (!lower) {
      out.push({
        heading: "Recent",
        items: [
          ...accounts.slice(0, 3),
          ...contacts.slice(0, 2),
        ].slice(0, 5),
      });
    }
    return out;
  }, [lower, onNavigate]);

  /* Flat list for keyboard navigation */
  const flat = groups.flatMap(g => g.items);
  React.useEffect(() => { setActive(0); }, [lower]);
  React.useEffect(() => {
    if (!focused) return;
    const el = popRef.current?.querySelector(`[data-result-idx="${active}"]`);
    el?.scrollIntoView({ block: "nearest" });
  }, [active, focused]);

  const handleKey = (e) => {
    if (e.key === "ArrowDown") { e.preventDefault(); setActive(i => Math.min(flat.length - 1, i + 1)); }
    else if (e.key === "ArrowUp")   { e.preventDefault(); setActive(i => Math.max(0, i - 1)); }
    else if (e.key === "Enter")     {
      e.preventDefault();
      const pick = flat[active];
      if (pick) { pick.onPick?.(); setQ(""); inputRef.current?.blur(); }
    } else if (e.key === "Escape")   { setQ(""); inputRef.current?.blur(); }
  };

  const open = focused; /* show panel whenever focused (even empty query → Recent) */

  return (
    <div style={{ position: "relative" }}>
      {/* Input — styled identical to old TextField (sm) */}
      <div style={{
        display: "flex", alignItems: "center", gap: 8,
        height: 28, padding: "0 10px",
        background: "var(--surface)",
        border: `1px solid ${focused ? "var(--accent)" : "var(--line-strong)"}`,
        boxShadow: focused ? "0 0 0 3px color-mix(in oklch, var(--accent) 18%, transparent)" : "none",
        borderRadius: 7,
        transition: "border-color 120ms, box-shadow 120ms",
      }}>
        <Icon name="search" size={14} style={{ color: "var(--ink-3)", flexShrink: 0 }} />
        <input
          ref={inputRef}
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setTimeout(() => setFocused(false), 140)}
          onKeyDown={handleKey}
          placeholder="Search accounts, contacts…"
          style={{
            flex: 1, border: "none", outline: "none", background: "transparent",
            fontSize: 13, color: "var(--ink)",
          }}
        />
        {q ? (
          <button onMouseDown={(e) => { e.preventDefault(); setQ(""); inputRef.current?.focus(); }} title="Clear" style={{
            color: "var(--ink-4)", padding: 2, display: "inline-flex", alignItems: "center",
          }}><Icon name="x" size={11} stroke={2.4} /></button>
        ) : (
          <Kbd>⌘K</Kbd>
        )}
      </div>

      {/* Popover */}
      {open && (
        <div
          ref={popRef}
          style={{
            position: "absolute", top: "calc(100% + 6px)", left: -4, right: -4,
            zIndex: 80,
            background: "var(--surface)",
            border: "1px solid var(--line-strong)",
            borderRadius: 10,
            boxShadow: "0 18px 48px oklch(0.2 0 0 / 0.14), 0 4px 12px oklch(0.2 0 0 / 0.08)",
            padding: 6,
            maxHeight: "70vh", overflowY: "auto",
            animation: "fadein 160ms ease",
          }}
        >
          {flat.length === 0 ? (
            <div style={{ padding: "20px 14px", textAlign: "center", color: "var(--ink-3)", fontSize: 12.5 }}>
              <Icon name="search" size={16} style={{ color: "var(--ink-4)", marginBottom: 6 }} />
              <div style={{ fontWeight: 500, color: "var(--ink-2)" }}>No matches</div>
              <div style={{ marginTop: 2 }}>Try a company, person or page name.</div>
            </div>
          ) : (
            <>
              {groups.map((g, gi) => {
                /* compute starting flat index for this group */
                let base = 0;
                for (let i = 0; i < gi; i++) base += groups[i].items.length;
                return (
                  <div key={g.heading}>
                    <div style={{
                      padding: "8px 10px 4px",
                      fontSize: 10.5, fontWeight: 600,
                      color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.05em",
                      display: "flex", alignItems: "center", gap: 6,
                    }}>
                      {g.heading}
                      <span className="mono num" style={{ color: "var(--ink-4)", fontWeight: 500 }}>{g.items.length}</span>
                    </div>
                    {g.items.map((r, ri) => {
                      const idx = base + ri;
                      const isActive = idx === active;
                      return (
                        <button
                          key={`${g.heading}-${r.id}`}
                          data-result-idx={idx}
                          onMouseEnter={() => setActive(idx)}
                          onMouseDown={(e) => { e.preventDefault(); r.onPick?.(); setQ(""); inputRef.current?.blur(); }}
                          style={{
                            display: "flex", alignItems: "center", gap: 10,
                            padding: "7px 10px", width: "100%", borderRadius: 6,
                            textAlign: "left", fontSize: 13,
                            background: isActive ? "var(--inset)" : "transparent",
                            color: "var(--ink)",
                            transition: "background 100ms",
                            position: "relative",
                          }}
                        >
                          {/* Left visual: company logo / contact avatar / icon */}
                          {r.company
                            ? <CompanyLogo company={r.company} size={22} />
                            : r.contact
                              ? <Avatar name={`${r.contact.firstName} ${r.contact.lastName}`} src={r.contact.profilePictureUrl} size={22} />
                              : <div style={{
                                  width: 22, height: 22, borderRadius: 5,
                                  background: "var(--inset)", color: "var(--ink-3)",
                                  display: "flex", alignItems: "center", justifyContent: "center",
                                  flexShrink: 0,
                                }}><Icon name={r.icon} size={12} /></div>}
                          <div style={{ minWidth: 0, flex: 1 }}>
                            <div style={{ fontSize: 13, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                              {highlight(r.primary, lower)}
                            </div>
                            {r.secondary && <div style={{ fontSize: 11, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                              {r.secondary}
                            </div>}
                          </div>
                          {isActive && (
                            <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 10.5, color: "var(--ink-3)" }}>
                              <Kbd>↵</Kbd>
                            </span>
                          )}
                        </button>
                      );
                    })}
                  </div>
                );
              })}

              {/* Footer hints */}
              <div style={{
                marginTop: 4, padding: "8px 10px",
                borderTop: "1px solid var(--line)",
                display: "flex", alignItems: "center", gap: 10,
                fontSize: 11, color: "var(--ink-3)",
              }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><Kbd>↑</Kbd><Kbd>↓</Kbd> navigate</span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><Kbd>↵</Kbd> open</span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><Kbd>esc</Kbd> close</span>
                <span style={{ flex: 1 }} />
                <span className="mono num" style={{ color: "var(--ink-4)" }}>{flat.length}</span>
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
}

/* highlight matching substring in result text */
function highlight(text, q) {
  if (!q) return text;
  const i = text.toLowerCase().indexOf(q);
  if (i === -1) return text;
  return (
    <>
      {text.slice(0, i)}
      <span style={{ background: "color-mix(in oklch, var(--accent) 18%, transparent)", color: "var(--accent-ink)", borderRadius: 2, padding: "0 1px" }}>
        {text.slice(i, i + q.length)}
      </span>
      {text.slice(i + q.length)}
    </>
  );
}
