/* 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>
  );
}

/* SQLite stores created_at as UTC "YYYY-MM-DD HH:MM:SS" (no zone). Parsing that
   as-is in JS treats it as local time, shifting by the UTC offset. Normalise. */
function parseWhen(iso) {
  if (!iso || iso === "now") return null;
  if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(iso)) return new Date(iso.replace(" ", "T") + "Z");
  const d = new Date(iso);
  return isNaN(d) ? null : d;
}

function fmtWhen(iso, lang) {
  if (iso === "now" || !iso) return lang === "de" ? "Jetzt" : "Now";
  const d = parseWhen(iso);
  if (!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 = parseWhen(iso);
  if (!d) return fmtWhen(iso, lang);
  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));
}

/* ---- hole-aware point-in-polygon (matches server.js even-odd logic) ---- */
function pointInRing(lat, lng, ring) {
  let inside = false;
  const n = ring.length;
  for (let i = 0, j = n - 1; i < n; j = i++) {
    const [yi, xi] = ring[i];
    const [yj, xj] = ring[j];
    if ((yi > lat) !== (yj > lat) && lng < ((xj - xi) * (lat - yi)) / (yj - yi) + xi) {
      inside = !inside;
    }
  }
  return inside;
}

function pointInPolygonRings(lat, lng, rings) {
  let inside = false;
  for (const ring of rings) {
    // GeoJSON rings are [ [lon,lat], ... ]; convert to [lat,lng] for the test.
    const converted = ring.map((c) => [c[1], c[0]]);
    if (pointInRing(lat, lng, converted)) inside = !inside;
  }
  return inside;
}

function geometryContains(geojson, lat, lng) {
  const geom = geojson && geojson.type === "Feature" ? geojson.geometry : geojson;
  if (!geom) return false;
  if (geom.type === "Polygon") return pointInPolygonRings(lat, lng, geom.coordinates);
  if (geom.type === "MultiPolygon") return geom.coordinates.some((poly) => pointInPolygonRings(lat, lng, poly));
  return false;
}

/* Returns the matching area object (with .name) or null. */
function findAreaForPoint(lat, lng, areas) {
  if (!areas || !areas.length) return null;
  for (const a of areas) {
    try {
      const gj = typeof a.geojson === "string" ? JSON.parse(a.geojson) : a.geojson;
      if (geometryContains(gj, lat, lng)) return a;
    } catch (e) { /* ignore */ }
  }
  return null;
}

function isInAnyGeoJSONArea(lat, lng, areas) {
  if (!areas || !areas.length) return false;
  return !!findAreaForPoint(lat, lng, areas);
}

function zoneNameOf(loc) {
  if (!loc) return null;
  return loc.zone || (loc.place && (loc.place.locality || loc.place.display)) || null;
}

function fmtBytes(b) {
  if (!b && b !== 0) return "";
  if (b < 1024) return b + " B";
  if (b < 1048576) return (b / 1024).toFixed(0) + " KB";
  return (b / 1048576).toFixed(1) + " MB";
}

Object.assign(window, {
  Ico, fmtWhen, relTime, catById, genRef,
  pointInRing, pointInPolygonRings, geometryContains, findAreaForPoint, isInAnyGeoJSONArea,
  parseWhen, fmtBytes, zoneNameOf,
});
