// shell.jsx — Login + AppShell (sidebar + topbar)

const { useState, useEffect, useRef } = React;

// ─────────────────────────────────────────────────────────────
// Logo (original, not Daikin)
// ─────────────────────────────────────────────────────────────
function Logo({ size = 'md' }) {
  const cls = size === 'xl' ? 'rtdc-logo rtdc-logo--xl' :
              size === 'lg' ? 'rtdc-logo rtdc-logo--lg' : 'rtdc-logo';
  return <div className={cls}><span>RTDC</span></div>;
}

// ─────────────────────────────────────────────────────────────
// Login Page
// ─────────────────────────────────────────────────────────────
function LoginPage({ onLogin }) {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [remember, setRemember] = useState(true);
  const [err, setErr] = useState('');
  const [loading, setLoading] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    if (!username.trim() || !password.trim()) {
      setErr('Please enter your username and password.');
      return;
    }
    setErr('');
    setLoading(true);
    try {
      // Credentials are validated server-side by the Apps Script backend.
      const res = await window.RTDC_SHEETS.login(username.trim(), password);
      if (!res || !res.ok) {
        setErr(res && res.error ? res.error : 'Invalid username or password.');
        setLoading(false);
        return;
      }
      const u = res.user;
      onLogin({
        username: u.username,
        name: u.name || u.username,
        role: u.role,
        title: u.role,      // replaced with the role's display name once permissions load
        image: u.image,
      });
    } catch (ex) {
      setErr('Could not reach the sign-in service. Please check your connection and try again.');
      setLoading(false);
    }
  };

  return (
    <div className="login-page">
      <div className="login-hero">
        <div className="row gap-md">
          <Logo size="lg" />
          <div>
            <div style={{ fontSize: 14, opacity: 0.7, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
              Talent Development
            </div>
            <div style={{ fontSize: 18, fontWeight: 600 }}>
              Regional Talent Development Center
            </div>
          </div>
        </div>

        <div>
          <h1>Develop the people who develop our future.</h1>
          <p>
            A unified workspace for identifying high-potential talent, evaluating performance,
            and aligning growth across the region. Built for HR teams and employees alike.
          </p>
        </div>

        <div style={{ fontSize: 12, opacity: 0.6, letterSpacing: '0.04em' }}>
          © 2026 RTDC · Internal use only · v2.5.0
        </div>
      </div>

      <div className="login-form-wrap">
        <form className="login-form" onSubmit={submit}>
          <div className="brand-stack">
            <Logo size="xl" />
            <h2>Regional Talent Development Center</h2>
            <p className="subtitle">Sign in to your RTDC account</p>
          </div>

          <div className="form-field">
            <label>Username or Employee ID</label>
            <input
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="Enter your username or employee ID"
              disabled={loading}
              autoFocus
            />
          </div>

          <div className="form-field">
            <label>Password</label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Enter your password"
              disabled={loading}
            />
          </div>

          {err && <div style={{ color: 'var(--rtdc-red)', fontSize: 12, marginBottom: 12 }}>{err}</div>}

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, fontSize: 12 }}>
            <label style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--text-2)' }}>
              <input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)} />
              Remember me
            </label>
            <a href="#">Forgot password?</a>
          </div>

          <button type="submit" className="btn btn-primary btn-block" disabled={loading}>
            {loading ? 'Signing in…' : 'Sign in'}
          </button>
        </form>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Sidebar
// ─────────────────────────────────────────────────────────────
// Navigation. Each item's `id` matches a column header (col C onward) in the
// "permission" sheet — that sheet decides which roles see which page.
const NAV = [
  { type: 'item',    id: 'home',       label: 'Home',                  icon: 'home'    },
  { type: 'item',    id: 'talent-box', label: 'Talent Box',            icon: 'box'     },
  { type: 'section', label: 'Evaluation System' },
  { type: 'item',    id: 'ccd',        label: 'Color Code Detection (CCD)', icon: 'palette' },
  { type: 'item',    id: 'kpi',        label: 'Key Performance Indicators (KPI)', icon: 'gauge' },
  { type: 'item',    id: 'core',       label: 'Core Values',           icon: 'heart'   },
  { type: 'item',    id: 'comp',       label: 'Competency',            icon: 'star'    },
  { type: 'item',    id: 'report',     label: 'Talent Report',         icon: 'report'  },
];

// Canonical page order — used by the router to pick a landing page.
const NAV_PAGE_IDS = NAV.filter(n => n.type === 'item').map(n => n.id);

function Sidebar({ active, onNavigate, allowed, permsReady, collapsed }) {
  if (!permsReady) {
    return (
      <nav className="sidebar">
        <div className="nav-section"><span>Loading…</span></div>
      </nav>
    );
  }
  const canSee = (id) => !!(allowed && allowed[id]);
  return (
    <nav className="sidebar">
      {NAV.map((item, idx) => {
        if (item.type === 'section') {
          // Only show a section header if at least one item beneath it is visible.
          let anyVisible = false;
          for (let j = idx + 1; j < NAV.length && NAV[j].type !== 'section'; j++) {
            if (canSee(NAV[j].id)) { anyVisible = true; break; }
          }
          if (!anyVisible) return null;
          return <div className="nav-section" key={'sec' + idx}><span>{item.label}</span></div>;
        }
        if (!canSee(item.id)) return null;
        const I = window.Icons[item.icon] || window.Icons.home;
        return (
          <button
            key={item.id}
            className={'nav-item ' + (active === item.id ? 'active' : '')}
            onClick={() => onNavigate(item.id)}
            title={collapsed ? item.label : ''}
          >
            <span className="nav-icon"><I size={17} /></span>
            <span className="nav-label">{item.label}</span>
          </button>
        );
      })}
    </nav>
  );
}

// ─────────────────────────────────────────────────────────────
// Topbar
// ─────────────────────────────────────────────────────────────
function Topbar({ user, onLogout, onToggleSidebar }) {
  const initials = (user.name || '').split(' ').map(s => s[0]).join('').slice(0, 2).toUpperCase();
  return (
    <header className="topbar">
      <div className="topbar-left">
        <button className="btn btn-ghost btn-icon" onClick={onToggleSidebar} title="Toggle sidebar">
          <window.Icons.menu size={18} />
        </button>
        <Logo size="md" />
        <div className="topbar-title">
          Regional Talent Development Center
          <span className="sub">(RTDC)</span>
        </div>
        <div className="topbar-search" style={{ marginLeft: 16 }}>
          <window.Icons.search size={14} />
          <input placeholder="Search employees, reports, KPIs…" />
        </div>
      </div>

      <div className="topbar-right">
        <button className="btn btn-ghost btn-icon" title="Notifications">
          <window.Icons.bell size={17} />
        </button>
        <div className="user-chip" title="Account">
          <div className="avatar" style={{ position: 'relative', overflow: 'hidden' }}>
            <span>{initials}</span>
            {user.image && (
              <img
                src={window.RTDC_SHEETS.driveImageUrl(user.image, 80)}
                alt=""
                referrerPolicy="no-referrer"
                style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }}
                onError={(e) => { e.target.style.display = 'none'; }}
              />
            )}
          </div>
          <div className="meta">
            <span className="name">{user.name}</span>
            <span className="role">{user.title}</span>
          </div>
        </div>
        <button className="btn btn-ghost" onClick={onLogout} style={{ color: 'var(--rtdc-red)' }}>
          <window.Icons.logout size={15} />
          <span>Log out</span>
        </button>
      </div>
    </header>
  );
}

window.Logo = Logo;
window.LoginPage = LoginPage;
window.Sidebar = Sidebar;
window.Topbar = Topbar;
window.NAV_PAGE_IDS = NAV_PAGE_IDS;
