/**
 * InstallPromptButton Component
 *
 * Story 3.4: PWA install prompt button
 *
 * Architecture Compliance:
 * - Uses atomic selectors from InstallPromptStore
 * - Follows Logic Sandwich: UI -> Store -> Service
 * - Non-intrusive, fixed bottom-right position
 * - Only shows when: isInstallable AND !isInstalled AND hasEngaged
 *
 * User Flow:
 * 1. User engages with app (completes 1+ drafts)
 * 2. Browser fires beforeinstallprompt event
 * 3. InstallPromptButton appears in bottom-right
 * 4. User clicks button -> native install prompt appears
 * 5. User accepts -> app installs, button disappears
 */

'use client';

import { useState, useEffect } from 'react';
import { Download } from 'lucide-react';
import { useInstallPromptStore } from '@/lib/store/install-prompt-store';
import { InstallPromptService } from '@/services/install-prompt-service';
import { EngagementTracker } from '@/services/engagement-tracker';

/**
 * InstallPromptButton Component
 *
 * Shows a non-intrusive "Install App" button when:
 * 1. Browser supports install prompt (beforeinstallprompt fired)
 * 2. App is not already installed (not in standalone mode)
 * 3. User has engaged (completed at least 1 draft)
 */
export function InstallPromptButton() {
  // Atomic selectors for performance
  const isInstallable = useInstallPromptStore(s => s.isInstallable);
  const isInstalled = useInstallPromptStore(s => s.isInstalled);
  // Remove direct store action access


  // Track engagement state
  const [hasEngaged, setHasEngaged] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  // Check engagement status on mount and when drafts change
  useEffect(() => {
    const checkEngagement = async () => {
      setIsLoading(true);
      const engaged = await EngagementTracker.hasEngaged();
      setHasEngaged(engaged);
      setIsLoading(false);
    };

    checkEngagement();

    // Re-check engagement periodically (in case user completes a draft)
    const interval = setInterval(checkEngagement, 5000);

    return () => clearInterval(interval);
  }, []);

  /**
   * Handle install button click
   * Triggers the native browser install prompt
   */
  const handleInstall = async () => {
    const accepted = await InstallPromptService.promptInstall();

    if (accepted) {
      console.log('[InstallPromptButton] App installed successfully');
      // Button will disappear due to isInstalled becoming true
    }
  };

  /**
   * Dismiss the install prompt
   * Clears the stored event so button won't show again this session
   */
  const handleDismiss = () => {
    InstallPromptService.dismissInstall();
  };

  // Only show if:
  // 1. Browser supports install prompt (isInstallable)
  // 2. App is not already installed (!isInstalled)
  // 3. User has engaged (completed at least 1 draft)
  // 4. Not still loading engagement status
  const shouldShow = isInstallable && !isInstalled && hasEngaged && !isLoading;

  if (!shouldShow) {
    return null;
  }

  return (
    <div className="fixed bottom-20 right-4 z-40 flex flex-col gap-2 items-end">
      {/* Non-intrusive install button */}
      <button
        onClick={handleInstall}
        type="button"
        className="flex items-center gap-2 px-4 py-3 bg-slate-800 text-white rounded-lg shadow-lg hover:bg-slate-700 transition-all hover:scale-105 min-h-[44px]"
        aria-label="Install Test01 app to home screen"
      >
        <Download className="w-5 h-5" aria-hidden="true" />
        <span className="font-medium">Install App</span>
      </button>

      {/* Dismiss button */}
      <button
        onClick={handleDismiss}
        type="button"
        className="text-xs text-slate-500 hover:text-slate-700 underline pr-1"
        aria-label="Dismiss install prompt"
      >
        Not now
      </button>
    </div>
  );
}
