/* ==========================================================
   organizer-chrome.jsx — Arena Organizer structural chrome
   Login · Sidebar · Topbar · DocFooter
   React 18 in-browser Babel (no build step). No import/export.
   Deps: window.React, window.ORG_NAV
   ========================================================== */

/* ----------------------------------------------------------
   Helpers
   ---------------------------------------------------------- */
function _initials(displayName) {
  if (!displayName) return '?';
  var parts = String(displayName).trim().split(/\s+/);
  if (parts.length >= 2) {
    return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
  }
  return parts[0].slice(0, 2).toUpperCase();
}

/* ----------------------------------------------------------
   OrgLoginScreen
   Props:
     onLogin  {(email, password) => Promise}
     loading  {boolean}
   ---------------------------------------------------------- */
window.OrgLoginScreen = function OrgLoginScreen(props) {
  var onLogin = props.onLogin;
  var loading  = props.loading;

  var emailState    = React.useState('');
  var email         = emailState[0];
  var setEmail      = emailState[1];

  var passwordState = React.useState('');
  var password      = passwordState[0];
  var setPassword   = passwordState[1];

  var errorState    = React.useState('');
  var error         = errorState[0];
  var setError      = errorState[1];

  function handleSubmit(e) {
    if (e && e.preventDefault) e.preventDefault();
    if (loading) return;
    setError('');
    Promise.resolve(onLogin(email, password)).catch(function(err) {
      setError(err && err.message ? err.message : 'Sign-in failed. Please try again.');
    });
  }

  function handleKeyDown(e) {
    if (e.key === 'Enter') handleSubmit();
  }

  return (
    <div className="login-shell">
      <div className="login-card">

        {/* Brand lockup */}
        <div className="brand login-brand">
          <span className="mk">A</span>
          <div>
            <div className="nm"><em>Arena</em> · studio</div>
            <small>Organizer console</small>
          </div>
        </div>

        {/* Form */}
        <form className="login-form" onSubmit={handleSubmit} autoComplete="on">
          <div className="login-field">
            <label className="login-label">Email</label>
            <input
              className="login-input"
              type="email"
              placeholder="admin@cisco.com"
              value={email}
              onChange={function(e) { setEmail(e.target.value); }}
              onKeyDown={handleKeyDown}
              autoFocus
              autoComplete="username"
              disabled={loading}
            />
          </div>

          <div className="login-field">
            <label className="login-label">Password</label>
            <input
              className="login-input"
              type="password"
              placeholder="••••••••"
              value={password}
              onChange={function(e) { setPassword(e.target.value); }}
              onKeyDown={handleKeyDown}
              autoComplete="current-password"
              disabled={loading}
            />
          </div>

          {error && (
            <div className="login-error">{error}</div>
          )}

          <button
            className="btn primary login-btn"
            type="submit"
            disabled={loading || !email || !password}
          >
            {loading ? 'Signing in…' : 'Sign in'}
          </button>
        </form>

      </div>
    </div>
  );
};

/* ----------------------------------------------------------
   OrgSidebar
   Props:
     activePage  {string}
     onNavigate  {(pageId) => void}
     admin       {{ email, display_name, role } | null}
     onLogout    {() => void}
     gameCount   {number}
   ---------------------------------------------------------- */
window.OrgSidebar = function OrgSidebar(props) {
  var activePage = props.activePage;
  var onNavigate = props.onNavigate;
  var admin      = props.admin;
  var onLogout   = props.onLogout;
  var gameCount  = props.gameCount;

  var nav = window.ORG_NAV;

  var displayName = admin && admin.display_name ? admin.display_name : (admin && admin.email ? admin.email : 'Admin');
  var role        = admin && admin.role        ? admin.role        : '';
  var initials    = _initials(displayName);

  function resolveCount(item) {
    if (item.id === 'sessions' && gameCount != null) return gameCount;
    if (item.count != null) return item.count;
    return null;
  }

  return (
    <aside className="side">

      {/* Brand lockup */}
      <div className="brand">
        <span className="mk">A</span>
        <div>
          <div className="nm"><em>Arena</em> · studio</div>
          <small>Organizer console</small>
        </div>
      </div>

      {/* Nav sections */}
      {nav.map(function(section) {
        return (
          <div className="navsec" key={section.title}>
            <h6>{section.title}</h6>
            <nav className="nav">
              {section.items.map(function(item) {
                var count = resolveCount(item);
                return (
                  <a
                    key={item.id}
                    className={item.id === activePage ? 'on' : ''}
                    onClick={function(e) {
                      e.preventDefault();
                      if (item.href) { window.open(item.href, '_blank'); return; }
                      onNavigate(item.id);
                    }}
                    href={item.href || '#'}
                    target={item.href ? '_blank' : undefined}
                    rel={item.href ? 'noopener noreferrer' : undefined}
                  >
                    <span className="ic">{item.icon}</span>
                    {item.label}
                    {count != null && <span className="ct">{count}</span>}
                  </a>
                );
              })}
            </nav>
          </div>
        );
      })}

      {/* User footer */}
      <div className="sideuser">
        <div className="av">{initials}</div>
        <div className="sideuser-info">
          <b>{displayName}</b>
          <small>{role}</small>
        </div>
        {onLogout && (
          <button
            className="btn ghost sideuser-logout"
            onClick={onLogout}
            title="Log out"
          >
            ⏻
          </button>
        )}
      </div>

    </aside>
  );
};

/* ----------------------------------------------------------
   OrgTopbar
   Props:
     breadcrumbs   {string[]}  e.g. ["Workspace","Sessions","Apr 2026"]
     onNavigate    {function}  Navigate to a page
     admin         {object}
   ---------------------------------------------------------- */
window.OrgTopbar = function OrgTopbar(props) {
  var breadcrumbs  = props.breadcrumbs  || [];
  var onNavigate   = props.onNavigate;

  var crumbNodes = breadcrumbs.map(function(crumb, i) {
    var isLast = i === breadcrumbs.length - 1;
    return (
      <React.Fragment key={i}>
        {isLast ? <b>{crumb}</b> : crumb}
        {!isLast && <span className="sep">›</span>}
      </React.Fragment>
    );
  });

  return (
    <div className="topbar">
      <span className="crumb">{crumbNodes}</span>
      <div className="grow" />

      <input
        className="search"
        placeholder="Search sessions, squads, questions…"
        type="search"
      />
      <button className="btn primary" onClick={function() { if (onNavigate) onNavigate('create-wizard'); }}>
        ＋ New session
      </button>
    </div>
  );
};

/* ----------------------------------------------------------
   OrgDocFooter
   Props: none
   ---------------------------------------------------------- */
window.OrgDocFooter = function OrgDocFooter() {
  return (
    <div className="docfoot">
      <span>Arena · Organizer console v0.6</span>
      <span>ship order: calendar · ingest · assign · monitor</span>
    </div>
  );
};
