const { useState, useEffect, useRef } = React;

function t(key, lang) { return window.__t(key, lang); }

function initialsFrom(str) {
  if (!str) return '?';
  const parts = String(str).trim().split(/[\s._-]+/);
  if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
  return str.slice(0, 2).toUpperCase();
}

const UserChip = ({ session, lang }) => {
  const user = session?.user;
  const name = user?.user_metadata?.full_name || user?.user_metadata?.name || user?.email?.split('@')[0] || 'User';
  const email = user?.email || '';
  const avatar = user?.user_metadata?.avatar_url || user?.user_metadata?.picture;

  const handleSignOut = async (e) => {
    e.stopPropagation();
    await window.__api.signOut();
  };

  return (
    <div className="user-chip" style={{ position: 'relative', cursor: 'pointer' }}>
      {avatar ? (
        <img src={avatar} alt="" className="avatar" style={{ width: 28, height: 28, borderRadius: '50%', objectFit: 'cover' }} />
      ) : (
        <div className="avatar">{initialsFrom(name)}</div>
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="name" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{name}</div>
        <div className="role" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{email}</div>
      </div>
      <button
        onClick={handleSignOut}
        title={t('top.signOut', lang)}
        style={{
          marginLeft: 6, width: 28, height: 28, borderRadius: 6,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--fg-3)'
        }}
        onMouseEnter={e => e.currentTarget.style.color = 'var(--neg)'}
        onMouseLeave={e => e.currentTarget.style.color = 'var(--fg-3)'}
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
          <polyline points="16 17 21 12 16 7" />
          <line x1="21" y1="12" x2="9" y2="12" />
        </svg>
      </button>
    </div>
  );
};

const Sidebar = ({ current, onNav, session, lang, mobileOpen, onCloseMobile, mode = 'advanced' }) => {
  const isEasy = mode === 'easy';
  const items = [
    { key: 'overview', label: t('nav.overview', lang), icon: 'overview' },
    { key: 'chat', label: t('nav.chat', lang), icon: 'chat' },
    { key: 'leads', label: t('nav.leads', lang), icon: 'leads' },
  ];
  // Enterprise tools are only available in Advanced mode. Easy mode keeps it to
  // the three essentials above (Overview, Conversation, Leads).
  const items2 = isEasy ? [] : [
    { key: 'analytics', label: t('nav.analytics', lang), icon: 'analytics' },
    { key: 'swot', label: t('nav.swot', lang), icon: 'target' },
    { key: 'settings', label: t('nav.settings', lang), icon: 'settings' },
  ];
  return (
    <>
      {mobileOpen && <div className="mobile-backdrop active" onClick={onCloseMobile} />}
      <aside className={`sidebar ${mobileOpen ? 'mobile-open' : ''}`}>
        <button className="mobile-close-btn" onClick={onCloseMobile} aria-label="Close menu">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
        </button>
      <div className="brand">
        <div className="brand-mark">{lang === 'ar' ? 'ف' : 'F'}</div>
        <div>
          <div className="brand-name">{t('brand.name', lang)}</div>
          <div className="brand-sub">{t('brand.sub', lang)}</div>
        </div>
      </div>

      <div className="nav-label">{t('nav.workspace', lang)}</div>
      {items.map(it => (
        <button key={it.key} data-onboarding-id={`nav-${it.key}`} className={`nav-item ${current === it.key ? 'active' : ''}`} onClick={() => onNav(it.key)}>
          <Icon name={it.icon} />
          <span>{it.label}</span>
        </button>
      ))}

      {items2.length > 0 && <div className="nav-label">{t('nav.enterprise', lang)}</div>}
      {items2.map(it => (
        <button key={it.key} data-onboarding-id={`nav-${it.key}`} className={`nav-item ${current === it.key ? 'active' : ''}`} onClick={() => onNav(it.key)}>
          <Icon name={it.icon} />
          <span>{it.label}</span>
        </button>
      ))}

      <div className="sidebar-foot">
        <div className="sidebar-meta">
          <div className="row"><span>{t('side.currency', lang)}</span><b>1 = 0.2747</b></div>
          <div className="row"><span>{t('side.listings', lang)}</span><b>40</b></div>
          <div className="row"><span>{t('side.market', lang)}</span><b>{lang === 'ar' ? 'الدوحة' : 'Doha'}</b></div>
        </div>
        <UserChip session={session} lang={lang} />
      </div>
      </aside>
    </>
  );
};

const SunIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"/>
  </svg>
);
const MoonIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
  </svg>
);
const GlobeIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
  </svg>
);

const ModeSwitch = ({ mode, setMode, lang }) => (
  <div className="mode-switch" data-onboarding-id="mode-switch" role="group" aria-label={t('mode.label', lang)}>
    <span className="mode-switch-label">{t('mode.label', lang)}</span>
    <button
      className={mode === 'easy' ? 'active' : ''}
      onClick={() => setMode('easy')}
      aria-pressed={mode === 'easy'}
    >{t('mode.easy', lang)}</button>
    <button
      className={mode === 'advanced' ? 'active' : ''}
      onClick={() => setMode('advanced')}
      aria-pressed={mode === 'advanced'}
    >{t('mode.advanced', lang)}</button>
  </div>
);

const TopBar = ({ title, crumb, lang, setLang, theme, setTheme, onToggleMobile, mode, setMode }) => {
  const toggleTheme = () => setTheme(theme === 'dark' ? 'light' : 'dark');
  const toggleLang = () => {
    const next = lang === 'ar' ? 'en' : 'ar';
    window.__lang = next;
    if (window.__dataFor) window.__data = window.__dataFor(next);
    if (window.__mockChatsFor) window.__mockChats = window.__mockChatsFor(next);
    document.documentElement.setAttribute('lang', next);
    document.documentElement.setAttribute('dir', next === 'ar' ? 'rtl' : 'ltr');
    setLang(next);
  };

  return (
    <header className="topbar">
      <button className="mobile-menu-btn" onClick={onToggleMobile} aria-label="Open menu">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12h18M3 6h18M3 18h18"/></svg>
      </button>
      <div className="topbar-left">
        <div className="path">{crumb}</div>
        <h1>{title}</h1>
      </div>
      <div className="topbar-right">
        {setMode && <ModeSwitch mode={mode} setMode={setMode} lang={lang} />}

        <button className="icon-btn" aria-label="Notifications">
          <Icon name="bell" />
          <span className="dot" />
        </button>

        {/* Theme toggle */}
        <button
          data-onboarding-id="top-theme"
          className="icon-btn"
          onClick={toggleTheme}
          title={theme === 'dark' ? t('top.theme.light', lang) : t('top.theme.dark', lang)}
          aria-label={theme === 'dark' ? t('top.theme.light', lang) : t('top.theme.dark', lang)}
        >
          {theme === 'dark' ? <SunIcon /> : <MoonIcon />}
        </button>

        {/* Language toggle */}
        <button
          data-onboarding-id="top-lang"
          className="btn"
          onClick={toggleLang}
          style={{ minWidth: 58, justifyContent: 'center' }}
          title={lang === 'ar' ? t('top.lang.en', lang) : t('top.lang.ar', lang)}
        >
          <GlobeIcon />
          <span style={{ fontSize: 12, fontWeight: 600 }}>{lang === 'ar' ? 'EN' : 'AR'}</span>
        </button>

      </div>
    </header>
  );
};

window.Sidebar = Sidebar;
window.TopBar = TopBar;
