/* global React, ReactDOM */
const { useState, useEffect, useRef, useMemo } = React;

const videoById = (list, id) => list.find(v => v.id === id);
const userByHandle = (list, h) => list.find(u => u.handle === h);

function initials(name) {
  if (!name) return '??';
  return name.split(/\s+/).map(w => w[0]).slice(0,2).join('').toUpperCase();
}

function fmt(n) {
  n = Number(n) || 0;
  if (n >= 1000000) return (n/1000000).toFixed(1)+'M';
  if (n >= 1000) return (n/1000).toFixed(1)+'k';
  return String(n);
}

function timeAgo(iso) {
  if (!iso) return '';
  const d = new Date(iso);
  const now = new Date();
  const sec = Math.floor((now - d) / 1000);
  if (sec < 60) return 'przed chwilą';
  const min = Math.floor(sec/60);
  if (min < 60) return min + ' min temu';
  const h = Math.floor(min/60);
  if (h < 24) return h + ' godz. temu';
  const days = Math.floor(h/24);
  if (days === 1) return 'wczoraj';
  if (days < 30) return days + ' dni temu';
  if (days < 60) return 'miesiąc temu';
  if (days < 365) return Math.floor(days/30) + ' mies. temu';
  return Math.floor(days/365) + ' lat temu';
}

function fmtDate(iso) {
  if (!iso) return '';
  const d = new Date(iso);
  return d.toLocaleDateString('pl-PL', { year:'numeric', month:'short', day:'numeric' });
}

const TILES = {
  light: {
    url: 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png',
    attr: '&copy; <a href="https://www.openstreetmap.org/copyright">OSM</a> &copy; <a href="https://carto.com/attributions">CARTO</a>'
  },
  dark: {
    url: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png',
    attr: '&copy; <a href="https://www.openstreetmap.org/copyright">OSM</a> &copy; <a href="https://carto.com/attributions">CARTO</a>'
  },
};

const SEV_PL = {
  'collision': 'kolizja',
  'near-miss': 'prawie-kolizja',
  'wildlife': 'zwierzęta',
  'weather': 'pogoda',
  'other': 'inne',
  'all': 'wszystkie',
};

function Toast({ msg }) {
  if (!msg) return null;
  return <div className="toast">{msg}</div>;
}

function useToast() {
  const [msg, setMsg] = useState(null);
  useEffect(() => {
    if (!msg) return;
    const t = setTimeout(() => setMsg(null), 3500);
    return () => clearTimeout(t);
  }, [msg]);
  return [msg, setMsg];
}

Object.assign(window, { videoById, userByHandle, initials, fmt, timeAgo, fmtDate, TILES, SEV_PL, Toast, useToast });
