/* ============ INSTALL: add-to-home-screen prompt (Android prompt + iOS guide) ============ */
(function(){
  const { useState, useEffect, useRef } = React;
  const LOGO = 'icons/icon-192.png';
  const DISMISS = 'bottlex-install-dismissed';
  const SNOOZE_MS = 7*24*60*60*1000; // re-offer after a week if dismissed

  function isStandalone(){
    return (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) || window.navigator.standalone === true;
  }
  function isIOS(){
    const ua = navigator.userAgent || '';
    const iOSUA = /iphone|ipad|ipod/i.test(ua);
    const iPadOS = navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1; // iPadOS 13+ masquerades as Mac
    return iOSUA || iPadOS;
  }
  function isInApp(){
    const ua = navigator.userAgent || '';
    // in-app browsers (FB/IG/WhatsApp/etc.) can't add to home screen
    return /FBAN|FBAV|Instagram|Line\/|Twitter|WhatsApp|MicroMessenger|; wv\)/i.test(ua);
  }
  function snoozed(){
    try{ const v=localStorage.getItem(DISMISS); if(!v) return false; if(v==='installed') return true; const t=parseInt(v,10); return Number.isFinite(t) && (Date.now()-t) < SNOOZE_MS; }catch(e){ return false; }
  }

  // simple iOS share glyph (square tray + up arrow)
  const ShareGlyph=()=>(
    <svg width="17" height="17" viewBox="0 0 24 24" fill="none" aria-hidden="true" style={{verticalAlign:'-3px',margin:'0 2px'}}>
      <path d="M12 3v11" stroke="#1fd9e6" strokeWidth="2.2" strokeLinecap="round"/>
      <path d="M8.5 6.5L12 3l3.5 3.5" stroke="#1fd9e6" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M6 10.5H5.5A1.5 1.5 0 004 12v6.5A1.5 1.5 0 005.5 20h13a1.5 1.5 0 001.5-1.5V12a1.5 1.5 0 00-1.5-1.5H18" stroke="#1fd9e6" strokeWidth="2.2" strokeLinecap="round"/>
    </svg>
  );

  function InstallPrompt({ lifted }){
    const [show,setShow]=useState(false);
    const [mode,setMode]=useState(null);   // 'android' | 'ios'
    const [iosOpen,setIosOpen]=useState(false);
    const deferred=useRef(null);

    useEffect(()=>{
      if(isStandalone()) return;        // already installed → never show
      if(snoozed()) return;             // recently dismissed

      const onBIP=(e)=>{ e.preventDefault(); deferred.current=e; setMode('android'); setShow(true); };
      const onInstalled=()=>{ setShow(false); try{localStorage.setItem(DISMISS,'installed');}catch(e){} };
      window.addEventListener('beforeinstallprompt', onBIP);
      window.addEventListener('appinstalled', onInstalled);

      let t;
      if(isIOS() && !isInApp()){ t=setTimeout(()=>{ setMode('ios'); setShow(true); }, 1400); }

      return ()=>{ window.removeEventListener('beforeinstallprompt', onBIP); window.removeEventListener('appinstalled', onInstalled); clearTimeout(t); };
    },[]);

    const dismiss=()=>{ setShow(false); try{localStorage.setItem(DISMISS, String(Date.now()));}catch(e){} };

    const installAndroid=async()=>{
      const e=deferred.current; if(!e){ dismiss(); return; }
      try{ e.prompt(); await e.userChoice; }catch(_){}
      deferred.current=null; setShow(false);
    };

    if(!show) return null;
    return (
      <div className={'install-bar'+(lifted?' lifted':'')+(iosOpen?' open':'')} role="dialog" aria-label="התקנת בנקבוק">
        <button className="install-x" onClick={dismiss} aria-label="סגירה">✕</button>
        <div className="install-top">
          <img className="install-logo" src={LOGO} alt=""/>
          <div className="install-body">
            <b>התקינו את בנקבוק 📲</b>
            <span>{mode==='ios' ? 'מוסיפים למסך הבית — גישה מהירה, בלי חנות אפליקציות' : 'הוסיפו למסך הבית לגישה מהירה כמו אפליקציה'}</span>
          </div>
          {mode==='android'
            ? <button className="install-go" onClick={installAndroid}>התקנה</button>
            : <button className="install-go" onClick={()=>setIosOpen(o=>!o)}>{iosOpen?'הבנתי':'איך?'}</button>}
        </div>
        {mode==='ios' && iosOpen && (
          <ol className="install-steps">
            <li>לחצו על כפתור השיתוף <ShareGlyph/> בתחתית המסך</li>
            <li>גללו ובחרו <b>«הוספה למסך הבית»</b> ➕</li>
            <li>לחצו <b>«הוספה»</b> — והאפליקציה על המסך! 🎉</li>
          </ol>
        )}
      </div>
    );
  }

  window.InstallPrompt = InstallPrompt;
})();
