// components/CoordinatePopup.js
import React from "react";

const CoordinatePopup = ({ isOpen, coordinates, onClose }) => {
  if (!isOpen) return null;

  const copyToClipboard = () => {
    if (typeof navigator !== "undefined" && navigator.clipboard) {
      navigator.clipboard
        .writeText(coordinates)
        .then(() => {
          alert("Koordinaten kopiert!");
        })
        .catch((err) => {
          console.error("Clipboard-API Fehler:", err);
          fallbackCopyToClipboard(coordinates);
        });
    } else {
      fallbackCopyToClipboard(coordinates);
    }
  };

  const fallbackCopyToClipboard = (text) => {
    const textArea = document.createElement("textarea");
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    try {
      const successful = document.execCommand("copy");
      if (successful) {
        alert("Koordinaten kopiert!");
      } else {
        alert("Kopieren fehlgeschlagen (Fallback).");
      }
    } catch (err) {
      alert("Kopieren fehlgeschlagen: " + err.message);
    }
    document.body.removeChild(textArea);
  };

  return (
    <div
      className="fixed inset-0 bg-black bg-opacity-30 flex justify-center z-50"
      onClick={onClose}
      style={{
        alignItems: "flex-start",
        paddingTop: "5px",
      }}
    >
      <div className="bg-white p-4 rounded-lg shadow-xl" style={{ width: "300px" }} onClick={(e) => e.stopPropagation()}>
        <h2 className="text-xl font-bold text-center mb-2 text-gray-800">Koordinaten</h2>
        <p className="text-center text-lg text-gray-600 font-mono mb-0">lat , lng</p>
        <p className="text-center text-lg text-gray-600 font-mono mb-6">{coordinates}</p>
        <div className="flex justify-center gap-4">
          <button onClick={copyToClipboard} className="bg-blue-500 text-white px-6 py-2 rounded-lg shadow hover:bg-blue-600 transition-all">
            Kopieren
          </button>
          <button onClick={onClose} className="bg-gray-300 text-gray-800 px-6 py-2 rounded-lg shadow hover:bg-gray-400 transition-all">
            Schließen
          </button>
        </div>
      </div>
    </div>
  );
};

export default CoordinatePopup;
