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

function VoteWidget({ video, onVote, userVote, disabled }) {
  const score = (video.up || 0) - (video.down || 0);
  return (
    <div className="vote-widget">
      <button disabled={disabled} className={'up ' + (userVote===1?'active up':'')} onClick={() => onVote(userVote === 1 ? 0 : 1)}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12l7-7 7 7"/></svg>
        za
      </button>
      <span className="vote-score">{score > 0 ? '+' : ''}{score}</span>
      <button disabled={disabled} className={'down ' + (userVote===-1?'active down':'')} onClick={() => onVote(userVote === -1 ? 0 : -1)}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 19V5M5 12l7 7 7-7"/></svg>
        przeciw
      </button>
    </div>
  );
}

function VideoMap({ video, theme }) {
  const ref = useRef(null);
  const inst = useRef(null);
  const tile = useRef(null);
  useEffect(() => {
    if (inst.current) return;
    const map = L.map(ref.current, { zoomControl: false, scrollWheelZoom: false, dragging: true }).setView([video.lat, video.lng], 14);
    inst.current = map;
    const icon = L.divIcon({ className: '', html: `<div class="dc-marker ${video.severity}"></div>`, iconSize: [14,14], iconAnchor: [7,7] });
    L.marker([video.lat, video.lng], { icon }).addTo(map);
    return () => { map.remove(); inst.current = null; };
  }, [video.id]);
  useEffect(() => {
    if (!inst.current) return;
    if (tile.current) inst.current.removeLayer(tile.current);
    const t = TILES[theme === 'dark' ? 'dark' : 'light'];
    tile.current = L.tileLayer(t.url, { attribution: t.attr, subdomains: 'abcd' }).addTo(inst.current);
  }, [theme]);
  return <div ref={ref} className="vp-location-map"></div>;
}

function Comment({ c }) {
  const u = c.author_profile || {};
  return (
    <div className="comment">
      <div className="avatar" title={u.name}>{initials(u.name || u.handle)}</div>
      <div>
        <div className="comment-head">
          <b>{u.handle || 'anon'}</b>
          <time>· {timeAgo(c.created_at)}</time>
        </div>
        <div className="comment-body">{c.body}</div>
      </div>
    </div>
  );
}

function VideoPage({ videoId, setRoute, theme, user, profile, onLogin, onToast }) {
  const [v, setV] = useState(null);
  const [userVote, setUserVote] = useState(0);
  const [comments, setComments] = useState([]);
  const [related, setRelated] = useState([]);
  const [loading, setLoading] = useState(true);
  const [commentBody, setCommentBody] = useState('');
  const [reportOpen, setReportOpen] = useState(false);

  useEffect(() => {
    (async () => {
      setLoading(true);
      try {
        const video = await MZ.getVideo(videoId);
        setV(video);
        const [cmts, mv, rel] = await Promise.all([
          MZ.listComments(videoId),
          user ? MZ.myVote(videoId) : Promise.resolve(0),
          MZ.listVideos({ severity: video.severity, limit: 5 }),
        ]);
        setComments(cmts);
        setUserVote(mv || 0);
        setRelated(rel.filter(x => x.id !== videoId).slice(0, 4));
        MZ.incViews(videoId);
      } catch (e) { console.error(e); }
      setLoading(false);
    })();
  }, [videoId, user]);

  const vote = async (val) => {
    if (!user) { onLogin(); return; }
    try {
      await MZ.castVote(videoId, val);
      setUserVote(val);
      const updated = await MZ.getVideo(videoId);
      setV(updated);
    } catch (e) { onToast('Błąd głosowania'); }
  };

  const submitComment = async (e) => {
    e.preventDefault();
    if (!commentBody.trim()) return;
    try {
      const nc = await MZ.addComment({ videoId, body: commentBody.trim() });
      setComments([...comments, nc]);
      setCommentBody('');
    } catch (err) { onToast(err.message || 'Błąd'); }
  };

  if (loading) return <div className="page"><p style={{padding:40, color:'var(--ink-2)'}}>Ładowanie nagrania…</p></div>;
  if (!v) return <div className="page"><p style={{padding:40}}>Nie znaleziono nagrania.</p></div>;

  const author = v.author_profile || {};

  return (
    <div className="page">
      <div className="vp-breadcrumb">
        <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'home'}); }}>START</a> / {(v.city || 'POLSKA').toUpperCase()}
      </div>

      <div className="vp-grid">
        <div>
          <div className="vp-player">
            {v.youtube_id ? (
              <iframe
                src={`https://www.youtube-nocookie.com/embed/${v.youtube_id}?rel=0`}
                title={v.title}
                frameBorder="0"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen
                style={{width:'100%', height:'100%', position:'absolute', inset:0, border:0}}
              />
            ) : (
              <div className="player-placeholder">// BRAK ID YOUTUBE</div>
            )}
          </div>
          <h1 className="vp-title">{v.title}</h1>
          <div className="vp-meta-row">
            <div className="vp-author">
              <div className="avatar">{initials(author.name || author.handle)}</div>
              <div className="vp-author-info">
                <b>{author.name || author.handle}</b>
                <span>@{author.handle} · {fmt(author.karma)} karmy</span>
              </div>
            </div>
            <VoteWidget video={v} onVote={vote} userVote={userVote} disabled={loading} />
          </div>
          <div className="vp-meta-row" style={{borderTop:'none'}}>
            <div className="vp-tags">
              <span className="vp-tag sev">{SEV_PL[v.severity] || v.severity}</span>
              {(v.tags || []).map(t => <span className="vp-tag" key={t}>#{t}</span>)}
            </div>
            <div style={{fontFamily:'var(--mono)', fontSize:11, color:'var(--ink-3)', display:'flex', gap:12, alignItems:'center'}}>
              <span>{fmt(v.views)} WYŚWIETLEŃ · {timeAgo(v.created_at).toUpperCase()}</span>
              {user && <button onClick={() => setReportOpen(true)} style={{color:'var(--ink-3)', fontSize:11}}>Zgłoś</button>}
            </div>
          </div>

          {v.description && <div className="vp-desc">{v.description}</div>}

          <div className="comments-head">
            <h3>Dyskusja</h3>
            <span>{comments.length} KOMENTARZY</span>
          </div>

          {user ? (
            <form className="comment-compose" onSubmit={submitComment}>
              <div className="avatar">{initials(profile?.name || profile?.handle)}</div>
              <div style={{flex:1}}>
                <textarea
                  placeholder="Napisz przemyślany komentarz — co się stało, kto zawinił, lokalny kontekst…"
                  value={commentBody}
                  onChange={e => setCommentBody(e.target.value)}
                  maxLength={2000}
                />
                <div className="compose-actions">
                  <span>ZACHOWAJ KULTURĘ · BEZ UJAWNIANIA DANYCH OSOBOWYCH</span>
                  <button type="submit" className="btn btn-primary btn-sm" disabled={!commentBody.trim()}>Opublikuj</button>
                </div>
              </div>
            </form>
          ) : (
            <div className="comment-compose" style={{justifyContent:'center', textAlign:'center'}}>
              <div><button className="btn btn-sm" onClick={onLogin}>Zaloguj się</button>, aby komentować.</div>
            </div>
          )}

          {comments.map(c => <Comment key={c.id} c={c} />)}
          {comments.length === 0 && <p style={{color:'var(--ink-3)', padding:'20px 0', fontSize:13}}>Brak komentarzy. Bądź pierwszy.</p>}
        </div>

        <aside className="vp-side">
          <div className="vp-card">
            <div className="vp-card-head">LOKALIZACJA <span>OSM</span></div>
            <VideoMap video={v} theme={theme} />
            <div className="vp-location-meta">
              <div><b style={{color:'var(--ink)',fontWeight:500}}>{v.city || 'Polska'}</b></div>
              <div className="coord">SZER {Number(v.lat).toFixed(4)} · DŁ {Number(v.lng).toFixed(4)}</div>
              {v.recorded_on && <div className="coord">NAGRANO {fmtDate(v.recorded_on)}</div>}
            </div>
          </div>

          {related.length > 0 && (
            <div className="vp-card">
              <div className="vp-card-head">PODOBNE — TEN SAM RODZAJ</div>
              <div className="related-list">
                {related.map(r => (
                  <div className="related-row" key={r.id} onClick={() => setRoute({name:'video', id:r.id})}>
                    <div className="related-thumb" style={{backgroundImage: r.youtube_id ? `url(https://i.ytimg.com/vi/${r.youtube_id}/default.jpg)` : undefined}}></div>
                    <div className="related-info">
                      <div className="rt">{r.title}</div>
                      <div className="rm">{r.city || '—'} · +{fmt((r.up||0)-(r.down||0))}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </aside>
      </div>

      {reportOpen && <ReportModal videoId={v.id} onClose={() => setReportOpen(false)} onToast={onToast} />}
    </div>
  );
}

function ReportModal({ videoId, onClose, onToast }) {
  const [reason, setReason] = useState('Dane osobowe / tablice rej.');
  const [details, setDetails] = useState('');
  const [sending, setSending] = useState(false);
  const send = async (e) => {
    e.preventDefault();
    setSending(true);
    try {
      await MZ.report({ videoId, reason, details });
      onToast('Zgłoszenie wysłane — moderator sprawdzi w ciągu 6 godzin');
      onClose();
    } catch (err) { onToast(err.message || 'Błąd'); }
    setSending(false);
  };
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <form className="modal" onClick={e => e.stopPropagation()} onSubmit={send}>
        <div className="modal-head">
          <h2>Zgłoś nagranie</h2>
          <button type="button" className="close-x" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          <div className="field">
            <label>Powód</label>
            <select value={reason} onChange={e => setReason(e.target.value)}>
              <option>Dane osobowe / tablice rej.</option>
              <option>Przemoc / treści drastyczne bez ostrzeżenia</option>
              <option>Nękanie / mowa nienawiści</option>
              <option>Duplikat</option>
              <option>Spam / nie na temat</option>
              <option>Naruszenie praw autorskich</option>
              <option>Inne</option>
            </select>
          </div>
          <div className="field">
            <label>Szczegóły (opcjonalnie)</label>
            <textarea rows="3" value={details} onChange={e => setDetails(e.target.value)} placeholder="Opisz problem…" />
          </div>
        </div>
        <div className="modal-foot">
          <button type="button" className="btn" onClick={onClose}>Anuluj</button>
          <button type="submit" className="btn btn-primary" disabled={sending}>{sending ? 'Wysyłanie…' : 'Wyślij zgłoszenie'}</button>
        </div>
      </form>
    </div>
  );
}

Object.assign(window, { VideoPage, VoteWidget, ReportModal });
