// Home screen — greeting, streak, latest materials, subjects grid.

function Home({ onOpenMaterial, onNav }) {
  const { MATERIALS, SUBJECTS, LEVELS } = window.ECC_DATA;
  const latest = MATERIALS.slice(0, 4);

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

      {/* INTRO */}
      <section style={{ marginBottom: 40 }}>
        <Label>Apuntes y ejercicios · Matemáticas 4º ESO</Label>
        <h1 style={{ font: 'var(--type-h1)', letterSpacing: 'var(--tracking-tight)', margin: '6px 0 12px', maxWidth: 720 }}>
          Apuntes y ejercicios de la ESO,<br/>para estudiar en casa.
        </h1>
        <p style={{ font: 'var(--type-body-lg)', color: 'var(--ink-2)', margin: 0, maxWidth: 620 }}>
          Explicaciones claras y actividades que se corrigen solas, organizadas por unidades. Una ayuda para que padres e hijos repasen juntos y lleven el curso al día.
        </p>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '10px 22px', marginTop: 18 }}>
          {[
            { icon: 'lock',   text: 'Gratis y sin registro' },
            { icon: 'check',  text: 'Se corrige solo, al instante' },
            { icon: 'book',   text: 'Explicado paso a paso' },
          ].map(t => (
            <span key={t.text} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, font: 'var(--type-ui-sm)', color: 'var(--ink-2)' }}>
              <Icon name={t.icon} size={15} color="var(--terracotta)" strokeWidth={1.75} />
              {t.text}
            </span>
          ))}
        </div>
      </section>

      {/* LATEST */}
      <section style={{ marginBottom: 48 }}>
        <SectionHeader title="Últimos materiales" action={{ label: 'Ver todo →', onClick: () => onNav('library') }} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16 }}>
          {latest.map(m => <MaterialCard key={m.id} m={m} onClick={() => onOpenMaterial(m.id)} />)}
        </div>
      </section>

      {/* COURSES */}
      {LEVELS.length > 1 && (
      <section style={{ marginBottom: 48 }}>
        <SectionHeader title="Por curso" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16 }}>
          {LEVELS.map(lv => {
            const count = MATERIALS.filter(m => m.level === lv.id).length;
            return (
              <button key={lv.id} onClick={() => onNav('library', { level: lv.id })} style={{
                background: 'var(--bg-surface)',
                border: '1px solid var(--line)',
                borderRadius: 'var(--r-lg)',
                padding: '18px 20px',
                textAlign: 'left',
                cursor: 'pointer',
                transition: 'all var(--t-fast) var(--ease)',
                display: 'flex', alignItems: 'center', gap: 14,
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--ink-3)'; e.currentTarget.style.boxShadow = 'var(--shadow-hover)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.boxShadow = 'none'; }}>
                <div style={{
                  width: 44, height: 44, borderRadius: 'var(--r-md)',
                  background: 'var(--forest)', color: '#FBF8F0',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  font: 'var(--fw-medium) 15px/1 var(--font-mono)', flexShrink: 0,
                }}>{lv.id === '4eso' ? '4º' : '3º'}</div>
                <div>
                  <div style={{ font: 'var(--type-h4)', color: 'var(--ink)' }}>{lv.label}</div>
                  <div style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>{count} {count === 1 ? 'material' : 'materiales'}</div>
                </div>
                <Icon name="chevron" size={18} color="var(--ink-3)" style={{ marginLeft: 'auto' }} />
              </button>
            );
          })}
        </div>
      </section>
      )}

      {/* SUBJECTS */}
      <section style={{ marginBottom: 48 }}>
        <SectionHeader title="Por asignatura" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
          {SUBJECTS.filter(s => MATERIALS.some(m => m.subject === s.id)).map(s => {
            const count = MATERIALS.filter(m => m.subject === s.id).length;
            return (
              <button key={s.id} onClick={() => onNav('library', { subject: s.id })} style={{
                background: 'var(--bg-surface)',
                border: '1px solid var(--line)',
                borderLeft: `4px solid ${s.color}`,
                borderRadius: 'var(--r-lg)',
                padding: '16px 18px',
                textAlign: 'left',
                cursor: 'pointer',
                transition: 'all var(--t-fast) var(--ease)',
                display: 'flex', flexDirection: 'column', gap: 4,
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--ink-3)'; e.currentTarget.style.borderLeftColor = s.color; e.currentTarget.style.boxShadow = 'var(--shadow-hover)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.borderLeftColor = s.color; e.currentTarget.style.boxShadow = 'none'; }}>
                <div style={{ font: 'var(--type-h4)', color: 'var(--ink)' }}>{s.label}</div>
                <div style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>{count} {count === 1 ? 'material' : 'materiales'}</div>
              </button>
            );
          })}
        </div>
      </section>

      {/* HOW IT WORKS */}
      <section>
        <SectionHeader title="Cómo está organizado" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
          <HowItem icon="folder" title="Por asignatura" desc="Cada tema dentro de su materia. Mates, Lengua, Bio, Física, Historia." />
          <HowItem icon="file" title="Apuntes y ejercicios" desc="Resúmenes para entender, ejercicios para practicar, esquemas para repasar." />
          <HowItem icon="lock" title="Sin registro" desc="Todo abierto. Pronto habrá área privada para guardar progreso." />
        </div>
      </section>
    </main>
  );
}

function SectionHeader({ title, action }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
      marginBottom: 14, paddingBottom: 10, borderBottom: '1px solid var(--line)',
    }}>
      <h3 style={{ font: 'var(--type-h3)', margin: 0 }}>{title}</h3>
      {action && (
        <button onClick={action.onClick} style={{
          background: 'transparent', border: 0, font: 'var(--type-ui-sm)',
          color: 'var(--terracotta-deep)', cursor: 'pointer',
        }}>
          {action.label}
        </button>
      )}
    </div>
  );
}

function StreakCard() {
  const dots = [1,1,1,1,1,1,1,0,0,0];
  return (
    <div style={{
      background: 'var(--bg-surface)',
      border: '1px solid var(--line)',
      borderRadius: 'var(--r-lg)',
      padding: '16px 18px',
      display: 'flex', flexDirection: 'column', gap: 10,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <Icon name="flame" size={22} color="var(--terracotta)" strokeWidth={1.75} />
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
          <span style={{ font: 'var(--fw-medium) 28px/1 var(--font-mono)', color: 'var(--ink)' }}>7</span>
          <span style={{ font: 'var(--type-ui-sm)', color: 'var(--ink-3)' }}>días seguidos</span>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 4 }} aria-label="últimos 10 días">
        {dots.map((on, i) => (
          <div key={i} style={{
            width: 18, height: 18, borderRadius: 4,
            background: on ? 'var(--terracotta)' : 'var(--bg-muted)',
            border: `1px solid ${on ? 'var(--terracotta)' : 'var(--line)'}`,
          }}/>
        ))}
      </div>
      <div style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>
        ¡Sigue así! 3 días más para tu próximo logro.
      </div>
    </div>
  );
}

function MaterialCard({ m, onClick }) {
  const { SUBJECTS, KINDS } = window.ECC_DATA;
  const s = SUBJECTS.find(x => x.id === m.subject);
  const k = KINDS[m.kind];

  const cardProps = m.href
    ? { as: 'a', href: m.href }
    : { as: 'article', onClick };

  const sharedStyle = {
    background: 'var(--bg-surface)',
    border: '1px solid var(--line)',
    borderRadius: 'var(--r-lg)',
    padding: '18px 20px',
    display: 'flex', flexDirection: 'column', gap: 8,
    cursor: 'pointer',
    transition: 'all var(--t-fast) var(--ease)',
    textDecoration: 'none',
    color: 'inherit',
  };

  const inner = (
    <>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'space-between' }}>
        <Chip subject={m.subject} />
        {m.status === 'new' && <Badge kind="new">nuevo</Badge>}
      </div>
      <h4 style={{ font: 'var(--type-h4)', margin: '4px 0 0', color: 'var(--ink)' }}>{m.title}</h4>
      <p style={{ font: 'var(--type-body-sm)', color: 'var(--ink-2)', margin: 0 }}>{m.desc}</p>
      <div style={{ display: 'flex', gap: 10, font: 'var(--type-meta)', color: 'var(--ink-3)', marginTop: 4, alignItems: 'center', flexWrap: 'wrap' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, whiteSpace: 'nowrap' }}>
          <Icon name={k.icon} size={12} color="var(--ink-3)" />{k.label}
        </span>
        {m.pages && <><span>·</span><span style={{ whiteSpace: 'nowrap' }}>{m.pages} págs</span></>}
        {m.time && <><span>·</span><span style={{ whiteSpace: 'nowrap' }}>{m.time}</span></>}
        <span>·</span>
        <span style={{ whiteSpace: 'nowrap' }}>{m.updated}</span>
      </div>
    </>
  );

  const hoverHandlers = {
    onMouseEnter: e => { e.currentTarget.style.borderColor = 'var(--ink-3)'; e.currentTarget.style.boxShadow = 'var(--shadow-hover)'; },
    onMouseLeave: e => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.boxShadow = 'none'; },
  };

  if (m.href) {
    const isPdf = /\.pdf$/i.test(m.href);
    return (
      <a href={m.href}
         target={isPdf ? '_blank' : undefined}
         rel={isPdf ? 'noopener' : undefined}
         style={sharedStyle} {...hoverHandlers}>{inner}</a>
    );
  }
  return (
    <article onClick={onClick} style={sharedStyle} {...hoverHandlers}>{inner}</article>
  );
}

function ContinueRow({ material: m, onClick }) {
  if (!m) return null;
  const progress = m.progress || 0.25;
  return (
    <button onClick={onClick} style={{
      width: '100%',
      background: 'var(--bg-surface)',
      border: '1px solid var(--line)',
      borderRadius: 'var(--r-lg)',
      padding: '18px 20px',
      display: 'flex', alignItems: 'center', gap: 18,
      cursor: 'pointer', textAlign: 'left',
      transition: 'all var(--t-fast) var(--ease)',
    }}
    onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--ink-3)'; e.currentTarget.style.boxShadow = 'var(--shadow-hover)'; }}
    onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.boxShadow = 'none'; }}>
      <div style={{
        width: 48, height: 48, borderRadius: 8,
        background: 'var(--bg-muted)', border: '1px solid var(--line)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: 'var(--ink-2)',
      }}>
        <Icon name="pencil" size={22} />
      </div>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <Chip subject={m.subject} />
          <span style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>{m.chapter}</span>
        </div>
        <div style={{ font: 'var(--type-h4)', color: 'var(--ink)' }}>{m.title}</div>
        <div style={{
          height: 4, background: 'var(--bg-muted)', borderRadius: 4, overflow: 'hidden',
        }}>
          <div style={{ width: `${progress * 100}%`, height: '100%', background: 'var(--terracotta)' }}/>
        </div>
        <div style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>
          {Math.round(progress * 100)}% completado · 3 de 12 ejercicios
        </div>
      </div>
      <Icon name="chevron" size={18} color="var(--ink-3)" />
    </button>
  );
}

Object.assign(window, { Home, MaterialCard, SectionHeader });

function HowItem({ icon, title, desc }) {
  return (
    <div style={{
      background: 'var(--bg-surface)',
      border: '1px solid var(--line)',
      borderRadius: 'var(--r-lg)',
      padding: '16px 18px',
      display: 'flex', flexDirection: 'column', gap: 8,
    }}>
      <Icon name={icon} size={20} color="var(--terracotta)" strokeWidth={1.75} />
      <div style={{ font: 'var(--type-h4)', color: 'var(--ink)' }}>{title}</div>
      <p style={{ font: 'var(--type-body-sm)', color: 'var(--ink-2)', margin: 0 }}>{desc}</p>
    </div>
  );
}
