// HireArt Onboarding Form — Compensation, Team, Contract sections
const { useState: useState2, useEffect: useEffect2, useMemo: useMemo2, useRef } = React;

// ---------- Step 3: Compensation ----------
function CompensationSection({ data, set, errors, derivedJob }) {
  const {
    hasPayRateDecided, payRate, payFrequency, currency,
    bonusContext, deliverableRateType,
    eorProvider, eorProviderOther, billRate, billRateFrequency,
  } = data;

  const isContractor = derivedJob.classification === "contractor" || derivedJob.employmentType === "ic_1099" || derivedJob.employmentType === "international_ic";
  const isEor = derivedJob.employmentType === "international_eor";
  const warnSalary = isContractor && payFrequency === "salary";

  const freqLabel = (f) => ({
    hourly: "hour", daily: "day", weekly: "week",
    biweekly: "two weeks", monthly: "month",
    salary: "year", lump_sum: "deliverable",
  })[f] || f;

  return (
    <SectionCard id="compensation" num="3" title="Compensation" description="Set the compensation details for this offer.">
      <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
        <div>
          <Label required>Has the pay rate been decided?</Label>
          <RadioCardGroup value={hasPayRateDecided} onChange={(v) => set("hasPayRateDecided", v)} name="payDecided" layout="horizontal">
            <RadioCard
              value="pay"
              title="Yes, we've agreed on a rate"
              description="I'll enter it now."
            />
            <RadioCard
              value="none"
              title="Not yet"
              description="HireArt will help finalize."
            />
          </RadioCardGroup>
        </div>

        {hasPayRateDecided === "pay" && (
          <div className="nested-reveal" style={{ display: "flex", flexDirection: "column", gap: 20 }}>
            <div>
              <Label required>Pay frequency</Label>
              <RadioCardGroup value={payFrequency} onChange={(v) => set("payFrequency", v)} name="payFreq" layout="grid">
                {!isContractor && <RadioCard value="salary" title="Annual salary" description="Fixed yearly amount." />}
                <RadioCard value="hourly" title="Hourly" description="Worker logs hours." />
                {isContractor && <RadioCard value="lump_sum" title="Per deliverable" description="Fixed milestone payments." />}
                <RadioCard value="weekly" title="Weekly" description="Recurring weekly payment." />
                <RadioCard value="monthly" title="Monthly" description="Recurring monthly payment." />
              </RadioCardGroup>
              {warnSalary && (
                <div style={{ marginTop: 12 }}>
                  <Alert variant="warn" icon="alert-triangle">
                    Annual salary isn't typical for contractors. Consider hourly or per-deliverable instead.
                  </Alert>
                </div>
              )}
            </div>

            {payFrequency === "lump_sum" && (
              <div className="nested-reveal">
                <Label required>Rate structure</Label>
                <RadioGroup value={deliverableRateType} onChange={(v) => set("deliverableRateType", v)} name="delivRate">
                  <RadioItem value="fixed" label="Fixed price per deliverable" description="Same amount each time." />
                  <RadioItem value="variable" label="Variable" description="Amount differs per deliverable; we'll capture each one." />
                </RadioGroup>
              </div>
            )}

            {!(payFrequency === "lump_sum" && deliverableRateType === "variable") && (
            <div className="pay-grid">
              <div>
                <Label required>Currency</Label>
                <SearchableSelect
                  value={currency}
                  onChange={(v) => set("currency", v)}
                  items={CURRENCIES}
                  placeholder="USD"
                  searchPlaceholder="Search…"
                />
              </div>
              <div>
                <Label required>Pay rate / {freqLabel(payFrequency)}</Label>
                <div style={{ position: "relative" }}>
                  <span style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", color: "var(--color-neutral-60)", fontWeight: 600 }}>
                    {currency === "USD" || currency === "CAD" || currency === "AUD" ? "$" : currency === "GBP" ? "£" : currency === "EUR" ? "€" : currency === "INR" ? "₹" : ""}
                  </span>
                  <Input
                    type="number"
                    value={payRate}
                    onChange={(v) => set("payRate", v)}
                    placeholder={payFrequency === "salary" ? "120,000" : payFrequency === "hourly" ? "75" : "5,000"}
                    style={{ paddingLeft: 28 }}
                    error={errors.payRate}
                  />
                </div>
                {errors.payRate && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.payRate}</p>}
              </div>
            </div>
            )}

            {isEor && (
              <div className="eor-block" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
                <div>
                  <div className="eyebrow" style={{ marginBottom: 4 }}>EOR Placement</div>
                  <h3 style={{ fontFamily: "var(--font-headline)", fontSize: 18, fontWeight: 700, margin: 0 }}>
                    Bill rate &amp; provider
                  </h3>
                  <p style={{ fontSize: 13, color: "var(--color-neutral-80)", margin: "6px 0 0" }}>
                    Required because HireArt will act as the international Employer of Record.
                  </p>
                </div>
                <div>
                  <Label required>EOR provider</Label>
                  <SearchableSelect
                    value={eorProvider}
                    onChange={(v) => set("eorProvider", v)}
                    items={EOR_PROVIDERS}
                    placeholder="Choose provider…"
                    searchPlaceholder="Search…"
                  />
                </div>
                {eorProvider === "other" && (
                  <div className="nested-reveal">
                    <Label required>Provider name</Label>
                    <Input
                      value={eorProviderOther}
                      onChange={(v) => set("eorProviderOther", v)}
                      placeholder="Enter provider name"
                    />
                  </div>
                )}
                <div className="pay-grid">
                  <div>
                    <Label required>Bill rate frequency</Label>
                    <SearchableSelect
                      value={billRateFrequency}
                      onChange={(v) => set("billRateFrequency", v)}
                      items={[
                        { id: "hourly", label: "Hourly" },
                        { id: "monthly", label: "Monthly" },
                        { id: "salary", label: "Annual" },
                      ]}
                    />
                  </div>
                  <div>
                    <Label required>Bill rate</Label>
                    <Input
                      type="number"
                      value={billRate}
                      onChange={(v) => set("billRate", v)}
                      placeholder="Bill rate amount"
                    />
                  </div>
                </div>
              </div>
            )}
          </div>
        )}

        {hasPayRateDecided === "none" && (
          <Alert variant="info" icon="info">
            <strong>HireArt will help you determine fair pay.</strong>
            <div style={{ marginTop: 4, fontSize: 13 }}>
              We'll review market data and follow up with a recommendation within 1 business day.
            </div>
          </Alert>
        )}

        <div>
          <Label optional>Bonus or other context</Label>
          <Textarea
            value={bonusContext}
            onChange={(v) => set("bonusContext", v)}
            placeholder="e.g. $5k signing bonus, 10% performance bonus, equity grant…"
            rows={3}
          />
        </div>
      </div>
    </SectionCard>
  );
}

// ---------- Step 4: Team ----------
function TeamSection({ data, set, errors }) {
  const { department, teamId, supervisorId } = data;

  const filteredTeams = useMemo2(() => {
    if (!department) return TEAMS;
    return TEAMS.filter(t => t.department === department);
  }, [department]);

  const filteredSupervisors = useMemo2(() => {
    if (teamId) {
      const t = TEAMS.find(x => x.id === teamId);
      return SUPERVISORS.filter(s => s.department === t?.department && s.team === t?.team);
    }
    if (department) return SUPERVISORS.filter(s => s.department === department);
    return SUPERVISORS;
  }, [department, teamId]);

  const [inviteOpen, setInviteOpen] = useState2(false);
  const [inviteName, setInviteName] = useState2("");
  const [inviteEmail, setInviteEmail] = useState2("");

  return (
    <SectionCard id="team" num="4" title="Team" description="Assign the worker to a team and manager.">
      <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
        <div>
          <Label required>Department</Label>
          <SearchableSelect
            value={department}
            onChange={(v) => { set("department", v); set("teamId", ""); set("supervisorId", ""); }}
            items={DEPARTMENTS.map(d => ({ id: d, label: d }))}
            placeholder="Select department…"
            searchPlaceholder="Search…"
          />
          {errors.department && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.department}</p>}
        </div>

        <div>
          <Label optional>Team</Label>
          <SearchableSelect
            value={teamId}
            onChange={(v) => { set("teamId", v); set("supervisorId", ""); }}
            items={filteredTeams.map(t => ({ id: t.id, label: `${t.team} — ${t.department}`, team: t }))}
            placeholder="Select team…"
            searchPlaceholder="Search teams…"
          />
          <p className="helper-text">Filtered to {department || "all"} teams.</p>
        </div>

        <div>
          <Label required>Manager / supervisor</Label>
          <div style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
            <div style={{ flex: 1 }}>
              <SearchableSelect
                value={supervisorId}
                onChange={(v) => set("supervisorId", v)}
                items={filteredSupervisors.map(s => ({ id: s.id, label: s.name, sup: s }))}
                placeholder="Select manager…"
                searchPlaceholder="Search by name or email…"
                renderItem={(item) => (
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <span className="pill-avatar" style={{ background: "var(--color-purple-60)" }}>
                      {item.sup.name.split(" ").map(p => p[0]).join("").slice(0,2)}
                    </span>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: 600, fontSize: 14 }}>{item.sup.name}</div>
                      <div style={{ fontSize: 12, color: "var(--color-neutral-60)" }}>
                        {item.sup.email} · {item.sup.team}
                      </div>
                    </div>
                  </div>
                )}
                renderSelected={(item) => (
                  <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <span className="pill-avatar" style={{ background: "var(--color-purple-60)" }}>
                      {item.sup.name.split(" ").map(p => p[0]).join("").slice(0,2)}
                    </span>
                    <span style={{ fontWeight: 600 }}>{item.sup.name}</span>
                    <span style={{ color: "var(--color-neutral-60)", fontSize: 13 }}>{item.sup.email}</span>
                  </span>
                )}
              />
            </div>
            <Button variant="secondary" iconLeft="plus" onClick={() => setInviteOpen(true)}>Invite</Button>
          </div>
          {errors.supervisorId && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.supervisorId}</p>}
        </div>

        <Dialog
          open={inviteOpen}
          onClose={() => setInviteOpen(false)}
          title="Invite a team member"
          description="They'll be added as the manager for this worker with Lead-level access."
          icon="users"
          footer={
            <>
              <Button variant="ghost" onClick={() => setInviteOpen(false)}>Cancel</Button>
              <Button
                variant="primary"
                iconLeft="mail"
                onClick={() => {
                  setInviteOpen(false);
                  set("supervisorInvite", { name: inviteName, email: inviteEmail });
                  setInviteName(""); setInviteEmail("");
                }}
              >
                Send invite
              </Button>
            </>
          }
        >
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div>
              <Label required>Name</Label>
              <Input value={inviteName} onChange={setInviteName} placeholder="Full name" />
            </div>
            <div>
              <Label required>Email</Label>
              <Input type="email" value={inviteEmail} onChange={setInviteEmail} placeholder="name@company.com" />
            </div>
          </div>
        </Dialog>
      </div>
    </SectionCard>
  );
}

// ---------- Step 5: Contract Details ----------
function ContractSection({ data, set, errors, derivedJob }) {
  const {
    workSchedule,
    startDateType, startDate,
    hasPlannedEnd, knownDurationType, endDate, estimatedDurationValue, estimatedDurationUnit,
    candidateAware, candidateAgreedPay, candidateAgreedStart, additionalDetails,
  } = data;

  const isContractor = derivedJob.classification === "contractor" || derivedJob.employmentType === "ic_1099" || derivedJob.employmentType === "international_ic";
  const warnDuration = isContractor && hasPlannedEnd === "no";

  const [startCalOpen, setStartCalOpen] = useState2(false);
  const [endCalOpen, setEndCalOpen] = useState2(false);
  const startRef = useRef(); const endRef = useRef();

  useEffect2(() => {
    function onClick(e) {
      if (startRef.current && !startRef.current.contains(e.target)) setStartCalOpen(false);
      if (endRef.current && !endRef.current.contains(e.target)) setEndCalOpen(false);
    }
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, []);

  return (
    <SectionCard id="contract" num="5" title="Contract Details" description="Specify contract duration, start date, and other details.">
      <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
        <div>
          <Label required>Work schedule</Label>
          <RadioCardGroup value={workSchedule} onChange={(v) => set("workSchedule", v)} name="workSchedule" layout="horizontal">
            <RadioCard value="full_time" title="Full-time" description="30+ hours per week" />
            <RadioCard value="part_time" title="Part-time" description="Less than 30 hours per week" />
          </RadioCardGroup>
          {errors.workSchedule && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.workSchedule}</p>}
        </div>

        <div>
          <Label required>Start date</Label>
          <RadioCardGroup value={startDateType} onChange={(v) => set("startDateType", v)} name="startDate" layout="horizontal">
            <RadioCard value="asap" title="As soon as possible" description="We'll target the next available start." />
            <RadioCard value="date" title="On a specific date" description="Pick a target date." />
          </RadioCardGroup>

          {startDateType === "date" && (
            <div className="nested-reveal" style={{ position: "relative" }} ref={startRef}>
              <Label required>Pick a date</Label>
              <button
                type="button"
                className="select-trigger"
                onClick={() => setStartCalOpen(o => !o)}
                style={{ width: 240 }}
              >
                <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <Icon name="calendar" size={14} />
                  {startDate ? startDate.toLocaleDateString() : <span style={{ color: "var(--color-neutral-50)" }}>Pick a date</span>}
                </span>
                <Icon name="chevron-down" size={14} className="chevron" />
              </button>
              {startCalOpen && (
                <div className="popover" style={{ width: "auto" }}>
                  <Calendar value={startDate} onChange={(d) => { set("startDate", d); setStartCalOpen(false); }} />
                </div>
              )}
              {errors.startDate && <p className="error-text"><Icon name="alert-circle" size={14} /> {errors.startDate}</p>}
            </div>
          )}
        </div>

        <hr className="separator-subtle" />

        <div>
          <Label required>Is there a planned end date?</Label>
          <RadioCardGroup value={hasPlannedEnd} onChange={(v) => set("hasPlannedEnd", v)} name="plannedEnd" layout="grid">
            <RadioCard value="yes" title="Yes" description="Contract has a defined duration." />
            <RadioCard value="no" title="No" description="Indefinite / open-ended." />
            <RadioCard value="unsure" title="Not sure" description="HireArt will follow up." />
          </RadioCardGroup>

          {warnDuration && (
            <div style={{ marginTop: 12 }}>
              <Alert variant="warn" icon="alert-triangle">
                Open-ended contractor engagements can trigger misclassification reviews. Consider adding a planned end date.
              </Alert>
            </div>
          )}

          {hasPlannedEnd === "yes" && (
            <div className="nested-reveal" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <Label>How long will the contract be?</Label>
              <RadioGroup value={knownDurationType} onChange={(v) => set("knownDurationType", v)} name="durType">
                <RadioItem value="date" label="I have a specific end date" />
                <RadioItem value="estimate" label="It's an estimate" />
              </RadioGroup>

              {knownDurationType === "date" && (
                <div ref={endRef} style={{ position: "relative" }}>
                  <Label required>End date</Label>
                  <button
                    type="button"
                    className="select-trigger"
                    onClick={() => setEndCalOpen(o => !o)}
                    style={{ width: 240 }}
                  >
                    <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <Icon name="calendar" size={14} />
                      {endDate ? endDate.toLocaleDateString() : <span style={{ color: "var(--color-neutral-50)" }}>Pick a date</span>}
                    </span>
                    <Icon name="chevron-down" size={14} className="chevron" />
                  </button>
                  {endCalOpen && (
                    <div className="popover" style={{ width: "auto" }}>
                      <Calendar value={endDate} onChange={(d) => { set("endDate", d); setEndCalOpen(false); }} />
                    </div>
                  )}
                </div>
              )}

              {knownDurationType === "estimate" && (
                <div>
                  <Label required>Estimated duration</Label>
                  <div style={{ display: "flex", gap: 8, alignItems: "stretch", maxWidth: 360 }}>
                    <Input
                      type="number"
                      value={estimatedDurationValue}
                      onChange={(v) => set("estimatedDurationValue", v)}
                      placeholder="6"
                      style={{ flex: 1 }}
                    />
                    <div style={{ flex: "0 0 140px" }}>
                      <SearchableSelect
                        value={estimatedDurationUnit || "months"}
                        onChange={(v) => set("estimatedDurationUnit", v)}
                        items={[
                          { id: "days", label: "Days" },
                          { id: "weeks", label: "Weeks" },
                          { id: "months", label: "Months" },
                          { id: "years", label: "Years" },
                        ]}
                      />
                    </div>
                  </div>
                  {(() => {
                    const v = parseFloat(estimatedDurationValue);
                    if (!v) return null;
                    const u = estimatedDurationUnit || "months";
                    const years = u === "years" ? v : u === "months" ? v / 12 : u === "weeks" ? v / 52 : v / 365;
                    if (years > 2) {
                      return (
                        <div style={{ marginTop: 12 }}>
                          <Alert variant="warn" icon="alert-triangle">
                            <strong>Heads up &mdash; engagements over 2 years may trigger compliance review.</strong>
                            <div style={{ marginTop: 4, fontSize: 13 }}>
                              Long-duration contracts can raise misclassification or permanent-employee questions in many jurisdictions. HireArt will review this with you before onboarding.
                            </div>
                          </Alert>
                        </div>
                      );
                    }
                    return null;
                  })()}
                </div>
              )}
            </div>
          )}
        </div>

        <hr className="separator-subtle" />

        <div>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div>
              <Label>The candidate knows this offer is coming</Label>
              <RadioCardGroup value={candidateAware} onChange={(v) => set("candidateAware", v)} name="aware" layout="horizontal">
                <RadioCard value="yes" title="Yes" description="They expect this email." />
                <RadioCard value="no" title="No" description="HireArt will reach out before sending offer." />
              </RadioCardGroup>
            </div>
            <div>
              <Label>The candidate has agreed to the pay</Label>
              <RadioCardGroup value={candidateAgreedPay} onChange={(v) => set("candidateAgreedPay", v)} name="agreedPay" layout="horizontal">
                <RadioCard value="yes" title="Yes" description="Compensation discussed and accepted." />
                <RadioCard value="no" title="No" description="HireArt will confirm pay with them." />
              </RadioCardGroup>
            </div>
            <div>
              <Label>The candidate has agreed to the start date</Label>
              <RadioCardGroup value={candidateAgreedStart} onChange={(v) => set("candidateAgreedStart", v)} name="agreedStart" layout="horizontal">
                <RadioCard value="yes" title="Yes" description="Start date is locked in." />
                <RadioCard value="no" title="No" description="HireArt will confirm timing with them." />
              </RadioCardGroup>
            </div>
          </div>
        </div>

        <hr className="separator-subtle" />

        <div>
          <Label optional>Additional details</Label>
          <Textarea
            value={additionalDetails}
            onChange={(v) => set("additionalDetails", v)}
            placeholder="Anything else we should know?"
            rows={3}
          />
        </div>
      </div>
    </SectionCard>
  );
}

Object.assign(window, { CompensationSection, TeamSection, ContractSection });
