// HireArt Onboarding Form — Job + Candidate sections
const { useState, useEffect, useMemo } = React;

// ---------- Section card wrapper ----------
function SectionCard({ id, num, title, description, children }) {
  return (
    <section id={`section-${id}`} className="card" style={{ marginBottom: 24 }}>
      <div className="card-header">
        <h2 className="card-title">
          <span className="card-title-eyebrow">{num}</span>
          {title}
        </h2>
        {description && <p className="card-description">{description}</p>}
      </div>
      <div className="card-content">{children}</div>
    </section>
  );
}

// ---------- Office location nested reveal (used inside work-env card group) ----------
function OfficeLocationReveal({ newJob, officeItems, pickOffice, setOfficeDialogOpen, errors, style }) {
  return (
    <div className="nested-reveal tight" style={style}>
      <Label required>Office location</Label>
      <SearchableSelect
        value={newJob.officeId}
        onChange={pickOffice}
        items={officeItems}
        placeholder="Select office…"
        searchPlaceholder="Search offices…"
        emptyMessage="No matching offices."
        onCreateNew={() => setOfficeDialogOpen(true)}
        createLabel="Add new office address"
        createPlacement="top"
        renderItem={(it) => (
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            <span style={{ fontWeight: 600, color: "var(--color-neutral-100)" }}>{it.office.label}</span>
            <span style={{ fontSize: 13, color: "var(--color-neutral-70)" }}>{it.office.address}</span>
          </div>
        )}
        renderSelected={(it) => (
          <span>
            <span style={{ fontWeight: 600 }}>{it.office.label}</span>
            <span style={{ color: "var(--color-neutral-70)" }}> — {it.office.address}</span>
          </span>
        )}
      />
      {errors.officeId && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.officeId}</p>}
    </div>
  );
}

// ---------- Step 1: Job ----------
function JobSection({ data, set, errors }) {
  const { jobTab, jobId, newJob, classification } = data;
  const collaborators = data.collaborators || [];
  const [collabDialogOpen, setCollabDialogOpen] = React.useState(false);
  const [officeDialogOpen, setOfficeDialogOpen] = React.useState(false);

  const filteredJobs = EXISTING_JOBS;
  const selectedJob = EXISTING_JOBS.find(j => j.id === jobId);

  const effectiveEmploymentType =
    jobTab === "existing"
      ? selectedJob?.employmentType
      : deriveEmploymentType(newJob.country, classification);

  const stateOptions = useMemo(() => {
    if (newJob.country === "USA") return STATES_USA.map(s => ({ id: s, label: s }));
    if (newJob.country === "CAN") return PROVINCES_CAN.map(s => ({ id: s, label: s }));
    return [];
  }, [newJob.country]);

  const showStateField =
    newJob.workEnvironment === "remote" &&
    (newJob.country === "USA" || newJob.country === "CAN");

  const officeItems = React.useMemo(() => {
    const items = OFFICES.map(o => ({ id: o.id, label: o.label, office: o }));
    if (newJob.newOffice) {
      items.push({ id: newJob.newOffice.id, label: newJob.newOffice.label, office: newJob.newOffice });
    }
    return items;
  }, [newJob.newOffice]);

  function pickOffice(officeId) {
    const all = [...OFFICES, ...(newJob.newOffice ? [newJob.newOffice] : [])];
    const o = all.find(x => x.id === officeId);
    if (!o) return;
    set("newJob", { ...newJob, officeId, country: o.country, state: o.state || "" });
  }

  function setWorkEnv(env) {
    if (env === "remote") {
      set("newJob", { ...newJob, workEnvironment: env, officeId: "" });
    } else {
      set("newJob", { ...newJob, workEnvironment: env, country: "", state: "" });
    }
  }

  return (
    <SectionCard id="job" num="1" title="Job Details" description="Choose an existing job or create a new one.">
      <Tabs value={jobTab} onChange={(v) => set("jobTab", v)}>
        <Tab value="existing" label="Existing job" />
        <Tab value="new" label="New job" />
      </Tabs>

      {jobTab === "existing" ? (
        <div style={{ marginTop: 20 }}>
          <Label htmlFor="job-search" required>Search for a job</Label>
          <SearchableSelect
            value={jobId}
            onChange={(v) => set("jobId", v)}
            placeholder="Search by role, country…"
            searchPlaceholder="Search jobs…"
            items={filteredJobs.map(j => ({
              id: j.id,
              label: `${j.roleName} — ${j.country} — ${employmentTypeLabel(j.employmentType)}`,
              job: j,
            }))}
            renderItem={(item) => {
              const j = item.job;
              const QB = ({ icon, children }) => (
                <span className={"badge badge-quiet" + (icon ? " has-icon" : "")}>
                  {icon && (() => {
                    const __u = (window.__resources && window.__resources["icon-" + icon]) || `assets/icons/${icon}.svg`;
                    return <span className="badge-icon" style={{ WebkitMaskImage: `url(${__u})`, maskImage: `url(${__u})` }} />;
                  })()}
                  {children}
                </span>
              );
              return (
                <div>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{j.roleName}</div>
                  <div style={{ display: "flex", flexWrap: "wrap", gap: 4, marginTop: 6 }}>
                    <QB icon="briefcase">{j.department}</QB>
                    <QB>{j.country}{j.state ? `, ${j.state}` : ""}</QB>
                    <QB icon="award">{employmentTypeLabel(j.employmentType)}</QB>
                    {j.workEnvironment && <QB icon="agency">{workEnvLabel(j.workEnvironment)}</QB>}
                    {j.schedule && <QB icon="clock">{scheduleLabel(j.schedule)}</QB>}
                  </div>
                </div>
              );
            }}
            renderSelected={(item) => (
              <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ fontWeight: 600 }}>{item.job.roleName}</span>
                <Badge variant={item.job.classification === "employee" ? "purple" : "yellow"}>
                  {classificationLabel(item.job.classification)}
                </Badge>
                <span style={{ color: "var(--color-neutral-60)", fontSize: 13 }}>
                  {item.job.country}{item.job.state ? `, ${item.job.state}` : ""}
                </span>
              </span>
            )}
          />
          {errors.jobId && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.jobId}</p>}
          {selectedJob && (
            <div className="summary-card" style={{ marginTop: 16 }}>
              <div className="summary-row">
                <div className="summary-row-label">Role</div>
                <div className="summary-row-value">{selectedJob.roleName}</div>
              </div>
              <div className="summary-row">
                <div className="summary-row-label">Department</div>
                <div className="summary-row-value">{selectedJob.department}</div>
              </div>
              <div className="summary-row">
                <div className="summary-row-label">Location</div>
                <div className="summary-row-value">
                  {selectedJob.country}{selectedJob.state ? `, ${selectedJob.state}` : ""}
                </div>
              </div>
              <div className="summary-row">
                <div className="summary-row-label">Type</div>
                <div className="summary-row-value">
                  <Badge variant={selectedJob.classification === "employee" ? "purple" : "yellow"}>
                    {classificationLabel(selectedJob.classification)}
                  </Badge>
                  <span style={{ marginLeft: 8, color: "var(--color-neutral-70)" }}>
                    {employmentTypeLabel(selectedJob.employmentType)}
                  </span>
                </div>
              </div>
            </div>
          )}
        </div>
      ) : (
        <div style={{ marginTop: 20, display: "flex", flexDirection: "column", gap: 20 }}>
          <div>
            <Label required htmlFor="role-name">Role title</Label>
            <Input
              id="role-name"
              value={newJob.roleName}
              onChange={(v) => set("newJob", { ...newJob, roleName: v })}
              placeholder="e.g. Senior Software Engineer"
              error={errors.roleName}
            />
            {errors.roleName && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.roleName}</p>}
          </div>

          <div>
            <Label required>Work environment</Label>
            <RadioCardGroup value={newJob.workEnvironment} onChange={setWorkEnv} name="work-env" layout="horizontal">
              <RadioCard
                value="remote"
                title="Fully remote"
                description="Anywhere the role allows."
              />
              <RadioCard
                value="hybrid"
                title="Hybrid"
                description="Mix of office and remote."
              />
              <RadioCard
                value="onsite"
                title="In-person"
                description="Based at a company office."
              />
            </RadioCardGroup>
            {errors.workEnvironment && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.workEnvironment}</p>}

            {newJob.workEnvironment === "remote" && (
              <div className="nested-reveal tight" style={{ marginTop: 12 }}>
                <Label required>Country of work</Label>
                <SearchableSelect
                  value={newJob.country}
                  onChange={(v) => set("newJob", { ...newJob, country: v, state: "" })}
                  items={COUNTRIES}
                  placeholder="Select country…"
                  searchPlaceholder="Search countries…"
                />
                {errors.country && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.country}</p>}
                {showStateField && (
                  <div style={{ marginTop: 12 }}>
                    <Label required>{newJob.country === "USA" ? "State" : "Province"}</Label>
                    <SearchableSelect
                      value={newJob.state}
                      onChange={(v) => set("newJob", { ...newJob, state: v })}
                      items={stateOptions}
                      placeholder={`Select ${newJob.country === "USA" ? "state" : "province"}…`}
                      searchPlaceholder="Search…"
                    />
                  </div>
                )}
              </div>
            )}

            {(newJob.workEnvironment === "hybrid" || newJob.workEnvironment === "onsite") && (
              <OfficeLocationReveal newJob={newJob} officeItems={officeItems} pickOffice={pickOffice} setOfficeDialogOpen={setOfficeDialogOpen} errors={errors} style={{ marginTop: 12 }} />
            )}
          </div>

          <div>
            <Label required>Worker classification</Label>
            <RadioCardGroup value={classification} onChange={(v) => set("classification", v)} name="classification" layout="vertical">
              <RadioCard
                value="employee"
                title="Employee"
                description="Full-time W-2 / T4 / EOR employee. Benefits, taxes, and overtime are handled by HireArt."
                badge={{ label: "Most common", variant: "blue" }}
              />
              <RadioCard
                value="contractor"
                title="Independent Contractor"
                description="1099 / international IC. Worker invoices for hours or deliverables. No benefits."
              />
              <RadioCard
                value="eor"
                title="Let HireArt decide"
                description="Tell us about the role and we'll recommend the right classification."
              />
            </RadioCardGroup>
            {errors.classification && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.classification}</p>}
          </div>

          {effectiveEmploymentType && (
            <div style={{ marginTop: -10 }}>
              <Alert variant="brand" icon="info">
                <strong>Employment type: {employmentTypeLabel(effectiveEmploymentType)}</strong>
                <div style={{ fontSize: 13, marginTop: 4 }}>
                  Derived from {COUNTRIES.find(c => c.id === newJob.country)?.label || newJob.country} + {classificationLabel(classification)}.
                </div>
              </Alert>
            </div>
          )}

          <div>
            <Label required>Description</Label>
            <Textarea
              value={newJob.description}
              onChange={(v) => set("newJob", { ...newJob, description: v })}
              placeholder="Briefly describe the role and responsibilities…"
              rows={3}
            />
            {errors.description && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.description}</p>}
          </div>
        </div>
      )}

      <CollaboratorsBlock
        collaborators={collaborators}
        onAdd={() => setCollabDialogOpen(true)}
        onRemove={(id) => set("collaborators", collaborators.filter(c => c.id !== id))}
      />

      <AddCollaboratorDialog
        open={collabDialogOpen}
        onClose={() => setCollabDialogOpen(false)}
        existingIds={collaborators.map(c => c.id)}
        onAdd={(c) => {
          set("collaborators", [...collaborators, c]);
          setCollabDialogOpen(false);
        }}
      />

      <AddOfficeDialog
        open={officeDialogOpen}
        onClose={() => setOfficeDialogOpen(false)}
        onAdd={(office) => {
          set("newJob", { ...newJob, newOffice: office, officeId: office.id, country: office.country, state: office.state || "" });
          setOfficeDialogOpen(false);
        }}
      />
    </SectionCard>
  );
}

// ---------- Collaborators sub-block ----------
function CollaboratorsBlock({ collaborators, onAdd, onRemove }) {
  return (
    <div style={{ marginTop: 24, paddingTop: 24, borderTop: "1px solid var(--color-neutral-20)" }}>
      <div className="collab-header">
        <div>
          <Label>Collaborators</Label>
          <p className="helper-text" style={{ margin: 0 }}>
            Give teammates access to this hire. They’ll see the job and the candidate.
          </p>
        </div>
        <Button variant="secondary" iconLeft="plus" onClick={onAdd}>
          Add collaborator
        </Button>
      </div>

      {collaborators.length === 0 ? (
        <div className="collab-empty">
          <Icon name="users" size={16} />
          <span>No collaborators yet — it’s just you on this hire.</span>
        </div>
      ) : (
        <div className="collab-list">
          {collaborators.map((c) => (
            <CollaboratorRow key={c.id} c={c} onRemove={() => onRemove(c.id)} />
          ))}
        </div>
      )}
    </div>
  );
}

function CollaboratorRow({ c, onRemove }) {
  const initials = (c.displayName || c.name).split(" ").map(p => p[0]).join("").slice(0, 2);
  const permLabels = {
    hiring: "Manages hiring",
    hours: "Manages hours",
    pay: "Views pay data",
  };
  return (
    <div className="collab-row">
      <span className="pill-avatar">{initials}</span>
      <div className="collab-identity">
        <div className="collab-name">{c.displayName || c.name}</div>
        <div className="collab-email">{c.email}</div>
      </div>
      <div className="collab-meta">
        <Badge variant={c.role === "admin" ? "purple" : "quiet"}>
          {c.role === "admin" ? "Admin" : "Member"}
        </Badge>
        {c.invited && <Badge variant="yellow">Invited</Badge>}
        {(c.permissions || []).map(p => (
          <Badge key={p} variant="quiet">{permLabels[p] || p}</Badge>
        ))}
      </div>
      <Button
        variant="ghost"
        size="sm"
        iconLeft="trash-2"
        aria-label={`Remove ${c.displayName || c.name}`}
        onClick={onRemove}
        className="collab-remove"
      />
    </div>
  );
}

function AddCollaboratorDialog({ open, onClose, existingIds, onAdd }) {
  const [mode, setMode] = React.useState("existing");
  const [userId, setUserId] = React.useState("");
  const [inviteEmail, setInviteEmail] = React.useState("");
  const [displayName, setDisplayName] = React.useState("");
  const [role, setRole] = React.useState("member");
  const [permissions, setPermissions] = React.useState([]);

  // Reset on open
  React.useEffect(() => {
    if (open) {
      setMode("existing");
      setUserId("");
      setInviteEmail("");
      setDisplayName("");
      setRole("member");
      setPermissions([]);
    }
  }, [open]);

  const candidateUsers = SUPERVISORS.filter(u => !existingIds.includes(u.id));
  const selected = SUPERVISORS.find(u => u.id === userId);

  function togglePerm(key) {
    setPermissions(prev =>
      prev.includes(key) ? prev.filter(p => p !== key) : [...prev, key]
    );
  }

  function handleAdd() {
    if (mode === "existing") {
      if (!selected) return;
      onAdd({
        id: selected.id,
        name: selected.name,
        email: selected.email,
        displayName: selected.name,
        role,
        permissions,
      });
    } else {
      const email = inviteEmail.trim();
      const name = displayName.trim();
      if (!email || !name) return;
      onAdd({
        id: `invite_${email}`,
        name,
        email,
        displayName: name,
        invited: true,
        role,
        permissions,
      });
    }
  }

  const canSubmit =
    permissions.length > 0 &&
    (mode === "existing"
      ? !!selected
      : !!inviteEmail.trim() && !!displayName.trim() && /\S+@\S+\.\S+/.test(inviteEmail.trim()));

  return (
    <Dialog
      open={open}
      onClose={onClose}
      title="Add collaborator"
      description="Give a teammate access. Pick someone from your org or invite a new person by email."
      icon="users"
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button
            variant="primary"
            iconLeft={mode === "invite" ? "mail" : "plus"}
            onClick={handleAdd}
            disabled={!canSubmit}
          >
            {mode === "invite" ? "Send invite" : "Add collaborator"}
          </Button>
        </>
      }
    >
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        <div>
          <Label required>Add a collaborator</Label>
          <SearchableSelect
            value={mode === "invite" ? "" : userId}
            onChange={(id) => {
              // Picking a real user from invite mode → switch back to existing
              if (mode === "invite") {
                setMode("existing");
                setInviteEmail("");
                setDisplayName("");
              }
              setUserId(id);
            }}
            items={candidateUsers.map(u => ({ id: u.id, label: u.name, user: u }))}
            placeholder="Search organization…"
            searchPlaceholder="Search by name or email…"
            onCreateNew={mode === "invite" ? undefined : () => setMode("invite")}
            createLabel="Add new collaborator by email"
            selectedOverride={mode === "invite" ? (
              <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span className="pill-avatar pill-avatar-invite">
                  <Icon name="mail" size={12} />
                </span>
                <span style={{ fontWeight: 600 }}>Add new collaborator by email</span>
              </span>
            ) : undefined}
            renderItem={(item) => (
              <div style={{ display: "flex", alignItems: "center", gap: 10, width: "100%" }}>
                <span className="pill-avatar">
                  {item.user.name.split(" ").map(p => p[0]).join("").slice(0,2)}
                </span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{item.user.name}</div>
                  <div style={{ fontSize: 12, color: "var(--color-neutral-60)", marginTop: 2 }}>
                    {item.user.email}
                  </div>
                </div>
              </div>
            )}
            renderSelected={(item) => (
              <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span className="pill-avatar">
                  {item.user.name.split(" ").map(p => p[0]).join("").slice(0,2)}
                </span>
                <span style={{ fontWeight: 600 }}>{item.user.name}</span>
                <span style={{ color: "var(--color-neutral-60)", fontSize: 13 }}>{item.user.email}</span>
              </span>
            )}
          />
        </div>

        {mode === "invite" && (
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div>
              <Label required>Email</Label>
              <Input
                type="email"
                value={inviteEmail}
                onChange={setInviteEmail}
                placeholder="jane@example.com"
              />
              <p className="helper-text">We’ll email them an invite to join HireArt and view this hire.</p>
            </div>
            <div>
              <Label required>Display name</Label>
              <Input
                value={displayName}
                onChange={setDisplayName}
                placeholder="Jane Smith"
              />
            </div>
          </div>
        )}

        <div>
          <Label required>Role</Label>
          <RadioCardGroup value={role} onChange={setRole} name="collab-role" layout="horizontal">
            <RadioCard value="admin" title="Admin" description="Can edit the hire and invite others." />
            <RadioCard value="member" title="Member" description="Can view and comment on the hire." />
          </RadioCardGroup>
        </div>

        <div>
          <Label required>Permissions</Label>
          <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            <Checkbox
              id="perm-hiring"
              checked={permissions.includes("hiring")}
              onChange={() => togglePerm("hiring")}
              label="Manages hiring"
              description="Move the candidate forward, send offers."
            />
            <Checkbox
              id="perm-hours"
              checked={permissions.includes("hours")}
              onChange={() => togglePerm("hours")}
              label="Manages employee hours"
              description="Approve timesheets once the worker starts."
            />
            <Checkbox
              id="perm-pay"
              checked={permissions.includes("pay")}
              onChange={() => togglePerm("pay")}
              label="Views pay data"
              description="See pay rates, bonuses, and bill rate."
            />
          </div>
        </div>
      </div>
    </Dialog>
  );
}

// ---------- Step 2: Candidate ----------
function CandidateSection({ data, set, errors }) {
  const { candidateTab, candidateId, newCandidate } = data;

  return (
    <SectionCard id="candidate" num="2" title="Candidate" description="Who are you making an offer to?">
      <Tabs value={candidateTab} onChange={(v) => set("candidateTab", v)}>
        <Tab value="new" label="New candidate" />
        <Tab value="existing" label="From your roster" />
      </Tabs>

      {candidateTab === "existing" ? (
        <div style={{ marginTop: 20 }}>
          <Label required>Search candidates</Label>
          <SearchableSelect
            value={candidateId}
            onChange={(v) => set("candidateId", v)}
            items={EXISTING_CANDIDATES.map(c => ({ id: c.id, label: c.name, candidate: c }))}
            placeholder="Search by name or email…"
            searchPlaceholder="Search…"
            renderItem={(item) => (
              <div>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{item.candidate.name}</div>
                <div style={{ fontSize: 12, color: "var(--color-neutral-60)", marginTop: 2 }}>
                  {item.candidate.email}
                </div>
              </div>
            )}
          />
          {errors.candidateId && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.candidateId}</p>}
        </div>
      ) : (
        <div style={{ marginTop: 20, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
          <div>
            <Label required>First name</Label>
            <Input
              value={newCandidate.firstName}
              onChange={(v) => set("newCandidate", { ...newCandidate, firstName: v })}
              placeholder="Jordan"
              error={errors.firstName}
            />
          </div>
          <div>
            <Label required>Last name</Label>
            <Input
              value={newCandidate.lastName}
              onChange={(v) => set("newCandidate", { ...newCandidate, lastName: v })}
              placeholder="Liu"
              error={errors.lastName}
            />
          </div>
          <div style={{ gridColumn: "span 2" }}>
            <Label required>Email</Label>
            <Input
              type="email"
              value={newCandidate.email}
              onChange={(v) => set("newCandidate", { ...newCandidate, email: v })}
              placeholder="jordan.liu@example.com"
              error={errors.email}
            />
            {errors.email && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.email}</p>}
          </div>
          <div style={{ gridColumn: "span 2" }}>
            <Label required>Country of residence</Label>
            <SearchableSelect
              value={newCandidate.country}
              onChange={(v) => set("newCandidate", { ...newCandidate, country: v })}
              items={COUNTRIES}
              placeholder="Select country…"
              searchPlaceholder="Search countries…"
            />
            {errors.candidateCountry && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.candidateCountry}</p>}
          </div>
          <div style={{ gridColumn: "span 2" }}>
            <Label optional>Phone</Label>
            <div className="phone-input-row">
              <SearchableSelect
                value={newCandidate.phoneCode || "+1"}
                onChange={(v) => set("newCandidate", { ...newCandidate, phoneCode: v })}
                items={PHONE_CODES.map(p => ({ id: p.id, label: `${p.label} (${p.dial || p.id})`, dial: p.dial || p.id, country: p.country }))}
                renderSelected={(it) => (
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>
                    <span>{it.country}</span>
                    <span>{it.dial}</span>
                  </span>
                )}
                renderItem={(it) => (
                  <div style={{ display: "flex", alignItems: "center", gap: 10, width: "100%" }}>
                    <span style={{ fontSize: 11, color: "var(--color-neutral-70)", letterSpacing: "0.04em", width: 22 }}>{it.country}</span>
                    <span style={{ flex: 1 }}>{it.label.replace(/ \([^)]*\)$/, "")}</span>
                    <span style={{ color: "var(--color-neutral-70)", fontVariantNumeric: "tabular-nums" }}>{it.dial}</span>
                  </div>
                )}
                searchPlaceholder="Search country or code…"
                popoverWidth="320px"
              />
              <Input
                type="tel"
                value={newCandidate.phone}
                onChange={(v) => set("newCandidate", { ...newCandidate, phone: v })}
                placeholder="(555) 555-0123"
              />
            </div>
          </div>
        </div>
      )}
    </SectionCard>
  );
}

// ---------- File drop component ----------
function FileDrop({ file, onChange, accept, hint }) {
  const [drag, setDrag] = useState(false);
  const inputRef = React.useRef();

  function pickFile() { inputRef.current?.click(); }
  function onSelect(e) {
    const f = e.target.files?.[0];
    if (f) onChange({ name: f.name, size: f.size });
  }
  function onDrop(e) {
    e.preventDefault();
    setDrag(false);
    const f = e.dataTransfer.files?.[0];
    if (f) onChange({ name: f.name, size: f.size });
  }

  if (file) {
    return (
      <div className="file-item">
        <span className="file-item-icon">
          <Icon name="copy" size={16} />
        </span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 14, color: "var(--color-neutral-100)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            {file.name}
          </div>
          <div style={{ fontSize: 12, color: "var(--color-neutral-70)", marginTop: 2 }}>
            {(file.size / 1024).toFixed(0)} KB
          </div>
        </div>
        <button type="button" className="btn btn-ghost btn-sm" onClick={() => onChange(null)}>
          <Icon name="trash-2" size={14} /> Remove
        </button>
      </div>
    );
  }

  return (
    <div
      className={`file-drop ${drag ? "dragover" : ""}`}
      onClick={pickFile}
      onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
      onDragLeave={() => setDrag(false)}
      onDrop={onDrop}
    >
      <input ref={inputRef} type="file" style={{ display: "none" }} accept={accept} onChange={onSelect} />
      <div style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 44, height: 44, borderRadius: 10, background: "var(--color-purple-20)", marginBottom: 8 }}>
        <Icon name="plus" size={20} />
      </div>
      <div style={{ fontWeight: 600, color: "var(--color-neutral-100)", fontSize: 14 }}>
        Drop a file here, or <span style={{ color: "var(--color-purple-80)", textDecoration: "underline" }}>browse</span>
      </div>
      <div style={{ fontSize: 12, color: "var(--color-neutral-70)", marginTop: 4 }}>{hint}</div>
    </div>
  );
}

Object.assign(window, { SectionCard, JobSection, CandidateSection, FileDrop });

// ---------- Add office address dialog ----------
function AddOfficeDialog({ open, onClose, onAdd }) {
  const [label, setLabel] = React.useState("");
  const [street, setStreet] = React.useState("");
  const [city, setCity] = React.useState("");
  const [region, setRegion] = React.useState("");
  const [postal, setPostal] = React.useState("");
  const [country, setCountry] = React.useState("");

  React.useEffect(() => {
    if (open) {
      setLabel(""); setStreet(""); setCity(""); setRegion(""); setPostal(""); setCountry("");
    }
  }, [open]);

  const stateItems = React.useMemo(() => {
    if (country === "USA") return STATES_USA.map(s => ({ id: s, label: s }));
    if (country === "CAN") return PROVINCES_CAN.map(s => ({ id: s, label: s }));
    return [];
  }, [country]);
  const showRegion = country === "USA" || country === "CAN";

  const canSubmit = label.trim() && street.trim() && city.trim() && country && (!showRegion || region);

  function handleAdd() {
    if (!canSubmit) return;
    const addressBits = [street.trim(), `${city.trim()}${region ? ", " + region : ""}${postal ? " " + postal : ""}`].filter(Boolean).join(", ");
    onAdd({
      id: `office_new_${Date.now()}`,
      label: label.trim(),
      address: addressBits,
      country,
      state: showRegion ? region : "",
    });
  }

  return (
    <Dialog
      open={open}
      onClose={onClose}
      title="Add new office address"
      description="This office will be available for future hires too."
      icon="briefcase"
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" iconLeft="plus" onClick={handleAdd} disabled={!canSubmit}>
            Add office
          </Button>
        </>
      }
    >
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <div>
          <Label required>Office name</Label>
          <Input value={label} onChange={setLabel} placeholder="e.g. Austin Studio" />
        </div>
        <div>
          <Label required>Street address</Label>
          <Input value={street} onChange={setStreet} placeholder="123 Main St, Suite 400" />
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <div>
            <Label required>City</Label>
            <Input value={city} onChange={setCity} placeholder="Austin" />
          </div>
          <div>
            <Label optional>Postal code</Label>
            <Input value={postal} onChange={setPostal} placeholder="78701" />
          </div>
        </div>
        <div>
          <Label required>Country</Label>
          <SearchableSelect
            value={country}
            onChange={(v) => { setCountry(v); setRegion(""); }}
            items={COUNTRIES}
            placeholder="Select country…"
            searchPlaceholder="Search countries…"
          />
        </div>
        {showRegion && (
          <div className="nested-reveal tight">
            <Label required>{country === "USA" ? "State" : "Province"}</Label>
            <SearchableSelect
              value={region}
              onChange={setRegion}
              items={stateItems}
              placeholder={`Select ${country === "USA" ? "state" : "province"}…`}
              searchPlaceholder="Search…"
            />
          </div>
        )}
      </div>
    </Dialog>
  );
}
