import {useEffect,useState} from 'react';
import {Download,Smartphone,X} from 'lucide-react';

type InstallEvent=Event&{prompt:()=>Promise<void>;userChoice:Promise<{outcome:'accepted'|'dismissed'}>};

export default function InstallApp(){
 const [prompt,setPrompt]=useState<InstallEvent|null>(null),[open,setOpen]=useState(false),[installed,setInstalled]=useState(false);
 useEffect(()=>{
  const update=()=>setInstalled(matchMedia('(display-mode: standalone)').matches||(navigator as Navigator&{standalone?:boolean}).standalone===true);
  const capture=(event:Event)=>{event.preventDefault();setPrompt(event as InstallEvent);};
  const done=()=>{setPrompt(null);setOpen(false);update();};
  update();window.addEventListener('beforeinstallprompt',capture);window.addEventListener('appinstalled',done);
  return()=>{window.removeEventListener('beforeinstallprompt',capture);window.removeEventListener('appinstalled',done);};
 },[]);
 if(installed)return null;
 const isApple=/iPad|iPhone|iPod/.test(navigator.userAgent);
 async function install(){if(prompt){await prompt.prompt();await prompt.userChoice;setPrompt(null);setOpen(false);}else setOpen(v=>!v);}
 return <div className="install-control"><button className="install-trigger" type="button" onClick={install} aria-expanded={open} aria-label="Install mobile app"><Download size={15}/><span>Install app</span></button>{open&&<div className="install-panel" role="dialog" aria-label="Install Personfolio"><button className="install-close" type="button" onClick={()=>setOpen(false)} aria-label="Close"><X size={15}/></button><Smartphone size={26}/><strong>Add Personfolio to your phone</strong><p>{isApple?'In Safari, tap Share, then Add to Home Screen.':'In your browser menu, choose Install app or Add to Home Screen.'}</p><small>Free to install. A connection is needed to sign in and open records.</small></div>}</div>;
}
