// Trove — Home / landing screen
function HomeScreen({ onSearch, onOpenLibrary, onOpenResource, onOpenWiki, onOpenArticle, onOpenCalendar, onNavigate, variant = 1, presale }) {
  const [q, setQ] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [honeypot, setHoneypot] = React.useState('');
  const [waitlist, setWaitlist] = React.useState('idle'); // idle | sending | done | error

  async function submitWaitlist(e) {
    e.preventDefault();
    if (honeypot !== '') return; // bot
    setWaitlist('sending');
    try {
      const res = await fetch('/api/register-interest', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      if (!res.ok) throw new Error('Submission failed');
      setWaitlist('done');
      setEmail('');
    } catch (err) {
      setWaitlist('error');
    }
  }
  const { isMobile } = window.useViewport();
  const all = window.RESOURCES || [];
  const featured = all.filter(r => r.featured).slice(0, 6);
  // Homepage showcase: use the curated SHOWCASE_IDS order when set,
  // otherwise fall back to the most recently approved resources.
  const showcaseIds = window.SHOWCASE_IDS || [];
  const curated = showcaseIds
    .map(id => all.find(r => r.docId === id || r.id === `d-${id}`))
    .filter(Boolean);
  const popular = curated.length
    ? curated
    // Curated IDs live in Supabase; while that's still loading, show nothing here
    // rather than flashing unrelated sample resources.
    : (showcaseIds.length ? [] : [...all].sort((a, b) => new Date(b.approvedAt || 0) - new Date(a.approvedAt || 0) || a.id.localeCompare(b.id)).slice(0, 8));

  return (
    <div style={{ position: 'relative' }}>
      {/* Hero */}
      <section style={{
        position: 'relative',
        padding: isMobile ? '32px 20px 24px' : '44px 48px 32px',
        background: variant === 2 ? 'linear-gradient(180deg, var(--cool-100), var(--bg) 90%)'
          : variant === 3 ? 'var(--navy-900)'
          : 'var(--bg)',
        color: variant === 3 ? '#FFFFFF' : 'var(--fg)',
        borderBottom: variant === 3 ? 'none' : '1px solid var(--border)',
        overflow: 'visible',
      }}>
        {/* Decorative motif removed — the faint navy magnifying-glass only showed in light mode. */}

        <div style={{ maxWidth: 1184, margin: '0 auto', position: 'relative' }}>
          <h1 className="t-display" style={{ margin: '0 0 14px', textWrap: 'balance', maxWidth: presale ? 'none' : 820 }}>
            {presale ? (<>Free tools for the <em style={{ fontStyle: 'italic', color: 'var(--gold-deep)' }}>primary classroom</em>.</>) : (<>
            {variant === 1 && (<>The teaching library that just <em style={{ fontStyle: 'italic', color: 'var(--gold-deep)' }}>works</em>.</>)}
            {variant === 2 && (<>A quieter way to find <em style={{ fontStyle: 'italic', color: 'var(--gold-deep)' }}>classroom-ready</em> resources.</>)}
            {variant === 3 && (<>Carefully planned. <em style={{ fontStyle: 'italic', color: 'var(--gold-soft)' }}>Beautifully made.</em></>)}
            </>)}
          </h1>
          <p style={{ margin: '0 0 26px', fontSize: 18, lineHeight: 1.55, color: variant === 3 ? 'rgba(255,255,255,.78)' : 'var(--fg-muted)', maxWidth: presale ? 'none' : 640 }}>
            {presale
              ? 'Interactive whiteboard tools, plain-English explainers and a calendar of the school year. Free to use, no login, no subscription. Our resource library opens soon.'
              : <>
                  {variant === 1 && 'Search primary teaching resources across the KS1 and KS2 curriculum, every one written by a former primary teacher and aligned to the National Curriculum.'}
                  {variant === 2 && 'No clutter, no clip-art chaos. Just curriculum-aligned KS1 and KS2 resources for every primary subject, written, planned and quietly proofread by primary teachers.'}
                  {variant === 3 && 'A growing library of premium, teacher-made KS1 and KS2 resources across every primary subject. Search, preview and download, without the mess.'}
                </>}
          </p>

          {presale ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                <a href={window.TOOLS_URL} className="btn btn-accent btn-lg" style={{ textDecoration: 'none' }}>
                  Open the free tools<Icon.ArrowRight width="15" height="15" />
                </a>
                <button onClick={onOpenWiki} className="btn btn-lg">Browse the Wiki<Icon.ArrowRight width="15" height="15" /></button>
              </div>
              <window.DiscoverSearch onOpenArticle={onOpenArticle} onOpenCalendar={onOpenCalendar} />
            </div>
          ) : (
          <div style={{ maxWidth: 900 }}>
          <SmartSearchBar
            value={q}
            onChange={setQ}
            onSubmit={(query, resource) => {
              if (resource) onOpenResource(resource);
              else onSearch(query);
            }}
            onFilterChip={(chip) => onSearch(q, chip)}
            big
          />

          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 18, alignItems: 'center' }}>
            <span className="t-small" style={{ color: variant === 3 ? 'rgba(255,255,255,.6)' : 'var(--fg-subtle)' }}>Try</span>
            {['Year 1 phonics', 'Year 5 fractions', 'KS2 SATs revision', 'Iron Man unit'].map(p => (
              <button
                key={p}
                onClick={() => setQ(p)}
                className="pill"
                style={{
                  cursor: 'pointer',
                  background: variant === 3 ? 'rgba(255,255,255,.06)' : 'var(--bg-sunken)',
                  borderColor: variant === 3 ? 'rgba(255,255,255,.14)' : 'var(--border)',
                  color: variant === 3 ? 'rgba(255,255,255,.85)' : 'var(--fg-muted)',
                  fontWeight: 500,
                }}>{p}</button>
            ))}
            <button
              onClick={onOpenLibrary}
              className="btn btn-sm"
              style={{
                marginLeft: 'auto', color: variant === 3 ? '#FFFFFF' : 'var(--fg)',
                fontWeight: 600,
              }}>
              Browse the entire library<Icon.ArrowRight width="15" height="15" />
            </button>
          </div>
          </div>
          )}
        </div>
      </section>

      {presale && <window.ShowcaseStrip />}

      {presale && <window.ThisWeek onOpenCalendar={onOpenCalendar} onOpenArticle={onOpenArticle} />}

      {/* Pre-sale: free toolkit, front and centre (this is what's actually usable now) */}
      {presale && (
        <section style={{ padding: isMobile ? '36px 20px 8px' : '52px 48px 12px', maxWidth: 1280, margin: '0 auto', width: '100%' }}>
          <div style={{ marginBottom: 22 }}>
            <div className="t-micro" style={{ color: 'var(--gold-deep)', marginBottom: 6 }}>Free to use right now, no account needed</div>
            <h2 className="t-h1" style={{ margin: 0 }}>Also free, also ready now</h2>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(auto-fit, minmax(240px, 1fr))', gap: 16 }}>
            {[
              { onClick: onOpenWiki, tag: 'Wiki', title: 'Primary Wiki', blurb: 'Plain-English explainers for the questions pupils and parents actually ask.', meta: '135 articles' },
              { onClick: onOpenCalendar, tag: 'Calendar', title: 'School calendar', blurb: 'Festivals, awareness days and term markers across the whole school year.', meta: 'The year ahead' },
            ].map(c => {
              const inner = (<>
                <div className="t-micro" style={{ color: 'var(--gold-deep)' }}>{c.tag}</div>
                <h3 className="t-h3" style={{ margin: 0 }}>{c.title}</h3>
                <p className="t-small" style={{ color: 'var(--fg-muted)', margin: 0, lineHeight: 1.5, textWrap: 'pretty', flex: 1 }}>{c.blurb}</p>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 2 }}>
                  <span className="t-small" style={{ color: 'var(--fg-subtle)', fontWeight: 600 }}>{c.meta}</span>
                  <Icon.ArrowRight width="16" height="16" style={{ color: 'var(--gold-deep)' }} />
                </div>
              </>);
              const cardStyle = { padding: 22, textAlign: 'left', cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 10, background: 'var(--surface)', minHeight: 176 };
              return c.href ? (
                <a key={c.tag} href={c.href} className="card" style={{ ...cardStyle, textDecoration: 'none', color: 'inherit' }}>{inner}</a>
              ) : (
                <button key={c.tag} onClick={c.onClick} className="card" style={cardStyle}>{inner}</button>
              );
            })}
          </div>
        </section>
      )}


      {/* Trending strip — the single library peek kept in pre-sale */}
      {popular.length > 0 && (
      <section style={{ padding: isMobile ? '24px 20px 16px' : '36px 48px 24px', maxWidth: 1280, margin: '0 auto', width: '100%' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 22 }}>
          <div>
            <div className="t-micro" style={{ color: 'var(--gold-deep)', marginBottom: 6 }}>{presale ? 'A sample of the library' : 'Most downloaded this term'}</div>
            <h2 className="t-h1" style={{ margin: 0 }}>{presale ? 'A few resources we’re finishing' : 'What teachers are using right now'}</h2>
            {presale && <p className="t-small" style={{ color: 'var(--fg-subtle)', margin: '8px 0 0', maxWidth: 520, lineHeight: 1.5 }}>Previews only, to show the standard we’re working to. Nothing is on sale yet.</p>}
          </div>
        </div>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
          gap: 16,
        }}>
          {popular.map(r => (
            <ResourceCard key={r.id} resource={r} onClick={() => onOpenResource(r)} />
          ))}
        </div>
      </section>
      )}


      {/* Pre-sale: a “coming soon” prompt replaces the pricing/subscription banner */}
      {presale && (
        <section style={{ padding: isMobile ? '36px 20px 60px' : '52px 48px 80px', maxWidth: 1280, margin: '0 auto', width: '100%' }}>
          <div className="card" style={{
            padding: isMobile ? '28px 22px' : '40px 48px',
            background: variant === 3 ? 'var(--surface)' : 'var(--navy-900)',
            color: variant === 3 ? 'var(--fg)' : '#FFFFFF',
            border: variant === 3 ? '1px solid var(--border)' : 'none',
            display: 'flex', flexDirection: 'column', gap: 16, alignItems: 'flex-start',
            position: 'relative', overflow: 'hidden',
          }}>
            <svg aria-hidden="true" width="320" height="320" viewBox="0 0 200 200" style={{ position: 'absolute', right: -60, bottom: -140, opacity: .07, color: 'var(--gold)', pointerEvents: 'none' }}>
              <g stroke="currentColor" strokeWidth=".6" fill="none"><circle cx="100" cy="100" r="48" /><path d="M100 148 v44 M92 176 h16 M92 184 h12" /></g>
            </svg>
            <div className="t-micro" style={{ color: 'var(--gold)' }}>Resource library coming soon</div>
            <h3 style={{ fontFamily: 'var(--font-serif)', fontWeight: 400, fontSize: 36, lineHeight: 1.1, margin: 0, letterSpacing: '-.02em' }}>
              The full library opens soon.
            </h3>
            <p style={{ margin: 0, color: variant === 3 ? 'var(--fg-muted)' : 'rgba(255,255,255,.74)', maxWidth: 900, lineHeight: 1.55 }}>
              We’re finishing the last resources before they go on sale. Every one is written and checked by primary teachers, and mapped to the National Curriculum. Leave your email and we’ll tell you the moment it opens.
            </p>
            {/* Waitlist capture — posts to /api/register-interest (same endpoint as the holding page). */}
            <form onSubmit={submitWaitlist} style={{ display: 'flex', gap: 10, marginTop: 8, flexWrap: 'wrap', width: '100%', maxWidth: 640 }}>
              <input type="text" name="b_username" tabIndex="-1" autoComplete="off" aria-hidden="true"
                value={honeypot} onChange={(e) => setHoneypot(e.target.value)}
                style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }} />
              <input type="email" required placeholder="you@school.sch.uk" aria-label="Email address"
                value={email} onChange={(e) => setEmail(e.target.value)} disabled={waitlist === 'sending'}
                style={{ flex: '1 1 220px', minWidth: 0, padding: '13px 16px', fontSize: 15, fontFamily: 'inherit', borderRadius: 'var(--radius)',
                         border: variant === 3 ? '1px solid var(--border)' : '1px solid rgba(255,255,255,.22)',
                         background: variant === 3 ? 'var(--bg)' : 'rgba(255,255,255,.08)',
                         color: variant === 3 ? 'var(--fg)' : '#FFFFFF' }} />
              <button type="submit" className="btn btn-accent btn-lg" disabled={waitlist === 'sending'}>
                {waitlist === 'sending' ? 'Joining…' : 'Notify me'}
              </button>
            </form>
            {waitlist === 'done' && (
              <p role="status" style={{ margin: 0, fontSize: 14, fontWeight: 600, color: variant === 3 ? 'oklch(0.52 0.13 150)' : '#86EFAC' }}>
                You’re on the list. We’ll email you when the library opens.
              </p>
            )}
            {waitlist === 'error' && (
              <p role="status" style={{ margin: 0, fontSize: 14, fontWeight: 600, color: variant === 3 ? 'oklch(0.55 0.16 25)' : '#FCA5A5' }}>
                Something went wrong. Please try again.
              </p>
            )}
            <p style={{ margin: 0, fontSize: 12.5, lineHeight: 1.5, color: variant === 3 ? 'var(--fg-subtle)' : 'rgba(255,255,255,.6)', maxWidth: 900 }}>
              We’ll only use your email to tell you when the library opens. No other marketing, and you can unsubscribe at any time. See our <button type="button" onClick={() => onNavigate('privacy')} style={{ background: 'none', border: 0, padding: 0, cursor: 'pointer', font: 'inherit', color: variant === 3 ? 'var(--gold-deep)' : 'var(--gold-soft)', textDecoration: 'underline', textUnderlineOffset: 2 }}>privacy notice</button>.
            </p>
            <button onClick={onOpenWiki} className={`btn btn-sm ${variant === 3 ? 'btn-ghost' : 'btn-on-dark'}`} style={{ marginTop: 2 }}>Explore the free Wiki<Icon.ArrowRight width="15" height="15" /></button>
          </div>
        </section>
      )}

    </div>
  );
}

window.HomeScreen = HomeScreen;
