/* eslint-disable */
// Search screen — filters all articles by a free-text query against title,
// lead, category, author and body paragraphs.

const SearchScreen = ({ setRoute, query: initialQuery = '' }) => {
  const t   = (window.useT   && window.useT())   || ((k) => k);
  const lang = (window.useLang && window.useLang().lang) || 'nl';

  const [query, setQuery] = React.useState(decodeURIComponent(initialQuery));
  const inputRef = React.useRef(null);

  React.useEffect(() => { window.scrollTo({ top: 0, behavior: 'instant' }); }, []);
  React.useEffect(() => { if (inputRef.current) inputRef.current.focus(); }, []);

  // Sync query back into the URL hash so back/forward works.
  React.useEffect(() => {
    const encoded = encodeURIComponent(query);
    const desired = query ? '#/search/' + encoded : '#/search';
    if (window.location.hash !== desired) {
      window.history.replaceState(null, '', desired);
    }
  }, [query]);

  const results = React.useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return [];
    const slugs = Object.keys(window.ARTICLES || {});
    return slugs.reduce((acc, slug) => {
      const a = window.ARTICLES[slug];
      const b = a[lang] || a.nl || a.en;
      if (!b) return acc;
      const haystack = [
        b.title || '', b.lead || '', b.category || '',
        a.author || '',
        ...(b.paragraphs || []),
      ].join(' ').toLowerCase();
      if (haystack.includes(q)) {
        acc.push({
          slug, image: a.image, author: a.author,
          date: b.date, date_iso: a.date_iso || '',
          category: b.category, title: b.title, excerpt: b.lead,
        });
      }
      return acc;
    }, []).sort((x, y) => (y.date_iso || '').localeCompare(x.date_iso || ''));
  }, [query, lang]);

  const handleNavigate = (slug) => {
    window.currentArticleSlug = slug;
    setRoute('article');
  };

  return (
    <div data-screen-label="Search">
      <section className="cbm-section cbm-section--dark" style={{paddingTop: 72, paddingBottom: 40}}>
        <div className="cbm-section__inner">
          <span className="cbm-eyebrow">Zoeken</span>
          <div className="cbm-section-rule" />
          <h1 className="cbm-section__title" style={{marginBottom: 24}}>Wat zoek je?</h1>
          <div style={{display:'flex', gap: 10, maxWidth: 560}}>
            <input
              ref={inputRef}
              value={query}
              onChange={e => setQuery(e.target.value)}
              placeholder="Zoek artikelen…"
              style={{
                flex: 1, padding: '12px 16px', fontSize: 16,
                border: '1px solid rgba(255,255,255,0.3)', borderRadius: 2,
                background: 'rgba(255,255,255,0.1)', color: '#fff',
                outline: 'none', fontFamily: 'var(--font-body)',
              }}
              onFocus={e => e.target.style.borderColor = 'var(--cbm-gold)'}
              onBlur={e => e.target.style.borderColor = 'rgba(255,255,255,0.3)'}
            />
            {query && (
              <button
                onClick={() => setQuery('')}
                style={{
                  padding: '0 16px', background: 'rgba(255,255,255,0.15)',
                  border: 'none', borderRadius: 2, color: '#fff',
                  cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 13,
                }}
              >✕ Wis</button>
            )}
          </div>
        </div>
      </section>

      <section className="cbm-section" style={{paddingTop: 40, paddingBottom: 80}}>
        <div className="cbm-section__inner">
          {!query.trim() && (
            <p style={{color: 'var(--cbm-muted)', fontSize: 15}}>
              Typ een zoekterm hierboven om artikelen te vinden.
            </p>
          )}
          {query.trim() && results.length === 0 && (
            <p style={{color: 'var(--cbm-muted)', fontSize: 15}}>
              Geen artikelen gevonden voor <strong>"{query}"</strong>.
            </p>
          )}
          {results.length > 0 && (
            <>
              <p style={{fontSize: 13, color: 'var(--cbm-muted)', marginBottom: 24}}>
                {results.length} {results.length === 1 ? 'resultaat' : 'resultaten'} voor <strong>"{query}"</strong>
              </p>
              <div className="cbm-article-grid">
                {results.map(a => (
                  <ArticleCard
                    key={a.slug}
                    article={a}
                    onClick={() => handleNavigate(a.slug)}
                  />
                ))}
              </div>
            </>
          )}
        </div>
      </section>
    </div>
  );
};

Object.assign(window, { SearchScreen });
