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

// Iconițele de meniu — SVG inline (set Lucide), nu emoji.
// Primesc `active` ca să poată colora stroke-ul din CSS prin currentColor.
function MaIcon({ name }) {
  const common = {
    width: 18, height: 18, viewBox: '0 0 24 24', fill: 'none',
    stroke: 'currentColor', strokeWidth: 1.75,
    strokeLinecap: 'round', strokeLinejoin: 'round',
    'aria-hidden': true, focusable: false,
  };
  const paths = {
    dashboard: <><rect x="3" y="3" width="7" height="9" rx="1" /><rect x="14" y="3" width="7" height="5" rx="1" /><rect x="14" y="12" width="7" height="9" rx="1" /><rect x="3" y="16" width="7" height="5" rx="1" /></>,
    influencers: <><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" /><circle cx="9" cy="7" r="4" /><path d="M22 21v-2a4 4 0 0 0-3-3.87" /><path d="M16 3.13a4 4 0 0 1 0 7.75" /></>,
    campaigns: <><path d="m3 11 18-5v12L3 14v-3z" /><path d="M11.6 16.8a3 3 0 1 1-5.8-1.6" /></>,
    brands: <><rect x="3" y="7" width="18" height="14" rx="2" /><path d="M8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" /><path d="M3 13h18" /></>,
    blacklist: <><circle cx="12" cy="12" r="9" /><path d="m5.6 5.6 12.8 12.8" /></>,
    messages: <><rect x="2" y="4" width="20" height="16" rx="2" /><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7" /></>,
    staff: <><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" /><circle cx="12" cy="12" r="3" /></>,
    menu: <><path d="M4 6h16" /><path d="M4 12h16" /><path d="M4 18h16" /></>,
    close: <><path d="M18 6 6 18" /><path d="m6 6 12 12" /></>,
  };
  return <svg {...common}>{paths[name] || null}</svg>;
}

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

  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);
    };
  }, []);

  // Cu meniul deschis pe telefon, blocăm scroll-ul din spate — altfel se scrolează
  // pagina sub drawer și te pierzi.
  useEffectMAL(() => {
    if (!menuOpen) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') setMenuOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener('keydown', onKey);
    };
  }, [menuOpen]);

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

  const go = (id) => {
    setMenuOpen(false);
    onNav(id);
  };

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

  // Total de procesat — pe telefon, butonul de meniu îl arată ca punct roșu,
  // ca să nu trebuiască să deschizi drawer-ul ca să afli că ai ceva nou.
  const pendingTotal = counts.influencers + counts.brands + counts.messages;

  return (
    <div className={'media-admin-shell' + (menuOpen ? ' ma-menu-open' : '')}>
      {/* Fundal care închide meniul — doar pe mobil, doar când e deschis */}
      <div className="ma-backdrop" onClick={() => setMenuOpen(false)} aria-hidden="true" />

      <aside className="ma-sidebar" aria-label="Navigare principală">
        <div className="ma-sidebar-top">
          <div className="pill" style={{ display: 'inline-flex' }}>
            <span className="dot" />
            <span className="mono" style={{ fontSize: 11, letterSpacing: '0.1em' }}>4U MEDIA</span>
          </div>
          <button
            type="button"
            className="ma-drawer-close"
            onClick={() => setMenuOpen(false)}
            aria-label="Închide meniul"
          >
            <MaIcon name="close" />
          </button>
        </div>

        <nav>
          {navItems.map(item => {
            const active = currentPage === item.id;
            return (
              <button
                key={item.id}
                onClick={() => go(item.id)}
                className={'ma-nav-item' + (active ? ' is-active' : '')}
                aria-current={active ? 'page' : undefined}
              >
                <MaIcon name={item.icon} />
                <span style={{ flex: 1 }}>{item.label}</span>
                {item.count > 0 && <span className="ma-badge">{item.count}</span>}
              </button>
            );
          })}
        </nav>
      </aside>

      <div className="ma-content">
        <Mesh />
        <header className="ma-header">
          <button
            type="button"
            className="ma-burger"
            onClick={() => setMenuOpen(true)}
            aria-label="Deschide meniul"
            aria-expanded={menuOpen}
          >
            <MaIcon name="menu" />
            {pendingTotal > 0 && <span className="ma-burger-dot" aria-hidden="true" />}
          </button>

          <div className="pill ma-header-brand">
            <span className="dot" />
            <span className="mono" style={{ fontSize: 11, letterSpacing: '0.1em' }}>4U MEDIA</span>
          </div>

          <div className="ma-header-right">
            <div className="ma-user">
              <div className="ma-user-name">{profile && profile.full_name}</div>
              <div className="mono ma-user-role">{(profile && profile.role || '').toUpperCase()}</div>
            </div>
            <button className="btn btn-glass btn-sm ma-logout" onClick={handleLogout}>
              <span className="ma-logout-long">Deconectează-te</span>
              <span className="ma-logout-short">Ieși</span>
            </button>
          </div>
        </header>

        <main className="ma-main">
          {children}
        </main>
      </div>
    </div>
  );
}

window.MediaAdminLayout = MediaAdminLayout;
