// Header.jsx
'use strict';
const { useState, useRef, useEffect } = React;

const PAGE_TITLES = {
  dashboard:'Dashboard', os:'Ordens de Serviço', clientes:'Clientes',
  agenda:'Agenda', servicos:'Serviços', financeiro:'Financeiro',
  relatorios:'Relatórios', configuracoes:'Configurações',
};

function Header({ page, user, onMenuToggle, notifications, onMarkRead, globalSearch, setGlobalSearch, onSearchNav }) {
  const initials = (user?.name || 'AD').split(' ').map(w => w[0]).slice(0,2).join('').toUpperCase();
  const [showNotifs, setShowNotifs] = useState(false);
  const [showSearch, setShowSearch] = useState(false);
  const unread = (notifications || []).filter(n => !n.read).length;
  const notifRef = useRef(null);

  useEffect(() => {
    const h = e => { if (notifRef.current && !notifRef.current.contains(e.target)) setShowNotifs(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);

  const typeIcon = { warning:'AlertCircle', info:'Bell', success:'CheckCircle', error:'XCircle' };
  const typeColor = { warning:'#F59E0B', info:'#3B82F6', success:'#10B981', error:'#EF4444' };

  return (
    <header className="flex-shrink-0 bg-white border-b border-slate-100 no-print"
      style={{ zIndex: 200, paddingTop: 'max(env(safe-area-inset-top), 0px)' }}>
    <div className="px-4 md:px-6 h-16 flex items-center gap-3 md:gap-4"
      style={{ paddingLeft: 'max(1rem, env(safe-area-inset-left))', paddingRight: 'max(1rem, env(safe-area-inset-right))' }}>
      {/* Mobile hamburger */}
      <button onClick={onMenuToggle} aria-label="Abrir menu"
        className="md:hidden w-10 h-10 -ml-1 rounded-xl flex items-center justify-center hover:bg-slate-100 active:scale-95 transition-all">
        <Icon name="Menu" size={22} color="#0A1F44" />
      </button>

      {/* Marca (mobile) / Título da página (desktop) */}
      <div className="flex-1 min-w-0 flex items-center">
        <div className="flex items-center gap-2 md:hidden">
          <BrandMark size={28} style={{ filter:'drop-shadow(0 3px 8px rgba(255,107,53,0.35))' }} />
          <span className="font-extrabold text-[15px] tracking-tight truncate" style={{ color:'#0A1F44' }}>
            Demo<span style={{ color:'#CBD5E1', fontWeight:400, margin:'0 3px' }}>·</span><span style={{ color:'#FF6B35' }}>Serviços</span>
          </span>
        </div>
        <h1 className="text-lg font-bold hidden md:block" style={{ color: '#0A1F44' }}>{PAGE_TITLES[page] || page}</h1>
      </div>

      {/* Search */}
      <div className="hidden md:flex items-center relative">
        <Icon name="Search" size={15} color="#94A3B8" style={{ position:'absolute', left:12, zIndex:1 }} />
        <input
          value={globalSearch} onChange={e => setGlobalSearch(e.target.value)}
          placeholder="Buscar OS, cliente..."
          className="pl-9 pr-4 py-2 w-56 rounded-xl border border-slate-200 bg-slate-50 text-sm transition-all focus:bg-white focus:border-blue-300 focus:w-72 focus:ring-2 focus:ring-blue-100"
          style={{ color:'#1E293B' }}
          onKeyDown={e => e.key==='Enter' && onSearchNav && onSearchNav()}
        />
      </div>

      {/* Notifications */}
      <div className="relative" ref={notifRef}>
        <button onClick={() => setShowNotifs(v => !v)}
          className="w-9 h-9 rounded-xl flex items-center justify-center hover:bg-slate-100 transition-colors relative">
          <Icon name="Bell" size={19} color="#64748b" />
          {unread > 0 && (
            <span className="absolute -top-0.5 -right-0.5 w-4 h-4 rounded-full text-white text-xs flex items-center justify-center font-bold"
              style={{ background:'#FF6B35', fontSize:10 }}>{unread}</span>
          )}
        </button>

        {showNotifs && (
          <div className="absolute right-0 top-12 w-80 bg-white rounded-2xl shadow-card-lg border border-slate-100 anim-fade overflow-hidden" style={{ zIndex: 400 }}>
            <div className="flex items-center justify-between px-4 py-3 border-b border-slate-100">
              <span className="font-semibold text-sm" style={{ color:'#0A1F44' }}>Notificações</span>
              {unread > 0 && (
                <button onClick={onMarkRead} className="text-xs font-medium hover:underline" style={{ color:'#FF6B35' }}>Marcar todas como lidas</button>
              )}
            </div>
            <div className="divide-y divide-slate-50 max-h-72 overflow-y-auto">
              {(notifications || []).map(n => (
                <div key={n.id} className={`flex items-start gap-3 px-4 py-3 transition-colors ${n.read ? '' : 'bg-blue-50 bg-opacity-50'}`}>
                  <div className="w-7 h-7 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5"
                    style={{ background: (typeColor[n.type]||'#94A3B8')+'20' }}>
                    <Icon name={typeIcon[n.type]||'Bell'} size={13} color={typeColor[n.type]||'#94A3B8'} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-xs text-slate-700 leading-snug">{n.msg}</p>
                    <p className="text-xs text-slate-400 mt-0.5">{n.time}</p>
                  </div>
                  {!n.read && <span className="w-2 h-2 rounded-full flex-shrink-0 mt-1.5" style={{ background:'#3B82F6' }} />}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* User avatar */}
      <div className="w-9 h-9 rounded-full flex items-center justify-center text-xs font-bold cursor-pointer hover:opacity-90 transition-opacity flex-shrink-0"
        style={{ background:'#0A1F44', color:'white' }}>{initials}</div>
    </div>
    </header>
  );
}

Object.assign(window, { Header });
