// Store and PWA shortcuts shared by the hero and the footer.
const STORE_LINKS = {
  ios: 'https://apps.apple.com/vn/app/aquanix/id6790356932',
  android: 'https://aquanix.co/app',
  pwa: '/app',
};

let deferredInstallPrompt = null;

function bindInstallPrompt() {
  if (window.__aquanixPwaBound) return;
  window.__aquanixPwaBound = true;
  window.addEventListener('beforeinstallprompt', (event) => {
    event.preventDefault();
    deferredInstallPrompt = event;
  });
  window.addEventListener('appinstalled', () => {
    deferredInstallPrompt = null;
  });
}

function pwaInstallHelp() {
  const ua = navigator.userAgent || '';
  if (/iphone|ipad|ipod/i.test(ua)) {
    return 'Mở Aquanix bằng Safari. Nhấn nút Chia sẻ, rồi chọn “Thêm vào Màn hình chính”.';
  }
  if (/android/i.test(ua)) {
    return 'Mở Aquanix bằng Chrome. Nhấn menu trình duyệt, rồi chọn “Cài đặt ứng dụng” hoặc “Thêm vào màn hình chính”.';
  }
  return 'Mở Aquanix bằng Chrome hoặc Edge. Nhấn biểu tượng cài đặt trên thanh địa chỉ để thêm ứng dụng vào máy.';
}

function IconApple() {
  return <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true" fill="currentColor"><path d="M16.37 12.72c.03 2.9 2.54 3.86 2.57 3.88-.02.07-.4 1.38-1.32 2.73-.8 1.16-1.63 2.31-2.94 2.34-1.29.03-1.7-.76-3.17-.76-1.47 0-1.93.74-3.15.79-1.26.05-2.22-1.25-3.03-2.41-1.65-2.38-2.91-6.72-1.22-9.65.84-1.46 2.34-2.38 3.97-2.41 1.24-.02 2.41.83 3.17.83.76 0 2.18-1.03 3.67-.88.63.03 2.38.25 3.51 1.9-.09.06-2.09 1.22-2.06 3.64zM14.3 6.3c.66-.8 1.1-1.91.98-3.02-1.05.04-2.32.7-3.07 1.58-.67.78-1.26 2.03-1.1 3.22 1.17.09 2.36-.6 3.19-1.78z" /></svg>;
}
function IconPlay() {
  return <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true" fill="currentColor"><path d="M3.5 2.8v18.4c0 .8.9 1.3 1.6.9l15.2-9.2c.7-.4.7-1.4 0-1.8L5.1 1.9c-.7-.4-1.6.1-1.6.9z" /></svg>;
}
function IconPwa() {
  return <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v10" /><path d="M8 9l4 4 4-4" /><path d="M5 15v3a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-3" /></svg>;
}

function StoreBadge({ href, onClick, external, icon, kicker, title, label, tone }) {
  const onDark = tone === 'onDark';
  const [hover, setHover] = React.useState(false);
  return <a
    href={href}
    onClick={onClick}
    target={external ? '_blank' : undefined}
    rel={external ? 'noopener noreferrer' : undefined}
    aria-label={label}
    onMouseEnter={() => setHover(true)}
    onMouseLeave={() => setHover(false)}
    style={{
      display: 'inline-flex',
      alignItems: 'center',
      gap: 10,
      minHeight: 48,
      padding: '6px 14px 6px 12px',
      borderRadius: 10,
      background: onDark ? (hover ? 'rgba(255,255,255,.22)' : 'rgba(11,42,51,.45)') : (hover ? 'var(--brand-700)' : 'var(--ink)'),
      color: '#fff',
      border: onDark ? '1px solid rgba(255,255,255,.55)' : '1px solid transparent',
      textDecoration: 'none',
      backdropFilter: onDark ? 'blur(8px)' : undefined,
      boxShadow: onDark ? 'none' : 'var(--shadow-card)',
      fontFamily: 'var(--font-sans)',
      whiteSpace: 'nowrap',
    }}
  >
    <span style={{ width: 20, height: 20, display: 'inline-flex', flex: 'none' }}>{icon}</span>
    <span style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.15, textAlign: 'left' }}>
      <span style={{ fontSize: 10, fontWeight: 500, letterSpacing: '.04em', opacity: .85 }}>{kicker}</span>
      <span style={{ fontSize: 15, fontWeight: 700 }}>{title}</span>
    </span>
  </a>;
}

function PwaInstallDialog({ onClose }) {
  React.useEffect(() => {
    const onKey = (event) => { if (event.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [onClose]);
  return <div onClick={onClose} role="dialog" aria-modal="true" aria-labelledby="pwa-install-title" style={{ position: 'fixed', inset: 0, zIndex: 1100, background: 'rgba(11,42,51,.72)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'var(--space-5)' }}>
    <div onClick={(event) => event.stopPropagation()} style={{ width: 'min(440px, 100%)', background: 'var(--surface)', color: 'var(--ink)', borderRadius: 'var(--radius-xl)', padding: 'var(--space-6)', boxShadow: 'var(--shadow-pop)' }}>
      <h2 id="pwa-install-title" className="t-display-m" style={{ margin: '0 0 var(--space-3)', fontSize: 24, lineHeight: '32px' }}>Cài Aquanix trên trình duyệt</h2>
      <p className="t-body" style={{ margin: '0 0 var(--space-5)', color: 'var(--ink-muted)' }}>{pwaInstallHelp()}</p>
      <div style={{ display: 'flex', gap: 'var(--space-3)', flexWrap: 'wrap' }}>
        <a href={STORE_LINKS.pwa} style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', minHeight: 48, padding: '12px 18px', borderRadius: 'var(--radius-md)', background: 'var(--brand-600)', color: '#fff', fontWeight: 600, textDecoration: 'none' }}>Mở ứng dụng</a>
        <button type="button" onClick={onClose} style={{ minHeight: 48, padding: '12px 18px', borderRadius: 'var(--radius-md)', border: '1.5px solid var(--border)', background: 'var(--surface)', color: 'var(--ink)', fontWeight: 600, fontFamily: 'var(--font-sans)', cursor: 'pointer' }}>Đóng</button>
      </div>
    </div>
  </div>;
}

function InstallLinks({ tone = 'onLight' }) {
  const [open, setOpen] = React.useState(false);
  const close = React.useCallback(() => setOpen(false), []);
  React.useEffect(() => { bindInstallPrompt(); }, []);
  async function onPwaClick(event) {
    event.preventDefault();
    if (!deferredInstallPrompt) {
      setOpen(true);
      return;
    }
    const prompt = deferredInstallPrompt;
    deferredInstallPrompt = null;
    await prompt.prompt();
  }
  return <>
    <div className="install-links" style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
      <StoreBadge tone={tone} href={STORE_LINKS.ios} external icon={<IconApple />} kicker="Tải trên" title="App Store" label="Tải Aquanix trên App Store" />
      <StoreBadge tone={tone} href={STORE_LINKS.android} external icon={<IconPlay />} kicker="Tải trên" title="Google Play" label="Tải Aquanix trên Google Play" />
      <StoreBadge tone={tone} href={STORE_LINKS.pwa} onClick={onPwaClick} icon={<IconPwa />} kicker="Cài đặt" title="PWA" label="Cài Aquanix dưới dạng PWA" />
    </div>
    {open ? <PwaInstallDialog onClose={close} /> : null}
  </>;
}

Object.assign(window, { InstallLinks, STORE_LINKS });
