const { useState: useStateMAL, useEffect: useEffectMAL } = React;

function MediaAdminLayout({ onNav, currentPage, profile, children }) {
  const [counts, setCounts] = useStateMAL({ influencers: 0, brands: 0, campaigns: 0, messages: 0 });

  useEffectMAL(() => {
    if (!window.sb) return;

    const fetchCounts = async () => {
      try {
        const [
          { count: inf },
          { count: br },
          { count: msg },
          { count: camp }
        ] = await Promise.all([
          window.sb.from('influencer_applications').select('*', { count: 'exact', head: true }).eq('status', 'Nou'),
          window.sb.from('brand_applications').select('*', { count: 'exact', head: true }).eq('status', 'Nou'),
          window.sb.from('contact_messages').select('*', { count: 'exact', head: true }).eq('status', 'Necitit'),
          window.sb.from('campaigns').select('*', { count: 'exact', head: true }).eq('status', 'Activă'),
        ]);
        setCounts({ influencers: inf || 0, brands: br || 0, messages: msg || 0, campaigns: camp || 0 });
      } catch (err) {
        console.error('[4U Media Admin] Sidebar counts error:', err);
      }
    };

    fetchCounts();

    const channel = window.sb.channel('media-admin-sidebar-notifications')
      .on('postgres_changes', { event: '*', schema: 'public', table: 'influencer_applications' }, fetchCounts)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'brand_applications' }, fetchCounts)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'contact_messages' }, fetchCounts)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'campaigns' }, fetchCounts)
      .subscribe();

    return () => {
      window.sb.removeChannel(channel);
    };
  }, []);

  const handleLogout = async () => {
    await window.sb.auth.signOut();
    onNav('media-login');
  };

  const navItems = [
    { id: 'media-admin', label: 'Dashboard', icon: '📊', count: 0 },
    { id: 'media-admin-influencers', label: 'Influenceri', icon: '🎬', count: counts.influencers },
    { id: 'media-admin-campaigns', label: 'Campanii', icon: '📢', count: counts.campaigns },
    { id: 'media-admin-brands', label: 'Branduri', icon: '🏢', count: counts.brands },
    { id: 'media-admin-messages', label: 'Mesaje contact', icon: '✉️', count: counts.messages },
  ];
  if (profile && profile.role === 'admin') {
    navItems.push({ id: 'media-admin-staff', label: 'Staff', icon: '⚙️' });
  }

  return (
    <div style={{ minHeight: '100vh', display: 'flex' }}>
      <aside style={{
        width: 240, position: 'fixed', top: 0, left: 0, height: '100vh',
        borderRight: '.5px solid var(--line)', background: 'rgba(0,0,0,.5)',
        padding: '28px 16px', overflowY: 'auto', zIndex: 5
      }}>
        <div className="pill" style={{ display: 'inline-flex', marginBottom: 32 }}>
          <span className="dot" />
          <span className="mono" style={{ fontSize: 11, letterSpacing: '0.1em' }}>4U MEDIA</span>
        </div>
        <nav>
          {navItems.map(item => {
            const active = currentPage === item.id;
            return (
              <button key={item.id} onClick={() => onNav(item.id)} style={{
                width: '100%', padding: '12px 14px', borderRadius: 10,
                border: 'none', background: active ? 'rgba(82,242,15,.1)' : 'transparent',
                color: active ? 'var(--accent-1)' : 'var(--txt-2)',
                fontSize: 14, fontWeight: 500, textAlign: 'left', cursor: 'pointer',
                marginBottom: 4, display: 'flex', alignItems: 'center', gap: 12,
                transition: 'all .2s'
              }}
              onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'rgba(255,255,255,.04)'; }}
              onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}
              >
                <span style={{ fontSize: 16 }}>{item.icon}</span>
                <span style={{ flex: 1 }}>{item.label}</span>
                {item.count > 0 && (
                  <span style={{
                    background: '#FF5A5A',
                    color: '#fff',
                    borderRadius: 999,
                    padding: '2px 8px',
                    fontSize: 11,
                    fontWeight: 700,
                    minWidth: 22,
                    textAlign: 'center',
                    lineHeight: 1.4,
                    boxShadow: '0 0 8px rgba(255,90,90,.4)'
                  }}>{item.count}</span>
                )}
              </button>
            );
          })}
        </nav>
      </aside>

      <div style={{ marginLeft: 240, flex: 1, minHeight: '100vh', position: 'relative' }}>
        <Mesh />
        <header style={{
          position: 'sticky', top: 0, zIndex: 10, padding: '14px 32px',
          background: 'rgba(0,0,0,.6)', backdropFilter: 'blur(12px)',
          borderBottom: '.5px solid var(--line)',
          display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 16
        }}>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--txt-0)' }}>{profile && profile.full_name}</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em' }}>{(profile && profile.role || '').toUpperCase()}</div>
          </div>
          <button className="btn btn-glass btn-sm" onClick={handleLogout}>Deconectează-te</button>
        </header>
        <main style={{ position: 'relative', zIndex: 2, padding: '40px 32px', maxWidth: 1400 }}>
          {children}
        </main>
      </div>
    </div>
  );
}

window.MediaAdminLayout = MediaAdminLayout;
