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

export default function PwaInstallStatusCard() {
  const [installPrompt, setInstallPrompt] = useState(null);
  const standalone = window.matchMedia?.('(display-mode: standalone)').matches || window.navigator.standalone;

  useEffect(() => {
    const onPrompt = (event) => {
      event.preventDefault();
      setInstallPrompt(event);
    };
    window.addEventListener('beforeinstallprompt', onPrompt);
    return () => window.removeEventListener('beforeinstallprompt', onPrompt);
  }, []);

  const install = async () => {
    if (!installPrompt) return;
    installPrompt.prompt();
    await installPrompt.userChoice;
    setInstallPrompt(null);
  };

  return (
    <section className="pwa-card-section">
      <div className="pwa-section-title">
        <h2>وضعیت نصب برنامه</h2>
        <span>{standalone ? 'نصب‌شده' : 'مرورگر'}</span>
      </div>
      <div className="pwa-install-grid">
        <span><Smartphone size={16} /> مدیریت پروژه</span>
        <span>مسیر PWA: /pwa</span>
        <span>حالت اجرا: {standalone ? 'نصب‌شده / Standalone' : 'مرورگر'}</span>
      </div>
      {installPrompt ? (
        <button type="button" className="pwa-profile-action" onClick={install}><Download size={17} /> نصب نسخه موبایل</button>
      ) : null}
    </section>
  );
}
