"use client";

import dynamic from "next/dynamic";
import { useSearchParams } from "next/navigation";

const MaterialsList = dynamic(
    () => import("@/app/materials/materials/page"),
                              { ssr: false }
);
const CoatingsList = dynamic(
    () => import("@/app/materials/materials-coatings/page"),
                             { ssr: false }
);

function DetailsFrame({ src }: { src: string }) {
    return (
        <iframe
        key={src}
        src={src}
        className="w-full h-[70vh] rounded-md border"
        sandbox="allow-same-origin allow-scripts allow-forms allow-popups"
        />
    );
}

export default function MaterialsClient() {
    const search = useSearchParams();
    const t = (search.get("t") || "materials").toLowerCase();
    const id = search.get("id");

    const detailSrc =
    !id
    ? null
    : t === "materials"
    ? `/materials/materials/${id}`
    : t === "materials-coatings"
    ? `/materials/materials-coatings/${id}`
    : null;

    return (
        <div className="space-y-4">
        <div className="rounded-lg border p-6">
        <h2 className="mb-4 text-xl font-semibold">Materials</h2>
        {t === "materials" ? <MaterialsList /> : <CoatingsList />}
        </div>

        {detailSrc && (
            <div className="rounded-lg border p-4">
            <div className="mb-2 text-sm opacity-70">
            Viewing {t.replace("-", " ")} #{id}
            </div>
            <DetailsFrame src={detailSrc} />
            </div>
        )}
        </div>
    );
}
