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

function LoginModal({ onClose, onLoggedIn, onToast }) {
  const [mode, setMode] = useState('signin');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [handle, setHandle] = useState('');
  const [name, setName] = useState('');
  const [rodo, setRodo] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);

  const submit = async (e) => {
    e.preventDefault();
    setErr(null); setBusy(true);
    try {
      if (mode === 'signin') {
        await MZ.signIn({ email, password });
      } else {
        if (!rodo) throw new Error('Musisz zaakceptować regulamin i politykę prywatności');
        if (!/^[a-z0-9_]{3,20}$/.test(handle)) throw new Error('Nazwa: małe litery, cyfry, podkreślniki, 3–20 znaków');
        if (password.length < 8) throw new Error('Hasło musi mieć min. 8 znaków');
        await MZ.signUp({ email, password, handle, name });
        onToast('Konto utworzone — jesteś zalogowany.');
      }
      onLoggedIn();
    } catch (e2) {
      setErr(e2.message || 'Błąd');
    }
    setBusy(false);
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <form className="modal" onClick={e => e.stopPropagation()} onSubmit={submit}>
        <div className="modal-head">
          <h2>{mode==='signin' ? 'Zaloguj się' : 'Załóż konto'}</h2>
          <button type="button" className="close-x" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          <div style={{display:'flex', gap:16, marginBottom:18, borderBottom:'1px solid var(--line)'}}>
            <button type="button" onClick={() => { setMode('signin'); setErr(null); }} style={{padding:'8px 0', borderBottom: mode==='signin'?'2px solid var(--accent)':'2px solid transparent', fontWeight: mode==='signin'?600:400, fontSize:13}}>Logowanie</button>
            <button type="button" onClick={() => { setMode('signup'); setErr(null); }} style={{padding:'8px 0', borderBottom: mode==='signup'?'2px solid var(--accent)':'2px solid transparent', fontWeight: mode==='signup'?600:400, fontSize:13}}>Rejestracja</button>
          </div>
          {mode === 'signup' && (
            <>
              <div className="field">
                <label>Nazwa użytkownika</label>
                <input value={handle} onChange={e => setHandle(e.target.value.toLowerCase())} placeholder="np. kierowca_kasia" required />
                <div className="hint">MAŁE LITERY, CYFRY, PODKREŚLNIKI · 3–20 ZNAKÓW</div>
              </div>
              <div className="field">
                <label>Imię (opcjonalnie)</label>
                <input value={name} onChange={e => setName(e.target.value)} placeholder="Wyświetlane publicznie" />
              </div>
            </>
          )}
          <div className="field">
            <label>E-mail</label>
            <input type="email" required value={email} onChange={e => setEmail(e.target.value)} placeholder="ty@example.pl" />
          </div>
          <div className="field">
            <label>Hasło</label>
            <input type="password" required value={password} onChange={e => setPassword(e.target.value)} placeholder="min. 8 znaków" />
          </div>
          {mode === 'signup' && (
            <div className="field" style={{padding:'10px 12px', background:'var(--bg-2)', border:'1px solid var(--line)', borderRadius:4}}>
              <label style={{display:'flex', gap:8, alignItems:'flex-start', cursor:'pointer'}}>
                <input type="checkbox" checked={rodo} onChange={e => setRodo(e.target.checked)} style={{marginTop:3}} />
                <span style={{fontSize:12, fontWeight:400, color:'var(--ink-2)', textTransform:'none', letterSpacing:0}}>
                  Akceptuję <a href="#terms" onClick={e => { e.preventDefault(); window.dispatchEvent(new CustomEvent('mz-page', {detail:'terms'})); onClose(); }} style={{borderBottom:'1px solid var(--accent)', color:'var(--accent)'}}>Regulamin</a> oraz <a href="#privacy" onClick={e => { e.preventDefault(); window.dispatchEvent(new CustomEvent('mz-page', {detail:'privacy'})); onClose(); }} style={{borderBottom:'1px solid var(--accent)', color:'var(--accent)'}}>Politykę Prywatności</a> i wyrażam zgodę na przetwarzanie danych osobowych w celu świadczenia usługi zgodnie z RODO.
                </span>
              </label>
            </div>
          )}
          {err && <div style={{padding:'10px 12px', background:'oklch(0.95 0.05 25)', color:'oklch(0.4 0.15 25)', borderRadius:4, fontSize:12, marginBottom:8}}>{err}</div>}
        </div>
        <div className="modal-foot">
          <button type="button" className="btn" onClick={onClose}>Anuluj</button>
          <button type="submit" className="btn btn-primary" disabled={busy}>{busy ? '…' : (mode==='signin'?'Zaloguj':'Załóż konto')}</button>
        </div>
      </form>
    </div>
  );
}

function SubmitModal({ onClose, theme, onSubmitted, onToast }) {
  const [step, setStep] = useState(1);
  const [data, setData] = useState({
    url: '', title: '', severity: 'collision', city: '', tags: '', description: '', duration: '', recorded_on: '', start_at: '', end_at: '',
  });
  const [coords, setCoords] = useState({ lat: 52.23, lng: 21.01 });
  const [rules, setRules] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);
  const mapRef = useRef(null);
  const instRef = useRef(null);
  const markerRef = useRef(null);

  const set = (k, v) => setData(d => ({ ...d, [k]: v }));

  useEffect(() => {
    if (step !== 2 || instRef.current) return;
    const m = L.map(mapRef.current).setView([coords.lat, coords.lng], 6);
    instRef.current = m;
    const t = TILES[theme==='dark'?'dark':'light'];
    L.tileLayer(t.url, { attribution: t.attr, subdomains: 'abcd' }).addTo(m);
    const icon = L.divIcon({ className:'', html:'<div class="dc-marker collision"></div>', iconSize:[14,14], iconAnchor:[7,7] });
    markerRef.current = L.marker([coords.lat, coords.lng], { icon, draggable: true }).addTo(m);
    markerRef.current.on('dragend', () => {
      const p = markerRef.current.getLatLng();
      setCoords({ lat: p.lat, lng: p.lng });
    });
    m.on('click', (e) => {
      markerRef.current.setLatLng(e.latlng);
      setCoords({ lat: e.latlng.lat, lng: e.latlng.lng });
    });
    return () => { m.remove(); instRef.current = null; };
  }, [step]);

  const nextStep = () => {
    setErr(null);
    if (step === 1) {
      const yid = MZ.extractYouTubeId(data.url);
      if (!yid) { setErr('Niepoprawny link YouTube'); return; }
      if (data.title.trim().length < 5) { setErr('Tytuł musi mieć min. 5 znaków'); return; }
    }
    setStep(step + 1);
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!rules) { setErr('Zaakceptuj zasady społeczności'); return; }
    setBusy(true); setErr(null);
    try {
      // double-check session before hitting the DB
      const sess = await MZ.currentSession();
      if (!sess) {
        throw new Error('Sesja wygasła — zaloguj się ponownie i spróbuj jeszcze raz.');
      }
      const yid = MZ.extractYouTubeId(data.url);
      const sevMap = { 'Kolizja':'collision', 'Prawie-kolizja':'near-miss', 'Zwierzęta':'wildlife', 'Pogoda':'weather', 'Inne':'other' };
      const severity = sevMap[data.severity] || data.severity;
      const payload = {
        title: data.title.trim(),
        youtube_id: yid,
        severity,
        city: data.city.trim() || null,
        lat: coords.lat, lng: coords.lng,
        duration: data.duration.trim() || null,
        start_at: MZ.parseTime(data.start_at),
        end_at: MZ.parseTime(data.end_at),
        tags: data.tags.split(',').map(s => s.trim()).filter(Boolean),
        description: data.description.trim() || null,
        recorded_on: data.recorded_on || null,
      };
      const result = await MZ.createVideo(payload);
      const msg = result.status === 'published'
        ? 'Nagranie opublikowane — dziękujemy!'
        : 'Nagranie wysłane do moderacji (do ~6h).';
      onToast(msg);
      onSubmitted?.(result);
      onClose();
    } catch (er) {
      // Always surface the error — in both the dialog AND as a toast
      const msg = (er && (er.message || er.details || er.hint)) || 'Błąd wysyłania. Spróbuj ponownie.';
      console.error('Submit error:', er);
      setErr(msg);
      onToast?.(msg);
    }
    setBusy(false);
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <form className="modal" onClick={e => e.stopPropagation()} onSubmit={submit} style={{maxWidth: 640}}>
        <div className="modal-head">
          <h2>Dodaj nagranie <span style={{fontFamily:'var(--mono)', fontSize:11, color:'var(--ink-3)', marginLeft: 8}}>KROK {step} Z 3</span></h2>
          <button type="button" className="close-x" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          {step === 1 && (
            <>
              <div className="field">
                <label>Link do YouTube</label>
                <input value={data.url} onChange={e => set('url', e.target.value)} placeholder="https://youtube.com/watch?v=..." required />
                <div className="hint">PUBLICZNE LUB NIEPUBLICZNE · NIE PRYWATNE</div>
              </div>
              <div className="field">
                <label>Tytuł</label>
                <input value={data.title} onChange={e => set('title', e.target.value)} placeholder="Krótki opis — co się stało, gdzie" required />
              </div>
              <div className="field">
                <label>Rodzaj zdarzenia</label>
                <select value={data.severity} onChange={e => set('severity', e.target.value)}>
                  <option>Kolizja</option>
                  <option>Prawie-kolizja</option>
                  <option>Zwierzęta</option>
                  <option>Pogoda</option>
                  <option>Inne</option>
                </select>
              </div>
              <div className="field">
                <label>Długość nagrania (opcjonalnie)</label>
                <input value={data.duration} onChange={e => set('duration', e.target.value)} placeholder="np. 1:24" />
              </div>
              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
                <div className="field">
                  <label>Start (opcjonalnie)</label>
                  <input value={data.start_at} onChange={e => set('start_at', e.target.value)} placeholder="np. 26 lub 0:26" />
                </div>
                <div className="field">
                  <label>Koniec (opcjonalnie)</label>
                  <input value={data.end_at} onChange={e => set('end_at', e.target.value)} placeholder="np. 1:12" />
                </div>
              </div>
            </>
          )}
          {step === 2 && (
            <>
              <div className="field">
                <label>Przypnij miejsce zdarzenia</label>
                <div ref={mapRef} style={{height: 260, border:'1px solid var(--line)', borderRadius: 4}}></div>
                <div className="hint" style={{marginTop: 8}}>KLIKNIJ NA MAPIE LUB PRZECIĄGNIJ PINEZKĘ · {coords.lat.toFixed(4)}, {coords.lng.toFixed(4)}</div>
              </div>
              <div className="field">
                <label>Najbliższe miasto / nazwa drogi</label>
                <input value={data.city} onChange={e => set('city', e.target.value)} placeholder="np. A4, Wrocław" />
              </div>
              <div className="field">
                <label>Data nagrania (opcjonalnie)</label>
                <input type="date" value={data.recorded_on} onChange={e => set('recorded_on', e.target.value)} />
              </div>
            </>
          )}
          {step === 3 && (
            <>
              <div className="field">
                <label>Tagi (oddzielone przecinkami)</label>
                <input value={data.tags} onChange={e => set('tags', e.target.value)} placeholder="skrzyżowanie, rowerzysta, czerwone-światło" />
              </div>
              <div className="field">
                <label>Opis</label>
                <textarea rows="4" value={data.description} onChange={e => set('description', e.target.value)} placeholder="Co się stało, kontekst, czy zgłoszono na policję…" />
              </div>
              <div className="field" style={{padding:'10px 12px', background:'var(--bg-2)', border:'1px solid var(--line)', borderRadius:4}}>
                <label style={{display:'flex', gap:8, alignItems:'flex-start', cursor:'pointer'}}>
                  <input type="checkbox" checked={rules} onChange={e => setRules(e.target.checked)} style={{marginTop:3}} />
                  <span style={{fontSize:12, fontWeight:400, color:'var(--ink-2)', textTransform:'none', letterSpacing:0, lineHeight:1.5}}>
                    Oświadczam, że jestem autorem nagrania lub mam prawo do jego publikacji, nagranie nie zawiera danych osobowych w sposób naruszający prywatność osób trzecich, i akceptuję zasady społeczności.
                  </span>
                </label>
              </div>
            </>
          )}
          {err && <div style={{padding:'10px 12px', background:'oklch(0.95 0.05 25)', color:'oklch(0.4 0.15 25)', borderRadius:4, fontSize:12, marginBottom:8}}>{err}</div>}
        </div>
        <div className="modal-foot">
          {step > 1 && <button type="button" className="btn" onClick={() => setStep(step-1)}>← Wstecz</button>}
          <button type="button" className="btn" onClick={onClose}>Anuluj</button>
          {step < 3 ? (
            <button type="button" className="btn btn-primary" onClick={nextStep}>Dalej →</button>
          ) : (
            <button type="submit" className="btn btn-primary" disabled={busy}>{busy ? 'Wysyłanie…' : 'Opublikuj'}</button>
          )}
        </div>
      </form>
    </div>
  );
}

Object.assign(window, { LoginModal, SubmitModal });
