// Leonard's Farm full-screen article reader for the learning center.
// Opens over the page when a guide's "Read more" is clicked. Preserves site
// styling, tokens and gentle motion; scroll-locks the page while open.
const LFReaderBtn = Button;
const LFReaderCard = ArticleCard;

function ArticleReader({ guide, onClose, onNavigate }) {
  const [visible, setVisible] = React.useState(false);
  const scrollRef = React.useRef(null);

  // Entrance animation
  React.useEffect(() => {
    const id = requestAnimationFrame(() => setVisible(true));
    return () => cancelAnimationFrame(id);
  }, []);

  // Lock page scroll while the reader is open
  React.useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, []);

  // Escape closes; reset scroll to top when switching guides
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') requestClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [guide.slug]);

  const requestClose = () => {
    setVisible(false);
    setTimeout(onClose, 320);
  };

  const relatedGuides = (guide.related || [])
    .map((s) => window.LF_GUIDES.find((g) => g.slug === s))
    .filter(Boolean);

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label={guide.title}
      onClick={(e) => { if (e.target === e.currentTarget) requestClose(); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(15,36,27,0.5)',
        backdropFilter: 'blur(3px)',
        opacity: visible ? 1 : 0,
        transition: 'opacity var(--dur) var(--ease-out)',
        overflow: 'hidden',
      }}
    >
      <div
        ref={scrollRef}
        style={{
          position: 'absolute', inset: 0,
          overflowY: 'auto',
          background: 'var(--surface-page)',
          transform: visible ? 'translateY(0)' : 'translateY(24px)',
          opacity: visible ? 1 : 0,
          transition: 'transform var(--dur-slow) var(--ease-out), opacity var(--dur) var(--ease-out)',
        }}
      >
        {/* Slim sticky bar */}
        <div style={{
          position: 'sticky', top: 0, zIndex: 5,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          gap: 'var(--space-4)',
          padding: '12px var(--gutter)',
          background: 'rgba(250,248,241,0.9)',
          backdropFilter: 'blur(10px)',
          borderBottom: '1px solid var(--border-subtle)',
        }}>
          <button
            onClick={requestClose}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: '0.5em',
              background: 'none', border: 'none', cursor: 'pointer',
              fontFamily: 'var(--font-body)', fontSize: 'var(--fs-sm)', fontWeight: 'var(--fw-semibold)',
              color: 'var(--brand-primary-dark)', padding: '6px 4px',
            }}
          >
            <span aria-hidden="true">&larr;</span> All guides
          </button>
          <button
            onClick={requestClose}
            aria-label="Close"
            style={{
              width: 38, height: 38, borderRadius: 'var(--radius-pill)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              background: 'var(--surface-card)', border: '1px solid var(--border)',
              cursor: 'pointer', color: 'var(--text-body)', fontSize: '1.1rem', lineHeight: 1,
            }}
          >
            &#10005;
          </button>
        </div>

        {/* Hero */}
        <div style={{ maxWidth: 'var(--container)', margin: '0 auto', padding: 'var(--space-6) var(--gutter) 0' }}>
          <div style={{
            position: 'relative', width: '100%', borderRadius: 'var(--radius-xl)', overflow: 'hidden',
            boxShadow: 'var(--shadow-lg)', aspectRatio: '16 / 8', minHeight: 260,
            background: `#176334 center/cover no-repeat url("${guide.image}")`,
          }}>
            <div aria-hidden="true" style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(15,58,32,0.05) 30%, rgba(15,58,32,0.72) 100%)' }} />
            <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: 'var(--space-6)' }}>
              <span style={{
                display: 'inline-block', padding: '5px 13px', borderRadius: 'var(--radius-pill)',
                background: 'rgba(255,255,255,0.9)', color: 'var(--water-700)',
                fontFamily: 'var(--font-body)', fontSize: 'var(--fs-xs)', fontWeight: 'var(--fw-semibold)',
              }}>{guide.topic}</span>
            </div>
          </div>
        </div>

        {/* Article body */}
        <article style={{ maxWidth: 'var(--container-narrow)', margin: '0 auto', padding: 'var(--space-7) var(--gutter) var(--space-9)' }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: '0.6em',
            fontFamily: 'var(--font-body)', fontSize: 'var(--fs-sm)', color: 'var(--text-muted)',
            marginBottom: 'var(--space-4)',
          }}>
            <span style={{ color: 'var(--brand-primary)', fontWeight: 'var(--fw-semibold)' }}>{guide.topic}</span>
            <span aria-hidden="true">&middot;</span>
            <span>{guide.readTime}</span>
          </div>

          <h1 style={{ fontSize: 'var(--fs-h1)', letterSpacing: 'var(--ls-tight)', lineHeight: 'var(--lh-heading)', color: 'var(--text-heading)' }}>
            {guide.title}
          </h1>

          <p style={{ marginTop: 'var(--space-5)', fontSize: 'var(--fs-lead)', lineHeight: 'var(--lh-body)', color: 'var(--text-body)' }}>
            {guide.intro}
          </p>

          {guide.sections.map((sec, i) => (
            <div key={i} style={{ marginTop: 'var(--space-7)' }}>
              <h2 style={{ fontSize: 'var(--fs-h3)', color: 'var(--text-heading)', letterSpacing: 'var(--ls-tight)' }}>{sec.heading}</h2>
              {sec.paras.map((p, j) => (
                <p key={j} style={{ marginTop: 'var(--space-4)', fontSize: 'var(--fs-body)', lineHeight: 'var(--lh-body)', color: 'var(--text-body)' }}>{p}</p>
              ))}
              {sec.bullets && (
                <ul style={{ marginTop: 'var(--space-4)', paddingLeft: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
                  {sec.bullets.map((b, k) => (
                    <li key={k} style={{ display: 'flex', gap: 'var(--space-3)', fontSize: 'var(--fs-body)', lineHeight: 'var(--lh-snug)', color: 'var(--text-body)' }}>
                      <span aria-hidden="true" style={{ flex: 'none', marginTop: '0.5em', width: 7, height: 7, borderRadius: '50%', background: 'var(--brand-accent)' }} />
                      <span>{b}</span>
                    </li>
                  ))}
                </ul>
              )}
            </div>
          ))}

          {/* Key takeaways / quick tips */}
          {guide.tips && (
            <div style={{
              marginTop: 'var(--space-8)',
              background: 'var(--surface-brand-soft)',
              border: '1px solid var(--green-200)',
              borderRadius: 'var(--radius-lg)',
              padding: 'var(--space-6)',
            }}>
              <div style={{
                fontFamily: 'var(--font-body)', fontWeight: 'var(--fw-semibold)',
                fontSize: 'var(--fs-eyebrow)', letterSpacing: 'var(--ls-eyebrow)', textTransform: 'uppercase',
                color: 'var(--brand-primary-dark)', marginBottom: 'var(--space-4)',
              }}>{guide.tips.label}</div>
              <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
                {guide.tips.items.map((t, i) => (
                  <li key={i} style={{ display: 'flex', gap: 'var(--space-3)', fontSize: 'var(--fs-body)', lineHeight: 'var(--lh-snug)', color: 'var(--text-body)' }}>
                    <span aria-hidden="true" style={{ flex: 'none', color: 'var(--brand-primary)', fontWeight: 'var(--fw-bold)' }}>&#10003;</span>
                    <span>{t}</span>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </article>

        {/* Related guides */}
        {relatedGuides.length > 0 && (
          <div style={{ background: 'var(--surface-sunk)', borderTop: '1px solid var(--border-subtle)' }}>
            <div style={{ maxWidth: 'var(--container)', margin: '0 auto', padding: 'var(--section-y) var(--gutter)' }}>
              <div style={{
                fontFamily: 'var(--font-body)', fontWeight: 'var(--fw-semibold)',
                fontSize: 'var(--fs-eyebrow)', letterSpacing: 'var(--ls-eyebrow)', textTransform: 'uppercase',
                color: 'var(--brand-primary)', marginBottom: 'var(--space-5)',
              }}>Related guides</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 'var(--space-5)', alignItems: 'stretch' }}>
                {relatedGuides.map((g) => (
                  <LFReaderCard
                    key={g.slug}
                    topic={g.topic}
                    title={g.title}
                    summary={g.summary}
                    readTime={g.readTime}
                    image={g.image}
                    href="#learn"
                    onClick={(e) => { e.preventDefault(); onNavigate(g.slug); }}
                  />
                ))}
              </div>
              <div style={{ marginTop: 'var(--space-6)' }}>
                <LFReaderBtn variant="secondary" onClick={requestClose}>&larr; Back to all guides</LFReaderBtn>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.ArticleReader = ArticleReader;
