import { useState, useEffect } from "react";

export default function IosPromptModal() {
  const [show, setShow] = useState(false);
  const [active, setActive] = useState(false);
  const [dragY, setDragY] = useState(0);
  const [isDragging, setIsDragging] = useState(false);
  const [startY, setStartY] = useState(0);

  useEffect(() => {
    // Detect if user is on iOS or iPadOS
    const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) || 
                  (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
    
    // Check if app is in standalone mode (already installed)
    const isStandalone = window.matchMedia('(display-mode: standalone)').matches || 
                          window.navigator.standalone;

    // Check if user has already dismissed it this session
    const isDismissed = sessionStorage.getItem("ios-prompt-dismissed");

    if (isIOS && !isStandalone && !isDismissed) {
      setShow(true);
      const raf = requestAnimationFrame(() => setActive(true));
      return () => cancelAnimationFrame(raf);
    }
  }, []);

  useEffect(() => {
    if (show) {
      document.body.style.overflow = "hidden";
      return () => {
        document.body.style.overflow = "";
      };
    }
  }, [show]);

  if (!show) return null;

  const handleClose = () => {
    setActive(false);
    sessionStorage.setItem("ios-prompt-dismissed", "true");
    setTimeout(() => {
      setShow(false);
    }, 200);
  };

  const handleDragStart = (clientY) => {
    setIsDragging(true);
    setStartY(clientY);
  };

  const handleDragMove = (clientY) => {
    if (!isDragging) return;
    const deltaY = clientY - startY;
    if (deltaY > 0) {
      setDragY(deltaY);
    }
  };

  const handleDragEnd = () => {
    if (!isDragging) return;
    setIsDragging(false);
    if (dragY > 100) {
      handleClose();
    } else {
      setDragY(0);
    }
  };

  return (
    <div 
      className={`fixed inset-0 bg-[rgba(44,24,16,0.5)] z-[200] flex items-end justify-center transition-opacity duration-200 ease-in-out ${active ? "opacity-100" : "opacity-0"}`} 
      onClick={handleClose}
    >
      <div 
        className={`bg-[#FAF6F1] dark:bg-[#150B07] rounded-t-[28px] w-full max-w-[480px] px-6 pb-8 pt-4 relative shadow-[0_-8px_30px_rgba(44,24,16,0.15)] dark:shadow-none transition-transform duration-200 ease-in-out`} 
        onClick={e => e.stopPropagation()}
        style={{
          transform: isDragging 
            ? `translateY(${dragY}px)` 
            : active 
              ? `translateY(${dragY}px)`
              : "translateY(100%)",
          transition: isDragging ? "none" : "transform 0.2s ease-out"
        }}
      >
        {/* Handle bar */}
        <div 
          className="w-full py-4 -mt-4 cursor-grab active:cursor-grabbing flex justify-center select-none"
          onTouchStart={(e) => handleDragStart(e.touches[0].clientY)}
          onTouchMove={(e) => handleDragMove(e.touches[0].clientY)}
          onTouchEnd={handleDragEnd}
          onMouseDown={(e) => handleDragStart(e.clientY)}
          onMouseMove={(e) => {
            if (e.buttons === 1) handleDragMove(e.clientY);
          }}
          onMouseUp={handleDragEnd}
          onMouseLeave={handleDragEnd}
        >
          <div className="w-9 h-1 bg-[#E8DFD3] dark:bg-[#3B2217] rounded" />
        </div>
        
        {/* Close Button */}
        <button 
          onClick={handleClose} 
          className="absolute right-5 top-5 w-8 h-8 flex items-center justify-center rounded-full bg-white dark:bg-[#22120B] border border-[#E8DFD3] dark:border-[#3B2217] text-[#9C8B7A] dark:text-[#C8B9A6] hover:text-[#2C1810] dark:hover:text-[#FAF6F1] transition-colors cursor-pointer text-lg font-semibold"
          aria-label="Close"
        >
          &times;
        </button>

        {/* Content */}
        <div className="flex flex-col items-center text-center">
          {/* Brew Logo */}
          <div className="w-16 h-16 bg-white dark:bg-[#22120B] border border-[#E8DFD3] dark:border-[#3B2217] rounded-[22%] flex items-center justify-center overflow-hidden shadow-sm mb-3">
            <img src="/icon-192.png" alt="Brew Logo" className="w-full h-full object-cover" />
          </div>

          {/* Brew Text */}
          <div className="font-serif text-2xl font-bold text-[#2C1810] dark:text-[#FAF6F1] mb-3">Brew</div>

          {/* Description */}
          <p className="text-sm text-[#6B5744] dark:text-[#C8B9A6] leading-relaxed mb-6 px-4">
            Open this page on safari and then install this app to your homescreen for a better experience.
          </p>

          {/* Instruction */}
          <div className="w-full bg-white dark:bg-[#22120B] border border-[#E8DFD3] dark:border-[#3B2217] rounded-2xl p-4 flex items-center justify-center gap-3">
            <span className="text-sm text-[#2C1810] dark:text-[#FAF6F1] font-medium flex items-center justify-center flex-wrap">
              Tap 
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#D4A325" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="inline-block mx-1.5 align-middle">
                <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8" />
                <polyline points="16 6 12 2 8 6" />
                <line x1="12" y1="2" x2="12" y2="15" />
              </svg>
              then <span className="font-bold text-[#8B6914] dark:text-[#D4A325] ml-1">"Add to Home Screen"</span>
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}
