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

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

declare global {
  interface Window {
    leseKnotenpunkte?: (slotIndex: number) => void;
    knotenData?: {
      nodeIDs: string[];
      linkIDs: string[];
      linkLengths: number[];
    };
  }
}

interface Props {
  slot: number;
}

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

  useEffect(() => {
    const slotIndex = slot;

    // Schritt 1: Lade kueDataX.js vom CPL (oder Mock im Dev)
    const script = document.createElement("script");
    script.src = `/CPL?Service/kueData${slotIndex}.js`; // z. B. kueData0.js
    script.async = true;
    script.onload = () => {
      // Schritt 2: Lade Hilfs-Loader (dein JS zum Auslesen)
      const loaderScript = document.createElement("script");
      loaderScript.src = "/js/knotenAuslesen.js";
      loaderScript.async = true;
      loaderScript.onload = () => {
        if (typeof window.leseKnotenpunkte === "function") {
          window.leseKnotenpunkte(slotIndex);
          const knoten = window.knotenData?.nodeIDs ?? [];
          setKnotenNamen(knoten);
        }
      };
      document.body.appendChild(loaderScript);
    };
    document.body.appendChild(script);

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

  return (
    <div className="space-y-4">
      <h2 className="text-lg font-semibold mb-2">
        Knotenpunkte – Slot {slot + 1}
      </h2>
      {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>
  );
}
