// PWA install guide — converts new mobile visitors into installed users.
//
// • Shows a discreet, on-brand banner on MOBILE when the app is NOT installed
//   (not running standalone).
// • Android/Chrome: uses the captured `beforeinstallprompt` for a one-tap
//   "Instalar" button; falls back to ⋮-menu instructions when unavailable.
// • iPhone/Safari: step-by-step visual guide (Share → Añadir a pantalla de
//   inicio → Añadir) with icons, because it isn't discoverable.
// • Dismissable and remembered (won't nag), but re-openable from Perfil via
//   window.AtlasPWA.open().
// • Installed (standalone) → renders nothing.

// ── Detection ───────────────────────────────────────────────────────────────
function pwaIsStandalone() {
  try {
    return window.matchMedia('(display-mode: standalone)').matches
        || window.matchMedia('(display-mode: fullscreen)').matches
        || window.matchMedia('(display-mode: minimal-ui)').matches
        || window.navigator.standalone === true;
  } catch { return false; }
}
function pwaPlatform() {
  const ua = navigator.userAgent || '';
  // iPadOS 13+ can report as Mac; navigator.standalone only exists on iOS Safari.
  if (/iphone|ipod|ipad/i.test(ua) || typeof window.navigator.standalone !== 'undefined') return 'ios';
  if (/android/i.test(ua)) return 'android';
  return 'other';
}
const PWA_DISMISS_KEY = 'atlas.pwa.install.dismissed.v1';

// Global handle so a "Instalar app" link (Perfil/menu) can re-open the guide.
window.AtlasPWA = {
  available() { return !pwaIsStandalone() && pwaPlatform() !== 'other'; },
  open() { try { window.dispatchEvent(new Event('atlas:openinstall')); } catch {} },
};

// ── Icons ────────────────────────────────────────────────────────────────────
function PwIconShare({ size = 22 }) {
  // iOS Share glyph — square with an up arrow.
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="#2563EB" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
      <path d="M12 15V4" /><path d="m8 8 4-4 4 4" />
      <path d="M6 12H5a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-5a2 2 0 0 0-2-2h-1" />
    </svg>
  );
}
function PwIconPlusSquare({ size = 22 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="#2563EB" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
      <rect x="3" y="3" width="18" height="18" rx="4" /><path d="M12 8v8M8 12h8" />
    </svg>
  );
}
function PwIconDots({ size = 22 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="#2563EB" aria-hidden>
      <circle cx="12" cy="5" r="2" /><circle cx="12" cy="12" r="2" /><circle cx="12" cy="19" r="2" />
    </svg>
  );
}
function PwAppIcon({ size = 38 }) {
  // The Atlas "A" mark, on brand navy.
  return (
    <div style={{ width:size, height:size, borderRadius:9, flexShrink:0, background:'#0F1A2E', display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'0 2px 10px -2px rgba(15,26,46,0.5)' }}>
      <svg viewBox="0 0 100 100" width={size*0.62} height={size*0.62} fill="none" aria-hidden>
        <path d="M20 86 L50 14 L80 86" stroke="#2563EB" strokeWidth="10" strokeLinecap="round" strokeLinejoin="round" />
        <path d="M30 60 Q50 76 70 60" stroke="#2563EB" strokeWidth="10" strokeLinecap="round" />
      </svg>
    </div>
  );
}

// ── Step row ─────────────────────────────────────────────────────────────────
function PwStep({ n, icon, children }) {
  return (
    <div style={{ display:'flex', alignItems:'center', gap:12, padding:'11px 0' }}>
      <span style={{ flexShrink:0, width:24, height:24, borderRadius:999, background:'rgba(37,99,235,0.12)', color:'#2563EB', fontFamily:'ui-monospace,Menlo,monospace', fontSize:12, fontWeight:800, display:'flex', alignItems:'center', justifyContent:'center' }}>{n}</span>
      <div style={{ flex:1, fontFamily:'"Inter",system-ui', fontSize:14, color:'#0F1A2E', lineHeight:1.5 }}>{children}</div>
      {icon && <span style={{ flexShrink:0, width:40, height:40, borderRadius:10, background:'rgba(37,99,235,0.08)', border:'1px solid rgba(37,99,235,0.18)', display:'flex', alignItems:'center', justifyContent:'center' }}>{icon}</span>}
    </div>
  );
}

// ── Instructions sheet (bottom sheet) ────────────────────────────────────────
function PwSheet({ platform, hasPrompt, onInstall, onClose }) {
  const isAndroidOneTap = platform === 'android' && hasPrompt;
  return ReactDOM.createPortal(
    <div onClick={onClose} style={{ position:'fixed', inset:0, zIndex:7500, background:'rgba(15,26,46,0.45)', display:'flex', alignItems:'flex-end', justifyContent:'center', animation:'fadeIn .15s ease' }}>
      <div onClick={e => e.stopPropagation()} style={{ width:'100%', maxWidth:520, background:'#FFFFFF', borderRadius:'20px 20px 0 0', boxShadow:'0 -10px 40px rgba(15,26,46,0.25)', padding:'20px 22px', paddingBottom:'calc(22px + env(safe-area-inset-bottom))', maxHeight:'86vh', overflowY:'auto' }}>
        <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:6 }}>
          <PwAppIcon size={44} />
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontFamily:'"Inter",system-ui', fontSize:17, fontWeight:800, color:'#0F1A2E', letterSpacing:-0.3 }}>Instala Atlas</div>
            <div style={{ fontFamily:'"Inter",system-ui', fontSize:12.5, color:'#5C6477' }}>Ábrela como app, entrena sin conexión.</div>
          </div>
          <button onClick={onClose} aria-label="Cerrar" style={{ flexShrink:0, width:32, height:32, borderRadius:9, border:'1px solid rgba(15,26,46,0.10)', background:'transparent', color:'#5C6477', cursor:'pointer', fontSize:16 }}>✕</button>
        </div>

        {isAndroidOneTap ? (
          <div style={{ marginTop:14 }}>
            <button onClick={onInstall} className="wp-press" style={{ width:'100%', minHeight:52, borderRadius:13, border:'none', cursor:'pointer', background:'#2563EB', color:'#fff', fontFamily:'"Inter",system-ui', fontSize:15, fontWeight:800, letterSpacing:-0.2, boxShadow:'0 6px 20px -6px rgba(37,99,235,0.6)' }}>
              Instalar Atlas
            </button>
            <div style={{ fontFamily:'"Inter",system-ui', fontSize:12, color:'#6B7280', textAlign:'center', marginTop:10 }}>Se añadirá a tu pantalla de inicio en un toque.</div>
          </div>
        ) : platform === 'ios' ? (
          <div style={{ marginTop:6, borderTop:'1px solid rgba(15,26,46,0.07)' }}>
            <PwStep n="1" icon={<PwIconShare />}>Toca el botón <b>Compartir</b> en la barra de Safari.</PwStep>
            <div style={{ height:1, background:'rgba(15,26,46,0.05)' }} />
            <PwStep n="2" icon={<PwIconPlusSquare />}>Elige <b>“Añadir a pantalla de inicio”</b>.</PwStep>
            <div style={{ height:1, background:'rgba(15,26,46,0.05)' }} />
            <PwStep n="3">Toca <b>Añadir</b> arriba a la derecha. ¡Listo!</PwStep>
          </div>
        ) : (
          <div style={{ marginTop:6, borderTop:'1px solid rgba(15,26,46,0.07)' }}>
            <PwStep n="1" icon={<PwIconDots />}>Abre el menú <b>⋮</b> de Chrome (arriba a la derecha).</PwStep>
            <div style={{ height:1, background:'rgba(15,26,46,0.05)' }} />
            <PwStep n="2" icon={<PwIconPlusSquare />}>Toca <b>“Instalar aplicación”</b> (o “Añadir a pantalla principal”).</PwStep>
            <div style={{ height:1, background:'rgba(15,26,46,0.05)' }} />
            <PwStep n="3">Confirma <b>Instalar</b>. ¡Listo!</PwStep>
          </div>
        )}
      </div>
    </div>,
    document.body
  );
}

// ── Main component ───────────────────────────────────────────────────────────
function PwaInstall() {
  const { route } = useRoute();
  const { state } = useStore();
  const standalone = React.useMemo(() => pwaIsStandalone(), []);
  const platform   = React.useMemo(() => pwaPlatform(), []);
  const [installed, setInstalled] = React.useState(() => (window.__atlasInstall && window.__atlasInstall.installed) || false);
  const [dismissed, setDismissed] = React.useState(() => { try { return localStorage.getItem(PWA_DISMISS_KEY) === '1'; } catch { return false; } });
  const [hasPrompt, setHasPrompt] = React.useState(() => !!(window.__atlasInstall && window.__atlasInstall.deferred));
  const [sheetOpen, setSheetOpen] = React.useState(false);

  React.useEffect(() => {
    const onAvail = () => setHasPrompt(true);
    const onInst  = () => { setInstalled(true); setSheetOpen(false); };
    const onOpen  = () => setSheetOpen(true);   // re-open from Perfil/menu
    window.addEventListener('atlas:installavailable', onAvail);
    window.addEventListener('atlas:installed', onInst);
    window.addEventListener('atlas:openinstall', onOpen);
    return () => {
      window.removeEventListener('atlas:installavailable', onAvail);
      window.removeEventListener('atlas:installed', onInst);
      window.removeEventListener('atlas:openinstall', onOpen);
    };
  }, []);

  // Never show anything if installed / running standalone / on desktop.
  if (standalone || installed || platform === 'other') {
    // Still allow the re-open sheet to render if explicitly opened (edge case:
    // desktop won't fire it because AtlasPWA.available() is false).
    return sheetOpen ? <PwSheet platform={platform} hasPrompt={hasPrompt} onInstall={doInstall} onClose={() => setSheetOpen(false)} /> : null;
  }

  async function doInstall() {
    const dp = window.__atlasInstall && window.__atlasInstall.deferred;
    if (dp && dp.prompt) {
      try {
        dp.prompt();
        await dp.userChoice;          // {outcome:'accepted'|'dismissed'}
      } catch {}
      window.__atlasInstall.deferred = null;
      setHasPrompt(false);
      setSheetOpen(false);
    } else {
      setSheetOpen(true);             // fallback to manual steps
    }
  }

  function dismiss() {
    try { localStorage.setItem(PWA_DISMISS_KEY, '1'); } catch {}
    setDismissed(true);
  }

  const TABBAR = 'calc(56px + env(safe-area-inset-bottom))';
  // No en el reproductor (tapa los botones de acción); no en la primera visita:
  // a partir de la 2ª visita o tras el primer entreno.
  const inPlayer    = route === '/player';
  const visitNum    = (typeof window !== 'undefined' && window.__atlasVisit) || 1;
  const didWorkout  = (state?.sessions?.completed || 0) >= 1;
  const showBanner  = !dismissed && !inPlayer && (visitNum >= 2 || didWorkout);

  return (
    <>
      {showBanner && (
        <div className="pwa-banner-enter" style={{
          position:'fixed', left:12, right:12, bottom:`calc(${TABBAR} + 10px)`, zIndex:1200,
          display:'flex', alignItems:'center', gap:12,
          padding:'12px 12px 12px 14px', borderRadius:16,
          background:'#0F1A2E', border:'1px solid rgba(255,255,255,0.08)',
          boxShadow:'0 12px 34px -10px rgba(0,0,0,0.55)',
        }}>
          <PwAppIcon size={38} />
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontFamily:'"Inter",system-ui', fontSize:13.5, fontWeight:800, color:'#FAFAF7', letterSpacing:-0.2, lineHeight:1.25 }}>Instala Atlas en tu móvil</div>
            <div style={{ fontFamily:'"Inter",system-ui', fontSize:11.5, color:'rgba(250,250,247,0.55)', marginTop:1, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>Tenla como app · entrena sin conexión</div>
          </div>
          <button onClick={doInstall} className="wp-press" style={{ flexShrink:0, minHeight:38, padding:'0 15px', borderRadius:10, border:'none', cursor:'pointer', background:'#2563EB', color:'#fff', fontFamily:'"Inter",system-ui', fontSize:13, fontWeight:800, letterSpacing:-0.1 }}>
            {platform === 'android' && hasPrompt ? 'Instalar' : 'Cómo'}
          </button>
          <button onClick={dismiss} aria-label="Descartar" style={{ flexShrink:0, width:30, height:30, borderRadius:8, border:'none', background:'transparent', color:'rgba(250,250,247,0.4)', cursor:'pointer', fontSize:15 }}>✕</button>
        </div>
      )}
      {sheetOpen && <PwSheet platform={platform} hasPrompt={hasPrompt} onInstall={doInstall} onClose={() => setSheetOpen(false)} />}
    </>
  );
}

Object.assign(window, { PwaInstall });
