/* global React, Icon, ICONS, Avatar, Button, Field, sb */
const { useState: useStateTopbar, useEffect: useEffectTopbar, useRef: useRefTopbar } = React;

const PATH_SUN  = 'M12 18a6 6 0 1 0 0-12 6 6 0 0 0 0 12zM12 2v2M12 20v2m-7.07-14.07 1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2m-2.34-7.07-1.41 1.41M6.34 17.66l-1.41 1.41';
const PATH_MOON = 'M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z';

function Topbar({ title, subtitle, onAction, onBell, onNav, user }) {
  const [isDark, setIsDark] = useStateTopbar(
    () => document.documentElement.getAttribute('data-theme') !== 'light'
  );
  const [query,   setQuery]   = useStateTopbar('');
  const [results, setResults] = useStateTopbar([]);
  const [loading, setLoading] = useStateTopbar(false);
  const [open,    setOpen]    = useStateTopbar(false);
  const wrapRef  = useRefTopbar(null);
  const timerRef = useRefTopbar(null);

  // Close dropdown when clicking outside
  useEffectTopbar(() => {
    function handleClick(e) { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); }
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, []);

  // Debounced search
  useEffectTopbar(() => {
    clearTimeout(timerRef.current);
    if (!query.trim() || query.length < 2) { setResults([]); setOpen(false); return; }
    timerRef.current = setTimeout(async () => {
      setLoading(true);
      const q = query.trim().toLowerCase();
      const [{ data: projs }, { data: clients }, { data: tasks }] = await Promise.all([
        sb.from('projects').select('id,name,client,status').ilike('name', `%${q}%`).limit(4),
        sb.from('clients').select('id,name,email').ilike('name', `%${q}%`).limit(4),
        sb.from('tasks').select('id,title,status').ilike('title', `%${q}%`).limit(4),
      ]);
      const all = [
        ...(projs   || []).map(r => ({ type:'project', id:r.id, label:r.name,  sub:r.client||r.status, nav:'projects', icon:'folder' })),
        ...(clients || []).map(r => ({ type:'client',  id:r.id, label:r.name,  sub:r.email||'Cliente',  nav:'clients',  icon:'user'   })),
        ...(tasks   || []).map(r => ({ type:'task',    id:r.id, label:r.title, sub:r.status||'Tarefa',  nav:'tasks',    icon:'check'  })),
      ];
      setResults(all);
      setOpen(all.length > 0);
      setLoading(false);
    }, 280);
  }, [query]);

  function handleSelect(item) {
    setQuery('');
    setOpen(false);
    setResults([]);
    onNav?.(item.nav);
  }

  function toggleTheme() {
    const next = isDark ? 'light' : 'dark';
    document.documentElement.setAttribute('data-theme', next);
    document.body.className = 'ds-root theme-' + next;
    if (window.__setTheme) window.__setTheme(next);
    setIsDark(!isDark);
  }

  const iconStyle = {
    width: 38, height: 38, borderRadius: 10,
    background: 'var(--bg-surface)', border: '1px solid var(--border-subtle)',
    color: 'var(--fg-secondary)', cursor: 'pointer', display: 'grid', placeItems: 'center',
  };

  const TYPE_LABELS = { project:'Projeto', client:'Cliente', task:'Tarefa' };

  return (
    <header style={{
      display: 'flex', alignItems: 'center', gap: 16,
      padding: '20px 28px',
      borderBottom: '1px solid var(--border-subtle)',
      background: 'var(--bg-app)',
      position: 'sticky', top: 0, zIndex: 10,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.01em' }}>{title}</div>
        {subtitle && <div style={{ fontSize: 13, color: 'var(--fg-muted)', marginTop: 2 }}>{subtitle}</div>}
      </div>

      {/* Search */}
      <div ref={wrapRef} style={{ position: 'relative', width: 280 }}>
        <span style={{ display:'flex', alignItems:'center', gap:8, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', borderRadius:8, padding:'10px 12px' }}>
          <Icon d={ICONS.search} size={16} style={{ color:'var(--fg-muted)', flexShrink:0 }}/>
          <input
            value={query}
            onChange={e => setQuery(e.target.value)}
            onFocus={() => results.length > 0 && setOpen(true)}
            placeholder="Buscar projeto, cliente ou tarefa…"
            style={{ background:'transparent', border:'none', outline:'none', color:'var(--fg-primary)', fontFamily:'inherit', fontSize:14, flex:1, minWidth:0 }}
          />
          {loading && <span style={{ fontSize:11, color:'var(--fg-muted)', flexShrink:0 }}>…</span>}
          {query && !loading && (
            <button onClick={() => { setQuery(''); setOpen(false); }} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:0, lineHeight:1 }}>✕</button>
          )}
        </span>

        {open && results.length > 0 && (
          <div style={{ position:'absolute', top:'calc(100% + 6px)', left:0, right:0, background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:12, boxShadow:'0 16px 40px rgba(0,0,0,0.4)', overflow:'hidden', zIndex:200 }}>
            {results.map((r, i) => (
              <button key={r.type+r.id} onClick={() => handleSelect(r)} style={{
                display:'flex', alignItems:'center', gap:10, width:'100%', padding:'10px 14px',
                background: 'transparent', border:'none', borderTop: i > 0 ? '1px solid var(--border-subtle)' : 'none',
                cursor:'pointer', textAlign:'left', fontFamily:'inherit',
              }}
              onMouseEnter={e => e.currentTarget.style.background='var(--bg-elevated)'}
              onMouseLeave={e => e.currentTarget.style.background='transparent'}>
                <div style={{ width:30, height:30, borderRadius:8, background:'var(--primary-soft)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                  <Icon d={ICONS[r.icon]} size={14} style={{ color:'var(--primary)' }}/>
                </div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:13, fontWeight:600, color:'var(--fg-primary)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{r.label}</div>
                  <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:1 }}>{r.sub}</div>
                </div>
                <span style={{ fontSize:10, fontWeight:700, color:'var(--fg-muted)', background:'var(--bg-elevated)', padding:'2px 7px', borderRadius:999, flexShrink:0 }}>{TYPE_LABELS[r.type]}</span>
              </button>
            ))}
          </div>
        )}

        {open && query.length >= 2 && results.length === 0 && !loading && (
          <div style={{ position:'absolute', top:'calc(100% + 6px)', left:0, right:0, background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:12, padding:'16px 14px', textAlign:'center', color:'var(--fg-muted)', fontSize:13, zIndex:200 }}>
            Nenhum resultado para "{query}"
          </div>
        )}
      </div>

      <button onClick={onBell} style={{ ...iconStyle, position: 'relative' }}>
        <Icon d={ICONS.bell} size={18} />
        <span style={{ position:'absolute', top:6, right:6, width:8, height:8, borderRadius:'50%', background:'var(--accent-danger)', border:'2px solid var(--bg-surface)' }}/>
      </button>
      <button onClick={toggleTheme} title={isDark ? 'Modo claro' : 'Modo escuro'} style={iconStyle}
        onMouseEnter={e => { e.currentTarget.style.background='var(--bg-elevated)'; e.currentTarget.style.color='var(--fg-primary)'; }}
        onMouseLeave={e => { e.currentTarget.style.background='var(--bg-surface)'; e.currentTarget.style.color='var(--fg-secondary)'; }}>
        <svg viewBox="0 0 24 24" width={17} height={17} fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
          {isDark ? <path d={PATH_SUN}/> : <path d={PATH_MOON}/>}
        </svg>
      </button>
      <Button icon="plus" onClick={onAction}>Novo projeto</Button>
      <Avatar name={user?.name || ''} size={38} src={user?.avatarUrl || null} />
    </header>
  );
}
window.Topbar = Topbar;
