/* DoraVPN — hero bootstrap pour index.html
   Monte le composant AlpineHero (du proto v2) à la place de la div hero vanilla
   et branche les handlers sur les flux réels (POST /api/v1/accounts, hash routing).
*/
const { useState, useEffect } = React;

const SEASONS = {
  dawn:   { name:'Aube', skyTop:'#fbc78b', skyMid:'#f4d9b8', skyBot:'#d9d5e0', lkTop:'#a5b8cc', lkBot:'#5e7895', mtFar:'#c6b3d2', mtMid:'#84759f', mtNear:'#5a6a52', celest:'radial-gradient(circle at 38% 38%, #fff6e2, #ffd49a 38%, #ffae6a 62%, #e98448 88%)', celestGlow:'rgba(255,170,110,.55)', sunLeft:'62%', sunTop:'30%', stars:0, haze:0.65 },
  noon:   { name:'Plein jour', skyTop:'#7cc7e8', skyMid:'#b6dceb', skyBot:'#d8eaf2', lkTop:'#7eb8ce', lkBot:'#3d6a8e', mtFar:'#b9b3d4', mtMid:'#6e7eab', mtNear:'#4e7050', celest:'radial-gradient(circle at 38% 38%, #fffef0, #fff3b0 38%, #ffd96a 62%, #f3b03c 88%)', celestGlow:'rgba(255,230,140,.55)', sunLeft:'58%', sunTop:'16%', stars:0, haze:0.55 },
  golden: { name:'Heure dorée', skyTop:'#fbb060', skyMid:'#f7c89c', skyBot:'#d8c6c4', lkTop:'#a08aa0', lkBot:'#5e617e', mtFar:'#d2a9a6', mtMid:'#8e6f8d', mtNear:'#6a604a', celest:'radial-gradient(circle at 38% 38%, #ffe8b8, #ffc068 38%, #f59048 62%, #d76235 88%)', celestGlow:'rgba(255,170,90,.55)', sunLeft:'66%', sunTop:'38%', stars:0, haze:0.75 },
  dusk:   { name:'Crépuscule', skyTop:'#d77a86', skyMid:'#a98aa6', skyBot:'#5d6691', lkTop:'#5c6188', lkBot:'#2a3458', mtFar:'#8a8aa8', mtMid:'#535784', mtNear:'#39435a', celest:'radial-gradient(circle at 38% 38%, #ffd1a0, #f5916e 38%, #c25064 62%, #6b2c5a 88%)', celestGlow:'rgba(220,100,110,.45)', sunLeft:'70%', sunTop:'48%', stars:0.35, haze:0.4, heroInk:'#fbf6ec', heroInkDim:'#e6dcd4', heroInkMute:'#b8b0c0' },
  night:  { name:'Nuit', skyTop:'#0e1a36', skyMid:'#1a2750', skyBot:'#293a6e', lkTop:'#1c2c4a', lkBot:'#0b1428', mtFar:'#3a3f5c', mtMid:'#252b48', mtNear:'#1a1f33', celest:'radial-gradient(circle at 35% 35%, #fefcf2, #e8e4d2 60%, #b8b4a0 90%)', celestGlow:'rgba(220,220,200,.45)', sunLeft:'24%', sunTop:'18%', stars:1, haze:0.1, heroInk:'#fbf9f3', heroInkDim:'#c8cee0', heroInkMute:'#8a92a8' },
};

const pickSeason = (h) => {
  if (h >= 5 && h < 8) return 'dawn';
  if (h >= 8 && h < 17) return 'noon';
  if (h >= 17 && h < 19) return 'golden';
  if (h >= 19 && h < 21) return 'dusk';
  return 'night';
};

/* Handlers branchés sur les flux réels DoraVPN */
async function doraGenerate() {
  try {
    // Récupère le code parrain si l'utilisateur en a saisi un via le modal (#hero-ref-input
    // est l'input caché dans l'ancien hero, peuplé par dvpOpenReferralModal).
    const refInput = document.getElementById('hero-ref-input');
    const referralCode = (refInput && refInput.value || '').trim().toUpperCase() || null;
    const body = referralCode ? JSON.stringify({ referralCode }) : '{}';
    const res = await fetch('/api/v1/accounts', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body,
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      alert(res.status === 429
        ? "Trop de générations récentes. Réessayez d'ici quelques minutes."
        : (data.error || "Impossible de générer un identifiant."));
      return;
    }
    try { sessionStorage.setItem('dvpPendingClaim', JSON.stringify(data)); } catch (_) {}
    location.hash = '#claim-result';
  } catch (err) {
    alert('Erreur réseau : ' + (err.message || err));
  }
}
function doraLogin() { location.hash = '#login'; }
function doraAffiliate() {
  // Ouvre le modal de saisie du code parrain (+30 jours). Fallback alert si app.js
  // n'a pas encore exposé le modal (chargement asynchrone).
  if (typeof window.dvpOpenReferralModal === 'function') {
    window.dvpOpenReferralModal();
  } else {
    alert("Code parrain — +30 jours offerts. Réessayez dans une seconde, le module se charge.");
  }
}

function HeroApp() {
  const [autoSeason, setAutoSeason] = useState(() => pickSeason(new Date().getHours()));

  useEffect(() => {
    const id = setInterval(() => setAutoSeason(pickSeason(new Date().getHours())), 60_000);
    return () => clearInterval(id);
  }, []);

  const s = SEASONS[autoSeason] || SEASONS.noon;

  useEffect(() => {
    const r = document.documentElement;
    r.style.setProperty('--sky-top', s.skyTop);
    r.style.setProperty('--sky-mid', s.skyMid);
    r.style.setProperty('--sky-bot', s.skyBot);
    r.style.setProperty('--lk-top',  s.lkTop);
    r.style.setProperty('--lk-bot',  s.lkBot);
    r.style.setProperty('--mt-far',  s.mtFar);
    r.style.setProperty('--mt-mid',  s.mtMid);
    r.style.setProperty('--mt-near', s.mtNear);
    r.style.setProperty('--celest',  s.celest);
    r.style.setProperty('--celest-glow', s.celestGlow);
    r.style.setProperty('--stars-opacity', s.stars);
    r.style.setProperty('--haze-opacity',  s.haze ?? 0.55);
    r.style.setProperty('--hero-ink',     s.heroInk     || '#1a1f2c');
    r.style.setProperty('--hero-ink-dim', s.heroInkDim  || '#5a6273');
    r.style.setProperty('--hero-ink-mute',s.heroInkMute || '#8b91a0');
    const sun = document.querySelector('.sun');
    if (sun) { sun.style.left = s.sunLeft; sun.style.top = s.sunTop; }
    // À chaque re-render lié au changement de saison, le DOM AlpineHero est
    // recomposé par React et les textes reviennent au fallback FR. On rappelle
    // applyI18n pour restaurer la langue active.
    if (typeof window.applyI18n === 'function' && typeof window.dvpCurrentLang === 'function') {
      window.applyI18n(window.dvpCurrentLang());
    }
  }, [autoSeason]);

  return (
    <AlpineHero
      onGenerate={doraGenerate}
      onLogin={doraLogin}
      onAffiliate={doraAffiliate}
      showBats={autoSeason === 'dusk' || autoSeason === 'night'}
    />
  );
}

/* Monte le hero + les sections sélectionnées du proto v2 (HowItWorks § 02,
   About § 06, DoraCompliance, Foot) à leurs points de montage respectifs. */
function mountAll() {
  // 1. Hero — nécessite AlpineHero
  const heroEl = document.getElementById('alpine-hero-mount');
  if (heroEl && typeof AlpineHero !== 'undefined') {
    if (!heroEl.dataset.mounted) {
      ReactDOM.createRoot(heroEl).render(<HeroApp/>);
      heroEl.dataset.mounted = '1';
    }
  }

  // 2. Sections du proto v2 — nécessite window.BetaComponents (exposé par light-app-v2.jsx)
  const Beta = window.BetaComponents;
  if (Beta) {
    const mountSpecs = [
      ['beta-trust-mount',      Beta.TrustStrip,     {}],
      ['beta-howitworks-mount', Beta.HowItWorks,     {}],
      ['beta-about-mount',      Beta.About,          { indexOverride: '03' }],
      ['beta-dora-mount',       Beta.DoraCompliance, {}],
      ['beta-finalcta-mount',   Beta.FinalCTA,       {}],
      ['beta-foot-mount',       Beta.Foot,           {}],
    ];
    for (const [id, Comp, props] of mountSpecs) {
      const el = document.getElementById(id);
      if (el && Comp && !el.dataset.mounted) {
        ReactDOM.createRoot(el).render(<Comp {...props}/>);
        el.dataset.mounted = '1';
      }
    }
  }

  // Réapplique l'i18n après chaque montage React — les éléments montés portent
  // data-i18n / data-i18n-html mais n'existaient pas au premier applyI18n() de app.js.
  // Retry court car React peut prendre quelques frames pour peindre.
  if (typeof window.applyI18n === 'function' && typeof window.dvpCurrentLang === 'function') {
    const lang = window.dvpCurrentLang();
    setTimeout(() => window.applyI18n(lang), 0);
    setTimeout(() => window.applyI18n(lang), 100);
    setTimeout(() => window.applyI18n(lang), 400);
  }

  // Si AlpineHero ou BetaComponents pas encore prêts (Babel transpile en async), retry.
  const heroReady = typeof AlpineHero !== 'undefined';
  const sectionsReady = !!window.BetaComponents;
  if (!heroReady || !sectionsReady) {
    setTimeout(mountAll, 80);
  }
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', mountAll);
} else {
  mountAll();
}
