"use client";

import { useEffect, useState } from "react";

import {
  fetchCoursewareRuntimeConfig,
  normalizeCoursewareRuntimeConfig,
} from "~/lib/courseware-runtime";

export function Lab1NetronPanel() {
  const [runtimeConfig, setRuntimeConfig] = useState(() =>
    normalizeCoursewareRuntimeConfig(),
  );
  const [isResolved, setIsResolved] = useState(false);

  useEffect(() => {
    let isCancelled = false;

    void fetchCoursewareRuntimeConfig()
      .then((nextConfig) => {
        if (isCancelled) return;
        setRuntimeConfig(nextConfig);
      })
      .catch(() => {
        if (isCancelled) return;
        setRuntimeConfig(normalizeCoursewareRuntimeConfig());
      })
      .finally(() => {
        if (isCancelled) return;
        setIsResolved(true);
      });

    return () => {
      isCancelled = true;
    };
  }, []);

  return (
    <section className="lab1-netron-panel" data-widget-enhanced="true">
      <div>
        <p className="lab1-netron-panel__eyebrow">Lab 1 Model Structure</p>
        <h3>Open Netron on port 8338</h3>
        <p className="lab1-netron-panel__lede">
          Netron runs as a local browser tool for this lab. Open it, then use
          the download links in this section to load each GGUF file manually.
        </p>
      </div>

      <div className="lab1-netron-panel__actions">
        <a
          className="lab1-netron-panel__primary"
          href={runtimeConfig.lab1NetronUrl}
          rel="noreferrer"
          target="_blank"
        >
          Open Netron
        </a>
        <span className="lab1-netron-panel__note" aria-live="polite">
          {isResolved
            ? `Netron URL: ${runtimeConfig.lab1NetronUrl}`
            : "Resolving the Netron URL..."}
        </span>
      </div>
    </section>
  );
}
