// Caliber — "The 24-Month Contract Buyout" dark mega-section.
// Dominant hero moment: "Locked into Bullhorn?" cycles through 9 competitor
// wordmarks every 2.4s; below, a 4-step 9-day timeline and a real claim form.
//
// Business framing (per PLAN.md §A):
//   - We DON'T reimburse cash. We give Caliber free during the overlap.
//   - Page promises: (a) there is a buyout, (b) it's 24 months, (c) click to claim.
//   - Specifics (Core-free, Scout 50%) stay off the page — they happen in the
//     one-on-one that the "Claim my buyout" button kicks off.
//   - Carousel covers every big ATS so no agency feels "this isn't for me".
//
// Exports: <BuyoutSection />

/* ---------- Competitor carousel list ---------- */
// Brand-accurate colors, tuned for legibility on dark ink (#06082C).
// Fraunces italic treatment — sits cleanly in the giant display headline.
const BUYOUT_COMPETITORS = [
  { name: 'Bullhorn',    color: '#FF6A3D' },
  { name: 'JobAdder',    color: '#3DA8F4' },
  { name: 'Vincere',     color: '#00BFA6' },
  { name: 'Recruit CRM', color: '#4F7FFF' },
  { name: 'Crelate',     color: '#8566F8' },
  { name: 'Loxo',        color: '#A389FF' },
  { name: 'Manatal',     color: '#FF5A5F' },
  { name: 'TeamTailor',  color: '#F19AB2' },
  { name: 'Workable',    color: '#21C2A3' },
];

/* ---------- 4-step timeline (9-day sweep) ---------- */
const BUYOUT_TIMELINE = [
  { day: 'Day 0', title: 'Start the trial',       body: 'Spin up Caliber, invite your team, load one real role. No contract, no card.' },
  { day: 'Day 3', title: 'Kick-off call',         body: 'We scope your exports, seats, and the term left on your incumbent. You sign nothing yet.' },
  { day: 'Day 7', title: 'Cutover',               body: 'Candidates, notes, pipelines, contracts migrated. Caliber becomes your system of record. Incumbent keeps running until its term ends.' },
  { day: 'Day 8', title: 'First Scout shortlist', body: 'Brief it in plain English. Your first Scout pipeline lands the day after cutover.' },
];

/* ---------- Style tokens local to this section ---------- */
const BO_INK    = '#06082C';     // canonical dark-ink; matches Monday 9am section per design system
const BO_MONO   = 'ui-monospace, "SF Mono", Menlo, Consolas, monospace';
const BO_SERIF  = '"Fraunces", "Times New Roman", serif';

/* =========================================================
   MAIN
   ========================================================= */
function BuyoutSection() {
  return (
    <section
      className="cal-section"
      data-screen-label="24-Month Contract Buyout"
      data-nav-theme="dark"
      style={{
        background: BO_INK,
        color: '#fff',
        padding: '100px 72px 120px',
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      <BuyoutBackground />

      <div className="cal-container" style={{ position: 'relative' }}>
        {/* ─────── Eyebrow ─────── */}
        <div
          className="cal-eyebrow"
          style={{
            background: 'rgba(255,255,255,0.04)',
            color: 'rgba(255,255,255,0.85)',
            border: '1px solid rgba(255,255,255,0.12)',
            marginBottom: 36,
          }}
        >
          <CalStar size={11} grad={false} style={{ color: 'var(--cal-accent)' }} />
          The 24-Month Contract Buyout
        </div>

        {/* ─────── Headline with competitor carousel ─────── */}
        <BuyoutHeadline />

        {/* ─────── Subhead (eligible list moved into the form's left column) ─────── */}
        <div style={{ marginTop: 40, marginBottom: 48, maxWidth: 680 }}>
          <p style={{ margin: 0, fontSize: 'clamp(17px, 1.35vw, 21px)', lineHeight: 1.55, color: 'rgba(255,255,255,0.78)', textWrap: 'pretty' }}>
            We'll absorb up to{' '}
            <span style={{ color: '#fff', fontWeight: 500 }}>24 months of overlap</span>{' '}
            while your old tool runs out. One conversation, no hidden terms.
          </p>
        </div>

        {/* ─────── Timeline ─────── */}
        <BuyoutTimeline />

        {/* ─────── Claim form ─────── */}
        <BuyoutClaimForm />
      </div>
    </section>
  );
}

/* =========================================================
   Headline + carousel — dominant moment. Three-line structure
   per S11.7: cycling H1 → static H2 → small tag.
   ========================================================= */
function BuyoutHeadline() {
  const [i, setI] = React.useState(0);

  React.useEffect(() => {
    const id = setInterval(() => {
      setI((v) => (v + 1) % BUYOUT_COMPETITORS.length);
    }, 2400);
    return () => clearInterval(id);
  }, []);

  const widest = BUYOUT_COMPETITORS.reduce(
    (m, b) => (b.name.length > m ? b.name.length : m),
    0
  );

  return (
    <div>
      {/* Line 1 — cycling, Fraunces italic, brand-colored */}
      <h2
        style={{
          margin: 0,
          fontSize: 'clamp(56px, 7.2vw, 104px)',
          fontWeight: 500,
          letterSpacing: '-0.04em',
          lineHeight: 0.98,
          color: '#fff',
          textWrap: 'balance',
        }}
      >
        Locked into{' '}
        <span
          style={{
            display: 'inline-block',
            position: 'relative',
            verticalAlign: 'baseline',
            textAlign: 'left',
          }}
        >
          {BUYOUT_COMPETITORS.map((b, idx) => (
            <span
              key={b.name}
              aria-hidden={idx !== i}
              style={{
                position: idx === i ? 'relative' : 'absolute',
                top: 0,
                left: 0,
                opacity: idx === i ? 1 : 0,
                filter: idx === i ? 'blur(0)' : 'blur(8px)',
                transform: idx === i ? 'translateY(0)' : 'translateY(6px)',
                transition: 'opacity .5s ease, filter .5s ease, transform .5s ease, color .5s ease',
                fontFamily: BO_SERIF,
                fontStyle: 'normal',
                fontWeight: 700,
                fontVariationSettings: '"opsz" 14, "SOFT" 100, "WONK" 0, "wght" 700',
                color: b.color,
                letterSpacing: '-0.02em',
                whiteSpace: 'nowrap',
                willChange: 'opacity, filter, transform, color',
              }}
            >
              {b.name}
            </span>
          ))}
        </span>
        ?
      </h2>

      {/* Line 2 — static, medium */}
      <div
        style={{
          marginTop: 22,
          fontSize: 'clamp(26px, 2.6vw, 40px)',
          fontWeight: 500,
          letterSpacing: '-0.025em',
          lineHeight: 1.15,
          color: 'rgba(255,255,255,0.88)',
          textWrap: 'balance',
        }}
      >
        Two years left?{' '}
        <span style={{ color: '#fff' }}>We'll buy you out.</span>
      </div>
    </div>
  );
}

/* =========================================================
   6-step timeline
   ========================================================= */
function BuyoutTimeline() {
  const highlight = 3; // Day 8 first Scout shortlist — the payoff
  return (
    <div style={{ marginBottom: 72 }}>
      <div style={{ marginBottom: 36 }}>
        <h3
          style={{
            margin: 0,
            fontSize: 'clamp(22px, 2vw, 30px)',
            fontWeight: 500,
            letterSpacing: '-0.02em',
            color: '#fff',
            whiteSpace: 'nowrap',
          }}
        >
          One week to cutover.{' '}
          <span style={{ color: 'rgba(255,255,255,0.55)', fontWeight: 400 }}>
            If it takes longer, we eat the overlap month.
          </span>
        </h3>
      </div>

      <div style={{ position: 'relative' }}>
        {/* Rail */}
        <div
          style={{
            position: 'absolute',
            top: 20,
            left: '4%',
            right: '4%',
            height: 1,
            background: 'rgba(255,255,255,0.12)',
          }}
        />
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(4, 1fr)',
            gap: 20,
            position: 'relative',
          }}
        >
          {BUYOUT_TIMELINE.map((s, i) => (
            <div
              key={s.day}
              style={{
                display: 'flex',
                flexDirection: 'column',
                gap: 16,
              }}
            >
              <div
                style={{
                  width: 40,
                  height: 40,
                  borderRadius: 999,
                  background: i === highlight ? 'var(--cal-accent)' : '#fff',
                  color: i === highlight ? '#fff' : BO_INK,
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: 13,
                  fontWeight: 700,
                  border: `4px solid ${BO_INK}`,
                  boxShadow: `0 0 0 1px ${
                    i === highlight ? 'var(--cal-accent)' : 'rgba(255,255,255,0.2)'
                  }`,
                  fontFeatureSettings: '"tnum"',
                }}
              >
                {i + 1}
              </div>

              <div>
                <div
                  style={{
                    fontSize: 10.5,
                    fontWeight: 700,
                    letterSpacing: '0.14em',
                    textTransform: 'uppercase',
                    color: i === highlight ? 'var(--cal-accent)' : 'rgba(255,255,255,0.55)',
                    marginBottom: 6,
                    fontFamily: BO_MONO,
                  }}
                >
                  {s.day}
                </div>
                <div
                  style={{
                    fontSize: 16.5,
                    fontWeight: 500,
                    letterSpacing: '-0.015em',
                    marginBottom: 6,
                    color: '#fff',
                    lineHeight: 1.25,
                  }}
                >
                  {s.title}
                </div>
                <div
                  style={{
                    fontSize: 12.5,
                    color: 'rgba(255,255,255,0.6)',
                    lineHeight: 1.5,
                    textWrap: 'pretty',
                  }}
                >
                  {s.body}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* =========================================================
   Claim form — real button → short form inline.
   Submit is a no-op (prototype); shows a success state so the
   psychology lands without wiring an endpoint.
   ========================================================= */
function BuyoutClaimForm() {
  const [tool, setTool] = React.useState('Bullhorn');
  const [email, setEmail] = React.useState('');
  const [seats, setSeats] = React.useState('10');
  // Default renewal date = 12 months from today (YYYY-MM). Gives the form
  // something to show so the field doesn't read as empty/broken.
  const [renewal, setRenewal] = React.useState(() => {
    const d = new Date();
    d.setMonth(d.getMonth() + 12);
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
  });
  const [state, setState] = React.useState('idle'); // idle | submitting | done

  const submit = (e) => {
    e.preventDefault();
    if (state !== 'idle') return;
    setState('submitting');
    setTimeout(() => setState('done'), 900);
  };

  return (
    <div
      id="claim"
      style={{
        background: 'rgba(255,255,255,0.04)',
        border: '1px solid rgba(255,255,255,0.12)',
        borderRadius: 24,
        padding: '40px 44px',
        display: 'grid',
        gridTemplateColumns: '0.9fr 1.1fr',
        gap: 48,
        alignItems: 'stretch',
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      {/* LEFT — the pitch (flex col so the eligible block sits flush against the form bottom) */}
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        <h3
          style={{
            margin: '0 0 16px',
            fontSize: 'clamp(26px, 2.4vw, 36px)',
            fontWeight: 500,
            letterSpacing: '-0.025em',
            lineHeight: 1.1,
            color: '#fff',
            textWrap: 'balance',
          }}
        >
          Tell us what you’re locked into.{' '}
          <span
            style={{
              fontFamily: BO_SERIF,
              fontStyle: 'italic',
              fontWeight: 500,
              fontVariationSettings: '"opsz" 72, "SOFT" 100, "WONK" 0, "wght" 500',
              color: 'rgba(255,255,255,0.6)',
            }}
          >
            We’ll take it from there.
          </span>
        </h3>
        <p
          style={{
            fontSize: 14.5,
            lineHeight: 1.55,
            color: 'rgba(255,255,255,0.6)',
            margin: 0,
            maxWidth: 380,
            textWrap: 'pretty',
          }}
        >
          Claimed buyouts get a reply in under 24 hours, NZ business hours.
          A real person, not a lead-qual bot. Numbers and eligibility walked
          through on the call — nothing to argue with a chat widget.
        </p>
        <div
          style={{
            marginTop: 'auto',
            paddingTop: 16,
            fontSize: 12,
            color: 'rgba(255,255,255,0.5)',
            fontFamily: BO_MONO,
            letterSpacing: '0.04em',
            lineHeight: 1.6,
          }}
        >
          Eligible: any active ATS or CRM contract. {BUYOUT_COMPETITORS.map((b) => b.name).join(', ')}, and more.
        </div>
      </div>

      {/* RIGHT — the form */}
      {state === 'done' ? (
        <BuyoutSuccessCard tool={tool} seats={seats} renewal={renewal} />
      ) : (
        <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Field
              label="Work email"
              type="email"
              placeholder="you@agency.com"
              value={email}
              onChange={setEmail}
              required
            />
            <Field
              label="Seats on your current tool"
              type="text"
              inputMode="numeric"
              placeholder="10"
              value={seats}
              onChange={(v) => setSeats(v.replace(/[^\d]/g, '').slice(0, 3))}
              required
            />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <FieldSelect
              label="Current incumbent"
              value={tool}
              onChange={setTool}
              options={BUYOUT_COMPETITORS.map((b) => b.name).concat(['Other'])}
            />
            <Field
              label="Renewal date"
              type="month"
              placeholder="2027-04"
              value={renewal}
              onChange={setRenewal}
              className="cal-dark-date"
              required
            />
          </div>

          <button
            type="submit"
            disabled={state === 'submitting'}
            style={{
              marginTop: 8,
              padding: '15px 22px',
              borderRadius: 14,
              border: 'none',
              cursor: state === 'submitting' ? 'wait' : 'pointer',
              background: 'var(--cal-accent)',
              color: '#fff',
              fontSize: 15.5,
              fontWeight: 600,
              fontFamily: 'inherit',
              letterSpacing: '-0.005em',
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 10,
              boxShadow: state === 'submitting' ? 'none' : '0 18px 36px -14px rgba(255,106,61,0.55)',
              transition: 'transform .1s',
            }}
          >
            {state === 'submitting' ? (
              <>
                <span
                  style={{
                    width: 13,
                    height: 13,
                    borderRadius: 999,
                    border: '2px solid rgba(255,255,255,0.4)',
                    borderTopColor: '#fff',
                    animation: 'cal-star-spin .7s linear infinite',
                    display: 'inline-block',
                  }}
                />
                Claiming your buyout…
              </>
            ) : (
              <>
                Claim my buyout
                <span aria-hidden>→</span>
              </>
            )}
          </button>

          <div
            style={{
              fontSize: 11.5,
              color: 'rgba(255,255,255,0.45)',
              fontFamily: BO_MONO,
              letterSpacing: '0.03em',
              lineHeight: 1.6,
              marginTop: 2,
            }}
          >
            We reply in under 24 hours. Your data never leaves Caliber.
            Eligibility and specifics walked through on the call.
          </div>
        </form>
      )}
    </div>
  );
}

function Field({ label, type, placeholder, value, onChange, required, inputMode, className }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
      <span
        style={{
          fontSize: 11,
          letterSpacing: '0.08em',
          textTransform: 'uppercase',
          color: 'rgba(255,255,255,0.6)',
          fontWeight: 600,
          fontFamily: BO_MONO,
        }}
      >
        {label}
      </span>
      <input
        type={type}
        placeholder={placeholder}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        required={required}
        inputMode={inputMode}
        className={className}
        style={{
          background: 'rgba(255,255,255,0.06)',
          border: '1px solid rgba(255,255,255,0.14)',
          borderRadius: 10,
          padding: '13px 14px',
          color: '#fff',
          fontSize: 14.5,
          fontFamily: 'inherit',
          outline: 'none',
          transition: 'border-color .15s, background .15s',
        }}
        onFocus={(e) => {
          e.target.style.borderColor = 'var(--cal-accent)';
          e.target.style.background = 'rgba(255,255,255,0.08)';
        }}
        onBlur={(e) => {
          e.target.style.borderColor = 'rgba(255,255,255,0.14)';
          e.target.style.background = 'rgba(255,255,255,0.06)';
        }}
      />
    </label>
  );
}

function FieldSelect({ label, value, onChange, options }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
      <span
        style={{
          fontSize: 11,
          letterSpacing: '0.08em',
          textTransform: 'uppercase',
          color: 'rgba(255,255,255,0.6)',
          fontWeight: 600,
          fontFamily: BO_MONO,
        }}
      >
        {label}
      </span>
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{
          background: 'rgba(255,255,255,0.06)',
          border: '1px solid rgba(255,255,255,0.14)',
          borderRadius: 10,
          padding: '13px 14px',
          color: '#fff',
          fontSize: 14.5,
          fontFamily: 'inherit',
          outline: 'none',
          appearance: 'none',
          WebkitAppearance: 'none',
          backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='7' viewBox='0 0 12 7' fill='none'><path d='M1 1L6 6L11 1' stroke='white' stroke-opacity='0.6' stroke-width='1.6' stroke-linecap='round'/></svg>")`,
          backgroundRepeat: 'no-repeat',
          backgroundPosition: 'right 14px center',
          paddingRight: 36,
        }}
      >
        {options.map((o) => (
          <option key={o} value={o} style={{ background: BO_INK }}>
            {o}
          </option>
        ))}
      </select>
    </label>
  );
}

/* =========================================================
   Success state — replaces the form post-submit
   ========================================================= */
function BuyoutSuccessCard({ tool, seats, renewal }) {
  return (
    <div
      style={{
        background: 'rgba(34,197,94,0.08)',
        border: '1px solid rgba(34,197,94,0.3)',
        borderRadius: 16,
        padding: '28px 28px 26px',
        display: 'flex',
        flexDirection: 'column',
        gap: 18,
      }}
    >
      <div
        style={{ display: 'flex', alignItems: 'center', gap: 12 }}
      >
        <div
          style={{
            width: 32,
            height: 32,
            borderRadius: 999,
            background: '#22C55E',
            color: BO_INK,
            display: 'inline-flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: 15,
            fontWeight: 800,
          }}
        >
          ✓
        </div>
        <div
          style={{
            fontSize: 11,
            letterSpacing: '0.14em',
            textTransform: 'uppercase',
            color: '#86EFAC',
            fontWeight: 700,
            fontFamily: BO_MONO,
          }}
        >
          Buyout claimed
        </div>
      </div>

      <div
        style={{
          fontSize: 22,
          fontWeight: 500,
          letterSpacing: '-0.02em',
          lineHeight: 1.25,
          color: '#fff',
        }}
      >
        You’re in the queue. We’ll email you inside 24 hours to walk the numbers.
      </div>

      <div
        style={{
          fontSize: 13,
          color: 'rgba(255,255,255,0.55)',
          fontFamily: BO_MONO,
          lineHeight: 1.6,
          padding: '14px 0 0',
          borderTop: '1px solid rgba(34,197,94,0.2)',
          display: 'grid',
          gridTemplateColumns: '1fr 1fr',
          gap: 10,
        }}
      >
        <div><span style={{ color: 'rgba(255,255,255,0.35)' }}>tool:</span> {tool}</div>
        <div><span style={{ color: 'rgba(255,255,255,0.35)' }}>seats:</span> {seats}</div>
        <div style={{ gridColumn: '1 / -1' }}>
          <span style={{ color: 'rgba(255,255,255,0.35)' }}>renews:</span>{' '}
          {renewal || '—'}
        </div>
      </div>
    </div>
  );
}

/* =========================================================
   Background — ambient, not distracting
   ========================================================= */
function BuyoutBackground() {
  return (
    <div
      aria-hidden
      style={{
        position: 'absolute',
        inset: 0,
        pointerEvents: 'none',
        background: `
          radial-gradient(1100px 600px at 85% -5%, rgba(255,106,61,0.12), transparent 60%),
          radial-gradient(900px 600px at 5% 110%, rgba(0,82,255,0.18), transparent 65%),
          linear-gradient(to right, rgba(255,255,255,0.025) 1px, transparent 1px),
          linear-gradient(to bottom, rgba(255,255,255,0.025) 1px, transparent 1px)
        `,
        backgroundSize: '100% 100%, 100% 100%, 90px 90px, 90px 90px',
      }}
    />
  );
}

Object.assign(window, { BuyoutSection });
