// Shell.jsx — Sidebar + Topbar layout
(function () {
  const { useState, useRef } = React;

  // ── Inline SVG icons ──────────────────────────────────────────────
  const Ic = ({ d, size = 20, stroke = 'currentColor', fill = 'none', sw = 1.7 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={fill} stroke={stroke} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      {Array.isArray(d) ? d.map((p, i) => <path key={i} d={p} />) : <path d={d} />}
    </svg>
  );

  const icons = {
    dashboard:   <Ic d={['M3 3h7v7H3z','M14 3h7v7h-7z','M14 14h7v7h-7z','M3 14h7v7H3z']} />,
    kanban:      <Ic d={['M6 3h3v12H6z','M10.5 3h3v7.5h-3z','M15 3h3v9h-3z']} fill="currentColor" stroke="none" />,
    calendar:    <Ic d={['M8 2v4','M16 2v4','M3 10h18','M5 4h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z','M8 14h.01','M12 14h.01','M16 14h.01','M8 18h.01','M12 18h.01']} />,
    users:       <Ic d={['M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2','M23 21v-2a4 4 0 0 0-3-3.87','M16 3.13a4 4 0 0 1 0 7.75']} sw={1.8}>
                   <circle cx="9" cy="7" r="4" strokeWidth="1.8" />
                 </Ic>,
    tasks:       <Ic d={['M9 11l3 3L22 4','M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11']} />,
    reports:     <Ic d={['M18 20V10','M12 20V4','M6 20v-6']} sw={2} />,
    settings:    <Ic d="M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />,
    bell:        <Ic d={['M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9','M13.73 21a2 2 0 0 1-3.46 0']} />,
    search:      <Ic d="M21 21l-6-6m2-5a7 7 0 1 1-14 0 7 7 0 0 1 14 0" />,
    sun:         <Ic d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"><circle cx="12" cy="12" r="5" strokeWidth="1.7" /></Ic>,
    moon:        <Ic d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />,
    chevLeft:    <Ic d="M15 18l-6-6 6-6" sw={2} />,
    chevRight:   <Ic d="M9 18l6-6-6-6" sw={2} />,
    menu:        <Ic d={['M3 12h18','M3 6h18','M3 18h18']} sw={2} />,
  };

  // ── Nav items ──────────────────────────────────────────────────────
  const NAV = [
    { id: 'dashboard', label: 'Dashboard',        icon: 'dashboard' },
    { id: 'kanban',    label: 'Lejek sprzedaży',  icon: 'kanban'    },
    { id: 'clients',   label: 'Klienci',           icon: 'users'     },
    { id: 'tasks',     label: 'Zadania',           icon: 'tasks'     },
    { id: 'calendar',  label: 'Kalendarz',         icon: 'calendar'  },
    { id: 'reports',   label: 'Raporty',           icon: 'reports'   },
    { id: 'settings',  label: 'Ustawienia',        icon: 'settings'  },
  ];

  // ── Sidebar ────────────────────────────────────────────────────────
  function Sidebar({ active, setActive, collapsed, setCollapsed }) {
    const [showLogout, setShowLogout] = useState(false);
    return (
      <aside style={{
        width: collapsed ? 64 : 220,
        minWidth: collapsed ? 64 : 220,
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
        background: 'var(--bg-sidebar)',
        borderRight: '1px solid var(--bdr)',
        backdropFilter: 'blur(24px)',
        WebkitBackdropFilter: 'blur(24px)',
        transition: 'width .3s cubic-bezier(.4,0,.2,1), min-width .3s cubic-bezier(.4,0,.2,1)',
        overflow: 'hidden',
        position: 'relative',
        zIndex: 10,
        flexShrink: 0,
      }}>
        {/* Logo */}
        <div style={{ padding: collapsed ? '20px 0' : '20px 18px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: '1px solid var(--bdr)', minHeight: 65, justifyContent: collapsed ? 'center' : 'flex-start' }}>
          {collapsed ? (
            <div style={{ width: 32, height: 32, borderRadius: 8, background: 'linear-gradient(135deg,#7C5CFF,#4DA3FF)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, fontWeight: 800, color: '#fff', boxShadow: '0 0 14px rgba(124,92,255,.4)' }}>N</div>
          ) : (
            <span style={{ fontSize: 18, fontWeight: 800, letterSpacing: -0.8, background: 'linear-gradient(135deg,#a78bff,#4DA3FF)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>DemoCRM</span>
          )}
        </div>

        {/* Nav */}
        <nav style={{ flex: 1, padding: '12px 8px', display: 'flex', flexDirection: 'column', gap: 2 }}>
          {NAV.map(item => {
            const isActive = active === item.id;
            return (
              <button key={item.id} onClick={() => setActive(item.id)} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: collapsed ? '10px 0' : '10px 12px',
                justifyContent: collapsed ? 'center' : 'flex-start',
                borderRadius: 10, border: 'none', cursor: 'pointer', width: '100%',
                background: isActive ? 'var(--bg-active)' : 'transparent',
                color: isActive ? '#7C5CFF' : 'var(--t2)',
                fontWeight: isActive ? 600 : 400, fontSize: 14,
                transition: 'all .18s ease',
                outline: 'none',
                boxShadow: isActive ? 'inset 0 0 0 1px rgba(124,92,255,.3)' : 'none',
                whiteSpace: 'nowrap',
              }}
              onMouseEnter={e => { if (!isActive) e.currentTarget.style.background = 'var(--bg-hover)'; e.currentTarget.style.color = 'var(--t1)'; }}
              onMouseLeave={e => { e.currentTarget.style.background = isActive ? 'var(--bg-active)' : 'transparent'; e.currentTarget.style.color = isActive ? '#7C5CFF' : 'var(--t2)'; }}
              >
                <span style={{ flexShrink: 0, opacity: isActive ? 1 : 0.7 }}>{icons[item.icon]}</span>
                {!collapsed && <span>{item.label}</span>}
              </button>
            );
          })}
        </nav>

        {/* User */}
        <div style={{ padding: collapsed ? '16px 0' : '16px 12px', borderTop: '1px solid var(--bdr)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{
            width: 34, height: 34, borderRadius: 10, flexShrink: 0,
            background: 'linear-gradient(135deg,#7C5CFF,#4DA3FF)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 12, fontWeight: 700, color: '#fff',
            marginLeft: collapsed ? 'auto' : 0,
            marginRight: collapsed ? 'auto' : 0,
          }}>AK</div>
          {!collapsed && (
            <>
              <div style={{ overflow: 'hidden', flex:1 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--t1)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Aleksandra Kowalska</div>
                <div style={{ fontSize: 11, color: 'var(--t3)' }}>Sales Manager</div>
              </div>
              <button title="Wyloguj" onClick={() => setShowLogout(true)} style={{
                width: 30, height: 30, borderRadius: 8, border: '1px solid var(--bdr)', flexShrink:0,
                background: 'var(--bg1)', color: 'var(--t2)', cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center', outline: 'none',
              }}
              onMouseEnter={e=>{e.currentTarget.style.background='rgba(239,68,68,.12)'; e.currentTarget.style.color='#EF4444';}}
              onMouseLeave={e=>{e.currentTarget.style.background='var(--bg1)'; e.currentTarget.style.color='var(--t2)';}}
              >
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="M16 17l5-5-5-5"/><path d="M21 12H9"/></svg>
              </button>
            </>
          )}
        </div>

        {showLogout && ReactDOM.createPortal(
          <>
            <div onClick={()=>setShowLogout(false)} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,.5)', zIndex:300 }} />
            <div style={{ position:'fixed', top:'50%', left:'50%', transform:'translate(-50%,-50%)', width:320, background:'var(--bg-solid)', border:'1px solid var(--bdr2)', borderRadius:16, zIndex:301, padding:22, boxShadow:'0 24px 60px rgba(0,0,0,.5)' }}>
              <div style={{ fontSize:15, fontWeight:700, color:'var(--t1)', marginBottom:6 }}>Wylogować się?</div>
              <div style={{ fontSize:13, color:'var(--t3)', marginBottom:18 }}>Zostaniesz wylogowany z DemoCRM.</div>
              <div style={{ display:'flex', gap:8 }}>
                <button onClick={()=>setShowLogout(false)} style={{ flex:1, padding:'9px 0', borderRadius:10, border:'1px solid var(--bdr)', background:'var(--bg1)', color:'var(--t1)', fontWeight:600, fontSize:13, cursor:'pointer' }}>Anuluj</button>
                <button onClick={()=>{ setShowLogout(false); window.__onLogout && window.__onLogout(); }} style={{ flex:1, padding:'9px 0', borderRadius:10, border:'none', background:'linear-gradient(135deg,#EF4444,#F59E0B)', color:'#fff', fontWeight:600, fontSize:13, cursor:'pointer' }}>Wyloguj</button>
              </div>
            </div>
          </>,
          document.body
        )}

        {/* Collapse toggle */}
        <button onClick={() => setCollapsed(!collapsed)} style={{
          position: 'absolute', top: 18, right: collapsed ? '50%' : 12,
          transform: collapsed ? 'translateX(50%)' : 'none',
          width: 24, height: 24, borderRadius: 6, border: '1px solid var(--bdr)',
          background: 'var(--bg1)', color: 'var(--t2)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          transition: 'all .2s', fontSize: 12, padding: 0, outline: 'none',
        }}
        onMouseEnter={e => { e.currentTarget.style.background='var(--bg2)'; e.currentTarget.style.color='var(--t1)'; }}
        onMouseLeave={e => { e.currentTarget.style.background='var(--bg1)'; e.currentTarget.style.color='var(--t2)'; }}
        style={{display:'none'}} // hidden, using menu button in topbar instead
        >{collapsed ? icons.chevRight : icons.chevLeft}</button>
      </aside>
    );
  }

  // ── Notifications ──────────────────────────────────────────────────
  const NOTIFICATIONS = [
    { id:1, text:'Nowy lead: Altima Digital Sp. z o.o. (Meta Ads)', time:'12 min temu', color:'#7C5CFF', unread:true },
    { id:2, text:'Spotkanie z InnoPark za 24h — przypomnienie wysłane', time:'1 godz. temu', color:'#4DA3FF', unread:true },
    { id:3, text:'Nexus Technology — oferta zaakceptowana', time:'3 godz. temu', color:'#22C55E', unread:true },
    { id:4, text:'Zaległe zadanie: umowa Techlab Solutions', time:'wczoraj', color:'#EF4444', unread:false },
  ];

  function NotificationsBell() {
    const [open, setOpen] = useState(false);
    const [rect, setRect] = useState(null);
    const btnRef = useRef(null);
    const popRef = useRef(null);
    React.useEffect(() => {
      const onDoc = (e) => {
        if (btnRef.current && btnRef.current.contains(e.target)) return;
        if (popRef.current && popRef.current.contains(e.target)) return;
        setOpen(false);
      };
      document.addEventListener('mousedown', onDoc);
      return () => document.removeEventListener('mousedown', onDoc);
    }, []);
    const unreadCount = NOTIFICATIONS.filter(n => n.unread).length;
    const toggle = () => {
      if (!open && btnRef.current) setRect(btnRef.current.getBoundingClientRect());
      setOpen(v => !v);
    };
    return (
      <div style={{ position: 'relative' }}>
        <button ref={btnRef} onClick={toggle} style={{
          width: 36, height: 36, borderRadius: 10, border: '1px solid var(--bdr)',
          background: 'var(--bg1)', color: 'var(--t2)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', outline: 'none',
        }}
        onMouseEnter={e=>{e.currentTarget.style.background='var(--bg2)'; e.currentTarget.style.color='var(--t1)';}}
        onMouseLeave={e=>{e.currentTarget.style.background='var(--bg1)'; e.currentTarget.style.color='var(--t2)';}}
        >{icons.bell}</button>
        {unreadCount > 0 && (
          <div style={{
            position: 'absolute', top: 6, right: 6, width: 8, height: 8,
            borderRadius: '50%', background: '#7C5CFF',
            boxShadow: '0 0 8px rgba(124,92,255,.7)',
          }} />
        )}
        {open && rect && ReactDOM.createPortal(
          <div ref={popRef} style={{
            position:'fixed', top:rect.bottom+8, left:rect.right-320, width:320, zIndex:9999,
            background:'var(--bg-solid)', border:'1px solid var(--bdr2)', borderRadius:14,
            boxShadow:'0 16px 40px rgba(0,0,0,.45)', overflow:'hidden',
          }}>
            <div style={{ padding:'12px 16px', borderBottom:'1px solid var(--bdr)', fontSize:13, fontWeight:700, color:'var(--t1)' }}>Powiadomienia</div>
            <div style={{ maxHeight:320, overflowY:'auto' }}>
              {NOTIFICATIONS.map(n => (
                <div key={n.id} style={{ display:'flex', gap:10, padding:'12px 16px', borderBottom:'1px solid var(--bdr)', background: n.unread ? 'rgba(124,92,255,.05)' : 'transparent' }}>
                  <div style={{ width:8, height:8, borderRadius:'50%', background:n.color, marginTop:5, flexShrink:0, boxShadow:`0 0 6px ${n.color}88` }} />
                  <div>
                    <div style={{ fontSize:12.5, color:'var(--t1)', lineHeight:1.4 }}>{n.text}</div>
                    <div style={{ fontSize:11, color:'var(--t3)', marginTop:3 }}>{n.time}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>,
          document.body
        )}
      </div>
    );
  }

  // ── Topbar ─────────────────────────────────────────────────────────
  function Topbar({ darkMode, setDarkMode, collapsed, setCollapsed, activeView }) {
    const viewLabels = { dashboard:'Dashboard', kanban:'Lejek sprzedaży', clients:'Klienci', tasks:'Zadania', reports:'Raporty', settings:'Ustawienia' };

    return (
      <header style={{
        height: 60, display: 'flex', alignItems: 'center', gap: 12,
        padding: '0 20px', borderBottom: '1px solid var(--bdr)',
        background: 'var(--bg-sidebar)', backdropFilter: 'blur(24px)',
        WebkitBackdropFilter: 'blur(24px)', flexShrink: 0,
      }}>
        {/* Collapse toggle */}
        <button onClick={() => setCollapsed(!collapsed)} style={{
          width: 34, height: 34, borderRadius: 8, border: '1px solid var(--bdr)',
          background: 'var(--bg1)', color: 'var(--t2)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', outline: 'none', flexShrink: 0,
        }}
        onMouseEnter={e=>{e.currentTarget.style.background='var(--bg2)';}}
        onMouseLeave={e=>{e.currentTarget.style.background='var(--bg1)';}}
        >{icons.menu}</button>

        {/* Breadcrumb */}
        <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--t1)', whiteSpace: 'nowrap' }}>{viewLabels[activeView] || ''}</div>

        <div style={{ flex: 1 }} />

        {/* Bell */}
        <NotificationsBell />

        {/* Theme toggle */}
        <button onClick={() => setDarkMode(!darkMode)} style={{
          width: 36, height: 36, borderRadius: 10, border: '1px solid var(--bdr)',
          background: 'var(--bg1)', color: 'var(--t2)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', outline: 'none',
          transition: 'all .2s',
        }}
        onMouseEnter={e=>{e.currentTarget.style.background='var(--bg2)'; e.currentTarget.style.color='var(--t1)';}}
        onMouseLeave={e=>{e.currentTarget.style.background='var(--bg1)'; e.currentTarget.style.color='var(--t2)';}}
        >{darkMode ? icons.sun : icons.moon}</button>
      </header>
    );
  }

  // ── Custom Select (portal-based, avoids native <select> white-popup + z-index issues) ───────
  window.DemoSelect = function DemoSelect({ value, onChange, options, style }) {
    const [open, setOpen] = useState(false);
    const [rect, setRect] = useState(null);
    const btnRef = useRef(null);
    const popRef = useRef(null);
    React.useEffect(() => {
      const onDoc = (e) => {
        if (btnRef.current && btnRef.current.contains(e.target)) return;
        if (popRef.current && popRef.current.contains(e.target)) return;
        setOpen(false);
      };
      document.addEventListener('mousedown', onDoc);
      return () => document.removeEventListener('mousedown', onDoc);
    }, []);
    const opts = options.map(o => typeof o === 'string' ? { value: o, label: o } : o);
    const current = opts.find(o => o.value === value) || opts[0];
    const toggle = () => {
      if (!open && btnRef.current) setRect(btnRef.current.getBoundingClientRect());
      setOpen(v => !v);
    };
    return (
      <div style={{ position:'relative', width:'100%', ...style }}>
        <button ref={btnRef} type="button" onClick={toggle} style={{
          width:'100%', padding:'9px 12px', borderRadius:9, border:'1px solid var(--bdr)',
          background:'var(--bg-input)', color:'var(--t1)', fontSize:13, textAlign:'left',
          cursor:'pointer', outline:'none', display:'flex', alignItems:'center', justifyContent:'space-between',
        }}>
          <span>{current ? current.label : ''}</span>
          <span style={{ fontSize:10, color:'var(--t3)' }}>▾</span>
        </button>
        {open && rect && ReactDOM.createPortal(
          <div ref={popRef} style={{
            position:'fixed', top:rect.bottom+4, left:rect.left, width:rect.width, zIndex:9999,
            background:'var(--bg-solid)', border:'1px solid var(--bdr2)', borderRadius:10,
            boxShadow:'0 16px 40px rgba(0,0,0,.45)', overflow:'hidden', maxHeight:240, overflowY:'auto',
          }}>
            {opts.map(o => (
              <div key={o.value} onClick={() => { onChange(o.value); setOpen(false); }} style={{
                padding:'9px 12px', fontSize:13, color: o.value===value ? '#7C5CFF' : 'var(--t1)',
                fontWeight: o.value===value ? 600 : 400, cursor:'pointer',
                background: o.value===value ? 'rgba(124,92,255,.12)' : 'transparent',
              }}
              onMouseEnter={e=>{ if(o.value!==value) e.currentTarget.style.background='var(--bg-hover)'; }}
              onMouseLeave={e=>{ if(o.value!==value) e.currentTarget.style.background='transparent'; }}
              >{o.label}</div>
            ))}
          </div>,
          document.body
        )}
      </div>
    );
  };

  // ── Shell (main export) ────────────────────────────────────────────
  window.Shell = function Shell({ children, activeView, setActiveView, darkMode, setDarkMode }) {
    const [collapsed, setCollapsed] = useState(false);
    return (
      <div style={{ display: 'flex', height: '100vh', overflow: 'hidden' }}>
        <Sidebar active={activeView} setActive={setActiveView} collapsed={collapsed} setCollapsed={setCollapsed} />
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          <Topbar darkMode={darkMode} setDarkMode={setDarkMode} collapsed={collapsed} setCollapsed={setCollapsed} activeView={activeView} />
          <main style={{ flex: 1, overflowY: 'auto', padding: '24px', scrollbarWidth: 'thin' }}>
            {children}
          </main>
        </div>
      </div>
    );
  };
})();
