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

const STATUS_LABEL = {
  draft: 'Draft note — unsaved',
  review: 'Needs review — AI recommendations or unfinished post-analysis note'
};
const STATUS_COLOR = {
  draft: 'var(--sage-300)',
  review: 'var(--primary)'
};

function V2Sidebar({
  patients, activePatientId, onSelectPatient,
  notes, activeNoteId, onSelectNote, onDiscardDraft, onNewNote,
  collapsed, onToggleCollapsed
}) {
  const inactive = V2_DATA.inactivePatients || { last7: [], last30: [], earlierCount: 0 };

  const [filterOpen, setFilterOpen] = useState(false);
  const [filter, setFilter] = useState('');
  const filterInputRef = useRef(null);

  function toggleFilter() {
    setFilterOpen((o) => {
      const next = !o;
      if (next) setTimeout(() => filterInputRef.current?.focus(), 0);else
      setFilter('');
      return next;
    });
  }

  const matches = (p) => {
    if (!filter.trim()) return true;
    const q = filter.trim().toLowerCase();
    return [p.name, p.mrn, p.bed].filter(Boolean).join(' ').toLowerCase().includes(q);
  };

  const inactiveTotal = inactive.last7.length + inactive.last30.length + (inactive.earlierCount || 0);

  return (
    <aside style={{
      width: collapsed ? 56 : 260, flexShrink: 0,
      background: '#fff',
      borderRight: '1px solid var(--sage-200)',
      display: 'flex', flexDirection: 'column',
      minHeight: 0,
      transition: 'width 0.18s ease'
    }}>
      {/* Sidebar header: collapse toggle + logo */}
      <div style={{
        height: 48, flexShrink: 0,
        display: 'flex', alignItems: 'center',
        gap: 8, padding: collapsed ? '0' : '0 12px',
        justifyContent: collapsed ? 'center' : 'flex-start',
        borderBottom: '1px solid var(--sage-200)'
      }}>
        <button
          onClick={onToggleCollapsed}
          aria-label={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
          title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
          style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            width: 28, height: 28, borderRadius: 5,
            background: 'transparent', border: 0,
            color: 'var(--sage-500)', cursor: 'pointer',
            flexShrink: 0
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = 'var(--sage-100)'}
          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
          
          <V2Icon name="panelOpen" size={16} />
        </button>
        {!collapsed &&
        <React.Fragment>
            <img src="assets/clintech-mark.png" alt="Issued" style={{ height: 20, width: 'auto' }} />
            <span style={{
            fontSize: 14, fontWeight: 600,
            color: 'var(--sage-800)', letterSpacing: '-0.01em',
            fontFamily: 'var(--font-sans)'
          }}>Issued</span>
          </React.Fragment>
        }
      </div>

      {collapsed ? null :
      <React.Fragment>
      {/* Inline filter input */}
      {filterOpen &&
        <div style={{
          padding: '8px 10px 0 10px'
        }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '6px 8px', borderRadius: 6,
            background: 'var(--sage-100)', border: '1px solid var(--sage-200)'
          }}>
            <V2Icon name="search" size={12} stroke="var(--sage-500)" />
            <input
              ref={filterInputRef}
              value={filter}
              onChange={(e) => setFilter(e.target.value)}
              onKeyDown={(e) => {if (e.key === 'Escape') {setFilterOpen(false);setFilter('');}}}
              placeholder="Filter this list…"
              style={{
                flex: 1, border: 0, background: 'transparent', outline: 0,
                fontSize: 12, color: 'var(--sage-800)', fontFamily: 'var(--font-sans)'
              }} />
            
            <button
              onClick={() => {setFilterOpen(false);setFilter('');}}
              aria-label="Close filter"
              style={{ background: 'transparent', border: 0, padding: 2, cursor: 'pointer', color: 'var(--sage-500)', display: 'flex' }}>
              
              <V2Icon name="x" size={12} />
            </button>
          </div>
        </div>
        }

      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 8px 16px 8px' }}>
        <SectionHeader
            label={`Active patients · ${patients.length}`}
            rightAction={
            <button
              onClick={toggleFilter}
              aria-label="Filter list"
              title="Filter list"
              style={{
                background: filterOpen ? 'var(--primary-muted)' : 'transparent',
                color: filterOpen ? 'var(--primary)' : 'var(--sage-500)',
                border: 0, padding: 3, borderRadius: 4, cursor: 'pointer', display: 'flex'
              }}>
              
              <V2Icon name="search" size={12} />
            </button>
            } />
          

        {patients.filter(matches).length === 0 ?
          <div style={{ padding: '6px 10px', fontSize: 11, color: 'var(--sage-400)', fontStyle: 'italic' }}>
            No matches.
          </div> :
          patients.filter(matches).map((p) =>
          <PatientRow
            key={p.id}
            patient={p}
            expanded={p.id === activePatientId}
            onSelect={() => onSelectPatient(p.id)}
            notes={p.id === activePatientId ? notes[p.id] || [] : []}
            activeNoteId={activeNoteId}
            onSelectNote={onSelectNote}
            onDiscardDraft={onDiscardDraft}
            onNewNote={onNewNote} />

          )}

        <div style={{ height: 6 }} />

        <CollapsibleGroup label={`Inactive patients · ${inactiveTotal}`}>
          <SubsectionDivider label={`Last 7 days · ${inactive.last7.length}`} />
          {inactive.last7.filter(matches).map((p) =>
            <InactiveRow key={p.id} patient={p} />
            )}
          <SubsectionDivider label={`Last 30 days · ${inactive.last30.length}`} />
          {inactive.last30.filter(matches).map((p) =>
            <InactiveRow key={p.id} patient={p} />
            )}
          <SubsectionDivider label={`Earlier · ${inactive.earlierCount}`} />
          <button style={{
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              width: '100%', padding: '6px 6px',
              background: 'transparent', border: 0,
              color: 'var(--sage-500)', cursor: 'pointer',
              fontSize: 10, letterSpacing: '0.06em', textTransform: 'uppercase',
              fontWeight: 500, fontFamily: 'var(--font-sans)'
            }}>
            <span style={{ flex: 1, height: 1, background: 'var(--sage-200)' }} />
            <span>load · {inactive.earlierCount} earlier</span>
            <span style={{ flex: 1, height: 1, background: 'var(--sage-200)' }} />
          </button>
        </CollapsibleGroup>
      </div>

      <div style={{
          padding: 12, borderTop: '1px solid var(--sage-200)',
          fontSize: 11, color: 'var(--sage-400)', fontFamily: 'var(--font-sans)'
        }}>
        v0.34 · Royal Brisbane
      </div>
      </React.Fragment>
      }
    </aside>);

}

function SectionHeader({ label, rightAction }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 6,
      padding: '6px 8px 4px 8px'
    }}>
      <span style={{
        fontSize: 10, fontWeight: 600,
        letterSpacing: '0.06em', textTransform: 'uppercase',
        color: 'var(--sage-500)',
        flex: 1
      }}>{label}</span>
      {rightAction}
    </div>);

}

function CollapsibleGroup({ label, defaultOpen = false, children }) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div style={{ marginTop: 6 }}>
      <button
        onClick={() => setOpen((o) => !o)}
        style={{
          width: '100%', display: 'flex', alignItems: 'center', gap: 4,
          padding: '6px 8px',
          background: 'transparent', border: 0,
          cursor: 'pointer', textAlign: 'left',
          fontFamily: 'var(--font-sans)'
        }}>
        
        <V2Icon name={open ? 'chevronDown' : 'chevronRight'} size={11} stroke="var(--sage-500)" />
        <span style={{
          fontSize: 10, fontWeight: 600,
          letterSpacing: '0.06em', textTransform: 'uppercase',
          color: 'var(--sage-500)'
        }}>{label}</span>
      </button>
      {open && <div>{children}</div>}
    </div>);

}

function SubsectionDivider({ label }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      padding: '8px 6px 3px 6px',
      color: 'var(--sage-400)',
      fontSize: 9.5, fontWeight: 500,
      letterSpacing: '0.04em',
      fontFamily: 'var(--font-sans)',
      userSelect: 'none'
    }}>
      <span style={{ flex: 1, height: 1, background: 'currentColor', opacity: 0.35 }} />
      <span style={{ whiteSpace: 'nowrap' }}>{label.toLowerCase()}</span>
      <span style={{ flex: 1, height: 1, background: 'currentColor', opacity: 0.35 }} />
    </div>);

}

function StatusDot({ status }) {
  if (!status) return <span aria-hidden="true" style={{ width: 6, height: 6, flexShrink: 0 }} />;
  return (
    <span
      title={STATUS_LABEL[status]}
      aria-label={STATUS_LABEL[status]}
      style={{
        width: 6, height: 6, borderRadius: '50%',
        background: STATUS_COLOR[status],
        flexShrink: 0
      }} />);


}

function InactiveRow({ patient }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      padding: '5px 8px', borderRadius: 6,
      cursor: 'pointer', opacity: 0.75
    }}
    onMouseEnter={(e) => e.currentTarget.style.background = 'var(--sage-50)'}
    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
      
      <StatusDot status={null} />
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--sage-500)' }}>{patient.bed}</span>
          <span style={{
            fontSize: 12, fontWeight: 500, color: 'var(--sage-700)',
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
          }}>{patient.name}</span>
        </div>
        <div style={{
          fontSize: 10, color: 'var(--sage-500)',
          fontFamily: 'var(--font-mono)',
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
        }}>
          {patient.mrn} · disch {patient.dischargedOn}
        </div>
      </div>
    </div>);

}

function PatientRow({ patient, expanded, onSelect, notes, activeNoteId, onSelectNote, onDiscardDraft, onNewNote }) {
  return (
    <div style={{ marginBottom: 2 }}>
      <button
        onClick={onSelect}
        style={{
          width: '100%', textAlign: 'left',
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '6px 8px', borderRadius: 6,
          border: 0,
          background: expanded ? 'var(--primary-muted)' : 'transparent',
          borderLeft: expanded ? '2px solid var(--primary)' : '2px solid transparent',
          cursor: 'pointer',
          fontFamily: 'var(--font-sans)'
        }}
        onMouseEnter={(e) => {if (!expanded) e.currentTarget.style.background = 'var(--sage-50)';}}
        onMouseLeave={(e) => {if (!expanded) e.currentTarget.style.background = 'transparent';}}>
        
        <StatusDot status={patient.status} />
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
            <span style={{
              fontFamily: 'var(--font-mono)', fontSize: 10,
              color: expanded ? 'var(--primary)' : 'var(--sage-500)',
              fontWeight: expanded ? 600 : 400
            }}>{patient.bed}</span>
            <span style={{
              fontSize: 12, fontWeight: expanded ? 600 : 500,
              color: expanded ? 'var(--primary)' : 'var(--sage-700)',
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
            }}>{patient.name}</span>
          </div>
          <div style={{
            fontSize: 10, color: 'var(--sage-500)',
            fontFamily: 'var(--font-mono)',
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
          }}>
            {patient.mrn} · {patient.dob}
          </div>
        </div>
      </button>

      {expanded &&
      <div style={{
        marginLeft: 14, marginTop: 4, marginBottom: 8,
        paddingLeft: 12,
        borderLeft: '1px solid var(--sage-200)',
        display: 'flex', flexDirection: 'column', gap: 1
      }}>
          {notes.map((note) =>
        <NoteRow
          key={note.id}
          note={note}
          active={note.id === activeNoteId}
          onClick={() => onSelectNote(note.id)}
          onDiscard={() => onDiscardDraft(note.id)} />

        )}
          <button
          onClick={() => onNewNote(patient.id)}
          style={{
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '5px 8px', marginTop: 4,
            border: 0, background: 'transparent',
            color: 'var(--primary)', fontSize: 11.5, fontWeight: 500,
            cursor: 'pointer', borderRadius: 6,
            fontFamily: 'var(--font-sans)'
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = 'var(--sage-50)'}
          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'} data-comment-anchor="a08b06bcc0-button-362-11">
          
            <V2Icon name="plus" size={12} stroke="var(--primary)" />
            New note
          </button>
        </div>
      }
    </div>);

}

function NoteRow({ note, active, onClick, onDiscard }) {
  const [hover, setHover] = useState(false);
  const isDraft = note.state === 'draft' || note.state === 'analysing' ||
  note.state === 'ai_draft_ready' || note.state === 'user_reviewed';
  const subBadge = note.sub;

  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{ position: 'relative' }}>
      
      <button
        onClick={onClick}
        style={{
          width: '100%', textAlign: 'left', border: 0,
          padding: '6px 8px',
          background: active ? 'var(--sage-100)' : 'transparent',
          borderRadius: 6, cursor: 'pointer',
          display: 'flex', alignItems: 'flex-start', gap: 7,
          fontFamily: 'var(--font-sans)'
        }}>
        
        <span style={{
          width: 14, flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          marginTop: 2
        }}>
          {isDraft ?
          <V2Icon name="pencilOutline" size={11} stroke="var(--sage-500)" /> :

          <span style={{
            fontFamily: 'var(--font-mono)', fontSize: 9.5,
            color: 'var(--sage-400)', fontWeight: 600
          }}>{subBadge || ''}</span>
          }
        </span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 12, fontWeight: isDraft ? 600 : 500,
            color: 'var(--sage-700)',
            letterSpacing: '-0.005em',
            fontStyle: isDraft ? 'italic' : 'normal',
            display: 'flex', alignItems: 'center', gap: 5
          }}>
            <span>{note.type}</span>
            {isDraft && (() => {
              const isActive = note.state === 'analysing' || note.state === 'ai_draft_ready';
              const palette = isActive ?
              { bg: 'var(--ai-surface)', fg: 'var(--ai)', border: 'var(--ai-border)' } :
              { bg: 'var(--sage-100)', fg: 'var(--sage-600)', border: 'var(--sage-200)' };
              return (
                <span style={{
                  fontSize: 9.5, fontWeight: 600,
                  padding: '1px 5px', borderRadius: 9999,
                  background: palette.bg,
                  color: palette.fg,
                  letterSpacing: '0.04em',
                  border: `1px solid ${palette.border}`,
                  textTransform: 'uppercase'
                }}>
                  {note.state === 'analysing' ? 'analysing…' :
                  note.state === 'ai_draft_ready' ? 'ai ready' :
                  'draft'}
                </span>);

            })()}
          </div>
          <div style={{
            fontSize: 10.5, color: 'var(--sage-500)',
            fontFamily: 'var(--font-mono)', marginTop: 1
          }}>{note.startedAt}</div>
        </div>
      </button>
      {isDraft && hover &&
      <button
        onClick={(e) => {e.stopPropagation();onDiscard();}}
        aria-label="Discard draft"
        title="Discard draft"
        style={{
          position: 'absolute', right: 4, top: '50%', transform: 'translateY(-50%)',
          background: '#fff', border: '1px solid var(--sage-200)',
          width: 22, height: 22, borderRadius: 5,
          display: 'grid', placeItems: 'center',
          color: 'var(--sage-500)', cursor: 'pointer',
          boxShadow: 'var(--shadow-sm)'
        }}>
        
          <V2Icon name="trash" size={11} />
        </button>
      }
    </div>);

}

window.V2Sidebar = V2Sidebar;