// Export screen — final ATS-friendly resume preview + download

const { useState: useStateExp, useEffect: useEffectExp } = React;

function ExportScreen({ context, onBack, onDone }) {
  const [filename, setFilename] = useStateExp("Maya_Chen_Vercel_Senior_PM_Platform");
  const [format, setFormat] = useStateExp("pdf-ats");
  const [versionName, setVersionName] = useStateExp("Vercel · Senior PM, Platform");
  const [downloaded, setDownloaded] = useStateExp(false);
  const [exporting, setExporting] = useStateExp(null); // "pdf" | "docx" | null
  const [exportErr, setExportErr] = useStateExp(null);

  const onDownloadPdf = async () => {
    setExporting("pdf"); setExportErr(null);
    try {
      await window.ForgeExport.downloadPdf();
      setDownloaded(true);
    } catch (e) {
      setExportErr(String(e.message || e));
    } finally {
      setExporting(null);
    }
  };

  const onDownloadDocx = async () => {
    setExporting("docx"); setExportErr(null);
    try {
      const resume = window.finalizeResume(
        (context && context.decisions) || {},
        context && context.resumeId,
      );
      await window.ForgeExport.downloadDocx({ resume, label: versionName });
      setDownloaded(true);
    } catch (e) {
      setExportErr(String(e.message || e));
    } finally {
      setExporting(null);
    }
  };

  return (
    <div style={{ display: "flex", height: "calc(100vh - 73px)" }}>
      {/* Left: actions panel */}
      <div
        style={{
          width: 420,
          flexShrink: 0,
          borderRight: "1px solid var(--border)",
          background: "var(--paper)",
          overflowY: "auto",
        }}
      >
        <div style={{ padding: "40px 36px 80px" }}>
          <div style={{ marginBottom: 32 }}>
            <StepIndicator step="export" />
          </div>

          <Eyebrow style={{ marginBottom: 10 }}>Final step</Eyebrow>
          <h1
            style={{
              fontFamily: "Newsreader, serif",
              fontSize: 34,
              fontWeight: 400,
              letterSpacing: "-0.025em",
              color: "var(--ink)",
              margin: "0 0 32px",
              lineHeight: 1.1,
            }}
          >
            Ship it.
          </h1>

          {/* Summary of changes */}
          <div
            style={{
              padding: "20px 22px",
              border: "1px solid var(--border)",
              borderRadius: 8,
              background: "var(--paper-2)",
              marginBottom: 32,
            }}
          >
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
              <Eyebrow>This export</Eyebrow>
              <Pill tone="success">Ready</Pill>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <ReadoutRow label="Suggestions accepted" value="5 of 6" />
              <ReadoutRow label="Tailored from" value="Product Manager · v7" />
              <ReadoutRow label="Format" value="PDF, single column" />
            </div>
            <div
              style={{
                marginTop: 14,
                paddingTop: 14,
                borderTop: "1px dashed var(--border)",
                fontFamily: "Inter, sans-serif",
                fontSize: 11,
                color: "var(--muted)",
                lineHeight: 1.55,
              }}
            >
              Exports use a single-column, machine-parsable layout designed to round-trip cleanly through common ATS parsers (Greenhouse, Lever, Workday).
            </div>
          </div>

          {/* Format */}
          <Eyebrow style={{ marginBottom: 10 }}>Format</Eyebrow>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 28 }}>
            {[
              { key: "pdf-ats", label: "PDF · ATS-optimized", sub: "Plain layout, single column, machine-parsable", primary: true },
              { key: "pdf-design", label: "PDF · designed template", sub: "Looks pretty but some ATS may stumble", primary: false, disabled: true },
              { key: "docx", label: "DOCX", sub: "For application portals requiring Word", primary: false, disabled: true },
            ].map((f) => (
              <button
                key={f.key}
                disabled={f.disabled}
                onClick={() => !f.disabled && setFormat(f.key)}
                style={{
                  textAlign: "left",
                  padding: "14px 16px",
                  background: format === f.key ? "var(--paper-2)" : "transparent",
                  border: `1px solid ${format === f.key ? "var(--ink)" : "var(--border)"}`,
                  borderRadius: 6,
                  cursor: f.disabled ? "not-allowed" : "pointer",
                  opacity: f.disabled ? 0.45 : 1,
                  position: "relative",
                }}
              >
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 4 }}>
                  <div style={{ fontFamily: "Inter, sans-serif", fontSize: 13, fontWeight: 500, color: "var(--ink)" }}>
                    {f.label}
                  </div>
                  {f.disabled && <Pill style={{ fontSize: 9 }}>Soon</Pill>}
                </div>
                <div style={{ fontFamily: "Inter, sans-serif", fontSize: 12, color: "var(--muted)" }}>{f.sub}</div>
              </button>
            ))}
          </div>

          {/* Filename */}
          <Eyebrow style={{ marginBottom: 10 }}>Filename</Eyebrow>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              border: "1px solid var(--border)",
              borderRadius: 6,
              padding: "0 14px",
              background: "var(--paper-2)",
              marginBottom: 24,
            }}
          >
            <input
              value={filename}
              onChange={(e) => setFilename(e.target.value)}
              style={{
                flex: 1,
                background: "transparent",
                border: "none",
                outline: "none",
                fontFamily: "'JetBrains Mono', monospace",
                fontSize: 12,
                color: "var(--ink)",
                padding: "12px 0",
              }}
            />
            <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 12, color: "var(--muted)" }}>
              .pdf
            </span>
          </div>

          {/* Save version */}
          <Eyebrow style={{ marginBottom: 10 }}>Save as version</Eyebrow>
          <div
            style={{
              padding: 14,
              border: "1px solid var(--border)",
              borderRadius: 6,
              background: "var(--paper-2)",
              marginBottom: 28,
            }}
          >
            <input
              value={versionName}
              onChange={(e) => setVersionName(e.target.value)}
              style={{
                width: "100%",
                background: "transparent",
                border: "none",
                outline: "none",
                fontFamily: "Inter, sans-serif",
                fontSize: 13,
                color: "var(--ink)",
                marginBottom: 8,
              }}
            />
            <div style={{ fontFamily: "Inter, sans-serif", fontSize: 11, color: "var(--muted)", lineHeight: 1.5 }}>
              Saved under Product Manager · v8. Reuse for similar roles later.
            </div>
          </div>

          {/* CTAs */}
          <Button
            variant="accent"
            icon={Icon.download}
            onClick={onDownloadPdf}
            disabled={exporting === "pdf"}
            style={{ width: "100%", justifyContent: "center", padding: "12px 16px", fontSize: 14, marginBottom: 10 }}
          >
            {exporting === "pdf" ? "Opening print…" : "Download PDF"}
          </Button>
          <Button
            variant="quiet"
            icon={Icon.download}
            onClick={onDownloadDocx}
            disabled={exporting === "docx"}
            style={{ width: "100%", justifyContent: "center", padding: "12px 16px", fontSize: 14 }}
          >
            {exporting === "docx" ? "Building…" : "Download .docx"}
          </Button>
          {exportErr && (
            <div style={{ marginTop: 10, color: "#E08A6B", fontSize: 12 }}>{exportErr}</div>
          )}

          {downloaded && (
            <div
              style={{
                marginTop: 16,
                padding: 14,
                background: "color-mix(in oklab, #4a7a4a 8%, transparent)",
                borderRadius: 6,
                border: "1px solid color-mix(in oklab, #4a7a4a 20%, transparent)",
              }}
            >
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                <span style={{ color: "#3d6b3d" }}>{Icon.check}</span>
                <div style={{ fontFamily: "Inter, sans-serif", fontSize: 13, fontWeight: 500, color: "#3d6b3d" }}>
                  Version saved
                </div>
              </div>
              <div style={{ fontFamily: "Inter, sans-serif", fontSize: 12, color: "#3d6b3d", lineHeight: 1.5 }}>
                Find it in the Product Manager resume — Versions tab.
              </div>
              <button
                onClick={onDone}
                style={{
                  marginTop: 10,
                  background: "none",
                  border: "none",
                  color: "#3d6b3d",
                  fontFamily: "Inter, sans-serif",
                  fontSize: 12,
                  fontWeight: 500,
                  cursor: "pointer",
                  textDecoration: "underline",
                  textUnderlineOffset: 3,
                  padding: 0,
                }}
              >
                Back to library →
              </button>
            </div>
          )}

          <div style={{ marginTop: 28 }}>
            <Button variant="quiet" onClick={onBack}>
              ← Back to review
            </Button>
          </div>
        </div>
      </div>

      {/* Right: PDF preview */}
      <div
        style={{
          flex: 1,
          background: "var(--paper-3)",
          overflowY: "auto",
          padding: "48px 0",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
        }}
      >
        <div
          className="resume-print-region"
          style={{
            background: "white",
            width: 720,
            minHeight: 932,
            boxShadow: "0 20px 50px -20px rgba(27,24,20,0.25), 0 4px 12px -4px rgba(27,24,20,0.08)",
            padding: "64px 72px",
            position: "relative",
          }}
        >
          <ResumePaper
            decisions={(context && context.decisions) || {}}
            template={(context && context.template) || "modern"}
            resumeId={context && context.resumeId}
          />
        </div>
        <div
          style={{
            marginTop: 20,
            fontFamily: "'JetBrains Mono', monospace",
            fontSize: 11,
            color: "var(--muted)",
            letterSpacing: "0.08em",
          }}
        >
          PAGE 1 OF 1 · LETTER · ATS-OPTIMIZED
        </div>
      </div>
    </div>
  );
}

function ReadoutRow({ label, value }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
      <div style={{ fontFamily: "Inter, sans-serif", fontSize: 12, color: "var(--muted)" }}>{label}</div>
      <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: "var(--ink)", fontWeight: 500 }}>
        {value}
      </div>
    </div>
  );
}

Object.assign(window, { ExportScreen });
