// Library screen — subject filter sidebar + grid of materials.

function Library({ initialSubject, initialLevel, onOpenMaterial }) {
  const { MATERIALS, SUBJECTS, KINDS, LEVELS } = window.ECC_DATA;
  const [level, setLevel] = React.useState(initialLevel || 'all');
  const [subject, setSubject] = React.useState(initialSubject || 'all');
  const [kind, setKind] = React.useState('all');
  const [query, setQuery] = React.useState('');
  const [sort, setSort] = React.useState('recent');

  let items = MATERIALS.slice();
  if (level !== 'all')   items = items.filter(m => m.level === level);
  if (subject !== 'all') items = items.filter(m => m.subject === subject);
  if (kind !== 'all')    items = items.filter(m => m.kind === kind);
  if (query) {
    const q = query.toLowerCase();
    items = items.filter(m => m.title.toLowerCase().includes(q) || m.desc.toLowerCase().includes(q));
  }
  if (sort === 'title') items.sort((a,b) => a.title.localeCompare(b.title));

  // only show kinds that exist in the data
  const kinds = Object.keys(KINDS).filter(k => MATERIALS.some(m => m.kind === k));

  return (
    <main style={{ maxWidth: 'var(--w-page)', margin: '0 auto', padding: '32px var(--pad-page) 64px' }}>

      <div style={{ marginBottom: 24 }}>
        <Label>biblioteca</Label>
        <h1 style={{ font: 'var(--type-h1)', letterSpacing: 'var(--tracking-tight)', margin: '6px 0 4px' }}>
          Todo el material
        </h1>
        <p style={{ font: 'var(--type-body)', color: 'var(--ink-2)', margin: 0 }}>
          {MATERIALS.length} materiales · Matemáticas 4º ESO
        </p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 32, alignItems: 'start' }}>

        {/* SIDEBAR */}
        <aside style={{ position: 'sticky', top: 80, display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div>
            <Label style={{ display: 'block', marginBottom: 10 }}>Curso</Label>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              <SidebarItem active={level === 'all'} onClick={() => setLevel('all')}>
                Todos los cursos <span style={{ marginLeft: 'auto', color: 'var(--ink-3)' }}>{MATERIALS.length}</span>
              </SidebarItem>
              {LEVELS.map(lv => {
                const n = MATERIALS.filter(m => m.level === lv.id).length;
                return (
                  <SidebarItem key={lv.id} active={level === lv.id} onClick={() => setLevel(lv.id)}>
                    {lv.label}
                    <span style={{ marginLeft: 'auto', color: 'var(--ink-3)' }}>{n}</span>
                  </SidebarItem>
                );
              })}
            </div>
          </div>

          <div>
            <Label style={{ display: 'block', marginBottom: 10 }}>Asignaturas</Label>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              <SidebarItem active={subject === 'all'} onClick={() => setSubject('all')}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--ink-3)' }}/>
                Todas <span style={{ marginLeft: 'auto', color: 'var(--ink-3)' }}>{MATERIALS.length}</span>
              </SidebarItem>
              {SUBJECTS.filter(s => MATERIALS.some(m => m.subject === s.id)).map(s => {
                const n = MATERIALS.filter(m => m.subject === s.id).length;
                return (
                  <SidebarItem key={s.id} active={subject === s.id} onClick={() => setSubject(s.id)}>
                    <span style={{ width: 8, height: 8, borderRadius: '50%', background: s.color }}/>
                    {s.label}
                    <span style={{ marginLeft: 'auto', color: 'var(--ink-3)' }}>{n}</span>
                  </SidebarItem>
                );
              })}
            </div>
          </div>

          <div>
            <Label style={{ display: 'block', marginBottom: 10 }}>Tipo</Label>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              <SidebarItem active={kind === 'all'} onClick={() => setKind('all')}>
                Todos
              </SidebarItem>
              {kinds.map(k => (
                <SidebarItem key={k} active={kind === k} onClick={() => setKind(k)}>
                  <Icon name={KINDS[k].icon} size={14} color="var(--ink-3)" />
                  {KINDS[k].label}
                </SidebarItem>
              ))}
            </div>
          </div>
        </aside>

        {/* CONTENT */}
        <div>
          {/* Search + sort */}
          <div style={{ display: 'flex', gap: 12, marginBottom: 20 }}>
            <div style={{
              flex: 1, display: 'flex', alignItems: 'center', gap: 10,
              background: 'var(--bg-surface)', border: '1px solid var(--line)',
              borderRadius: 'var(--r-md)', padding: '8px 12px',
            }}>
              <Icon name="search" size={16} color="var(--ink-3)" />
              <input value={query} onChange={e => setQuery(e.target.value)}
                placeholder="Buscar por título o descripción…"
                style={{
                  flex: 1, border: 0, outline: 0, background: 'transparent',
                  font: 'var(--type-body-sm)', color: 'var(--ink)',
                }}/>
            </div>
            <select value={sort} onChange={e => setSort(e.target.value)} style={{
              background: 'var(--bg-surface)', border: '1px solid var(--line)',
              borderRadius: 'var(--r-md)', padding: '8px 12px',
              font: 'var(--type-ui-sm)', color: 'var(--ink)',
            }}>
              <option value="recent">Más recientes</option>
              <option value="title">Por título</option>
            </select>
          </div>

          {/* Active filter chips */}
          {(level !== 'all' || subject !== 'all' || kind !== 'all') && (
            <div style={{ display: 'flex', gap: 8, marginBottom: 16, alignItems: 'center', flexWrap: 'wrap' }}>
              <span style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>Filtros:</span>
              {level !== 'all' && (
                <span style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  padding: '3px 10px', borderRadius: 'var(--r-pill)',
                  background: 'var(--forest)', color: '#FBF8F0', whiteSpace: 'nowrap',
                  font: 'var(--type-ui-sm)', cursor: 'pointer',
                }} onClick={() => setLevel('all')}>
                  {LEVELS.find(l => l.id === level)?.label} ×
                </span>
              )}
              {subject !== 'all' && <Chip subject={subject} active onClick={() => setSubject('all')} />}
              {kind !== 'all' && (
                <span style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  padding: '3px 10px', borderRadius: 'var(--r-pill)',
                  background: 'var(--bg-muted)', color: 'var(--ink-2)', border: '1px solid var(--line)',
                  font: 'var(--type-ui-sm)', cursor: 'pointer', whiteSpace: 'nowrap',
                }} onClick={() => setKind('all')}>
                  {KINDS[kind].label} ×
                </span>
              )}
            </div>
          )}

          {/* Grid */}
          {items.length === 0 ? (
            <EmptyState />
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16 }}>
              {items.map(m => <MaterialCard key={m.id} m={m} onClick={() => onOpenMaterial(m.id)} />)}
            </div>
          )}
        </div>

      </div>
    </main>
  );
}

function SidebarItem({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '7px 10px', borderRadius: 'var(--r-sm)',
      background: active ? 'var(--bg-muted)' : 'transparent',
      border: 0, color: active ? 'var(--ink)' : 'var(--ink-2)',
      font: 'var(--type-ui-sm)', cursor: 'pointer', textAlign: 'left',
      whiteSpace: 'nowrap',
      transition: 'background var(--t-fast) var(--ease)',
    }}>
      {children}
    </button>
  );
}

function EmptyState() {
  return (
    <div style={{
      background: 'var(--bg-surface)', border: '1px dashed var(--line-strong)',
      borderRadius: 'var(--r-lg)', padding: '48px 24px',
      textAlign: 'center',
    }}>
      <Icon name="folder" size={32} color="var(--ink-3)" />
      <p style={{ font: 'var(--type-body)', color: 'var(--ink-2)', margin: '12px 0 4px' }}>
        Sin resultados.
      </p>
      <p style={{ font: 'var(--type-body-sm)', color: 'var(--ink-3)', margin: 0 }}>
        Prueba a quitar algún filtro o cambia la búsqueda.
      </p>
    </div>
  );
}

window.Library = Library;
