"use client";

import { useEffect, useState } from "react";
import { ClipLoader } from "react-spinners";
import IdiReportDisplay from "@/components/Idireportdisplay";
import { useIdiReportStore } from "@/store/idiReportStore";

export default function Page() {
  const storeReport = useIdiReportStore((s) => s.reportResponse);
  const [reportResponse, setReportResponse] = useState(storeReport);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (storeReport) {
      setReportResponse(storeReport);
      setLoading(false);
      return;
    }

    if (typeof window !== "undefined" && window.opener) {
      try {
        // Reach into the parent tab's Zustand store directly
        const openerData = window.opener.useIdiReportStore?.getState?.().reportResponse;
        if (openerData) {
          setReportResponse(openerData);
        }
      } catch (err) {
        // Cross-origin or opener closed — ignore
        console.error("Could not read opener's report data", err);
      }
    }

    setLoading(false);
  }, [storeReport]);

  if (loading) {
    return (
      <div
        className="d-flex justify-content-center align-items-center"
        style={{ height: "100vh" }}
      >
        <ClipLoader size={40} color="#0C3155" loading />
      </div>
    );
  }

  if (!reportResponse) {
    return (
      <div className="container py-4">
        <div className="norepotdata">
          <div className="norepotdatainner">
            <span className="svgicon">
              <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 16 16">
                <path d="M8.01 4.555 4.005 7.11 8.01 9.665 4.005 12.22 0 9.651l4.005-2.555L0 4.555 4.005 2zm-4.026 8.487 4.006-2.555 4.005 2.555-4.005 2.555zm4.026-3.39 4.005-2.556L8.01 4.555 11.995 2 16 4.555 11.995 7.11 16 9.665l-4.005 2.555z"/>
              </svg>
            </span>
            <p>No report data available. Please generate a report first.</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="container py-4">
      <IdiReportDisplay reportResponse={reportResponse} />
    </div>
  );
}