import { useState } from "react";
import { useBackLayer } from "../../app/useBackLayer.js";
import { useI18n } from "../../shared/I18nProvider.jsx";

export function ArtifactPreview({ artifact }) {
  const { t } = useI18n();
  const [open, setOpen] = useState(false);
  const dismiss = useBackLayer(open, () => setOpen(false), "artifact-preview", { preferTop: true });

  return <section className="artifact-preview-card">
    <header>
      <span><strong>{artifact.name}</strong><small>{t("artifact.htmlPreview")}</small></span>
      <button type="button" onClick={() => setOpen(true)}>{t("artifact.expand")}</button>
    </header>
    <iframe className="artifact-preview-frame" src={artifact.url} title={artifact.name} sandbox="" referrerPolicy="no-referrer" />
    {open && <div className="artifact-preview-overlay" role="dialog" aria-modal="true" aria-label={t("artifact.previewTitle", { name: artifact.name })} onClick={(event) => { if (event.target === event.currentTarget) dismiss(); }}>
      <div className="artifact-preview-dialog">
        <header><strong>{artifact.name}</strong><button type="button" aria-label={t("artifact.close")} onClick={() => dismiss()}>{"\u00d7"}</button></header>
        <iframe className="artifact-preview-frame is-expanded" src={artifact.url} title={artifact.name} sandbox="" referrerPolicy="no-referrer" />
      </div>
    </div>}
  </section>;
}
