/* global React, V2Icon, V2_DATA, SearchBar, Icon */
const { useState, useMemo, useRef, useEffect } = React;

function V2TopBar({ user, date, onSettings, onSelectPatient }) {
  return (
    <header style={{
      height: 48, display: 'flex', alignItems: 'center',
      padding: '0 12px 0 14px',
      background: '#fff',
      borderBottom: '1px solid var(--sage-200)',
      flexShrink: 0,
      gap: 14
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }} data-comment-anchor="376357e181-div-14-7">
        <span style={{ fontSize: 13, color: 'var(--sage-500)' }}>Team 2</span>
        <span style={{ fontSize: 13, color: 'var(--sage-300)' }}>/</span>
        <span style={{ fontSize: 13, color: 'var(--sage-800)', fontWeight: 600 }}>M. Turner</span>
      </div>

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

      {typeof SearchBar === 'function' ? <SearchBar /> : null}

      <button title="Switch team" style={{
        display: 'flex', alignItems: 'center', gap: 4, background: 'var(--primary-muted)',
        color: 'var(--primary)', border: '1px solid #d6e4dc', borderRadius: 6,
        padding: '5px 10px', fontSize: 12, fontWeight: 500, fontFamily: 'var(--font-sans)', cursor: 'pointer',
        whiteSpace: 'nowrap', flexShrink: 0
      }}>
        Team 2
        <V2Icon name="chevronDown" size={12} />
      </button>

      <button title="Notifications" style={{ background: 'transparent', border: 0, color: 'var(--sage-500)', padding: 6, cursor: 'pointer', display: 'flex', position: 'relative' }}>
        <V2Icon name="bell" size={16} />
        <span style={{ position: 'absolute', top: 4, right: 4, width: 6, height: 6, borderRadius: '50%', background: 'var(--flag, #d97706)' }} />
      </button>

      <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }} data-comment-anchor="a8b328ed46-div-42-7">
        <span style={{ fontSize: 12, color: 'var(--sage-700)', fontWeight: 500, whiteSpace: 'nowrap' }}>Dr. Chris Wilson</span>
        <div style={{
          width: 26, height: 26, borderRadius: '50%',
          background: 'var(--primary-light, var(--primary))', color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 10, fontWeight: 600
        }}>CW</div>
      </div>
    </header>);

}

function iconBtn() {
  return {
    width: 30, height: 30, borderRadius: 6,
    border: 0, background: 'transparent',
    color: 'var(--sage-500)', cursor: 'pointer',
    display: 'grid', placeItems: 'center'
  };
}

function GlobalSearch({ onSelectPatient }) {
  const [q, setQ] = useState('');
  const [open, setOpen] = useState(false);
  const [activeIdx, setActiveIdx] = useState(0);
  const inputRef = useRef(null);
  const wrapRef = useRef(null);

  // Cmd/Ctrl-K to focus
  useEffect(() => {
    function onKey(e) {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        inputRef.current?.focus();
        setOpen(true);
      }
      if (e.key === 'Escape') {
        setOpen(false);
        inputRef.current?.blur();
      }
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  // Click outside to close
  useEffect(() => {
    function onClick(e) {
      if (!wrapRef.current?.contains(e.target)) setOpen(false);
    }
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, []);

  const corpus = useMemo(() => {
    const active = (V2_DATA.patients || []).map((p) => ({ ...p, group: 'Active patients' }));
    const inactive = [
    ...(V2_DATA.inactivePatients?.last7 || []).map((p) => ({ ...p, group: 'Inactive · last 7 days' })),
    ...(V2_DATA.inactivePatients?.last30 || []).map((p) => ({ ...p, group: 'Inactive · last 30 days' }))];

    return [...active, ...inactive];
  }, []);

  const results = useMemo(() => {
    const term = q.trim().toLowerCase();
    if (!term) return corpus.slice(0, 8);
    return corpus.filter((p) =>
    [p.name, p.mrn, p.bed, p.dob].filter(Boolean).join(' ').toLowerCase().includes(term)
    ).slice(0, 12);
  }, [q, corpus]);

  function handleSelect(p) {
    if (p.group === 'Active patients' && onSelectPatient) onSelectPatient(p.id);
    setOpen(false);
    setQ('');
    inputRef.current?.blur();
  }

  function onKeyDown(e) {
    if (e.key === 'ArrowDown') {e.preventDefault();setActiveIdx((i) => Math.min(i + 1, results.length - 1));}
    if (e.key === 'ArrowUp') {e.preventDefault();setActiveIdx((i) => Math.max(i - 1, 0));}
    if (e.key === 'Enter' && results[activeIdx]) {e.preventDefault();handleSelect(results[activeIdx]);}
  }

  // group consecutive results
  const grouped = [];
  let lastGroup = null;
  results.forEach((r, i) => {
    if (r.group !== lastGroup) {
      grouped.push({ kind: 'header', label: r.group });
      lastGroup = r.group;
    }
    grouped.push({ kind: 'item', item: r, idx: i });
  });

  return (
    <div ref={wrapRef} style={{ position: 'relative', width: 360, maxWidth: '100%' }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '6px 10px',
        background: open ? '#fff' : 'var(--sage-100)',
        border: `1px solid ${open ? 'var(--primary)' : 'var(--sage-200)'}`,
        borderRadius: 8,
        boxShadow: open ? '0 0 0 3px var(--primary-muted)' : 'none',
        transition: 'all 0.12s ease'
      }} data-comment-anchor="583599d235-div-144-7">
        <V2Icon name="search" size={13} stroke="var(--sage-500)" />
        <input
          ref={inputRef}
          value={q}
          onChange={(e) => {setQ(e.target.value);setActiveIdx(0);setOpen(true);}}
          onFocus={() => setOpen(true)}
          onKeyDown={onKeyDown}
          placeholder="Search patients, MRN, bed…"
          style={{
            flex: 1, border: 0, outline: 0, background: 'transparent',
            fontSize: 12.5, color: 'var(--sage-800)', fontFamily: 'var(--font-sans)'
          }} />
        
        <span style={{
          fontFamily: 'var(--font-mono)', fontSize: 10,
          color: 'var(--sage-400)',
          padding: '1px 5px', borderRadius: 3,
          border: '1px solid var(--sage-200)',
          background: '#fff'
        }}>⌘K</span>
      </div>

      {open &&
      <div style={{
        position: 'absolute', top: 'calc(100% + 6px)', left: 0, right: 0,
        background: '#fff',
        border: '1px solid var(--sage-200)',
        borderRadius: 10,
        boxShadow: '0 12px 32px -8px rgba(13, 35, 33, 0.18)',
        maxHeight: 360, overflowY: 'auto',
        zIndex: 50,
        padding: 4,
        animation: 'fadeIn 0.12s ease'
      }}>
          {results.length === 0 &&
        <div style={{ padding: '14px 12px', fontSize: 12, color: 'var(--sage-500)', fontStyle: 'italic' }}>
              No matches for “{q}”.
            </div>
        }
          {grouped.map((row, i) => row.kind === 'header' ?
        <div key={'h' + i} style={{
          padding: '8px 10px 4px 10px',
          fontSize: 9.5, fontWeight: 600,
          letterSpacing: '0.06em', textTransform: 'uppercase',
          color: 'var(--sage-500)'
        }}>{row.label}</div> :

        <button
          key={row.item.id}
          onClick={() => handleSelect(row.item)}
          onMouseEnter={() => setActiveIdx(row.idx)}
          style={{
            width: '100%', display: 'flex', alignItems: 'center', gap: 10,
            padding: '7px 10px', borderRadius: 6,
            border: 0, background: row.idx === activeIdx ? 'var(--primary-muted)' : 'transparent',
            cursor: 'pointer', textAlign: 'left',
            fontFamily: 'var(--font-sans)'
          }}>
          
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--sage-500)', width: 42 }}>{row.item.bed}</span>
              <span style={{ flex: 1, fontSize: 12.5, fontWeight: 500, color: 'var(--sage-800)' }}>{row.item.name}</span>
              <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--sage-500)' }}>{row.item.mrn}</span>
            </button>
        )}
          <div style={{
          padding: '8px 12px 6px 12px',
          borderTop: '1px solid var(--sage-100)',
          marginTop: 4,
          display: 'flex', justifyContent: 'space-between',
          fontSize: 10, color: 'var(--sage-400)', fontFamily: 'var(--font-mono)'
        }}>
            <span>↑↓ navigate · ↵ open</span>
            <span>esc close</span>
          </div>
        </div>
      }
    </div>);

}

window.V2TopBar = V2TopBar;