// MaterialDetail — reading view for a single material.

function MaterialDetail({ materialId, onBack }) {
  const { MATERIALS, SUBJECTS, KINDS, COMMENTS } = window.ECC_DATA;
  const m = MATERIALS.find(x => x.id === materialId);
  if (!m) return null;
  const s = SUBJECTS.find(x => x.id === m.subject);
  const k = KINDS[m.kind];
  const comments = COMMENTS[m.id] || [];

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

      {/* Breadcrumb */}
      <nav style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 20, font: 'var(--type-meta)', color: 'var(--ink-3)' }}>
        <button onClick={onBack} style={{
          background: 'none', border: 0, padding: 0,
          font: 'var(--type-meta)', color: 'var(--ink-3)', cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', gap: 4,
        }}>
          <Icon name="chevronL" size={12} /> Biblioteca
        </button>
        <span>/</span>
        <span style={{ color: s.color }}>{s.label}</span>
        <span>/</span>
        <span style={{ color: 'var(--ink-2)' }}>{m.chapter}</span>
      </nav>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, var(--w-reading)) 280px', gap: 56, alignItems: 'start', justifyContent: 'start' }}>

        {/* MAIN CONTENT */}
        <article>
          {/* Header */}
          <header style={{ marginBottom: 28, paddingBottom: 20, borderBottom: '1px solid var(--line)' }}>
            <div style={{ display: 'flex', gap: 8, marginBottom: 12, alignItems: 'center' }}>
              <Chip subject={m.subject} />
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                font: 'var(--type-ui-sm)', color: 'var(--ink-3)',
              }}>
                <Icon name={k.icon} size={14} color="var(--ink-3)" />
                {k.label}
              </span>
              <span style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>· {m.chapter}</span>
            </div>
            <h1 style={{ font: 'var(--type-h1)', letterSpacing: 'var(--tracking-tight)', margin: '0 0 12px' }}>
              {m.title}
            </h1>
            <p style={{ font: 'var(--type-body-lg)', color: 'var(--ink-2)', margin: 0 }}>{m.desc}</p>
            <div style={{ display: 'flex', gap: 14, marginTop: 16, font: 'var(--type-meta)', color: 'var(--ink-3)', alignItems: 'center' }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                <Icon name="clock" size={12} /> {m.time}
              </span>
              <span>·</span>
              <span>{m.pages} páginas</span>
              <span>·</span>
              <span>actualizado {m.updated}</span>
            </div>
          </header>

          {/* Body */}
          <div style={{ marginBottom: 40 }}>
            {m.body.map((block, i) => {
              const [tag, content] = block;
              if (tag === 'h3') return <h3 key={i} style={{ font: 'var(--type-h3)', margin: '32px 0 12px' }}>{content}</h3>;
              if (tag === 'p')  return <p key={i} style={{ font: 'var(--type-body)', margin: '0 0 16px', color: 'var(--ink)' }}>{content}</p>;
              if (tag === 'list') return (
                <ul key={i} style={{ font: 'var(--type-body)', margin: '0 0 16px', paddingLeft: 22, color: 'var(--ink)' }}>
                  {content.map((it, j) => <li key={j} style={{ marginBottom: 6 }}>{it}</li>)}
                </ul>
              );
              if (tag === 'note') return (
                <aside key={i} style={{
                  background: 'var(--bg-muted)',
                  borderLeft: '3px solid var(--amber-deep)',
                  padding: '12px 16px',
                  margin: '20px 0',
                  font: 'var(--type-body-sm)',
                  color: 'var(--ink-2)',
                  borderRadius: '0 var(--r-sm) var(--r-sm) 0',
                }}>
                  <Label style={{ display: 'block', marginBottom: 4, color: 'var(--amber-deep)' }}>Nota de papá</Label>
                  {content}
                </aside>
              );
              return null;
            })}
          </div>

          {/* Actions */}
          <div style={{ display: 'flex', gap: 10, paddingTop: 20, borderTop: '1px solid var(--line)' }}>
            <Button variant="primary" icon="check">Marcar como completado</Button>
            <Button variant="secondary" icon="bookmark">Guardar</Button>
            <Button variant="ghost" icon="download">Descargar PDF</Button>
          </div>

          {/* Comments */}
          {comments.length > 0 && (
            <section style={{ marginTop: 48 }}>
              <h3 style={{ font: 'var(--type-h3)', margin: '0 0 16px' }}>Comentarios</h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                {comments.map((c, i) => <CommentRow key={i} c={c} />)}
              </div>
              <CommentComposer />
            </section>
          )}
        </article>

        {/* SIDE TOC */}
        <aside style={{ position: 'sticky', top: 80 }}>
          <div style={{
            background: 'var(--bg-surface)',
            border: '1px solid var(--line)',
            borderRadius: 'var(--r-lg)',
            padding: '16px 18px',
          }}>
            <Label style={{ display: 'block', marginBottom: 12 }}>En esta página</Label>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
              {m.body.filter(b => b[0] === 'h3').map((b, i) => (
                <li key={i}>
                  <a style={{ font: 'var(--type-body-sm)', color: 'var(--ink-2)', textDecoration: 'none', cursor: 'pointer' }}>
                    {b[1]}
                  </a>
                </li>
              ))}
              {m.body.every(b => b[0] !== 'h3') && (
                <li style={{ font: 'var(--type-body-sm)', color: 'var(--ink-3)' }}>Sin secciones.</li>
              )}
            </ul>
          </div>

          <div style={{
            marginTop: 16,
            background: 'var(--bg-muted)',
            border: '1px solid var(--line)',
            borderRadius: 'var(--r-lg)',
            padding: '14px 16px',
          }}>
            <Label style={{ display: 'block', marginBottom: 6 }}>tu progreso</Label>
            <div style={{ font: 'var(--type-body-sm)', color: 'var(--ink-2)' }}>
              {m.status === 'done' ? 'Completado ✓' : m.status === 'in-progress' ? 'En progreso' : 'Aún no empezado'}
            </div>
          </div>
        </aside>

      </div>
    </main>
  );
}

function CommentRow({ c }) {
  const isPapa = c.who === 'papá';
  return (
    <div style={{ display: 'flex', gap: 12 }}>
      <Avatar
        initials={isPapa ? 'P' : 'C'}
        color={isPapa ? 'var(--forest)' : 'var(--terracotta)'}
        size={32}
      />
      <div style={{ flex: 1 }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'baseline', marginBottom: 4 }}>
          <span style={{ font: 'var(--type-ui-sm)', color: 'var(--ink)' }}>{c.who}</span>
          <span style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>{c.when}</span>
        </div>
        <p style={{ font: 'var(--type-body-sm)', color: 'var(--ink-2)', margin: 0 }}>{c.text}</p>
      </div>
    </div>
  );
}

function CommentComposer() {
  const [val, setVal] = React.useState('');
  return (
    <div style={{ marginTop: 20, display: 'flex', gap: 12 }}>
      <Avatar initials="C" color="var(--terracotta)" size={32} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
        <textarea value={val} onChange={e => setVal(e.target.value)} placeholder="Escribe un comentario…" rows={2} style={{
          background: 'var(--bg-surface)', border: '1px solid var(--line)',
          borderRadius: 'var(--r-md)', padding: '10px 12px',
          font: 'var(--type-body-sm)', color: 'var(--ink)', resize: 'vertical',
        }}/>
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <Button variant="primary" size="sm" disabled={!val.trim()}>Enviar</Button>
        </div>
      </div>
    </div>
  );
}

window.MaterialDetail = MaterialDetail;
