/* demo/demo-ui.jsx — UI riêng của bản DEMO (chỉ render khi SWO_CONFIG.IS_DEMO).
   Nạp sau ui.jsx/i18n.jsx, trước login.jsx/shell.jsx sử dụng.
   - DemoLoginButtons: các nút "Vào với vai trò …" ở màn login (signInWithPassword tài khoản tạo sẵn).
   - DemoRoleSwitch: badge DEMO trên topbar kiêm dropdown chuyển nhanh vai trò (signOut → signIn, không rời trang). */

const DEMO_ROLE_ICONS = { admin: 'bi-shield-lock', manager: 'bi-person-gear', staff: 'bi-person' };

function DemoLoginButtons() {
  const { t } = useLang();
  const toast = useToast();
  const [busy, setBusy] = useState(false);
  const accounts = (window.SWO_CONFIG && window.SWO_CONFIG.DEMO_ACCOUNTS) || [];

  const doLogin = async (a) => {
    if (busy) return;
    if (!window.SB_READY) { toast(t('demo.notReady'), 'error'); return; }
    setBusy(true);
    const { error } = await sb.auth.signInWithPassword({ email: a.email, password: a.password });
    if (error) { toast(error.message, 'error'); setBusy(false); }
    // thành công: onAuthStateChange (main.jsx) tự chuyển màn — không cần setBusy(false)
  };

  return (
    <div className="col" style={{ gap: 8 }}>
      <p className="muted" style={{ margin: '0 0 2px', fontWeight: 600 }}>{t('login.demoTitle')}</p>
      {accounts.map(a => (
        <button key={a.role} className="sso-btn" disabled={busy} onClick={() => doLogin(a)}>
          <i className={'bi ' + (DEMO_ROLE_ICONS[a.role] || 'bi-person')} style={{ color: 'var(--primary)' }}></i>
          {t('role.' + a.role)}
        </button>
      ))}
      <p className="muted" style={{ margin: '6px 0 0', fontSize: 'var(--fs-md)' }}>{t('login.demoNote')}</p>
    </div>
  );
}

function DemoRoleSwitch() {
  const p = usePortal();
  const { t } = useLang();
  const [busy, setBusy] = useState(false);
  const accounts = (window.SWO_CONFIG && window.SWO_CONFIG.DEMO_ACCOUNTS) || [];

  const switchTo = async (a, close) => {
    if (busy || a.role === p.role) { close(); return; }
    setBusy(true); close();
    await sb.auth.signOut();
    const { error } = await sb.auth.signInWithPassword({ email: a.email, password: a.password });
    if (error) p.toast(error.message, 'error');
    setBusy(false);
    // đổi role/data do onAuthStateChange (main.jsx) tự nạp lại — không reload trang
  };

  return (
    <Popover align="left" width={190} button={({ toggle, open }) => (
      <button className={'demo-badge' + (open ? ' is-open' : '')} onClick={toggle} disabled={busy} title={t('demo.switchRole')}>
        DEMO · {t('role.' + p.role)} <i className="bi bi-chevron-down" style={{ fontSize: 10 }}></i>
      </button>
    )}>
      {({ close }) => (
        <>
          <span className="menu-label">{t('demo.switchRole')}</span>
          {accounts.map(a => (
            <button key={a.role} className="menu-item" onClick={() => switchTo(a, close)}>
              <i className={'bi ' + (DEMO_ROLE_ICONS[a.role] || 'bi-person')}></i>
              <span className="grow" style={{ textAlign: 'left' }}>{t('role.' + a.role)}</span>
              {a.role === p.role && <i className="bi bi-check-lg" style={{ color: 'var(--primary)' }}></i>}
            </button>
          ))}
        </>
      )}
    </Popover>
  );
}

Object.assign(window, { DemoLoginButtons, DemoRoleSwitch });
