/* global React, L, MZ */
const { useState, useEffect, useRef } = React;

function Header({ route, setRoute, user, profile, onLogin, onSubmit, onLogout }) {
  const [q, setQ] = useState('');
  const onSearch = (e) => {
    e.preventDefault();
    if (q.trim()) setRoute({ name: 'search', q: q.trim() });
  };
  return (
    <header className="site-header">
      <div className="site-header-inner">
        <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'home'}); }} className="logo">
          <span className="logo-mark"></span>
          MiejsceZdarzenia.pl
        </a>
        <nav className="nav">
          <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'home'}); }} className={route.name==='home'?'active':''}>Mapa</a>
          <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'home', scrollTo:'top'}); }}>Najlepsze</a>
          <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'home', scrollTo:'latest'}); }}>Najnowsze</a>
          {profile?.role === 'admin' || profile?.role === 'moderator' ? (
            <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'admin'}); }} className={route.name==='admin'?'active':''}>Admin</a>
          ) : null}
        </nav>
        <div className="header-spacer"></div>
        <form className="search-box" onSubmit={onSearch}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
          <input placeholder="Szukaj nagrań, miast, tagów…" value={q} onChange={e => setQ(e.target.value)} />
        </form>
        <div className="header-actions">
          <button className="btn btn-primary btn-sm" onClick={onSubmit}>+ Dodaj nagranie</button>
          {user ? (
            <>
              <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'account', id:user.id}); }} className="avatar" title={profile?.handle || ''}>{initials(profile?.name || profile?.handle || 'U')}</a>
              <button className="btn btn-ghost btn-sm" onClick={onLogout}>Wyloguj</button>
            </>
          ) : (
            <button className="btn btn-sm" onClick={onLogin}>Zaloguj się</button>
          )}
        </div>
      </div>
    </header>
  );
}

function Footer({ setRoute }) {
  return (
    <footer className="site-footer">
      <div className="site-footer-inner">
        <div className="footer-cols">
          <div>
            <b>MiejsceZdarzenia.pl</b>
            <p>Społecznościowe archiwum nagrań z wideorejestratorów. Publikowane materiały mają charakter informacyjny i edukacyjny.</p>
          </div>
          <div>
            <b>Serwis</b>
            <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'page', id:'rules'}); }}>Zasady społeczności</a>
            <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'page', id:'about'}); }}>O serwisie</a>
            <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'page', id:'contact'}); }}>Kontakt</a>
          </div>
          <div>
            <b>Prawne</b>
            <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'page', id:'terms'}); }}>Regulamin</a>
            <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'page', id:'privacy'}); }}>Polityka prywatności</a>
            <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'page', id:'cookies'}); }}>Cookies</a>
            <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'page', id:'rodo'}); }}>RODO</a>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© {new Date().getFullYear()} MiejsceZdarzenia.pl</span>
          <span>MAPA © OPENSTREETMAP · KAFELKI © CARTO</span>
        </div>
      </div>
    </footer>
  );
}

function VideoCard({ video, onOpen }) {
  const u = video.author_profile || {};
  const score = (video.up || 0) - (video.down || 0);
  return (
    <div className="video-card" onClick={() => onOpen(video.id)}>
      <div className="video-thumb" style={{backgroundImage: video.youtube_id ? `url(https://i.ytimg.com/vi/${video.youtube_id}/hqdefault.jpg)` : undefined}}>
        <span className="severity-tag" data-sev={video.severity}>{SEV_PL[video.severity] || video.severity}</span>
        {video.duration && <span className="duration">{video.duration}</span>}
      </div>
      <div>
        <div className="video-title">{video.title}</div>
        <div className="video-meta" style={{marginTop: 6}}>
          <span className="city">{video.city || '—'}</span>
          <span>{timeAgo(video.created_at)}</span>
        </div>
        <div className="video-meta" style={{marginTop: 4}}>
          <span>@{u.handle || 'anon'}</span>
          <span className="vote-pill">
            <span className="vote-arrow up">▲</span>
            <span className="score">{fmt(score)}</span>
            <span className="vote-arrow down">▽</span>
          </span>
        </div>
      </div>
    </div>
  );
}

function RankedRow({ video, rank, onOpen }) {
  const score = (video.up || 0) - (video.down || 0);
  return (
    <div className="ranked-row" onClick={() => onOpen(video.id)}>
      <div className="ranked-num">{String(rank).padStart(2, '0')}</div>
      <div className="ranked-thumb" style={{backgroundImage: video.youtube_id ? `url(https://i.ytimg.com/vi/${video.youtube_id}/hqdefault.jpg)` : undefined}}>
        {video.duration && <span className="duration">{video.duration}</span>}
      </div>
      <div className="ranked-info">
        <div className="ranked-title">{video.title}</div>
        <div className="ranked-meta">{video.city || '—'} · {fmt(video.views)} wyświetleń</div>
      </div>
      <div className="ranked-score">
        <div className="score-num">+{fmt(score)}</div>
        <div className="score-lbl">GŁOSY NETTO</div>
      </div>
    </div>
  );
}

function HomeMap({ theme, onOpen, filter, videos }) {
  const mapRef = useRef(null);
  const instRef = useRef(null);
  const tileRef = useRef(null);
  const markersRef = useRef([]);

  useEffect(() => {
    if (instRef.current) return;
    const map = L.map(mapRef.current, { zoomControl: true, worldCopyJump: true }).setView([52, 19], 6);
    instRef.current = map;
    return () => { map.remove(); instRef.current = null; };
  }, []);

  useEffect(() => {
    const map = instRef.current; if (!map) return;
    if (tileRef.current) map.removeLayer(tileRef.current);
    const t = TILES[theme === 'dark' ? 'dark' : 'light'];
    tileRef.current = L.tileLayer(t.url, { attribution: t.attr, subdomains: 'abcd', maxZoom: 19 }).addTo(map);
  }, [theme]);

  useEffect(() => {
    const map = instRef.current; if (!map) return;
    markersRef.current.forEach(m => map.removeLayer(m));
    markersRef.current = [];
    const filtered = filter === 'all' ? videos : videos.filter(v => v.severity === filter);
    filtered.forEach(v => {
      const icon = L.divIcon({
        className: '',
        html: `<div class="dc-marker ${v.severity}"></div>`,
        iconSize: [14,14],
        iconAnchor: [7,7]
      });
      const m = L.marker([v.lat, v.lng], { icon }).addTo(map);
      m.bindPopup(`
        <div class="popup-title">${v.title}</div>
        <div class="popup-meta">${v.city || '—'} · <b>${fmt((v.up||0)-(v.down||0))}</b> głosów · ${fmt(v.views)} wyśw.</div>
        <a href="#" class="popup-link" data-vid="${v.id}">OBEJRZYJ NAGRANIE →</a>
      `);
      markersRef.current.push(m);
    });
  }, [filter, videos]);

  useEffect(() => {
    const handler = (e) => {
      const a = e.target.closest('.popup-link');
      if (a) { e.preventDefault(); onOpen(a.dataset.vid); }
    };
    document.addEventListener('click', handler);
    return () => document.removeEventListener('click', handler);
  }, [onOpen]);

  return <div id="home-map" ref={mapRef}></div>;
}

function Home({ setRoute, theme }) {
  const [filter, setFilter] = useState('all');
  const [videos, setVideos] = useState([]);
  const [top, setTop] = useState([]);
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({ videos: 0, users: 0, views: 0 });

  useEffect(() => {
    (async () => {
      try {
        const [all, t, s] = await Promise.all([
          MZ.listVideos({ limit: 200 }),
          MZ.topVideos(8),
          MZ.stats(),
        ]);
        setVideos(all);
        setTop(t);
        const totalViews = all.reduce((a,v) => a + (v.views||0), 0);
        setStats({ videos: s.videos, users: s.users, views: totalViews });
      } catch (e) { console.error(e); }
      setLoading(false);
    })();
  }, []);

  const latest = videos.slice(0, 8);
  const open = (id) => setRoute({ name: 'video', id });

  return (
    <div className="page">
      <section className="home-hero">
        <div className="home-hero-meta">
          <div>
            <h1>{stats.videos === 0 ? 'Jeszcze nie dodano żadnego nagrania.' : `${stats.videos} ${stats.videos === 1 ? 'nagranie' : 'nagrań'} zebranych i przypiętych do miejsc zdarzeń.`}</h1>
            <p>Społecznościowe archiwum nagrań z wideorejestratorów z Polski — wypadki, niebezpieczne sytuacje, pogoda i zwierzęta na drodze. Przeglądaj według lokalizacji.</p>
            {stats.videos === 0 && (
              <p style={{marginTop:12}}>
                <a href="#" onClick={e => { e.preventDefault(); setRoute({ name:'home', openSubmit: true }); window.dispatchEvent(new CustomEvent('mz-open-submit')); }} style={{borderBottom:'1px solid var(--accent)', color:'var(--accent)'}}>Bądź pierwszy — dodaj nagranie →</a>
              </p>
            )}
          </div>
          <div className="map-stats">
            <div><b>{stats.videos}</b>NAGRAŃ</div>
            <div><b>{stats.users}</b>AUTORÓW</div>
            <div><b>{fmt(stats.views)}</b>WYŚWIETLEŃ</div>
          </div>
        </div>
        <div className="map-wrap">
          <div className="map-filter-bar">
            {['all','collision','near-miss','wildlife','weather','other'].map(f => (
              <button key={f} className={filter===f?'active':''} onClick={() => setFilter(f)}>{SEV_PL[f]}</button>
            ))}
          </div>
          <div className="map-legend">
            <b>RODZAJ ZDARZENIA</b>
            <div className="legend-row"><span className="legend-dot" style={{background:'oklch(0.62 0.18 25)'}}></span>kolizja</div>
            <div className="legend-row"><span className="legend-dot" style={{background:'oklch(0.7 0.15 80)'}}></span>prawie-kolizja</div>
            <div className="legend-row"><span className="legend-dot" style={{background:'oklch(0.55 0.12 150)'}}></span>zwierzęta</div>
            <div className="legend-row"><span className="legend-dot" style={{background:'oklch(0.55 0.12 240)'}}></span>pogoda</div>
          </div>
          <HomeMap theme={theme} onOpen={open} filter={filter} videos={videos} />
        </div>
      </section>

      {top.length > 0 && (
        <section id="top">
          <div className="section-head">
            <div>
              <div className="kicker">— Najczęściej głosowane · od zawsze</div>
              <h2>Najwyżej oceniane nagrania</h2>
            </div>
          </div>
          <div className="ranked-list">
            {top.map((v, i) => <RankedRow key={v.id} video={v} rank={i+1} onOpen={open} />)}
          </div>
        </section>
      )}

      {latest.length > 0 && (
        <section id="latest">
          <div className="section-head">
            <div>
              <div className="kicker">— Dopiero co dodane</div>
              <h2>Najnowsze zgłoszenia</h2>
            </div>
          </div>
          <div className="video-grid">
            {latest.map(v => <VideoCard key={v.id} video={v} onOpen={open} />)}
          </div>
        </section>
      )}

      {!loading && videos.length === 0 && (
        <section style={{textAlign:'center', padding:'60px 20px', color:'var(--ink-2)'}}>
          <h2 style={{fontSize:20, fontWeight:500, marginBottom:10}}>Witamy w MiejsceZdarzenia.pl</h2>
          <p>Serwis dopiero co wystartował. Zaloguj się i dodaj pierwsze nagranie z wideorejestratora — może to być link do filmu z YouTube.</p>
        </section>
      )}
    </div>
  );
}

function SearchPage({ query, setRoute }) {
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    (async () => {
      setLoading(true);
      try { setResults(await MZ.searchVideos(query)); } catch(e) { console.error(e); }
      setLoading(false);
    })();
  }, [query]);
  return (
    <div className="page">
      <div className="section-head">
        <div>
          <div className="kicker">— Wyniki wyszukiwania</div>
          <h2>"{query}"</h2>
        </div>
        <span style={{fontFamily:'var(--mono)', fontSize:11, color:'var(--ink-3)'}}>{loading ? 'WYSZUKIWANIE…' : `ZNALEZIONO ${results.length}`}</span>
      </div>
      {!loading && results.length === 0 && (
        <p style={{color:'var(--ink-2)', padding:'40px 0'}}>Brak wyników dla zapytania „{query}". Spróbuj innego słowa lub nazwy miasta.</p>
      )}
      <div className="video-grid">
        {results.map(v => <VideoCard key={v.id} video={v} onOpen={(id) => setRoute({name:'video', id})} />)}
      </div>
    </div>
  );
}

Object.assign(window, { Header, Footer, Home, VideoCard, RankedRow, SearchPage });
