/* YeYe Expat Centre — App shell: Sidebar + Topbar */

function navWithDocGenerator(nav, hasDiyServices) {
  if (!hasDiyServices || (nav || []).some((item) => item.key === 'docgen')) return nav || [];
  const next = [];
  (nav || []).forEach((item) => {
    next.push(item);
    if (item.key === 'documents') next.push({ key: 'docgen', icon: 'file-pen-line' });
  });
  return next;
}

function Sidebar({ nav, active, onNav, mini, open, onClose, ct, hasDiyServices = false }) {
  const { t } = useT();
  const visibleNav = navWithDocGenerator(nav, hasDiyServices);
  return (
    <aside className={'sidebar ' + (mini ? 'mini ' : '') + (open ? 'open' : '')}>
      <div className="sb-brand">
        <div className="brand-stack">
          <BrandLogo mini={mini} />
          {!mini && <BrandSlogan />}
        </div>
      </div>
      <nav className="sb-nav">
        {visibleNav.map((it) => (
          <a key={it.key} className={'nav-item ' + (active === it.key ? 'active' : '')}
             onClick={() => { onNav(it.key); onClose && onClose(); }}>
            <Icon name={it.icon} size={19} className="nav-ic" />
            <span className="nav-label">{t('nav.' + it.key)}</span>
            {it.badge && <span className={'nav-badge ' + (it.amber ? 'amber' : '')}>{it.badge}</span>}
          </a>
        ))}
      </nav>
      <div className="sb-foot">
        <a className={'nav-item ' + (active === 'settings' ? 'active' : '')} onClick={() => { onNav('settings'); onClose && onClose(); }}>
          <Icon name="settings" size={19} className="nav-ic" /><span className="nav-label">{t('nav.settings')}</span>
        </a>
        <a className="nav-item" onClick={() => onNav('logout')}>
          <Icon name="log-out" size={19} className="nav-ic" /><span className="nav-label">{t('nav.logout')}</span>
        </a>
        <div className="divider" />
        <div className="sb-user">
          {(() => {
            const s = (window.YEYE_AUTH && window.YEYE_AUTH.getState && window.YEYE_AUTH.getState()) || {};
            const u = s.user; const c = s.contact;
            const ghlName = c ? [c.firstName, c.lastName].filter(Boolean).join(' ').trim() : '';
            const displayName = ghlName || (u && u.name) || ct.who;
            const meta = (u && u.email) || t('ct.' + ct.key);
            const cap = (w) => w ? w.charAt(0).toUpperCase() + w.slice(1) : '';
            const niceName = displayName.split(' ').map(cap).join(' ');
            const initials = niceName.split(' ').map((w) => w[0]).join('').slice(0, 2);
            const customAv = window.YEYE_AUTH && window.YEYE_AUTH.getAvatar && window.YEYE_AUTH.getAvatar();
            const avatarEl = customAv && customAv.type === 'emoji'
              ? <div className="avatar a-sm" style={{ background: 'var(--brand-50)', color: 'var(--ink-900)', fontSize: 17 }}>{customAv.value}</div>
              : customAv && customAv.type === 'image'
                ? <img src={customAv.value} alt="" className="avatar a-sm" style={{ width: 30, height: 30, borderRadius: '50%', objectFit: 'cover' }} />
                : u && u.picture
                  ? <img src={u.picture} alt="" className="avatar a-sm" style={{ width: 30, height: 30, borderRadius: '50%', objectFit: 'cover' }} />
                  : <Avatar size="sm">{initials}</Avatar>;
            return (
              <>
                {avatarEl}
                <div className="sb-user-meta grow" style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--ink-900)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{niceName}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-400)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{meta}</div>
                </div>
              </>
            );
          })()}
        </div>
      </div>
    </aside>
  );
}

function MobileDocGeneratorBar({ active, onNav, hasDiyServices = false }) {
  const { t } = useT();
  if (!hasDiyServices) return null;
  return (
    <nav className="mobile-only" aria-label={t('nav.docgen')} style={{ position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 32, justifyContent: 'center', padding: '8px 12px calc(8px + env(safe-area-inset-bottom))', background: 'var(--surface)', borderTop: '1px solid var(--line)', boxShadow: '0 -5px 18px rgba(19,45,34,.08)' }}>
      <button type="button" onClick={() => onNav('docgen')} style={{ border: 'none', borderRadius: 10, background: active === 'docgen' ? 'var(--brand-50)' : 'transparent', color: active === 'docgen' ? 'var(--brand-700)' : 'var(--ink-600)', padding: '7px 16px', display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, fontWeight: 650, cursor: 'pointer' }}>
        <Icon name="file-pen-line" size={18} />
        <span>{t('nav.docgen')}</span>
      </button>
    </nav>
  );
}

/* Client-type switcher (demo) — dropdown of the 6 GHL expat types */
const CT_KEYS = ['employee_card', 'blue_card', 'family_reunion', 'business_visa', 'osvc', 'relocation'];
const CT_ICONS = { employee_card: 'id-card', blue_card: 'square-asterisk', family_reunion: 'users-round', business_visa: 'briefcase', osvc: 'user-round', relocation: 'plane' };
function ClientTypeMenu({ ctKey, onCt }) {
  const { t } = useT();
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h); return () => document.removeEventListener('mousedown', h);
  }, []);
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button className="icon-btn" onClick={() => setOpen((o) => !o)} title={t('c.clientType')}
        style={{ width: 'auto', padding: '0 11px', gap: 7, border: '1px solid var(--line)', maxWidth: 220 }}>
        <Icon name={CT_ICONS[ctKey]} size={17} />
        <span style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t('ct.' + ctKey)}</span>
        <Icon name="chevron-down" size={14} />
      </button>
      {open && (
        <div style={{ position: 'absolute', top: 44, right: 0, background: '#fff', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', boxShadow: 'var(--sh-lg)', padding: 6, width: 268, zIndex: 60 }}>
          <div className="eyebrow" style={{ padding: '6px 10px 4px' }}>{t('c.clientType')}</div>
          {CT_KEYS.map((k) => (
            <button key={k} onClick={() => { onCt(k); setOpen(false); }}
              className="flex ac jb" style={{ width: '100%', border: 'none', background: ctKey === k ? 'var(--brand-50)' : 'transparent', borderRadius: 8, padding: '9px 11px', cursor: 'pointer', textAlign: 'left' }}>
              <span className="flex ac gap-10" style={{ minWidth: 0 }}>
                <Icon name={CT_ICONS[k]} size={16} className={ctKey === k ? '' : 'dim'} />
                <span style={{ fontSize: 13, fontWeight: ctKey === k ? 700 : 500, color: ctKey === k ? 'var(--brand-700)' : 'var(--ink-700)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t('ct.' + k)}</span>
              </span>
              {ctKey === k && <Icon name="check" size={15} stroke={2.6} />}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function Topbar({ title, sub, ct, branding, onBranding, ctKey, onCt, lang, onLang, currency, onCurrency,
  onToggleSidebar, onHamburger, onNotif, onSearch, onNav, notifDot = false, cartCount = 0, onCart }) {
  const { t } = useT();
  const [userMenuOpen, setUserMenuOpen] = useState(false);
  const userMenuRef = useRef(null);
  useEffect(() => {
    const h = (e) => { if (userMenuRef.current && !userMenuRef.current.contains(e.target)) setUserMenuOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  const restartWelcomeTour = () => {
    if (window.YEYE_WELCOME && window.YEYE_WELCOME.clear) window.YEYE_WELCOME.clear();
    window.location.reload();
  };
  const corp = branding === 'corporate' && ct.org;
  return (
    <header className="topbar">
      <button className="icon-btn hamburger" onClick={onHamburger}><Icon name="menu" size={20} /></button>
      <button className="icon-btn desktop-only" onClick={onToggleSidebar} title={t('c.toggleSidebar')}><Icon name="panel-left" size={19} /></button>
      <div className="mobile-branding">
        <img className="mobile-brand-logo" src="assets/yeye-logo.png" alt="YeYe Expats Centre" />
        <span className="mobile-motto">{t('brand.slogan')}</span>
      </div>

      {corp ? (
        <div className="cobrand" style={{ flexShrink: 0 }}>
          <div className="clogo">
            <div className="brand-mark sm" style={{ background: 'linear-gradient(150deg,#3a4a63,#1f2b3d)' }}><b>{ct.org[0]}</b></div>
            <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.1, whiteSpace: 'nowrap' }}>
              <span style={{ fontWeight: 700, fontSize: 13.5, color: 'var(--ink-900)' }}>{ct.org}</span>
              <span style={{ fontSize: 10.5, color: 'var(--ink-400)' }}>{ct.region}</span>
            </div>
          </div>
          <div className="poweredby" style={{ whiteSpace: 'nowrap' }}>
            <span>{t('c.poweredBy')}</span>
            <img src="assets/yeye-mark.png" alt="YeYe" style={{ height: 17, width: 'auto' }} />
          </div>
        </div>
      ) : (
        <div className="tb-title">
          <span className="t1" style={{ whiteSpace: 'nowrap' }}>{title}</span>
          {sub && <span className="t2" style={{ whiteSpace: 'nowrap' }}>{sub}</span>}
        </div>
      )}

      <div className="tb-spacer" />

      <div className="desktop-only"><LangMenu lang={lang} onChange={onLang} /></div>
      <div className="desktop-only"><CurrencyMenu currency={currency} onChange={onCurrency} /></div>
      <div className="mobile-header-controls">
        <LangMenu lang={lang} onChange={onLang} />
        <CurrencyMenu currency={currency} onChange={onCurrency} />
      </div>

      <IconBtn name="bell" onClick={onNotif} dot={notifDot} />
      <CartIcon count={cartCount} onClick={onCart} />
      <div ref={userMenuRef} style={{ position: 'relative' }}>
      {(() => {
        const s = (window.YEYE_AUTH && window.YEYE_AUTH.getState && window.YEYE_AUTH.getState()) || {};
        const u = s.user; const c = s.contact;
        const cap = (w) => w ? w.charAt(0).toUpperCase() + w.slice(1) : '';
        const ghlName = c ? [c.firstName, c.lastName].filter(Boolean).map(cap).join(' ').trim() : '';
        const display = ghlName || (u && u.name) || ct.who;
        const title = display + ' · ' + ((u && u.email) || '');
        const onClick = () => setUserMenuOpen((open) => !open);
        const customAv = window.YEYE_AUTH && window.YEYE_AUTH.getAvatar && window.YEYE_AUTH.getAvatar();
        if (customAv && customAv.type === 'emoji') {
          return <div className="avatar a-md" style={{ background: 'var(--brand-100)', color: 'var(--ink-900)', fontSize: 22, cursor: 'pointer' }} onClick={onClick} title={title}>{customAv.value}</div>;
        }
        if (customAv && customAv.type === 'image') {
          return <img src={customAv.value} alt="" className="avatar a-md" style={{ width: 38, height: 38, borderRadius: '50%', objectFit: 'cover', cursor: 'pointer' }} onClick={onClick} title={title} />;
        }
        if (u && u.picture) {
          return <img src={u.picture} alt="" className="avatar a-md" style={{ width: 38, height: 38, borderRadius: '50%', objectFit: 'cover', cursor: 'pointer' }} onClick={onClick} title={title} />;
        }
        const initials = display.split(' ').map((w) => w[0]).join('').slice(0, 2);
        return <div onClick={onClick} title={title} style={{ cursor: 'pointer' }}><Avatar size="md" tone={{ bg: 'var(--brand-500)', fg: '#fff' }}>{initials}</Avatar></div>;
      })()}
      {userMenuOpen && (
        <div className="user-menu">
          <button type="button" onClick={restartWelcomeTour}><Icon name="rotate-ccw" size={15} />{t('welcome.restartTour')}</button>
          <button type="button" onClick={() => window.YEYE_AUTH.signOut()}><Icon name="log-out" size={15} />{t('nav.logout')}</button>
        </div>
      )}
      </div>
    </header>
  );
}

/* mobile bottom-bar client-type switch for small screens */
function MobileClientType({ ctKey, onCt }) {
  return (
    <div className="mobile-only" style={{ position: 'sticky', bottom: 0, zIndex: 20, background: 'var(--surface)', borderTop: '1px solid var(--line)', padding: '8px 12px', justifyContent: 'center' }}>
      <ClientTypeMenu ctKey={ctKey} onCt={onCt} />
    </div>
  );
}

Object.assign(window, { Sidebar, Topbar, MobileClientType, MobileDocGeneratorBar });
