/* user-menu.jsx — Topbar avatar trigger + popover menu + sign-out modal */
/* global React, Icon, useT, useRouter, Modal */
const { useState: useUMState, useEffect: useUMEffect, useRef: useUMRef } = React;

// Mock user records keyed by portal — in real app comes from /auth/me
const USERS = {
  brand: {
    name: 'An Trần',
    email: 'an.tran@coolmate.me',
    initials: 'AT',
    gradient: 'linear-gradient(135deg, #009CFF, #1C1CC9)',
    role: 'owner',
    workspace: 'Coolmate VN',
    portal: 'brand',
    verified: true,
    plan: 'pro',
  },
  creator: {
    name: 'Linh Châu',
    email: 'linh@linhchau.co',
    initials: 'LC',
    gradient: 'linear-gradient(135deg, #FF6FA3, #1C1CC9)',
    role: 'creator',
    workspace: '@linhchau',
    portal: 'creator',
    verified: true,
    plan: 'trial',
  },
};

function getCurrentUser(route) {
  if (route && route.startsWith('creator')) return USERS.creator;
  return USERS.brand;
}

// ─── Trigger pill (lives in the topbar) ──────────────────────────────
function UserMenuTrigger() {
  const { route, go } = useRouter();
  const { t } = useT();
  const user = getCurrentUser(route);

  const [open, setOpen] = useUMState(false);
  const [signoutOpen, setSignoutOpen] = useUMState(false);
  const [pos, setPos] = useUMState({ top: 0, right: 0 });
  const btnRef = useUMRef(null);

  const positionPopover = () => {
    if (!btnRef.current) return;
    const r = btnRef.current.getBoundingClientRect();
    setPos({ top: r.bottom + 8, right: Math.max(16, window.innerWidth - r.right) });
  };

  useUMEffect(() => {
    if (!open) return;
    positionPopover();
    const onResize = () => positionPopover();
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('resize', onResize);
    window.addEventListener('keydown', onKey);
    return () => {
      window.removeEventListener('resize', onResize);
      window.removeEventListener('keydown', onKey);
    };
  }, [open]);

  const onSignOut = () => {
    setOpen(false);
    setSignoutOpen(true);
  };
  const confirmSignOut = () => {
    setSignoutOpen(false);
    // Return to landing → auth; preserve UX intent
    go('auth');
  };
  const onSwitchPortal = () => {
    setOpen(false);
    const next = user.portal === 'brand' ? 'creator-dashboard' : 'brand-dashboard';
    go(next);
  };

  return (
    <>
      <button
        ref={btnRef}
        className={'um-trigger' + (open ? ' open' : '')}
        onClick={() => setOpen(o => !o)}
        aria-expanded={open}
        aria-haspopup="menu"
      >
        <div className="av" style={{ background: user.gradient }}>{user.initials}</div>
        <div className="who">
          <div className="nm">{user.name}</div>
          <div className="role">
            <span className="b">{user.portal === 'brand' ? 'BRAND' : 'CREATOR'}</span>
            <span>· {t('user.role.' + user.role)}</span>
          </div>
        </div>
        <span className="chev">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d={open ? 'm18 15-6-6-6 6' : 'm6 9 6 6 6-6'} />
          </svg>
        </span>
      </button>

      {open && (
        <>
          <div className="um-backdrop" onClick={() => setOpen(false)} />
          <UserMenuPopover
            user={user}
            top={pos.top}
            right={pos.right}
            onClose={() => setOpen(false)}
            onSignOut={onSignOut}
            onSwitchPortal={onSwitchPortal}
            onNavigate={(id) => { setOpen(false); go(id); }}
          />
        </>
      )}

      <UserSignoutModal
        open={signoutOpen}
        user={user}
        onCancel={() => setSignoutOpen(false)}
        onConfirm={confirmSignOut}
      />
    </>
  );
}

// ─── Popover ─────────────────────────────────────────────────────────
function UserMenuPopover({ user, top, right, onClose, onSignOut, onSwitchPortal, onNavigate }) {
  const { t } = useT();
  const isBrand = user.portal === 'brand';
  const otherPortalName = isBrand ? t('user.workspace.creator') : t('user.workspace.brand');
  const settingsRoute = isBrand ? 'brand-settings' : 'creator-settings';

  return (
    <div className="um-pop" role="menu" style={{ top, right }}>
      {/* Header card */}
      <div className="um-head">
        <div className="top">
          <div className="av" style={{ background: user.gradient }}>{user.initials}</div>
          <div className="meta">
            <div className="nm">
              {user.name}
              {user.verified && (
                <span className="verified" aria-label="Verified">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="m12 2 2.4 2.4L18 5l.5 3.5L21 11l-2.5 2.5L18 17l-3.6.6L12 20l-2.4-2.4L6 17l-.5-3.5L3 11l2.5-2.5L6 5l3.6-.6z" /><path d="m9 12 2 2 4-4" stroke="white" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
                </span>
              )}
            </div>
            <div className="email" title={user.email}>{user.email}</div>
          </div>
        </div>

        <div className={'ws-chip ' + (isBrand ? 'brand' : 'creator')}>
          <span className="dot"></span>
          <span><b style={{ fontWeight: 700 }}>{user.workspace}</b> · {isBrand ? t('user.workspace.brand') : t('user.workspace.creator')}</span>
          <span className="role-tag">{t('user.role.' + user.role).toUpperCase()}</span>
        </div>

        <div className="um-plan">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 2 14.4 8.6 21 9.3l-5 4.6L17.4 21 12 17.5 6.6 21 8 13.9l-5-4.6 6.6-.7L12 2Z" />
          </svg>
          {user.plan === 'pro'
            ? <span><b>{t('user.plan.pro')}</b> · all features unlocked</span>
            : <span>{t('user.plan.trial')}</span>}
          <span className="upgrade">{user.plan === 'pro' ? 'Manage' : 'Upgrade →'}</span>
        </div>
      </div>

      {/* Switch workspace */}
      <div className="um-list">
        <div className="switch" onClick={onSwitchPortal}>
          <span className="ic">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 3h5v5M4 20 21 3M21 16v5h-5M15 15l6 6M4 4l5 5"/></svg>
          </span>
          <div className="copy">
            <b>{t('user.menu.switchTo', { portal: otherPortalName })}</b>
            <span>{isBrand ? 'Browse open campaigns &amp; apply' : 'Run campaigns &amp; manage briefs'}</span>
          </div>
          <span className="arr">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
          </span>
        </div>

        <div className="group-label">{t('nav.group.account')}</div>
        <div className="item" onClick={() => onNavigate(isBrand ? 'brand-settings' : 'creator-profile')}>
          <span className="ic">{Icon.users}</span>
          {t('user.menu.profile')}
        </div>
        <div className="item" onClick={() => onNavigate(settingsRoute)}>
          <span className="ic">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="5" width="20" height="14" rx="3"/><path d="M2 10h20M6 15h4"/></svg>
          </span>
          {t('user.menu.account')}
        </div>
        {isBrand && (
          <div className="item" onClick={() => onNavigate('brand-settings')}>
            <span className="ic">{Icon.settings}</span>
            {t('user.menu.settings')}
          </div>
        )}
        {isBrand && (
          <div className="item" onClick={() => onNavigate('brand-settings')}>
            <span className="ic">{Icon.users}</span>
            {t('user.menu.team')}
            <span className="pill new">PRO</span>
          </div>
        )}

        <div className="sep"></div>
        <div className="item" onClick={() => window.open('#', '_blank')}>
          <span className="ic">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M9.1 9a3 3 0 0 1 5.8 1c0 2-3 3-3 3"/><circle cx="12" cy="17" r=".5" fill="currentColor"/></svg>
          </span>
          {t('user.menu.help')}
          <span className="kbd">?</span>
        </div>
        <div className="item" onClick={() => window.open('#', '_blank')}>
          <span className="ic">{Icon.spark}</span>
          {t('user.menu.changelog')}
          <span className="pill new">NEW</span>
        </div>

        <div className="sep"></div>
        <div className="item danger" onClick={onSignOut} role="menuitem">
          <span className="ic">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
              <path d="m16 17 5-5-5-5"/>
              <path d="M21 12H9"/>
            </svg>
          </span>
          {t('user.menu.signout')}
          <span className="kbd">⇧⌘Q</span>
        </div>
      </div>

      <div className="um-foot">
        <span>Prime · v2.4.1</span>
        <a href="#">Privacy · Terms</a>
      </div>
    </div>
  );
}

// ─── Sign-out confirm modal ──────────────────────────────────────────
function UserSignoutModal({ open, user, onCancel, onConfirm }) {
  const { t } = useT();
  if (!Modal) return null;
  return (
    <Modal
      open={open}
      onClose={onCancel}
      title={t('user.signout.title')}
      subtitle={t('user.signout.body')}
      width={460}
      footer={
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
          <button className="btn btn-ghost btn-sm" onClick={onCancel}>{t('user.signout.cancel')}</button>
          <button className="btn btn-primary btn-sm" style={{ background: '#B12B2B', boxShadow: '0 12px 30px rgba(177,43,43,0.25)' }} onClick={onConfirm}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: 4 }}>
              <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
              <path d="m16 17 5-5-5-5"/>
              <path d="M21 12H9"/>
            </svg>
            {t('user.signout.confirm')}
          </button>
        </div>
      }
    >
      <div className="um-signout-modal">
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '6px 0 0' }}>
          <div style={{ width: 44, height: 44, borderRadius: 999, background: user?.gradient || 'linear-gradient(135deg,#009CFF,#1C1CC9)', color: 'white', fontFamily: 'Space Grotesk', fontWeight: 800, fontSize: 17, display: 'grid', placeItems: 'center', letterSpacing: '-0.02em' }}>
            {user?.initials || 'A'}
          </div>
          <div>
            <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 14, letterSpacing: '-0.015em' }}>{user?.name}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-soft)' }}>{user?.email}</div>
          </div>
        </div>

        <div className="so-warn">
          <div className="ic">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M12 9v4M12 17h.01"/><path d="M10.3 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
            </svg>
          </div>
          <div className="copy">
            Signing out will end your session on this device. <b>Drafts auto-save every 2s</b>, so you won't lose work.
            If you only want to switch workspace, use <b>Switch workspace</b> instead.
          </div>
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { UserMenuTrigger, USERS, getCurrentUser });
