// AGENT_TARGET: texture-quality-preset — detect device tier, scale star density and reduce motion automatically

const QUALITY_PRESETS = {
  low: { starScale: 0.25, reducedMotion: true },
  medium: { starScale: 0.6, reducedMotion: false },
  high: { starScale: 1.0, reducedMotion: false },
};

// AGENT_TARGET: texture-quality-preset — hardware tier detection
function detectQualityTier() {
  try {
    const ua = navigator.userAgent || "";
    const isMobile =
      /Mobi|Android|iPhone|iPad|iPod/i.test(ua) ||
      (navigator.maxTouchPoints > 1 && window.innerWidth < 1024);
    const isTablet = navigator.maxTouchPoints > 1 && window.innerWidth >= 768;

    const hasWebGL = (() => {
      try {
        const c = document.createElement("canvas");
        return !!(c.getContext("webgl") || c.getContext("experimental-webgl"));
      } catch (_) {
        return false;
      }
    })();

    // navigator.hardwareConcurrency = logical CPU count (undefined on old browsers → 2)
    const cores = navigator.hardwareConcurrency || 2;
    // navigator.deviceMemory = RAM in GB (Chrome only, default 4)
    const ramGb = navigator.deviceMemory || 4;

    if (!hasWebGL || ramGb <= 1 || cores <= 2) return "low";
    if (isMobile && !isTablet) return "low";
    if (isTablet || cores <= 4 || ramGb <= 2) return "medium";
    return "high";
  } catch (_) {
    return "medium";
  }
}

let _cachedTier = null;
function getQualityTier() {
  // AGENT_TARGET: texture-quality-preset — cached tier read/write via sessionStorage
  if (_cachedTier) return _cachedTier;
  try {
    const stored = sessionStorage.getItem("planets_quality_tier");
    _cachedTier =
      stored === "low" || stored === "medium" || stored === "high"
        ? stored
        : detectQualityTier();
    sessionStorage.setItem("planets_quality_tier", _cachedTier);
  } catch (_) {
    _cachedTier = detectQualityTier();
  }
  return _cachedTier;
}

// AGENT_TARGET: texture-quality-preset — useQualityPreset hook used by App
function useQualityPreset() {
  const [tier] = React.useState(() => getQualityTier());
  const preset = QUALITY_PRESETS[tier] || QUALITY_PRESETS.medium;
  return { tier, ...preset };
}
