'use client';

import { useEffect } from 'react';
import { useLocalization } from '@akinon/next/hooks';
import { Button } from '@theme/components';
import { useInstallPrompt } from '@theme/hooks/use-install-prompt';
import { pushEventGA4 } from '@theme/utils/gtm';

const trackEvent = (event: string, params: Record<string, unknown>) => {
  try {
    pushEventGA4(event, params);
  } catch {
    // dataLayer unavailable (GTM blocked, script not loaded yet)
  }
};

export const InstallPrompt = () => {
  const { canInstall, isIOS, install, dismiss } = useInstallPrompt();
  const { t } = useLocalization();

  useEffect(() => {
    if (!canInstall) return;
    trackEvent('pwa_install_prompt_shown', {
      platform: isIOS ? 'ios' : 'native'
    });
  }, [canInstall, isIOS]);

  if (!canInstall) return null;

  const handleInstall = async () => {
    trackEvent('pwa_install_prompt_clicked', { platform: 'native' });
    const outcome = await install();
    if (outcome) {
      trackEvent('pwa_install_prompt_outcome', { outcome });
    }
  };

  const handleDismiss = () => {
    trackEvent('pwa_install_prompt_dismissed', {
      platform: isIOS ? 'ios' : 'native'
    });
    dismiss();
  };

  return (
    <div
      role="region"
      aria-label={t('common.install.title')}
      className="fixed bottom-0 left-0 right-0 z-40 border-t border-gray-200 bg-white p-4 shadow-lg"
    >
      <div className="mx-auto flex max-w-screen-lg items-start gap-4">
        <div className="flex-1 min-w-0">
          <h3 className="font-semibold mb-1">
            {t('common.install.title')}
          </h3>
          <p className="text-sm text-gray-700">
            {isIOS
              ? t('common.install.description.ios')
              : t('common.install.description.default')}
          </p>
        </div>
        <div className="flex items-center gap-2 shrink-0">
          {!isIOS && (
            <Button onClick={handleInstall} size="sm">
              {t('common.install.button')}
            </Button>
          )}
          <button
            type="button"
            onClick={handleDismiss}
            aria-label={t('common.install.dismiss')}
            className="p-2 text-gray-500 hover:text-gray-700 rounded focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth={2}
              strokeLinecap="round"
              strokeLinejoin="round"
              className="size-5"
              aria-hidden="true"
            >
              <line x1="18" y1="6" x2="6" y2="18" />
              <line x1="6" y1="6" x2="18" y2="18" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
};
