"use client";
// components/modales/kueModal/pages/Knotenpunkte.tsx

import React, { useEffect, useState } from "react";

declare global {
  interface Window {
    kueNodeID?: string[];
  }
}

interface Props {
  slot: number;
}

export default function Knotenpunkte({ slot }: Props) {
  const [knotenNamen, setKnotenNamen] = useState<string[]>(Array(10).fill(""));

  useEffect(() => {
    const slotIndex = slot;
    const isDev =
      typeof window !== "undefined" && window.location.hostname === "localhost";

    const scriptUrl = isDev
      ? `/api/cpl/readKnotenpunktAPIHandler?slot=${slotIndex}`
      : `/CPL?/CPL/Service/kueDataKnoten/kueData${slotIndex}.js`;

    const script = document.createElement("script");
    script.src = scriptUrl;
    script.async = true;

    script.onload = () => {
      console.log("✅ Script geladen:", scriptUrl);
      const werte = window.kueNodeID ?? [];
      setKnotenNamen(werte);
    };

    script.onerror = () => {
      console.error("❌ Fehler beim Laden von:", scriptUrl);
    };

    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    };
  }, [slot]);

  return (
    <div className="space-y-4">
      {knotenNamen.map((value, index) => (
        <div key={index} className="flex gap-2 items-center">
          <label className="w-24 text-right">Knoten {index + 1}:</label>
          <input
            type="text"
            className="border border-gray-300 rounded px-2 py-1 w-full"
            value={value}
            onChange={(e) => {
              const updated = [...knotenNamen];
              updated[index] = e.target.value;
              setKnotenNamen(updated);
            }}
          />
        </div>
      ))}

      <div className="flex justify-end mt-4">
        <button
          onClick={() => {
            alert("💾 Speichern kommt später – jetzt nur Anzeige.");
            console.log("Daten zum Speichern:", knotenNamen);
          }}
          className="bg-littwin-blue text-white px-4 py-2 rounded shadow hover:bg-blue-600 transition"
        >
          💾 Speichern
        </button>
      </div>
    </div>
  );
}
