/* ============================================================
   Login screen + App shell (sidebar / topbar / project tabs)
   ============================================================ */
const { useState: useS1, useEffect: useE1 } = React;

/* ---------------- LOGIN ---------------- */
const SSO_DOMAINS = ['lge.com', 'concentrix.com', '직접입력'];

/* role display helpers (ADMIN > CNX > LGE) */
const roleColor = (r) => r === 'ADMIN' ? 'var(--ink)' : r === 'CNX' ? 'var(--cnx-blue)' : 'var(--lg-red)';
const orgOf = (r) => r === 'ADMIN' ? '운영 관리자' : r === 'CNX' ? 'Concentrix' : 'LG Electronics';
const roleDesc = (r) => r === 'ADMIN' ? '시스템 관리' : r === 'CNX' ? '콘텐츠 관리' : '조회·선택·제출';

/* Shared SSO email field: local-part + domain select, or direct full-email entry.
   Parent owns the state and derives the final email from these three pieces. */
function SsoEmailField({ localPart, setLocalPart, domain, setDomain, customEmail, setCustomEmail, autoComplete }) {
  const isDirect = domain === '직접입력';
  return (
    <div className="field">
      <label>이메일</label>
      {isDirect
        ? <input type="email" value={customEmail} onChange={(e) => setCustomEmail(e.target.value)} placeholder="name@company.com" autoComplete={autoComplete} />
        : <div className="sso-email-row">
            <input type="text" value={localPart} onChange={(e) => setLocalPart(e.target.value)} placeholder="이름" autoComplete={autoComplete} />
            <span className="sso-at">@</span>
            <select value={domain} onChange={(e) => setDomain(e.target.value)}>
              {SSO_DOMAINS.map(d => <option key={d} value={d}>{d}</option>)}
            </select>
          </div>
      }
      {!isDirect
        ? <button type="button" className="sso-switch" onClick={() => setDomain('직접입력')}>직접입력</button>
        : <button type="button" className="sso-switch" onClick={() => { setDomain('lge.com'); setCustomEmail(''); }}>SSO 도메인 선택</button>
      }
    </div>);
}

function ssoEmail(localPart, domain, customEmail) {
  return domain === '직접입력' ? customEmail : (localPart + '@' + domain);
}

function SignUp({ onSignUp, onBack }) {
  const [localPart, setLocalPart] = useS1('');
  const [domain, setDomain] = useS1('lge.com');
  const [customEmail, setCustomEmail] = useS1('');
  const [name, setName] = useS1('');
  const [pw, setPw] = useS1('');
  const [pwConfirm, setPwConfirm] = useS1('');
  const [inviteCode, setInviteCode] = useS1('');
  const [err, setErr] = useS1('');
  const [busy, setBusy] = useS1(false);

  const email = ssoEmail(localPart, domain, customEmail);

  const submit = async (e) => {
    e.preventDefault();
    if (pw !== pwConfirm) { setErr('비밀번호가 일치하지 않습니다.'); return; }
    setBusy(true); setErr('');
    try { const r = await window.api.register({ email, name, password: pw, inviteCode: inviteCode.trim() }); onSignUp(r); }
    catch (ex) { setErr(ex.message); setBusy(false); }
  };

  return (
    <div className="login-stage">
      <div className="login-form-wrap">
        <form className="login-card" onSubmit={submit}>
          <div className="logo-lockup">
            <span style={{ background: 'var(--accent)', color: '#fff', fontWeight: 800, fontSize: 12, letterSpacing: '.08em', padding: '6px 11px', borderRadius: 7 }}>LG AI 365</span>
          </div>
          <h2>회원가입</h2>
          <p className="hint">계정 정보를 입력하세요.</p>

          <SsoEmailField {...{ localPart, setLocalPart, domain, setDomain, customEmail, setCustomEmail }} autoComplete="email" />
          <div className="field">
            <label>이름</label>
            <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="홍길동" autoComplete="name" />
          </div>
          <div className="field">
            <label>비밀번호</label>
            <input type="password" value={pw} onChange={(e) => setPw(e.target.value)} placeholder="••••••" autoComplete="new-password" />
          </div>
          <div className="field">
            <label>비밀번호 확인</label>
            <input type="password" value={pwConfirm} onChange={(e) => setPwConfirm(e.target.value)} placeholder="••••••" autoComplete="new-password" />
          </div>
          <div className="field">
            <label>초대 코드</label>
            <input type="text" value={inviteCode} onChange={(e) => setInviteCode(e.target.value)} placeholder="LG-XXXXXX" autoCapitalize="characters" />
          </div>
          {err && <div className="login-err">{err}</div>}
          <Btn variant="primary" size="lg" className="btn-block" type="submit" disabled={busy} icon={busy ? <Icon.clock className="spin" /> : null}>
            {busy ? '가입 중…' : '가입하기'}
          </Btn>
          <Btn variant="ghost" size="lg" className="btn-block" type="button" style={{ marginTop: 10 }} onClick={onBack}>
            로그인으로 돌아가기
          </Btn>
        </form>
      </div>
    </div>);
}

function Login({ onLogin }) {
  const [localPart, setLocalPart] = useS1('');
  const [domain, setDomain] = useS1('lge.com');
  const [customEmail, setCustomEmail] = useS1('');
  const [pw, setPw] = useS1('');
  const [err, setErr] = useS1('');
  const [busy, setBusy] = useS1(false);
  const [showSignUp, setShowSignUp] = useS1(false);

  const email = ssoEmail(localPart, domain, customEmail);

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true);setErr('');
    try {const r = await window.api.login({ email, password: pw });onLogin(r);}
    catch (ex) {setErr(ex.message);setBusy(false);}
  };

  if (showSignUp) return <SignUp onSignUp={onLogin} onBack={() => setShowSignUp(false)} />;

  return (
    <div className="login-stage">
      <div className="login-form-wrap">
        <form className="login-card" onSubmit={submit}>
          <div className="logo-lockup">
            <span style={{ background: 'var(--accent)', color: '#fff', fontWeight: 800, fontSize: 12, letterSpacing: '.08em', padding: '6px 11px', borderRadius: 7 }}>LG AI 365</span>
          </div>
          <h2>로그인</h2>
          <p className="hint">계정 정보를 입력하세요.</p>

          <SsoEmailField {...{ localPart, setLocalPart, domain, setDomain, customEmail, setCustomEmail }} autoComplete="username" />
          <div className="field">
            <label>비밀번호</label>
            <input type="password" value={pw} onChange={(e) => setPw(e.target.value)} placeholder="••••••" autoComplete="current-password" />
          </div>
          {err && <div className="login-err">{err}</div>}
          <Btn variant="primary" size="lg" className="btn-block" type="submit" disabled={busy} icon={busy ? <Icon.clock className="spin" /> : null}>
            {busy ? '로그인 중…' : '로그인'}
          </Btn>
          <Btn variant="ghost" size="lg" className="btn-block" type="button" style={{ marginTop: 10 }} onClick={() => setShowSignUp(true)}>
            회원가입
          </Btn>
        </form>
      </div>
    </div>);

}

/* ---------------- SHELL ---------------- */
function AppShell({ user, route, navigate, onLogout, project, children }) {
  const [mobileOpen, setMobileOpen] = useS1(false);
  const isAdmin = user.role === 'ADMIN';
  const isStaff = user.role === 'ADMIN' || user.role === 'CNX'; // content + audit access
  useE1(() => {setMobileOpen(false);}, [route]);

  // 사이드바 항목과 상단 제목의 단일 출처 — 둘이 따로 놀며 어긋나지 않게 한 테이블에서 파생.
  // 운영/에피소드는 같은 라우트(home·project)를 tab으로 가르므로 탭 항목으로 별도 취급.
  const onProject = route.name === 'home' || route.name === 'project';
  const isEpisodes = onProject && route.tab === 'episodes';
  const tabPages = [
    { ttl: '운영 일정',    icon: <Icon.flow />,   active: onProject && !isEpisodes, nav: { name: 'home', tab: 'ops' } },
    { ttl: '에피소드 선택', icon: <Icon.layers />, active: isEpisodes,               nav: { name: 'project', tab: 'episodes' } },
  ];
  const navPages = [
    { name: 'eplog',   ttl: '에피소드 로그', icon: <Icon.checkCircle />, show: isStaff },
    { name: 'epadmin', ttl: '에피소드 관리', icon: <Icon.layers />,      show: isStaff },
    { name: 'audit',   ttl: '감사 로그',    icon: <Icon.shield />,      show: isStaff },
    { name: 'users',   ttl: '사용자 관리',  icon: <Icon.users />,       show: isAdmin },
  ];
  const page = navPages.find((p) => p.name === route.name) || (isEpisodes ? tabPages[1] : tabPages[0]);

  return (
    <div className="shell">
      {mobileOpen && <div className="scrim" onClick={() => setMobileOpen(false)} />}
      <aside className={`sidebar ${mobileOpen ? 'open' : ''}`}>
        <div className="sb-brand">
          <span style={{ background: 'var(--accent)', color: '#fff', fontWeight: 800, fontSize: 11, letterSpacing: '.06em', padding: '6px 9px', borderRadius: 7 }}>LG AI 365</span>
          <span className="ttl">운영 콘솔<small>LGE × Concentrix</small></span>
        </div>
        <nav className="sb-nav">
          {tabPages.map((p) => (
            <a key={p.ttl} className={`sb-item ${p.active ? 'active' : ''}`} onClick={() => navigate(p.nav)}>{p.icon}{p.ttl}</a>
          ))}
          {isStaff && <div className="sb-section">관리</div>}
          {navPages.filter((p) => p.show).map((p) => (
            <a key={p.name} className={`sb-item ${route.name === p.name ? 'active' : ''}`} onClick={() => navigate({ name: p.name })}>{p.icon}{p.ttl}</a>
          ))}
        </nav>
        <div className="sb-foot">
          <div className="sb-user">
            <Avatar name={user.name} color={roleColor(user.role)} initial={user.initial} />
            <div style={{ minWidth: 0 }}>
              <div className="nm">{user.name}</div>
              <div className="rl">{orgOf(user.role)} · {user.role}</div>
            </div>
            <button className="logout-btn" title="로그아웃" onClick={onLogout}><Icon.logout /></button>
          </div>
        </div>
      </aside>

      <div className="main-col">
        <header className="topbar">
          <button className="icon-btn mobile-bar" onClick={() => setMobileOpen(true)}><Icon.menu /></button>
          <div className="crumb">
            <div className="page-crumb">
              <span className="pc-bar" />
              <span className="pc-ico hide-mobile">{page.icon}</span>
              <span className="pc-ttl">{page.ttl}</span>
            </div>
          </div>
          <div className="topbar-right">
            <RoleBadge role={user.role} />
            <span className="hide-mobile muted" style={{ fontSize: 12.5 }}>{roleDesc(user.role)}</span>
            <Btn variant="ghost" size="sm" icon={<Icon.logout />} onClick={onLogout}>로그아웃</Btn>
          </div>
        </header>

        <div className="scroll-area">{children}</div>
      </div>
    </div>);

}

Object.assign(window, { Login, AppShell });