/* ============================================================
   B1 — Ecosystem header: Home · Xem Ngày → · Cài đặt ↓
   Cùng pattern đã wire cho La Kinh/Xem Ngày (14/07): label chữ
   trước mũi tên sau, Home không mũi tên (chỉ là anchor).
   CHỈ hiện ở Tạo phiên · Lưu phiên · Trong phiên (member).
   KHÔNG hiện ở Chủ trì (đang live) — màn đó cần full diện tích,
   giữ đúng logic host: mở nav khác giữa lúc đang chủ trì dễ
   trượt màn hình / gây phân tâm giữa nghi lễ.
   Link Home/Xem Ngày mở tab mới (target=_blank) — B1 không bị
   unload, không cần confirm-trước-khi-rời.
   ============================================================ */

// TODO(Minh): điền URL thật của Xem Ngày khi có subdomain chính thức.
const HOME_URL = 'https://minh-kinh.com';
const XEMNGAY_URL = 'https://xemngay.minh-kinh.com'; // đã xác nhận với Minh 30/07

/* ---- cài đặt: beforeinstallprompt (Android/Chrome) + fallback 1 dòng cho iOS ---- */
function useInstallPrompt() {
  const [deferred, setDeferred] = useState(null);
  const [installed, setInstalled] = useState(
    () => typeof window !== 'undefined' && window.matchMedia('(display-mode: standalone)').matches
  );
  useEffect(() => {
    const onPrompt = (e) => { e.preventDefault(); setDeferred(e); };
    const onInstalled = () => setInstalled(true);
    window.addEventListener('beforeinstallprompt', onPrompt);
    window.addEventListener('appinstalled', onInstalled);
    return () => {
      window.removeEventListener('beforeinstallprompt', onPrompt);
      window.removeEventListener('appinstalled', onInstalled);
    };
  }, []);
  const install = async () => {
    if (deferred) {
      deferred.prompt();
      try { await deferred.userChoice; } catch (_) {}
      setDeferred(null);
    } else {
      alert('Để cài B1: chạm nút Chia sẻ → "Thêm vào Màn hình chính"');
    }
  };
  return { installed, install };
}

function EcosystemHeader({ style = {} }) {
  const { installed, install } = useInstallPrompt();
  const linkStyle = {
    fontFamily: 'var(--font-mono)', fontSize: 10.5, letterSpacing: '.08em',
    textDecoration: 'none', background: 'none', border: 'none', cursor: 'pointer', padding: 0,
    whiteSpace: 'nowrap',
  };
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 18,
      padding: '12px 20px', ...style,
    }}>
      <a href={HOME_URL} target="_blank" rel="noopener" style={{ ...linkStyle, color: 'var(--cream-dim)' }}>HOME</a>
      <div style={{ flex: 1 }} />
      <a href={XEMNGAY_URL} target="_blank" rel="noopener" style={{ ...linkStyle, color: 'var(--gold)' }}>XEM NGÀY →</a>
      {!installed && (
        <button onClick={install} style={{ ...linkStyle, color: 'var(--gold)' }}>CÀI ĐẶT ↓</button>
      )}
    </div>
  );
}

Object.assign(window, { EcosystemHeader, HOME_URL, XEMNGAY_URL, useInstallPrompt });
