/* global React, ARTICLES, BTN_BASE */
const BC = {
  bg: 'rgb(6,11,24)',
  bgDeep: 'rgb(21,19,49)',
  gold: '#E6C79C',
  goldDark: '#9E7B4B',
  lavender: 'rgb(186,171,212)',
  muted: 'rgb(78,70,114)',
  white: 'rgb(255,255,255)',
  violet: 'rgba(59,39,172,0.5)'
};

// Categories derived from the live article set.
const BLOG_CATEGORIES = ['Wszystkie', 'Tarot', 'Astrologia', 'Numerologia', 'Runy', 'Chirologia', 'Rozwój', 'Energia'];

function _posts() {
  return (typeof window !== 'undefined' && window.ARTICLES) || [];
}

// ── HERO ──
function BlogHero() {
  return (
    <section style={{
      position: 'relative', height: 559, paddingTop: 84,
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      overflow: 'hidden'
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: `url(assets/hero-bg.png)`,
        backgroundSize: 'cover', backgroundPosition: 'center'
      }} />
      <div style={{
        position: 'absolute', inset: 0,
        background: `linear-gradient(${BC.bg} 0%, rgba(6,11,24,0) 18%, rgba(6,11,24,0) 82%, ${BC.bg} 100%)`
      }} />
      <div style={{
        position: 'relative', zIndex: 2, maxWidth: 1100,
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 28,
        padding: '0 40px 72px', textAlign: 'center'
      }}>
        <span style={{
          fontFamily: 'Nunito', fontWeight: 700, fontSize: 14,
          letterSpacing: '0.3em', color: BC.gold
        }}>BLOG</span>
        <h1 style={{
          margin: 0, fontFamily: 'Playfair Display', fontWeight: 400, fontSize: 64,
          lineHeight: 1.15, letterSpacing: '-0.022em', color: BC.white
        }}>Teksty o tym, co domaga się<br />uwagi i zrozumienia</h1>
        <p style={{
          margin: 0, maxWidth: 780,
          fontFamily: 'Nunito', fontSize: 18, lineHeight: 1.6, color: BC.lavender
        }}>Archiwum artykułów przygotowanych przez ekspertów Luna Persona Hermetica — o tarocie, astrologii, numerologii, runach, chirologii i pracy z sobą.</p>
      </div>
    </section>);
}

// ── ARTICLE CARD ──
function BlogCard({ post }) {
  return (
    <a href={`${post.slug}.html`} style={{
      borderRadius: 16, border: '1px solid rgb(78, 70, 114)',
      display: 'flex', flexDirection: 'column',
      textDecoration: 'none', overflow: 'hidden',
      transition: 'border-color .3s, transform .3s'
    }}>
      <div style={{
        position: 'relative', height: 200, overflow: 'hidden', background: BC.bgDeep
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: `url(assets/hero-bg.png)`,
          backgroundSize: 'cover',
          backgroundPosition: `${(post.hue || 0) / 360 * 100}% center`,
          filter: `hue-rotate(${post.hue || 0}deg) saturate(0.85) brightness(0.85)`
        }} />
        <div style={{
          position: 'absolute', inset: 0,
          background: `linear-gradient(180deg, rgba(6,11,24,0) 40%, rgba(6,11,24,0.85) 100%)`
        }} />
      </div>
      <div style={{
        padding: 32, display: 'flex', flexDirection: 'column', gap: 16, flex: 1
      }}>
        <h3 style={{
          margin: 0, fontFamily: 'Nunito',
          lineHeight: 1.4, color: BC.white, fontWeight: 400, fontSize: 24
        }}>{post.title}</h3>
        <div style={{
          fontFamily: 'Nunito',
          letterSpacing: '0.05em', color: BC.muted, fontSize: 14
        }}>{post.date}</div>
        <div style={{
          marginTop: 'auto', fontFamily: 'Nunito', fontWeight: 700,
          color: BC.gold, fontSize: 16
        }}>Czytaj artykuł</div>
      </div>
    </a>);
}

// ── ARCHIVE GRID ──
function BlogArchive() {
  const [cat, setCat] = React.useState('Wszystkie');
  const [query, setQuery] = React.useState('');
  const [visible, setVisible] = React.useState(9);

  const posts = _posts();
  const filtered = posts.filter((p) => {
    const catOk = cat === 'Wszystkie' || p.category === cat;
    const q = query.trim().toLowerCase();
    const qOk = !q || p.title.toLowerCase().includes(q) || p.category.toLowerCase().includes(q);
    return catOk && qOk;
  });

  const shown = filtered.slice(0, visible);
  const canLoadMore = visible < filtered.length;

  return (
    <section style={{
      position: 'relative', background: BC.bg,
      borderBottom: `1px solid ${BC.muted}`,
      padding: '80px 24px', overflow: 'hidden'
    }}>
      <div style={{
        position: 'relative', maxWidth: 1312, margin: '0 auto', padding: '0 40px'
      }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
          gap: 48, flexWrap: 'wrap', marginBottom: 48
        }}>
          <div>
            <div style={{
              fontFamily: 'Nunito', fontWeight: 700, fontSize: 14,
              letterSpacing: '0.2em', color: BC.muted, marginBottom: 20
            }}>ARCHIWUM BLOGA</div>
            <h2 style={{
              margin: 0, fontFamily: 'Playfair Display', fontWeight: 400, fontSize: 40,
              lineHeight: 1.2, letterSpacing: '-0.022em', color: BC.white
            }}>Wszystkie artykuły</h2>
            <p style={{
              margin: '16px 0 0', fontFamily: 'Nunito', fontSize: 15, lineHeight: 1.6,
              color: BC.lavender
            }}>{filtered.length} {filtered.length === 1 ? 'artykuł' : filtered.length < 5 ? 'artykuły' : 'artykułów'} w wybranej kategorii.</p>
          </div>

          <div style={{ position: 'relative', width: 320 }}>
            <input
              type="text"
              placeholder="Szukaj w archiwum..."
              value={query}
              onChange={(e) => { setQuery(e.target.value); setVisible(9); }}
              style={{
                width: '100%', padding: '14px 44px 14px 20px',
                borderRadius: 8, background: 'rgba(21,19,49,0.6)',
                border: `1px solid ${BC.muted}`,
                fontFamily: 'Nunito', fontSize: 14, color: BC.white,
                outline: 'none', transition: 'border-color .2s'
              }}
              onFocus={(e) => e.target.style.borderColor = BC.gold}
              onBlur={(e) => e.target.style.borderColor = BC.muted} />
            <span style={{
              position: 'absolute', right: 16, top: '50%',
              transform: 'translateY(-50%)',
              color: BC.gold, fontSize: 14, pointerEvents: 'none'
            }}>⌕</span>
          </div>
        </div>

        <div style={{
          display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 48
        }}>
          {BLOG_CATEGORIES.map((c) => {
            const active = c === cat;
            const count = c === 'Wszystkie' ? posts.length : posts.filter((p) => p.category === c).length;
            const accent = 'hsla(251, 24%, 36%, 1)';
            return (
              <button key={c} onClick={() => { setCat(c); setVisible(9); }} style={{
                ...BTN_BASE,
                padding: '8px 24px',
                fontSize: 13,
                fontFamily: 'Nunito', fontWeight: 600,
                letterSpacing: '0.12em', textTransform: 'uppercase',
                background: active ? accent : 'hsla(242, 35%, 14%, 0.5)',
                border: `1px solid ${active ? accent : 'transparent'}`,
                color: active ? BC.white : BC.lavender,
                boxShadow: 'none',
                display: 'inline-flex', gap: 8, alignItems: 'center'
              }}
              onMouseEnter={(e) => { if (!active) e.currentTarget.style.borderColor = accent; }}
              onMouseLeave={(e) => { if (!active) e.currentTarget.style.borderColor = 'transparent'; }}>
                <span>{c}</span>
                <span style={{ fontSize: 12, opacity: 0.7, fontWeight: 500 }}>{count}</span>
              </button>);
          })}
        </div>

        {filtered.length === 0 ?
        <div style={{
          padding: '80px 24px', textAlign: 'center',
          border: `1px dashed ${BC.muted}`, borderRadius: 16
        }}>
            <div style={{
              fontFamily: 'Playfair Display', fontSize: 24, color: BC.white, marginBottom: 8
            }}>Nie znaleziono artykułów</div>
            <div style={{
              fontFamily: 'Nunito', fontSize: 15, color: BC.lavender
            }}>Spróbuj innego zapytania lub kategorii.</div>
          </div> :
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24
        }}>
            {shown.map((p) =>
            <BlogCard key={p.slug} post={p} />
            )}
          </div>
        }

        {canLoadMore &&
        <div style={{ textAlign: 'center', marginTop: 64 }}>
            <BtnSecond onClick={() => setVisible((v) => v + 6)}>
              Pokaż starsze artykuły
            </BtnSecond>
          </div>
        }
      </div>
    </section>);
}

Object.assign(window, { BlogHero, BlogArchive });
