// shell.jsx — Sidebar, TopBar, Login, Tenant picker — using DS classes verbatim

function Sidebar({
  route,
  onNavigate,
  alertCount = 3,
  taskCount = 14,
  tenant,
  user,
  role = "",
  onLogout,
  collapsed = false,
  onToggleCollapse,
}) {
  // Primary nav items are grouped by domain.
  // Sub-pages (site, hives, telemetry) and advanced screens (rules, commands,
  // ota, recommendations) are reached contextually, not from the sidebar.
  const NAV = [
    { group: "Объект", items: [
      { id:"overview",  icon:"ri-dashboard-2-line",    label:"Обзор" },
      { id:"sites",     icon:"ri-leaf-line",            label:"Теплицы" },
      { id:"devices",   icon:"ri-router-line",          label:"Устройства" },
      { id:"telemetry", icon:"ri-pulse-line",           label:"Телеметрия" },
      { id:"microclimate", icon:"ri-temp-hot-line",     label:"Микроклимат" },
    ]},
    { group: "Работа", items: [
      { id:"alerts",  icon:"ri-alarm-warning-line", label:"Уведомления", badge: alertCount,  badgeKind:"crit" },
      { id:"tasks",   icon:"ri-task-line",          label:"Задачи",      badge: taskCount,   badgeKind:"warn" },
      { id:"commands", icon:"ri-command-line",      label:"Команды", roleMin:"operator" },
      { id:"ota",      icon:"ri-upload-cloud-2-line", label:"OTA", roleMin:"operator" },
      { id:"rules",    icon:"ri-git-branch-line",   label:"Правила", roleMin:"operator" },
      { id:"reports", icon:"ri-bar-chart-2-line",   label:"Отчёты" },
      { id:"roi",     icon:"ri-funds-line",         label:"ROI" },
    ]},
    { group: "Настройки", items: [
      { id:"settings",   icon:"ri-settings-3-line",   label:"Настройки" },
      { id:"simulator",  icon:"ri-cpu-line",           label:"Виртуальный стенд" },
    ]},
  ];

  // [TASK_START:T014]
  const normalizedRole = String(role || "").toLowerCase();
  const isLimitedOperator = normalizedRole === "worker" || normalizedRole === "technician";
  const visibleNav = NAV.map(group => ({
    ...group,
    items: group.items.filter(item => !(item.roleMin === "operator" && isLimitedOperator)),
  }));
  // [TASK_COMPLETE:T014]

  return (
    <aside className="sidebar">
      <div className="brand">
        <img src="ds/assets/keeper-logo-mono-white.png" alt="" style={{height:24,width:"auto"}} onError={(e)=>{e.currentTarget.style.display="none"}}/>
        <div>
          <div className="brand-name">Keeper</div>
        </div>
      </div>
      <div className="org">
        <div>
          <span style={{fontSize:10,textTransform:"uppercase",letterSpacing:".05em"}}>Объект</span>
          <b>{tenant?.name || "Ahal Agro Park"}</b>
          <span>Теплицы 1–{tenant?.greenhouses||6} · {tenant?.devices||318} устройств</span>
        </div>
        <i className="ri-arrow-down-s-line" style={{fontSize:16}}></i>
      </div>
      {visibleNav.map(g => (
        <React.Fragment key={g.group}>
          <div className="section">{g.group}</div>
          {g.items.map(item => (
            <button
              key={item.id}
              className={"nav-item" + (route === item.id ? " active" : "")}
              onClick={() => onNavigate(item.id)}
            >
              <i className={item.icon}></i>
              <span>{item.label}</span>
              {item.badge && (
                <span className="badge" style={{
                  background: item.badgeKind === "warn" ? "#FFB300" : "#E5342B",
                  color: item.badgeKind === "warn" ? "#1D1C1D" : "#fff",
                }}>{item.badge}</span>
              )}
            </button>
          ))}
        </React.Fragment>
      ))}
      <div className="sidebar-foot">
        {onToggleCollapse && (
          <button
            className="nav-item sidebar-collapse-btn"
            onClick={onToggleCollapse}
            title={collapsed ? "Развернуть панель" : "Свернуть панель"}
          >
            <i className={collapsed ? "ri-layout-right-line" : "ri-layout-left-line"}></i>
            <span>{collapsed ? "Развернуть" : "Свернуть"}</span>
          </button>
        )}
        {onLogout && (
          // [TASK_START:T016]
          <button className="nav-item" onClick={onLogout}>
            <i className="ri-logout-box-r-line"></i>
            <span>Выйти</span>
          </button>
          // [TASK_COMPLETE:T016]
        )}
        <button className="nav-item"><i className="ri-question-line"></i><span>Помощь</span></button>
        <div className="user">
          <span className="av">{(user && user.initials) || (DATA.user && DATA.user.initials) || "?"}</span>
          <div>
            <b>{(user && user.name) || (DATA.user && DATA.user.name) || "—"}</b>
            <span>{(user && user.role) || (DATA.user && DATA.user.role) || "—"}</span>
          </div>
        </div>
      </div>
    </aside>
  );
}

function TopBar({ route, onSearch }) {
  // Derive the breadcrumb trail from the current route ID using the
  // centralised breadcrumb map.  Falls back to ["Ahal Agro Park"] for
  // unknown routes (matches Keeper.breadcrumbs fallback behaviour).
  const crumbs = Keeper.breadcrumbs.get(route);

  return (
    <div className="topbar">
      <div className="crumbs">
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <i className="ri-arrow-right-s-line"></i>}
            {i === crumbs.length - 1 ? <b>{c}</b> : <span>{c}</span>}
          </React.Fragment>
        ))}
      </div>
      <div className="search">
        <i className="ri-search-line"></i>
        <input placeholder="Поиск устройств, зон, ульев…"/>
      </div>
      <button className="icon-btn" title="Помощь"><i className="ri-question-line"></i></button>
      <button className="icon-btn" title="Уведомления"><i className="ri-notification-3-line"></i><span className="pulse"></span></button>
    </div>
  );
}

/* Login & tenant picker */
function Login({ onLogin, sessionMessage = "" }) {
  const [step, setStep] = React.useState("creds"); // creds | tenants
  // [TASK_START:T010]
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [remember, setRemember] = React.useState(true);
  const [loading, setLoading] = React.useState(false);
  const [formError, setFormError] = React.useState("");
  const [fieldErrors, setFieldErrors] = React.useState({ email: "", password: "" });
  // [TASK_COMPLETE:T010]
  const [user, setUser] = React.useState(null);
  const [tenants, setTenants] = React.useState([]);

  // [TASK_START:T011]
  function validate() {
    const errors = { email: "", password: "" };
    if (!email || !email.trim() || !email.includes("@")) {
      errors.email = "Введите корректный адрес почты";
    }
    if (!password || !password.trim()) {
      errors.password = "Введите пароль";
    }
    setFieldErrors(errors);
    return !errors.email && !errors.password;
  }
  // [TASK_COMPLETE:T011]

  async function handleLoginSubmit(event) {
    event.preventDefault();
    setFormError("");
    // [TASK_START:T012]
    if (!validate()) return;
    setLoading(true);
    try {
      const response = await Keeper.api.login(email.trim(), password);
      const availableTenants = Array.isArray(response.tenants) ? response.tenants : [];
      setUser(response.user || null);
      setTenants(availableTenants);
      window.DATA = Object.assign({}, window.DATA || {}, { user: response.user || null, tenants: availableTenants });
      setStep("tenants");
    } catch (error) {
      const fallbackMessage =
        error instanceof Keeper.ApiError && (error.status === 401 || error.status === 403)
          ? "Неверный адрес почты или пароль"
          : "Нет соединения с сервером";
      const formatted = typeof Keeper.formatApiFailure === "function"
        ? Keeper.formatApiFailure(error, { fallbackMessage })
        : fallbackMessage;
      setFormError(formatted);
    } finally {
      setLoading(false);
    }
    // [TASK_COMPLETE:T012]
  }

  // [TASK_START:T013]
  async function handleTenantSelect(selectedTenant) {
    setLoading(true);
    setFormError("");
    try {
      const selected = await Keeper.api.selectTenant(selectedTenant.id);
      const activeTenant = selected.activeTenant || selected.active_tenant || selectedTenant;
      if (remember) {
        localStorage.setItem("keeper.activeTenant", JSON.stringify(activeTenant));
      } else {
        localStorage.removeItem("keeper.activeTenant");
      }
      window.DATA = Object.assign({}, window.DATA || {}, { activeTenant, user: user || window.DATA?.user || null });
      onLogin({ user: user || window.DATA?.user || null, tenant: activeTenant });
    } catch (error) {
      const fallbackMessage = "Не удалось выбрать объект";
      const formatted = typeof Keeper.formatApiFailure === "function"
        ? Keeper.formatApiFailure(error, { fallbackMessage })
        : fallbackMessage;
      setFormError(formatted);
    } finally {
      setLoading(false);
    }
  }
  // [TASK_COMPLETE:T013]

  return (
    <div className="login-shell">
      <div className="login-form-side">
        <div className="login-brand">
          <div style={{width:28,height:28,borderRadius:6,background:"#FFB300",display:"flex",alignItems:"center",justifyContent:"center",fontSize:18}}>🐝</div>
          <b>Keeper</b>
        </div>

        {step === "creds" && (
          <form className="login-form" onSubmit={handleLoginSubmit} noValidate>
            <h1>Войти в систему</h1>
            <div className="sub">Платформа мониторинга теплиц и опыления</div>
            {sessionMessage && (
              <div style={{fontSize:12,color:"var(--status-critical)",marginBottom:8}}>{sessionMessage}</div>
            )}
            <div className="field">
              <label>Электронная почта</label>
              <input value={email} onChange={(e)=>setEmail(e.target.value)} />
              {fieldErrors.email && <div style={{fontSize:12,color:"var(--status-critical)",marginTop:6}}>{fieldErrors.email}</div>}
            </div>
            <div className="field">
              <label>Пароль</label>
              <input type="password" value={password} onChange={(e)=>setPassword(e.target.value)} />
              {fieldErrors.password && <div style={{fontSize:12,color:"var(--status-critical)",marginTop:6}}>{fieldErrors.password}</div>}
            </div>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:12,color:"var(--fg-muted)"}}>
              <label style={{display:"inline-flex",gap:6,alignItems:"center"}}><input type="checkbox" checked={remember} onChange={(e)=>setRemember(e.target.checked)} />Запомнить</label>
              <a href="#">Забыли пароль?</a>
            </div>
            {formError && <div style={{fontSize:12,color:"var(--status-critical)"}}>{formError}</div>}
            <button className="btn btn--primary" style={{height:40,justifyContent:"center"}} type="submit" disabled={loading}>
              {loading ? "Вход..." : "Войти"}<i className="ri-arrow-right-line"></i>
            </button>
            <div style={{textAlign:"center",fontSize:12,color:"var(--fg-muted)"}}>
              или <a href="#">войти через SSO</a>
            </div>
            <div className="login-foot">© 2026 Keeper IIoT · v3.4.2 · <a href="#">конфиденциальность</a></div>
          </form>
        )}

        {step === "tenants" && (
          <div className="login-form" style={{maxWidth:520}}>
            <h1>Выберите объект</h1>
            <div className="sub">Вам доступны {tenants.length} организации</div>
            <div className="tenant-grid">
              {tenants.map(t => (
                <div key={t.id} className="tenant-card" onClick={()=>!loading && handleTenantSelect(t)}>
                  <b>{t.name}</b>
                  <div className="meta">{t.country} · {t.greenhouses} теплиц · {t.devices} устройств</div>
                  <div style={{marginTop:8}}><span className="status status--muted"><span className="dot"></span>{t.role}</span></div>
                </div>
              ))}
            </div>
            {formError && <div style={{fontSize:12,color:"var(--status-critical)"}}>{formError}</div>}
            <button className="btn btn--ghost" onClick={()=>setStep("creds")} style={{alignSelf:"flex-start"}}><i className="ri-arrow-left-line"></i>Назад</button>
          </div>
        )}
      </div>

      <div className="login-art">
        <div className="login-art-copy">
          <h2>Видеть пасеку и теплицу как один организм</h2>
          <p>Активность колоний, состояние субстрата, прошивки шлейфов — на одном экране, в реальном времени, с автоматизацией для ваших агрономов.</p>
          <div className="login-art-stat">
            <div><div className="v">98,4 %</div><div className="l">Аптайм</div></div>
            <div><div className="v">312</div><div className="l">Устройств онлайн</div></div>
            <div><div className="v">76 %</div><div className="l">Активность ульев</div></div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Sidebar = Sidebar;
window.TopBar = TopBar;
window.Login = Login;
