// MDM SORP — App shell with sidebar + topbar + router.

const { useState, useEffect, useMemo, useRef, useCallback, createContext, useContext } = React;

function AppShell() {
  const { t, lang, setLang } = useI18n();
  const [route, setRoute] = useState(() => {
    const h = location.hash.slice(1).split("/");
    return { name: h[0] || "home", params: h[1] ? { id: decodeURIComponent(h[1]) } : {} };
  });
  const [cpOpen, setCpOpen] = useState(false);
  const [collapsed, setCollapsed] = useState(false);

  const navigate = useCallback((name, params = {}) => {
    setRoute({ name, params });
    const hash = params.id ? `${name}/${encodeURIComponent(params.id)}` : name;
    history.replaceState(null, "", "#" + hash);
  }, []);

  // listen for external hash changes (e.g. design canvas iframes)
  useEffect(() => {
    const h = () => {
      const seg = location.hash.slice(1).split("/");
      setRoute({ name: seg[0] || "home", params: seg[1] ? { id: decodeURIComponent(seg[1]) } : {} });
    };
    window.addEventListener("hashchange", h);
    return () => window.removeEventListener("hashchange", h);
  }, []);

  // hotkey: cmd-K
  useEffect(() => {
    const h = (e) => {
      if ((e.metaKey || e.ctrlKey) && (e.key === "k" || e.key === "K")) {
        e.preventDefault(); setCpOpen(true);
      }
    };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, []);

  const nav = [
    { sect: "nav_work", items: [
      { id: "home", icon: "home" },
    ]},
    { sect: "nav_data", items: [
      { id: "deals", icon: "deals", count: 38 },
      { id: "parties", icon: "parties", count: 2184 },
      { id: "nomenclature", icon: "box", count: 1248 },
      { id: "documents", icon: "docs", count: 1248 },
    ]},
    { sect: "nav_intake", items: [
      { id: "import", icon: "upload", count: 2 },
    ]},
    { sect: "nav_queues", items: [
      { id: "enrichment", icon: "queue", count: 13, hot: true },
      { id: "dedup", icon: "merge", count: 4 },
      { id: "normalize", icon: "list", count: 137 },
    ]},
    { sect: "nav_enrich", items: [
      { id: "sourcing", icon: "lightbulb" },
    ]},
    { sect: "nav_admin", items: [
      { id: "dashboards", icon: "bar" },
      { id: "schema", icon: "book" },
      { id: "integrations", icon: "plug" },
      { id: "audit", icon: "history" },
    ]},
  ];

  const crumbs = computeCrumbs(route, t);
  const fullBleed = route.name === "form";

  if (fullBleed) {
    return <FormLinkScreen/>;
  }

  return (
    <div className={"app" + (collapsed ? " nav-collapsed" : "")}>
      {/* Sidebar */}
      <aside className="sidebar">
        <div className="sidebar-logo">
          <img src="assets/logo.png" alt="SORP"/>
          {!collapsed && <span style={{ fontWeight: 600, fontSize: 13, color: "var(--fg-on-dark)" }}>MDM</span>}
          {!collapsed && <span className="env-tag">{t("env")}</span>}
        </div>
        {nav.map(group => (
          <React.Fragment key={group.sect}>
            {!collapsed && <div className="sidebar-section">{t(group.sect)}</div>}
            <nav>
              {group.items.map(it => (
                <button key={it.id}
                        className={"nav-item " + (route.name === it.id ? "active" : "") + (it.danger ? " danger" : "")}
                        onClick={() => navigate(it.id)}
                        title={t(it.id)}>
                  <Icon name={it.icon} size={16}/>
                  {!collapsed && <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{t(it.id)}</span>}
                  {!collapsed && it.count != null && <span className="count">{it.count}</span>}
                </button>
              ))}
            </nav>
          </React.Fragment>
        ))}

        <div className="sidebar-spacer"/>

        {!collapsed && (
          <div className="sidebar-user">
            <div className="avatar">ЕС</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 12, color: "var(--fg-on-dark)" }}>{t("userName")}</div>
              <div className="role">{t("role")}</div>
            </div>
            <button className="icon-btn" style={{ color: "var(--fg-on-dark-2)" }} onClick={() => setCollapsed(true)} title="Свернуть">
              <Icon name="chevron_right" size={14}/>
            </button>
          </div>
        )}
        {collapsed && (
          <button className="icon-btn" style={{ color: "var(--fg-on-dark-2)", margin: 8 }} onClick={() => setCollapsed(false)} title="Развернуть">
            <Icon name="arrow_right" size={14}/>
          </button>
        )}
      </aside>

      {/* Topbar */}
      <header className="topbar">
        <div className="crumbs">
          {crumbs.map((c, i) => (
            <React.Fragment key={i}>
              {i > 0 && <span className="sep">/</span>}
              {c.onClick ? <a onClick={c.onClick} style={{ cursor: "pointer" }}>{c.label}</a> : <strong>{c.label}</strong>}
            </React.Fragment>
          ))}
        </div>

        <div className="omnibox">
          <Icon name="search" size={14} className="icon"/>
          <input placeholder={t("search")} onFocus={(e) => { e.target.blur(); setCpOpen(true); }}/>
          <span className="hk">{t("searchHk")}</span>
        </div>

        <div className="topbar-right">
          <button className="icon-btn" title={lang === "ru" ? "Спросить ИИ" : "Ask AI"} onClick={() => navigate("search")}>
            <Icon name="sparkle" size={16}/>
          </button>
          <button className="icon-btn" title="Уведомления">
            <Icon name="bell" size={16}/>
            <span className="dot"/>
          </button>
          <div className="lang-toggle">
            <button className={lang === "ru" ? "active" : ""} onClick={() => setLang("ru")}>RU</button>
            <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
          </div>
        </div>
      </header>

      {/* Main */}
      <main className="main">
        <RouteView route={route} navigate={navigate}/>
      </main>

      <CommandPalette open={cpOpen} onClose={() => setCpOpen(false)} navigate={(name, params) => navigate(name, params || {})}/>
    </div>
  );
}

function RouteView({ route, navigate }) {
  switch (route.name) {
    case "home":         return <HomeScreen navigate={navigate}/>;
    case "deals":        return <DealsScreen navigate={navigate}/>;
    case "deal":         return <DealCardScreen navigate={navigate} params={route.params}/>;
    case "parties":      return <PartiesScreen navigate={navigate}/>;
    case "party":        return <PartyCardScreen navigate={navigate} params={route.params}/>;
    case "nomenclature": return <NomenclatureScreen navigate={navigate}/>;
    case "documents":    return <DocumentsScreen navigate={navigate}/>;
    case "sourcing":     return <SourcingScreen navigate={navigate}/>;
    case "normalize":    return <NormalizeScreen navigate={navigate}/>;
    case "capability":   return <SourcingScreen navigate={navigate}/>; /* legacy hash → sourcing */
    case "enrichment":   return <EnrichmentQueueScreen navigate={navigate}/>;
    case "dedup":        return <DedupScreen navigate={navigate}/>;
    case "import":       return <ImportScreen navigate={navigate}/>;
    case "sanctions":    return <ComingSoon title="Санкции" desc="Модуль отключён по решению владельца. Если нужно вернуть — скажи."/>;
    case "dashboards":   return <DashboardScreen navigate={navigate}/>;
    case "schema":       return <SchemaScreen navigate={navigate}/>;
    case "smart_table":      return <SmartTableScreen navigate={navigate}/>;
    case "relationship_map": return <RelationshipMapScreen navigate={navigate}/>;
    case "integrations": return <ComingSoon title="Интеграции" desc="Amo · Asana · Drive · 1C — статусы коннекторов, расписания, последние ошибки."/>;
    case "audit":        return <ComingSoon title="Журнал изменений" desc="Унифицированный audit_log по всем таблицам с фильтрами и откатом."/>;
    case "search":       return <SearchScreen navigate={navigate}/>;
    default:             return <HomeScreen navigate={navigate}/>;
  }
}

function ComingSoon({ title, desc }) {
  return (
    <div style={{ padding: 48, maxWidth: 720 }}>
      <h2 style={{ marginTop: 0 }}>{title}</h2>
      <p className="muted">{desc}</p>
      <div className="card" style={{ padding: 16, marginTop: 12 }}>
        <Icon name="info" size={14} className="muted"/>
        <span className="muted" style={{ marginLeft: 8, fontSize: 12 }}>Прототип покрывает основные операторские сценарии. Этот экран — заглушка для полного списка модулей.</span>
      </div>
    </div>
  );
}

function computeCrumbs(route, t) {
  const home = { label: t("home"), onClick: () => location.hash = "#home" };
  switch (route.name) {
    case "home":         return [{ label: t("home") }];
    case "deal":         return [home, { label: t("deals"), onClick: () => location.hash = "#deals" }, { label: route.params.id || "—" }];
    case "party":        return [home, { label: t("parties"), onClick: () => location.hash = "#parties" }, { label: route.params.id || "—" }];
    default:             return [home, { label: t(route.name) || route.name }];
  }
}

window.AppShell = AppShell;
