
// ============================================================
// JuFlow — Sidebar + Header Layout (responsive + safe-area)
// ============================================================
const { useState: useSt, useEffect: useEf } = React;
const U2 = window.JFUtils;

const NAV_ITEMS = [
  { id: 'dashboard',      label: 'Dashboard',      icon: 'LayoutDashboard' },
  { id: 'agenda',         label: 'Agenda',         icon: 'Calendar' },
  { id: 'clientes',       label: 'Clientes',       icon: 'Users' },
  { id: 'atendimentos',   label: 'Atendimentos',   icon: 'ClipboardList' },
  { id: 'servicos',       label: 'Serviços',       icon: 'Scissors' },
  { id: 'profissionais',  label: 'Profissionais',  icon: 'UserCheck' },
  { id: 'financeiro',     label: 'Financeiro',     icon: 'DollarSign' },
  { id: 'marketing',      label: 'Marketing',      icon: 'Megaphone' },
  { id: 'relatorios',     label: 'Relatórios',     icon: 'BarChart3' },
  { id: 'configuracoes',  label: 'Configurações',  icon: 'Settings' },
];

// ─── useIsMobile hook ─────────────────────────────────────
const useIsMobile = (breakpoint = 900) => {
  const [isMobile, setIsMobile] = useSt(typeof window !== 'undefined' && window.matchMedia(`(max-width: ${breakpoint}px)`).matches);
  useEf(() => {
    const mq = window.matchMedia(`(max-width: ${breakpoint}px)`);
    const handler = e => setIsMobile(e.matches);
    if (mq.addEventListener) mq.addEventListener('change', handler);
    else mq.addListener(handler);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener('change', handler);
      else mq.removeListener(handler);
    };
  }, [breakpoint]);
  return isMobile;
};

const SidebarLogo = ({ collapsed }) => (
  <>
    <svg width="36" height="36" viewBox="0 0 64 64" fill="none" style={{ flexShrink:0 }}>
      <defs>
        <linearGradient id="sb-phone" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#22D3EE" />
          <stop offset="55%" stopColor="#7C3AED" />
          <stop offset="100%" stopColor="#A855F7" />
        </linearGradient>
      </defs>
      <rect x="14" y="6" width="36" height="56" rx="6" stroke="url(#sb-phone)" strokeWidth="3" fill="none" />
      <line x1="26" y1="12" x2="38" y2="12" stroke="url(#sb-phone)" strokeWidth="2.5" strokeLinecap="round" />
      <rect x="29" y="54" width="6" height="2" rx="1" fill="url(#sb-phone)" />
      <line x1="14" y1="48" x2="50" y2="48" stroke="url(#sb-phone)" strokeWidth="1.6" />
      <path d="M27 26 L21 32 L27 38" stroke="url(#sb-phone)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" fill="none" />
      <path d="M37 26 L43 32 L37 38" stroke="url(#sb-phone)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" fill="none" />
      <line x1="34" y1="24" x2="30" y2="40" stroke="url(#sb-phone)" strokeWidth="3" strokeLinecap="round" />
      <circle cx="52" cy="10" r="1.5" fill="#A855F7" opacity=".8" />
      <circle cx="56" cy="14" r="1" fill="#A855F7" opacity=".6" />
    </svg>
    {!collapsed && (
      <div>
        <div style={{ fontSize:17, fontWeight:800, color:'#fff', letterSpacing:'-0.3px', lineHeight:1 }}>Juflow</div>
        <div style={{ fontSize:9, color:'#FF6B35', fontWeight:700, letterSpacing:2, textTransform:'uppercase', marginTop:3 }}>Digital</div>
      </div>
    )}
  </>
);

// ─── SIDEBAR ──────────────────────────────────────────────
const Sidebar = ({ page, onNavigate, collapsed, onToggle, isMobile, mobileOpen, onMobileClose }) => {
  const W = isMobile ? 280 : (collapsed ? 68 : 240);
  const showText = isMobile ? true : !collapsed;
  const showCollapseToggle = !isMobile;
  const showMobileClose = isMobile;

  // Mobile: drawer behavior (off-canvas)
  const mobileTransform = isMobile && !mobileOpen ? 'translateX(-100%)' : 'translateX(0)';

  return (
    <>
      {/* Mobile backdrop */}
      {isMobile && mobileOpen && (
        <div
          onClick={onMobileClose}
          style={{
            position:'fixed', inset:0, background:'rgba(10,31,68,.55)',
            backdropFilter:'blur(2px)', zIndex:300, animation:'fadeIn .2s ease',
          }}
        />
      )}

      <div style={{
        width: W, minWidth: W,
        height: isMobile ? '100dvh' : '100vh',
        position: isMobile ? 'fixed' : 'sticky',
        top: 0, left: 0,
        background:'#0A1F44', display:'flex', flexDirection:'column',
        transition:'transform .25s ease, width .25s ease',
        overflow:'hidden', flexShrink:0,
        boxShadow:'4px 0 24px rgba(10,31,68,.15)',
        zIndex: isMobile ? 400 : 100,
        transform: mobileTransform,
        paddingTop: 'var(--safe-top)',
      }}>
        {/* Logo */}
        <div style={{
          padding: collapsed && !isMobile ? '22px 0' : '22px 20px',
          display:'flex', alignItems:'center', gap:10,
          borderBottom:'1px solid rgba(255,255,255,.08)',
          justifyContent: collapsed && !isMobile ? 'center' : 'flex-start',
          flexShrink:0,
        }}>
          <SidebarLogo collapsed={collapsed && !isMobile} />
          {showMobileClose && (
            <button onClick={onMobileClose} style={{
              marginLeft:'auto', width:32, height:32, borderRadius:8,
              background:'rgba(255,255,255,.08)', border:'none', cursor:'pointer',
              display:'flex', alignItems:'center', justifyContent:'center',
            }}>
              <Icon name="X" size={16} color="#fff" />
            </button>
          )}
        </div>

        {/* Toggle button (desktop only) */}
        {showCollapseToggle && (
          <button
            onClick={onToggle}
            style={{
              position:'absolute', top:`calc(22px + var(--safe-top))`, right: collapsed ? '50%' : 12,
              transform: collapsed ? 'translateX(50%)' : 'none',
              width:24, height:24, borderRadius:6,
              background:'rgba(255,255,255,.08)', border:'none',
              cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center',
              opacity:0.6, transition:'opacity .15s',
              marginTop: collapsed ? 48 : 0,
              zIndex:1,
            }}
            title={collapsed ? 'Expandir menu' : 'Recolher menu'}
            onMouseEnter={e => e.currentTarget.style.opacity=1}
            onMouseLeave={e => e.currentTarget.style.opacity=0.6}
          >
            <Icon name={collapsed ? 'ChevronRight' : 'ChevronLeft'} size={13} color="white" />
          </button>
        )}

        {/* Nav */}
        <nav style={{ flex:1, padding:'12px 8px', overflow:'auto', scrollbarWidth:'none' }}>
          {NAV_ITEMS.map(item => {
            const active = page === item.id;
            return (
              <button
                key={item.id}
                onClick={() => { onNavigate(item.id); if (isMobile && onMobileClose) onMobileClose(); }}
                title={!showText ? item.label : ''}
                style={{
                  display:'flex', alignItems:'center',
                  gap:10, width:'100%',
                  padding: !showText ? '11px 0' : '12px 14px',
                  justifyContent: !showText ? 'center' : 'flex-start',
                  borderRadius:10, marginBottom:3,
                  background: active ? 'rgba(255,107,53,.18)' : 'none',
                  border: active ? '1px solid rgba(255,107,53,.25)' : '1px solid transparent',
                  cursor:'pointer', transition:'all .15s',
                  color: active ? '#FF6B35' : 'rgba(255,255,255,.6)',
                }}
                onMouseEnter={e => { if(!active) { e.currentTarget.style.background='rgba(255,255,255,.06)'; e.currentTarget.style.color='rgba(255,255,255,.9)'; }}}
                onMouseLeave={e => { if(!active) { e.currentTarget.style.background='none'; e.currentTarget.style.color='rgba(255,255,255,.6)'; }}}
              >
                <Icon name={item.icon} size={18} color={active ? '#FF6B35' : 'currentColor'} />
                {showText && (
                  <span style={{ fontSize:13.5, fontWeight: active ? 700 : 500, whiteSpace:'nowrap' }}>
                    {item.label}
                  </span>
                )}
                {showText && active && (
                  <div style={{ marginLeft:'auto', width:6, height:6, borderRadius:'50%', background:'#FF6B35' }} />
                )}
              </button>
            );
          })}
        </nav>

        {/* User avatar at bottom */}
        <div style={{
          padding: !showText ? '16px 8px' : '16px',
          paddingBottom: `calc(16px + var(--safe-bottom))`,
          borderTop:'1px solid rgba(255,255,255,.08)',
          display:'flex', alignItems:'center', gap:10,
          justifyContent: !showText ? 'center' : 'flex-start',
        }}>
          <div style={{
            width:34, height:34, borderRadius:10, background:'rgba(255,107,53,.25)',
            display:'flex', alignItems:'center', justifyContent:'center',
            flexShrink:0,
          }}>
            <span style={{ fontSize:13, fontWeight:700, color:'#FF6B35' }}>A</span>
          </div>
          {showText && (
            <div style={{ minWidth:0 }}>
              <div style={{ fontSize:12, fontWeight:700, color:'#fff', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>Admin Demo</div>
              <div style={{ fontSize:10, color:'rgba(255,255,255,.4)', whiteSpace:'nowrap' }}>demo@juflow.com</div>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

// ─── NOTIFICATION PANEL ───────────────────────────────────
const NotificationPanel = ({ onClose, appointments }) => {
  const today = window.JF.CLIENTS.filter(c => U2.isBirthdayThisMonth(c.birthdate)).slice(0, 3);
  const upcoming = appointments
    .filter(a => ['confirmed','pending'].includes(a.status) && new Date(a.datetime) >= window.JF.TODAY)
    .sort((a,b) => new Date(a.datetime) - new Date(b.datetime))
    .slice(0, 4);

  return (
    <div style={{
      position:'absolute', top:'calc(100% + 8px)', right:0,
      background:'#fff', borderRadius:14,
      boxShadow:'0 12px 40px rgba(10,31,68,.16)',
      border:'1px solid #E2E8F0', width:320, maxWidth:'calc(100vw - 24px)', zIndex:600,
      overflow:'hidden',
    }}>
      <div style={{ padding:'14px 16px', borderBottom:'1px solid #E2E8F0', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <span style={{ fontSize:14, fontWeight:700, color:'#0A1F44' }}>Notificações</span>
        <button onClick={onClose} style={{ border:'none', background:'none', cursor:'pointer', display:'flex' }}>
          <Icon name="X" size={14} color="#9CA3AF" />
        </button>
      </div>
      <div style={{ maxHeight:320, overflow:'auto' }}>
        {today.length > 0 && (
          <div style={{ padding:'10px 16px', background:'#FDF4FF', borderBottom:'1px solid #F3E8FF' }}>
            <div style={{ fontSize:11, fontWeight:700, color:'#7E22CE', marginBottom:6, textTransform:'uppercase', letterSpacing:.5 }}>🎂 Aniversariantes</div>
            {today.map(c => (
              <div key={c.id} style={{ fontSize:13, color:'#374151', padding:'3px 0' }}>
                {c.name} — {U2.formatDate(c.birthdate, 'dd/MM')}
              </div>
            ))}
          </div>
        )}
        {upcoming.map(a => {
          const client = U2.getClient(a.clientId);
          const service = U2.getService(a.serviceId);
          return (
            <div key={a.id} style={{ padding:'10px 16px', borderBottom:'1px solid #F9FAFB', display:'flex', gap:10 }}>
              <div style={{ width:8, height:8, borderRadius:'50%', background: U2.getProfessional(a.professionalId)?.color, marginTop:5, flexShrink:0 }} />
              <div>
                <div style={{ fontSize:13, fontWeight:600, color:'#0A1F44' }}>{client?.name}</div>
                <div style={{ fontSize:12, color:'#6B7280' }}>{service?.name} · {U2.formatDateTime(a.datetime)}</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// ─── HEADER ───────────────────────────────────────────────
const Header = ({ page, appointments, onNavigate, onLogout, onMenuOpen, isMobile }) => {
  const [notifOpen, setNotifOpen] = useSt(false);
  const [searchVal, setSearchVal] = useSt('');
  const [searchResults, setSearchResults] = useSt([]);
  const [searchFocus, setSearchFocus] = useSt(false);

  const pageLabels = {
    dashboard:'Dashboard', agenda:'Agenda', clientes:'Clientes',
    atendimentos:'Atendimentos', servicos:'Serviços', profissionais:'Profissionais',
    financeiro:'Financeiro', marketing:'Marketing', relatorios:'Relatórios', configuracoes:'Configurações',
  };

  const todayCount = appointments.filter(a =>
    U2.isSameDay(a.datetime, window.JF.TODAY) && ['confirmed','pending'].includes(a.status)
  ).length;

  useEf(() => {
    if (searchVal.length < 2) { setSearchResults([]); return; }
    const q = searchVal.toLowerCase();
    const clients = window.JF.CLIENTS.filter(c => c.name.toLowerCase().includes(q)).slice(0,3)
      .map(c => ({ type:'client', label:c.name, sub:'Cliente', id:c.id, icon:'User' }));
    const services = window.JF.SERVICES.filter(s => s.name.toLowerCase().includes(q)).slice(0,2)
      .map(s => ({ type:'service', label:s.name, sub:s.category, id:s.id, icon:'Scissors' }));
    setSearchResults([...clients, ...services]);
  }, [searchVal]);

  return (
    <header style={{
      minHeight: 64, background:'#fff', borderBottom:'1px solid #E2E8F0',
      display:'flex', alignItems:'center', justifyContent:'space-between',
      padding: isMobile ? '8px 14px' : '0 24px',
      paddingTop: `calc(${isMobile ? 8 : 0}px + var(--safe-top))`,
      paddingRight: `calc(${isMobile ? 14 : 24}px + var(--safe-right))`,
      paddingLeft: `calc(${isMobile ? 14 : 24}px + var(--safe-left))`,
      flexShrink:0, gap: isMobile ? 8 : 16, position:'sticky', top:0, zIndex:200,
    }}>
      {/* Hamburger (mobile) */}
      {isMobile && (
        <button onClick={onMenuOpen} style={{
          width:40, height:40, borderRadius:10, border:'1px solid #E2E8F0',
          background:'#F9FAFB', cursor:'pointer', display:'flex',
          alignItems:'center', justifyContent:'center', flexShrink:0,
        }}>
          <Icon name="Menu" size={18} color="#0A1F44" />
        </button>
      )}

      {/* Page title */}
      <div style={{ flex: isMobile ? 1 : 'initial', minWidth:0 }}>
        <h1 style={{ fontSize: isMobile ? 16 : 18, fontWeight:800, color:'#0A1F44', margin:0, letterSpacing:'-0.3px', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
          {pageLabels[page] || page}
        </h1>
        {!isMobile && <p style={{ fontSize:11, color:'#9CA3AF', margin:0 }}>{U2.formatDateLong(window.JF.TODAY)}</p>}
      </div>

      <div style={{ display:'flex', alignItems:'center', gap: isMobile ? 8 : 12, flex: isMobile ? 'initial' : 1, justifyContent:'flex-end' }}>
        {/* Search - hidden on mobile */}
        {!isMobile && (
          <div style={{ position:'relative', maxWidth:280, width:'100%' }}>
            <SearchBar
              value={searchVal}
              onChange={setSearchVal}
              placeholder="Buscar clientes, serviços…"
              style={{ width:'100%' }}
            />
            {searchFocus && searchResults.length > 0 && (
              <div style={{
                position:'absolute', top:'calc(100% + 6px)', left:0, right:0,
                background:'#fff', borderRadius:10, border:'1px solid #E2E8F0',
                boxShadow:'0 8px 24px rgba(10,31,68,.12)', zIndex:500, overflow:'hidden',
              }}>
                {searchResults.map((r, i) => (
                  <div key={i} onClick={() => { setSearchVal(''); setSearchResults([]); if(r.type==='client') onNavigate('clientes'); }}
                    style={{
                      display:'flex', alignItems:'center', gap:10,
                      padding:'10px 14px', cursor:'pointer', fontSize:13,
                    }}
                    onMouseEnter={e => e.currentTarget.style.background='#F9FAFB'}
                    onMouseLeave={e => e.currentTarget.style.background='#fff'}
                  >
                    <Icon name={r.icon} size={14} color="#9CA3AF" />
                    <div>
                      <div style={{ fontWeight:600, color:'#0A1F44' }}>{r.label}</div>
                      <div style={{ fontSize:11, color:'#9CA3AF' }}>{r.sub}</div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Today badge */}
        {todayCount > 0 && !isMobile && (
          <div style={{
            padding:'5px 12px', borderRadius:20, fontSize:12, fontWeight:700,
            background:'#FFF0EA', color:'#C2410C', border:'1px solid #FED7AA',
            whiteSpace:'nowrap',
          }}>
            {todayCount} hoje
          </div>
        )}

        {/* Notifications */}
        <div style={{ position:'relative' }}>
          <button
            onClick={() => setNotifOpen(o => !o)}
            style={{
              width: isMobile ? 40 : 38, height: isMobile ? 40 : 38, borderRadius:10,
              background: notifOpen ? '#FFF0EA' : '#F9FAFB',
              border:`1px solid ${notifOpen ? '#FED7AA' : '#E2E8F0'}`,
              cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center',
              position:'relative', flexShrink:0,
            }}
          >
            <Icon name="Bell" size={16} color={notifOpen ? '#FF6B35' : '#6B7280'} />
            <span style={{
              position:'absolute', top:7, right:7,
              width:7, height:7, borderRadius:'50%',
              background:'#FF6B35', border:'1.5px solid #fff',
            }} />
          </button>
          {notifOpen && (
            <NotificationPanel onClose={() => setNotifOpen(false)} appointments={appointments} />
          )}
        </div>

        {/* User menu */}
        <DropdownMenu
          trigger={
            isMobile ? (
              <div style={{
                width:40, height:40, borderRadius:10, border:'1px solid #E2E8F0',
                background:'#F9FAFB', display:'flex', alignItems:'center', justifyContent:'center',
                cursor:'pointer', flexShrink:0,
              }}>
                <span style={{ fontSize:13, fontWeight:700, color:'#FF6B35' }}>A</span>
              </div>
            ) : (
              <div style={{
                display:'flex', alignItems:'center', gap:8, cursor:'pointer',
                padding:'4px 10px', borderRadius:10, border:'1px solid #E2E8F0',
                background:'#F9FAFB',
              }}>
                <div style={{
                  width:28, height:28, borderRadius:8, background:'rgba(255,107,53,.15)',
                  display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700, color:'#FF6B35',
                }}>A</div>
                <span style={{ fontSize:13, fontWeight:600, color:'#0A1F44' }}>Admin</span>
                <Icon name="ChevronDown" size={13} color="#9CA3AF" />
              </div>
            )
          }
          items={[
            { label:'Perfil', icon:'User', onClick:() => {} },
            { label:'Configurações', icon:'Settings', onClick:() => onNavigate('configuracoes') },
            'divider',
            { label:'Sair', icon:'LogOut', onClick:onLogout, danger:true },
          ]}
        />
      </div>
    </header>
  );
};

Object.assign(window, { Sidebar, Header, useIsMobile });
