import { useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import confetti from "canvas-confetti";
import hozier from "./assets/hozier.jpeg"
import newberg_tree from "./assets/newberg_tree.jpeg"
import newberg_tractor from "./assets/newberg_tractor.jpeg"
import panic from "./assets/panic.jpeg"
import corvallis from "./assets/corvallis.jpeg"
import seal_rock from "./assets/seal_rock.jpeg"
import yaquina_lighthouse from "./assets/yaquina_lighthouse.jpeg"
import "./App.css";

export default function Homepage() {
  const navigate = useNavigate();

  const dialogRef = useRef<HTMLDialogElement>(null);
  const blockbusterButtonRef = useRef<HTMLButtonElement>(null);

  const isTouchDevice = () =>
    "ontouchstart" in window || navigator.maxTouchPoints > 0;

  const photos = [corvallis, panic, hozier, seal_rock, yaquina_lighthouse, newberg_tree, newberg_tractor];

  const [showConfirm, setShowConfirm] = useState(false);
  const [showConfirm2, setShowConfirm2] = useState(false);
  const [showConfirm3, setShowConfirm3] = useState(false);
  const [showConfirm4, setShowConfirm4] = useState(false);
  const [showDeclineQ, setShowDeclineQ] = useState(false);

  const openPopup = () => {
    dialogRef.current?.showModal();

    // Wait for layout to settle
    requestAnimationFrame(() => {
      const button = blockbusterButtonRef.current;
      if (!button) return;
      const rect = button.getBoundingClientRect();

      button.style.left = `${rect.left}px`;
      button.style.top = `${rect.top}px`;
    });
  };

  /* ------------------------------------------------------------------
   * Runaway Blockbuster button logic
   * ------------------------------------------------------------------ */
  const moveButton = () => {
    const button = blockbusterButtonRef.current;
    if (!button) return;

    const buttonRect = button.getBoundingClientRect();

    const padding = 16;

    const maxX = window.innerWidth - buttonRect.width - padding;
    const maxY = window.innerHeight - buttonRect.height - padding;

    const x = Math.random() * maxX;
    const y = Math.random() * maxY;

    button.style.left = `${Math.max(padding, x)}px`;
    button.style.top = `${Math.max(padding, y)}px`;
  };


  const handleRunawayPress = (event: React.MouseEvent<HTMLButtonElement> | React.TouchEvent<HTMLButtonElement>) => {
    if (isTouchDevice()) {
      event.preventDefault();
      event.stopPropagation();
      moveButton();
    }
  };

  /* ------------------------------------------------------------------
   * Button handlers
   * ------------------------------------------------------------------ */
  const handleAccept = () => {
    const bursts = 9;
    const delay = 200;
    const totalDuration = bursts * delay + 500;

    for (let i = 0; i < bursts; i++) {
      setTimeout(() => {
        confetti({
          particleCount: 80,
          spread: 70,
          origin: { x: Math.random(), y: 0.9 },
        });
      }, i * delay);
    }

    // Navigate AFTER confetti finishes
    setTimeout(() => {
      navigate("/yes");
    }, totalDuration);
  };

  const handleNo = () => {
    setShowConfirm(true);
  };

  const handleYes2 = () => {
    setShowConfirm2(true);
  };

  const handleYes3 = () => {
    setShowConfirm3(true);
  };

  const handleYes4 = () => {
    setShowConfirm4(true);
  };

  const handleNo5 = () => {
    setShowDeclineQ(true);
  };

  /* ------------------------------------------------------------------
   * Render
   * ------------------------------------------------------------------ */
  return (
    <div className="container">
      <h1>Will you be my Valentine? 💖</h1>

    <div className="photos">
    {photos.map((photo, index) => (
        <div className="photo" key={index}>
        <img src={photo} alt={`Photo ${index + 1}`} />
        </div>
    ))}
    </div>


      <div className="buttons">
        <button className="yes" onClick={handleAccept}>
          Yes 💕🥳
        </button>
        <button className="no" onClick={handleNo}>
          No 😢
        </button>
      </div>

      {showConfirm && (
        <div className="overlay">
          <div className="popup">
            <h3>Are you sure? 😢</h3>
            <button className="yes" onClick={handleYes2}>
              Yes
            </button>
            <button className="no" onClick={handleAccept}>
              No
            </button>
          </div>
        </div>
      )}

      {showConfirm2 && (
        <div className="overlay">
          <div className="popup">
            <h3>Are you sure you're sure? 😭</h3>
            <button className="yes" onClick={handleYes3}>
              Yes
            </button>
            <button className="no" onClick={handleAccept}>
              No
            </button>
          </div>
        </div>
      )}

      {showConfirm3 && (
        <div className="overlay">
          <div className="popup">
            <h3>Are you sure that you're sure of being sure? 💔😭</h3>
            <button className="yes" onClick={handleYes4}>
              Yes
            </button>
            <button className="no" onClick={handleAccept}>
              No
            </button>
          </div>
        </div>
      )}

      {showConfirm4 && (
        <div className="overlay">
          <div className="popup">
            <h3>Have you tried being unsure? 🤞🙏</h3>
            <button className="yes" onClick={handleAccept}>
              Yes
            </button>
            <button className="no" onClick={handleNo5}>
              No
            </button>
          </div>
        </div>
      )}

      {showDeclineQ && (
        <div className="overlay">
          <div className="popup">
            <h3>Would you like to decline to be my valentine? 💔😭😢</h3>
            <button className="yes" onClick={openPopup}>
              Yes
            </button>
            <button className="no" onClick={handleNo}>
              No
            </button>
          </div>
        </div>
      )}

      <dialog ref={dialogRef} className="modal">
        <h2>How to Decline Offer:</h2>
        <p>
          Return all Arc'teryx gear aquired from Nick's wardrobe.
          
          After returning Arc'teryx gear, offer can only be declined in person at your nearest Blockbuster
          location*
        </p>
        <p>
          *Bend, Oregon location is not a valid location to decline this offer
        </p>

        <button onClick={handleAccept}>
          I understand, I'll be your valentine 💖
        </button>

        <button
          ref={blockbusterButtonRef}
          className="runaway"
          onMouseEnter={moveButton}      // desktop
          onTouchStart={handleRunawayPress} // mobile
          onClick={handleRunawayPress}   // fallback
        >
          I understand, I will go to blockbuster
        </button>

      </dialog>
    </div>
  );
}
