// HireArt Onboarding Form — Review dialog (summary step)
const { useState: useS_R } = React;

function ReviewDialog({ open, onClose, onSubmit, data, derivedJob, onEdit }) {
  if (!open) return null;

  const candidate = data.candidateTab === "existing"
    ? EXISTING_CANDIDATES.find(c => c.id === data.candidateId)
    : { name: `${data.newCandidate.firstName} ${data.newCandidate.lastName}`.trim(), email: data.newCandidate.email, phone: data.newCandidate.phone, country: data.newCandidate.country };

  const supervisor = SUPERVISORS.find(s => s.id === data.supervisorId);

  function fmtPay() {
    if (!data.hasPayRateDecided) return "—";
    if (data.hasPayRateDecided === "none") return "To be decided with HireArt";
    const n = Number(data.payRate || 0).toLocaleString();
    const sym = data.currency === "USD" || data.currency === "CAD" ? "$" : data.currency === "GBP" ? "£" : data.currency === "EUR" ? "€" : "";
    const f = ({
      hourly: " / hour", daily: " / day", weekly: " / week",
      monthly: " / month", salary: " / year", lump_sum: " / deliverable",
    })[data.payFrequency] || "";
    return `${sym}${n} ${data.currency}${f}`;
  }

  function fmtDate(d) {
    if (!d) return "";
    return d.toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" });
  }

  function fmtStart() {
    if (data.startDateType === "asap") return "As soon as possible";
    return data.startDate ? fmtDate(data.startDate) : "—";
  }

  function fmtDuration() {
    if (data.hasPlannedEnd === "no") return "Indefinite / open-ended";
    if (data.hasPlannedEnd === "unsure") return "TBD";
    if (data.hasPlannedEnd === "yes") {
      if (data.knownDurationType === "date" && data.endDate) return `Until ${fmtDate(data.endDate)}`;
      if (data.knownDurationType === "estimate" && data.estimatedDurationValue) return `~${data.estimatedDurationValue} ${data.estimatedDurationUnit || "months"}`;
      return "—";
    }
    return "—";
  }

  return (
    <div className="dialog-overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="dialog" style={{ maxWidth: 720 }}>
        <div className="dialog-header">
          <h3 className="dialog-title">
            <Icon name="info" size={20} />
            Review onboarding details
          </h3>
          <p className="dialog-description">
            Take a moment to confirm everything below. You can still edit any section.
          </p>
        </div>
        <div className="dialog-body" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <ReviewBlock
            title="Job"
            onEdit={() => onEdit("job")}
            rows={[
              ["Role", derivedJob.roleName || "—"],
              ["Work environment", workEnvLabel(derivedJob.workEnvironment) || "—"],
              ...(derivedJob.workEnvironment === "remote"
                ? [["Country of work", `${derivedJob.country || "—"}${derivedJob.state ? `, ${derivedJob.state}` : ""}`]]
                : derivedJob.office
                  ? [["Office", `${derivedJob.office.label} — ${derivedJob.office.address}`]]
                  : []),
              ["Classification", classificationLabel(derivedJob.classification)],
              ["Employment type", employmentTypeLabel(derivedJob.employmentType) || "—"],
            ]}
          />
          <ReviewBlock
            title="Candidate"
            onEdit={() => onEdit("candidate")}
            rows={[
              ["Name", candidate?.name || "—"],
              ["Email", candidate?.email || "—"],
              ["Country of residence", candidate?.country || "—"],
              ["Phone", candidate?.phone || "—"],
            ]}
          />
          <ReviewBlock
            title="Compensation"
            onEdit={() => onEdit("compensation")}
            rows={[
              ["Pay rate", fmtPay()],
              ...(data.bonusContext ? [["Bonus / context", data.bonusContext]] : []),
            ]}
          />
          <ReviewBlock
            title="Team"
            onEdit={() => onEdit("team")}
            rows={[
              ["Department", data.department || "—"],
              ["Manager", supervisor ? `${supervisor.name} (${supervisor.email})` : (data.supervisorInvite ? `${data.supervisorInvite.name} — invited` : "—")],
            ]}
          />
          <ReviewBlock
            title="Contract"
            onEdit={() => onEdit("contract")}
            rows={[
              ["Start date", fmtStart()],
              ["Duration", fmtDuration()],
              ["Candidate aware", data.candidateAware === "yes" ? "Yes" : data.candidateAware === "no" ? "No — HireArt will reach out first" : "—"],
            ]}
          />

          <Alert variant="brand" icon="info">
            By submitting, you agree to HireArt's onboarding terms. The candidate will receive an email within 1 business day.
          </Alert>
        </div>
        <div className="dialog-footer">
          <Button variant="ghost" onClick={onClose}>Keep editing</Button>
          <Button variant="primary" iconRight="arrow-right" onClick={onSubmit}>
            Submit onboarding
          </Button>
        </div>
      </div>
    </div>
  );
}

function ReviewBlock({ title, rows, onEdit }) {
  return (
    <div className="summary-card">
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6, paddingBottom: 8, borderBottom: "1.5px solid var(--color-neutral-100)" }}>
        <div style={{ fontFamily: "var(--font-headline)", fontWeight: 700, fontSize: 16 }}>{title}</div>
        <button type="button" className="summary-edit" onClick={onEdit}>Edit</button>
      </div>
      {rows.map(([label, value], i) => (
        <div key={i} className="summary-row">
          <div className="summary-row-label">{label}</div>
          <div className="summary-row-value">{value || "—"}</div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { ReviewDialog, ReviewBlock });
