// "Install app" button — hidden when running as PWA (display-mode: standalone).
// Uses beforeinstallprompt where available (Android Chrome / Desktop Chrome/Edge);
// for iOS Safari shows a modal with Share → "На экран Домой" instructions.

function detectStandalone() {
  return (
    (typeof window.matchMedia === 'function' && window.matchMedia('(display-mode: standalone)').matches) ||
    window.navigator.standalone === true
  );
}

function detectIOS() {
  const ua = navigator.userAgent || '';
  return /iPad|iPhone|iPod/.test(ua) && !window.MSStream;
}

const InstallIOSModal = ({ open, onClose }) => {
  if (!open) return null;
  return (
    <Modal open={open} onClose={onClose} width={460}>
      <div style={{ padding: 24 }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 4 }}>
          <div className="mono" style={{ fontSize: 11, color:'var(--fg-subtle)', letterSpacing:'.08em', textTransform:'uppercase' }}>iOS · SAFARI</div>
          <button type="button" onClick={onClose} style={{ background:'none', border:'none', color:'var(--fg-subtle)', cursor:'pointer' }}><IconClose size={18}/></button>
        </div>
        <h2 style={{ margin:'4px 0 12px', fontSize: 22, fontWeight: 600 }}>Установить приложение</h2>
        <p style={{ margin:'0 0 16px', color:'var(--fg-muted)', fontSize: 14, lineHeight: 1.5 }}>
          На iPhone / iPad установка делается из меню Safari:
        </p>
        <ol style={{ paddingLeft: 18, margin:'0 0 16px', color:'var(--fg)', fontSize: 14, lineHeight: 1.7 }}>
          <li>Нажмите кнопку <b>Поделиться</b> <IconShare size={14} style={{ verticalAlign:'text-bottom' }}/> в нижней панели Safari</li>
          <li>Прокрутите меню и выберите <b>На экран «Домой»</b></li>
          <li>Подтвердите <b>Добавить</b> — иконка появится на главном экране</li>
        </ol>
        <div style={{ padding: 12, borderRadius: 10, background:'var(--surface-2)', fontSize: 12, color:'var(--fg-muted)', lineHeight: 1.5 }}>
          После установки приложение работает в отдельном окне, без адресной строки — и эта кнопка пропадёт.
        </div>
        <div style={{ marginTop: 18 }}>
          <Button variant="primary" full onClick={onClose}>Понятно</Button>
        </div>
      </div>
    </Modal>
  );
};

const InstallAppButton = ({ variant = 'ghost', size = 'sm', full = false, label = 'Установить приложение' }) => {
  const [deferredPrompt, setDeferredPrompt] = React.useState(null);
  const [standalone, setStandalone] = React.useState(() => detectStandalone());
  const [isIOS] = React.useState(() => detectIOS());
  const [showIOSModal, setShowIOSModal] = React.useState(false);
  const [installed, setInstalled] = React.useState(false);

  React.useEffect(() => {
    const onBIP = (e) => { e.preventDefault(); setDeferredPrompt(e); };
    const onInstalled = () => { setInstalled(true); setDeferredPrompt(null); };
    const mq = window.matchMedia?.('(display-mode: standalone)');
    const onMQ = (e) => setStandalone(e.matches);
    window.addEventListener('beforeinstallprompt', onBIP);
    window.addEventListener('appinstalled', onInstalled);
    if (mq && mq.addEventListener) mq.addEventListener('change', onMQ);
    return () => {
      window.removeEventListener('beforeinstallprompt', onBIP);
      window.removeEventListener('appinstalled', onInstalled);
      if (mq && mq.removeEventListener) mq.removeEventListener('change', onMQ);
    };
  }, []);

  if (standalone || installed) return null;
  if (!isIOS && !deferredPrompt) return null;

  const onClick = async () => {
    if (isIOS) { setShowIOSModal(true); return; }
    if (!deferredPrompt) return;
    try {
      deferredPrompt.prompt();
      await deferredPrompt.userChoice;
    } catch {}
    setDeferredPrompt(null);
  };

  return (
    <>
      <Button variant={variant} size={size} full={full} onClick={onClick} leading={<IconDownload size={14}/>}>
        {label}
      </Button>
      <InstallIOSModal open={showIOSModal} onClose={()=> setShowIOSModal(false)}/>
    </>
  );
};

Object.assign(window, { InstallAppButton, InstallIOSModal });
