import React, { useState, useEffect } from 'react';
import './index.css';
import Nav from './components/Nav';
import BentoCard from './components/BentoCard';
import BentoSlideshow from './components/BentoSlideshow';
import CookieBanner from './components/CookieBanner';
import { fetchLaboratoriumData, mapDirectusToContent } from './lib/directus';
import { slideshowData, articlesData, newsData, videosData } from './data/content';
import Hero from './sections/Hero';

const SubscribeBox = () => {
  const [email, setEmail] = useState('');
  const [subscribed, setSubscribed] = useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (email && email.includes('@')) {
      setSubscribed(true);
    }
  };

  return (
    <div className="subscribe-box">
      <h3>Stay Updated</h3>
      <p>Otrzymuj najnowsze wiadomości o AI prosto na swoją skrzynkę.</p>
      {subscribed ? (
        <p className="subscribe-success">Dziękujemy! Potwierdzenie wysłano na {email}.</p>
      ) : (
        <form onSubmit={handleSubmit} noValidate>
          <label htmlFor="subscribe-email" className="visually-hidden">Adres e-mail</label>
          <input
            id="subscribe-email"
            type="email"
            placeholder="Twój email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            aria-required="true"
          />
          <button type="submit">Subscribe</button>
        </form>
      )}
    </div>
  );
};

function App() {
  const [directusData, setDirectusData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function loadData() {
      try {
        const items = await fetchLaboratoriumData();
        const mapped = mapDirectusToContent(items);
        setDirectusData(mapped);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    }
    loadData();
  }, []);

  // Użyj danych z Directus lub fallback na statyczne
  const displaySlideshow = directusData?.slideshow || slideshowData;
  const displayArticles = directusData?.articles || articlesData;

  if (loading) {
    return (
      <div className="loading-screen">
        <div className="loading-spinner" />
        <p>Ładowanie danych z Laboratorium AI...</p>
      </div>
    );
  }

  return (
    <>
      <Nav />
      <Hero />

      {error && (
        <div className="error-banner">
          ⚠️ Nie można połączyć z bazą danych. Wyświetlam dane offline.
        </div>
      )}

      <div className="page-wrapper">

        {/* CENTER BENTO AREA */}
        <main className="bento-area" aria-label="Artykuły">
          <BentoSlideshow
            slides={displaySlideshow}
            style={{ gridColumn: '1 / 5', gridRow: '1 / 2' }}
          />

          {displayArticles.map((article, index) => (
            <BentoCard
              key={index}
              type={article.type}
              badge={article.badge}
              title={article.title}
              category={article.category}
              readTime={article.readTime}
              bgImage={article.bgImage}
              hero={article.hero}
              style={{ gridColumn: article.gridColumn, gridRow: article.gridRow }}
            />
          ))}
        </main>

        {/* RIGHT SIDEBAR */}
        <aside className="sidebar sidebar-right" aria-label="Najnowsze wideo">
          <div>
            <h3 className="sidebar-title">LATEST VIDEOS</h3>
            {videosData.map((video, index) => (
              <div key={index} className="video-item" tabIndex={0}>
                <div
                  className="video-thumb"
                  style={{ backgroundImage: `url(${video.bgImage})` }}
                  role="img"
                  aria-label={video.title}
                />
                <div className="video-info">
                  <div className="video-title">{video.title}</div>
                  <div className="video-views">{video.views}</div>
                </div>
              </div>
            ))}
          </div>

          <SubscribeBox />

          <div style={{ marginTop: '2rem' }}>
            <h3 className="sidebar-title">LATEST AI NEWS</h3>
            <div className="news-list">
              {newsData.map((item, index) => (
                <div key={index} className="news-item" tabIndex={0}>
                  <div className="news-time">{item.time}</div>
                  <div className="news-title">{item.title}</div>
                </div>
              ))}
            </div>
          </div>
        </aside>

      </div>

      {/* FOOTER */}
      <footer className="main-footer">
        <div className="footer-container">
          <div className="footer-brand">
            <div className="nav-logo">
              <span className="pulse-dot" aria-hidden="true"></span>
              DEX_OS
            </div>
            <p>Zbudowane przez deweloperów sztucznej inteligencji, dla agentów przyszłości.</p>
          </div>
          <div className="footer-links">
            <div className="footer-col">
              <h4>Platforma</h4>
              <a href="#">Architektura</a>
              <a href="#">Agent Swarms</a>
              <a href="#">Bezpieczeństwo</a>
            </div>
            <div className="footer-col">
              <h4>Firma</h4>
              <a href="#">O nas</a>
              <a href="#">Kariera</a>
              <a href="#">Kontakt</a>
            </div>
            <div className="footer-col">
              <h4>Zasady</h4>
              <a href="#">Regulamin</a>
              <a href="#">Polityka Prywatności</a>
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <p>&copy; {new Date().getFullYear()} DEX Operating System. Wszelkie prawa zastrzeżone.</p>
        </div>
      </footer>

      <CookieBanner />
    </>
  );
}

export default App;