import { useState } from "react";

export default function InfraPlot() {
  // Chainlit injects `props` as a global (same as Counter example uses props.count)
  const url = props?.url || "";
  const title = props?.title || "Infrastructure & Latency Plot";

  const [isExpanded, setIsExpanded] = useState(false);

  if (!url) return (
    <div style={{ padding: "12px", background: "#fff3cd", borderRadius: "8px", fontSize: "12px" }}>
      <strong>⚠️ No URL found</strong>
      <pre style={{ fontSize: "10px", marginTop: "4px" }}>
        {JSON.stringify(props, null, 2)}
      </pre>
    </div>
  );

  return (
    <div style={{
      border: "1px solid #e2e8f0",
      borderRadius: "8px",
      overflow: "hidden",
      margin: "8px 0",
      background: "#fff"
    }}>
      {/* Header */}
      <div style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        padding: "8px 12px",
        background: "#f8fafc",
        borderBottom: "1px solid #e2e8f0",
        fontFamily: "sans-serif"
      }}>
        <span style={{ fontWeight: 600, fontSize: "13px", color: "#334155" }}>
          📊 {title}
        </span>
        <div style={{ display: "flex", gap: "8px" }}>
          <button
            onClick={() => setIsExpanded(!isExpanded)}
            style={{
              padding: "4px 10px",
              fontSize: "12px",
              borderRadius: "4px",
              border: "1px solid #cbd5e0",
              background: "#fff",
              cursor: "pointer",
              color: "#475569"
            }}
          >
            {isExpanded ? "⬆ Collapse" : "⬇ Expand"}
          </button>
          <a
            href={url}
            target="_blank"
            rel="noreferrer"
            style={{
              padding: "4px 10px",
              fontSize: "12px",
              borderRadius: "4px",
              border: "1px solid #cbd5e0",
              background: "#fff",
              textDecoration: "none",
              color: "#3b82f6"
            }}
          >
            ↗ Open
          </a>
        </div>
      </div>

      {/* iframe */}
      <iframe
        src={url}
        title={title}
        style={{
          width: "100%",
          height: isExpanded ? "900px" : "580px",
          border: "none",
          display: "block",
          transition: "height 0.3s ease"
        }}
        sandbox="allow-scripts allow-same-origin allow-popups"
        loading="lazy"
      />
    </div>
  );
}