// Trove — Resource detail modal

function ResourcePopup({ resource, onClose, presale }) {
  const r = resource;
  // Stack to a single column on tablet-portrait widths too (a 440px preview + details is too wide below ~960px).
  const { isTablet: isMobile } = window.useViewport();
  const [pageIndex, setPageIndex] = React.useState(0);

  React.useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') onClose(); }
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [onClose]);

  // Preview pages: for a real thumbnail, however many pages are in the image.
  // Without one, keep the three stylised cover variants.
  const thumbPages = window.useThumbPages(r.thumbnail);
  const pageCount = r.thumbnail ? thumbPages : 3;
  React.useEffect(() => { setPageIndex(0); }, [r.id, pageCount]);

  const related = window.RESOURCES
    .filter(x => x.id !== r.id && (x.subject === r.subject) && (x.ks === r.ks))
    .slice(0, 4);

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, background: 'rgba(15,26,48,.55)',
        backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
        zIndex: 100, display: 'flex', alignItems: isMobile ? 'flex-start' : 'center', justifyContent: 'center',
        padding: isMobile ? 10 : 32, animation: 'fade-in .2s ease both',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="fade-in-scale"
        style={{
          background: 'var(--bg)', borderRadius: 18,
          width: 'min(1100px, 100%)', maxHeight: isMobile ? 'calc(100vh - 20px)' : 'calc(100vh - 64px)',
          display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '440px 1fr',
          overflowY: isMobile ? 'auto' : 'hidden', overflowX: 'hidden', boxShadow: 'var(--shadow-xl)',
          border: '1px solid var(--border)',
        }}
      >
        {/* Mobile: a big fixed close button, so it's always reachable without
            scrolling past the preview image. */}
        {isMobile && (
          <button onClick={onClose} aria-label="Close"
            style={{
              position: 'fixed', top: 18, right: 18, zIndex: 120,
              width: 46, height: 46, borderRadius: 999, cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              background: 'var(--navy-950)', color: '#FFFFFF',
              border: '1px solid rgba(255,255,255,.28)', boxShadow: '0 10px 24px -8px rgba(15,26,48,.55)',
            }}>
            <Icon.X width="24" height="24" />
          </button>
        )}

        {/* LEFT — Preview */}
        <div style={{
          background: 'var(--bg-sunken)', borderRight: isMobile ? 'none' : '1px solid var(--border)',
          borderBottom: isMobile ? '1px solid var(--border)' : 'none',
          padding: isMobile ? '22px 20px 18px' : '32px 32px 24px', display: 'flex', flexDirection: 'column',
        }}>
          <div style={{
            flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
            position: 'relative',
          }}>
            <div style={{
              width: '100%', maxWidth: 320,
              boxShadow: '0 30px 60px -20px rgba(20,33,61,.35), 0 12px 24px -12px rgba(20,33,61,.25)',
              transform: 'rotate(-1.2deg)',
              transition: 'transform .3s',
            }}>
              <ResourceCover resource={r} size="lg" page={r.thumbnail ? pageIndex : null} />
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 20 }}>
            <div style={{ display: 'flex', gap: 6 }}>
              {Array.from({ length: pageCount }).map((_, i) => (
                <button key={i} onClick={() => setPageIndex(i)}
                  aria-label={'Page ' + (i+1)}
                  style={{
                    width: i === pageIndex ? 22 : 8, height: 8, borderRadius: 4,
                    background: i === pageIndex ? 'var(--navy-900)' : 'var(--cool-300)',
                    border: 0, cursor: 'pointer', transition: 'all .2s',
                  }}/>
              ))}
            </div>
            <span className="t-small" style={{ color: 'var(--fg-muted)' }}>{pageCount > 1 ? `Page ${pageIndex+1} of ${pageCount}` : 'Preview'}</span>
          </div>
          <div style={{ marginTop: 22, padding: '14px 16px', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 12 }}>
            <div className="t-micro" style={{ color: 'var(--fg-subtle)', marginBottom: 6 }}>Curriculum alignment</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{
                fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 600,
                padding: '4px 8px', background: 'color-mix(in oklab, var(--accent) 16%, var(--bg))',
                color: 'var(--gold-deep)', borderRadius: 6, letterSpacing: '.02em',
              }}>{r.objective}</span>
              <span className="t-small" style={{ color: 'var(--fg-muted)', flex: 1, textWrap: 'pretty' }}>
                {r.objectiveText}
              </span>
            </div>
          </div>
        </div>

        {/* RIGHT — Details */}
        <div style={{ display: 'flex', flexDirection: 'column', maxHeight: isMobile ? 'none' : 'calc(100vh - 64px)' }}>
          <div style={{ padding: '20px 28px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              <span className={'pill ' + (r.ks === 'KS1' ? 'pill-ks1' : 'pill-ks2')}>{r.ks} · {r.year}</span>
              <span className="pill">{r.subject} · {r.strand}</span>
              <span className="pill">{r.type}</span>
            </div>
            {!isMobile && (
              <button onClick={onClose} className="btn btn-sm" style={{ padding: 6 }} aria-label="Close">
                <Icon.X width="18" height="18" />
              </button>
            )}
          </div>

          <div style={{ padding: '14px 28px 0', overflow: isMobile ? 'visible' : 'auto', flex: 1 }}>
            <h2 style={{ fontFamily: 'var(--font-serif)', fontWeight: 500, fontSize: 30, lineHeight: 1.15, margin: '8px 0 10px', letterSpacing: '-.014em', textWrap: 'pretty' }}>
              {r.title}
            </h2>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, color: 'var(--fg-muted)', fontSize: 13.5 }}>
              <Stars value={r.rating} count={r.reviews} />
              <span>·</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon.Pages width="14" height="14"/>{r.pages} pages</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon.Lessons width="14" height="14"/>{r.lessons} lessons</span>
              <span style={{ marginLeft: 'auto', fontSize: 12 }}>Scheme: <strong style={{ color: 'var(--fg)' }}>{r.scheme}</strong></span>
            </div>

            <p style={{ marginTop: 18, color: 'var(--fg)', lineHeight: 1.6, textWrap: 'pretty' }}>{r.description}</p>

            {/* Learning objectives */}
            <div style={{ marginTop: 22 }}>
              <div className="t-micro" style={{ color: 'var(--fg-muted)', marginBottom: 10 }}>Learning objectives</div>
              <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 8 }}>
                {[
                  r.objectiveText,
                  'Apply the skill in varied written and spoken contexts.',
                  'Self-assess against the success criteria provided.',
                ].map((t, i) => (
                  <li key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                    <span style={{ width: 18, height: 18, marginTop: 1, flexShrink: 0, borderRadius: '50%', background: 'color-mix(in oklab, var(--accent) 22%, var(--bg))', color: 'var(--gold-deep)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                      <Icon.Check width="11" height="11" />
                    </span>
                    <span style={{ fontSize: 14, color: 'var(--fg)' }}>{t}</span>
                  </li>
                ))}
              </ul>
            </div>

            {/* What's included */}
            <div style={{ marginTop: 24 }}>
              <div className="t-micro" style={{ color: 'var(--fg-muted)', marginBottom: 10 }}>What’s included</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
                {r.includes.map((t, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '9px 12px', border: '1px solid var(--border)', borderRadius: 10, fontSize: 13.5, background: 'var(--surface)' }}>
                    <Icon.Pages width="14" height="14" style={{ color: 'var(--fg-muted)', flexShrink: 0 }} />
                    <span>{t}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* Related */}
            {related.length > 0 && (
              <div style={{ marginTop: 28, marginBottom: 16 }}>
                <div className="t-micro" style={{ color: 'var(--fg-muted)', marginBottom: 10 }}>{presale ? 'Related resources' : 'Teachers also downloaded'}</div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
                  {related.slice(0, 2).map(rel => (
                    <div key={rel.id} className="card" style={{ display: 'flex', gap: 10, padding: 10, alignItems: 'center', background: 'var(--surface)' }}>
                      <div style={{ width: 40, flexShrink: 0 }}><ResourceCover resource={rel} /></div>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.3, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{rel.title}</div>
                        <div style={{ fontSize: 11.5, color: 'var(--fg-muted)' }}>{rel.year} · {rel.subject}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Sticky CTA footer */}
          <div style={{ padding: '16px 28px', borderTop: '1px solid var(--border)', background: 'var(--surface)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ width: 38, height: 38, flexShrink: 0, borderRadius: 10, background: 'color-mix(in oklab, var(--accent) 18%, var(--bg))', color: 'var(--gold-deep)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon.Sparkle width="18" height="18" />
              </span>
              <div>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg)' }}>Teaching resource library coming soon</div>
                <div style={{ fontSize: 13, color: 'var(--fg-muted)' }}>This pack isn’t available to download yet. The full library opens shortly.</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.ResourcePopup = ResourcePopup;
