/* utils.jsx — shared helpers */

function Ico({ name, size = 20, className, style }) {
  const _ref = React.useRef(null);
  React.useEffect(() => {
    if (!_ref.current || !window.lucide) return;
    _ref.current.innerHTML = `<i data-lucide="${name}"></i>`;
    try { window.lucide.createIcons(); } catch (e) {}
  }, [name]);
  return (
    <span ref={_ref} className={"ico " + (className || "")}
      style={{ width: size, height: size, display: "inline-flex", flex: "none", ...(style || {}) }}></span>
  );
}

function fmtWhen(iso, lang) {
  if (iso === "now" || !iso) return lang === "de" ? "Jetzt" : "Now";
  const d = new Date(iso);
  if (isNaN(d)) return iso;
  return d.toLocaleString(lang === "de" ? "de-AT" : "en-GB",
    { day: "2-digit", month: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit" });
}

function relTime(iso, lang) {
  if (!iso || iso === "now") return lang === "de" ? "gerade eben" : "just now";
  const d = new Date(iso);
  const now = new Date();
  const h = Math.round((now - d) / 36e5);
  if (isNaN(h) || h < 0) return fmtWhen(iso, lang);
  if (h < 1) return lang === "de" ? "gerade eben" : "just now";
  if (h < 24) return lang === "de" ? `vor ${h} Std` : `${h}h ago`;
  const days = Math.round(h / 24);
  return lang === "de" ? `vor ${days} T` : `${days}d ago`;
}

function catById(id) {
  if (!id) return window.MELD.categories[window.MELD.categories.length - 1];
  return window.MELD.categories.find((c) => c.id === id) || window.MELD.categories[window.MELD.categories.length - 1];
}

function genRef(id) {
  return "RD-" + (id || Math.floor(Math.random() * 9000 + 1000));
}

function isInAnyGeoJSONArea(lat, lng, areas) {
  if (!areas || !areas.length) return false;
  return areas.some(a => {
    try {
      const gj = typeof a.geojson === "string" ? JSON.parse(a.geojson) : a.geojson;
      const geom = gj.type === "Feature" ? gj.geometry : gj;
      const rings = geom.type === "Polygon" ? [geom.coordinates[0]]
                  : geom.type === "MultiPolygon" ? geom.coordinates.map(p => p[0]) : [];
      return rings.some(ring => pointInPolygon(lat, lng, ring.map(c => [c[1], c[0]])));
    } catch (e) { return false; }
  });
}

function pointInPolygon(lat, lng, polygon) {
  let inside = false;
  const n = polygon.length;
  for (let i = 0, j = n - 1; i < n; j = i++) {
    const [yi, xi] = polygon[i];
    const [yj, xj] = polygon[j];
    if ((yi > lat) !== (yj > lat) && lng < ((xj - xi) * (lat - yi)) / (yj - yi) + xi) {
      inside = !inside;
    }
  }
  return inside;
}

Object.assign(window, { Ico, fmtWhen, relTime, catById, genRef, pointInPolygon, isInAnyGeoJSONArea });
