// site/page-careers.jsx, Careers — open roles + how to apply.
//
// ALL posting copy lives in the CAREERS_JOBS array below — editing a job =
// editing text here; adding a job = copying one object and giving it a new
// slug. Per-role deep links work as fairs.com/careers#<slug> (and
// #careers/<slug> from inside the site).
//
// The apply section runs in one of two modes:
//   1. CAREERS_FORM_ID = '' (launch state): "Email your application" buttons —
//      a pre-addressed mailto to CAREERS_APPLY_EMAIL with the role in the
//      subject and a fill-in template in the body. Works with zero setup.
//   2. CAREERS_FORM_ID = '<jotform id>': embeds a JotForm application form,
//      the same account + embed pattern as the demo form on page-contact.jsx.
//      See TODO.md ("Careers page — swap in the real application form").

const CAREERS_APPLY_EMAIL = 'shane@fairs.com';
const CAREERS_FORM_ID = '262266253469060'; // JotForm "Careers at Fairs.com — Apply". '' = email fallback.

// ─── Job postings ───────────────────────────────────────────
const CAREERS_JOBS = [
  {
    slug: 'customer-success-manager',
    title: 'Customer Success Manager',
    dept: 'Customer Success',
    meta: ['Remote (US)', 'Full-time', 'Some travel during fair season'],
    summary: 'Fairs run on trust and one big week a year. As a Customer Success Manager you’ll own a portfolio of fairs on our platform and carry them through the whole annual cycle — onboarding, on-sale, fair week, and the recap that earns next year. You’re the person our fairs call first, and the reason they stay.',
    sections: [
      { heading: 'What you’ll do', items: [
        'Own a book of fair and festival partners end to end — you’re their main point of contact from kickoff to recap.',
        'Guide new fairs through onboarding: set up their events, tickets, and website alongside them, and get their first on-sale live.',
        'Train fair managers, boards, office staff, and gate volunteers — patiently, in plain English — on ticketing, scanning, and everything they’ll touch during fair week.',
        'Run the season’s key meetings: kickoff, run-of-show before the gates open, and the post-fair recap.',
        'Watch ticket sales pacing and account health, and raise a flag early when a fair needs help.',
        'Be calm, reachable, and useful during fair week — including occasional trips to the fairgrounds.',
        'Grow adoption beyond ticketing: websites, marketing, vendor and sponsor tools.',
        'Own renewals, and loop in sales when a fair is ready to do more.',
      ] },
      { heading: 'What you’ll bring', items: [
        '2+ years in customer success, account management, or another role where you owned the customer relationship (software, ticketing, or live events a plus).',
        'You explain technical things to non-technical people without making them feel small — our customers are fair boards and volunteers, not IT departments.',
        'Organized and self-directed: many of your accounts peak in the same few months, and you’ll keep every plate spinning.',
        'Comfortable with the basics of data — reading a sales report, spotting a trend, keeping the CRM tidy.',
        'Willing to travel occasionally during fair season.',
      ] },
      { heading: 'Nice to have', items: [
        'You grew up around fairs — 4-H, FFA, showing animals, working a food stand, marching in the parade.',
        'Experience with ticketing platforms, box offices, or live events.',
      ] },
    ],
  },
  {
    slug: 'account-executive',
    title: 'Account Executive',
    dept: 'Sales',
    meta: ['Remote (US)', 'Full-time', 'Travel for conventions + visits'],
    summary: 'Every fair we sign starts with a conversation — at a state convention booth, through a referral, or on a call with a fair board that’s tired of duct-taping five vendors together. As an Account Executive you’ll own that conversation from first hello to signed agreement, and bring new fairs onto the platform.',
    sections: [
      { heading: 'What you’ll do', items: [
        'Run the full sales cycle: prospect, discover, demo, propose, negotiate, close.',
        'Build pipeline across fairs, festivals, and expos — outbound, inbound, referrals, and industry relationships.',
        'Show up where the industry does: state and regional fair association conventions, with a booth, a demo, and sometimes a stage slot.',
        'Tailor every demo to the room — a full-time fair manager and a volunteer board have different jobs but the same big week.',
        'Keep your pipeline honest in the CRM: stages, next steps, forecasts.',
        'Hand new fairs to Customer Success cleanly, so their day one feels like we already know them.',
        'Feed what you hear — pricing pressure, competitor moves, missing features — back to the team.',
      ] },
      { heading: 'What you’ll bring', items: [
        '2+ years of closing experience (software, payments, or events a plus).',
        'A consultative style built for boards and committees — these are relationship sales with real decision cycles, not one-call closes.',
        'You demo like you’re telling a story, not reading a spec sheet.',
        'Self-managed and disciplined about pipeline — nobody will be checking whether you made your calls; the results will speak.',
        'Willing to travel for conventions and customer visits — heaviest in the winter convention season.',
      ] },
      { heading: 'Nice to have', items: [
        'Roots in the fair world, or you’ve sold into it — you know what a fair board meeting feels like.',
        'Experience selling ticketing, payments, or event software.',
      ] },
    ],
  },
];

const CAREERS_OFFER = [
  'Competitive pay and benefits',
  'Fully remote, US-based team',
  'Real ownership from day one',
  'A product fairs genuinely love',
  'Fair food. Annually. Professionally justified.',
];

// ─── Helpers ────────────────────────────────────────────────
const careersScrollTo = (id) => {
  const el = document.getElementById(id);
  if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
};

const careersMailto = (job) => (
  `mailto:${CAREERS_APPLY_EMAIL}` +
  `?subject=${encodeURIComponent(`Application — ${job.title}`)}` +
  `&body=${encodeURIComponent(
    `Hi Fairs.com team,\n\nI'd like to apply for the ${job.title} role.\n\n` +
    `Name:\nPhone:\nLinkedIn or website (optional):\nWhere you're based:\n\n` +
    `A few lines about you:\n\n\n` +
    `(Please attach your resume — PDF preferred.)`
  )}`
);

// Apply CTA: email fallback links straight to a pre-filled email for that
// role; once the form is live, it scrolls to the embedded form instead.
function CareersApplyBtn({ job, size = 'md', children }) {
  if (!CAREERS_FORM_ID) {
    return <StubBtn size={size} href={careersMailto(job)}>{children || 'Apply by email'}</StubBtn>;
  }
  return (
    <StubBtn size={size} onClick={() => {
      history.replaceState(null, '', '#careers/apply');
      careersScrollTo('careers-apply');
    }}>{children || 'Apply now'}</StubBtn>
  );
}

// ─── JotForm embed (mode 2) — same pattern as page-contact.jsx ─
function CareersFormEmbed() {
  React.useEffect(() => {
    const id = 'jotform-iframe-handler';
    const init = () => {
      if (window.jotformEmbedHandler) {
        window.jotformEmbedHandler(
          `iframe[id='JotFormIFrame-${CAREERS_FORM_ID}']`,
          'https://www.jotform.com'
        );
      }
    };
    if (document.getElementById(id)) { init(); return; }
    const s = document.createElement('script');
    s.id = id;
    s.src = 'https://cdn.jotfor.ms/s/umd/latest/for-form-embed-handler.js';
    s.async = true;
    s.onload = init;
    document.body.appendChild(s);
  }, []);

  return (
    <iframe
      id={`JotFormIFrame-${CAREERS_FORM_ID}`}
      title="Apply, Fairs.com careers"
      src={`https://form.jotform.com/${CAREERS_FORM_ID}`}
      allow="fullscreen"
      allowtransparency="true"
      scrolling="no"
      style={{
        width: '100%',
        minHeight: 700,
        border: 'none',
        borderRadius: 12,
        display: 'block',
        background: 'transparent',
      }}
    />
  );
}

// ─── Open-role card (roles grid) ────────────────────────────
function CareersRoleCard({ job }) {
  return (
    <div style={{
      background: S.cream2, border: `1.5px solid ${S.ink}`, borderRadius: 20,
      boxShadow: `6px 6px 0 0 ${S.red}`, padding: '30px 28px 26px',
      display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 14,
    }}>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, color: S.red, letterSpacing: '0.18em', textTransform: 'uppercase' }}>
        ★ {job.dept}
      </div>
      <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 36, lineHeight: 1.08, letterSpacing: '-0.025em', color: S.ink, margin: 0 }}>
        {job.title}
      </h3>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        {job.meta.map((m, i) => <StubChip key={i} tone="ink" color={S.ink}>{m}</StubChip>)}
      </div>
      <p style={{ fontSize: 16, lineHeight: 1.55, color: S.ink, opacity: 0.75, margin: '2px 0 6px' }}>{job.summary}</p>
      <div style={{ marginTop: 'auto', display: 'flex', gap: 12, flexWrap: 'wrap' }}>
        <StubBtn onClick={() => {
          history.replaceState(null, '', `#careers/${job.slug}`);
          careersScrollTo(`careers-${job.slug}`);
        }}>Read the full role</StubBtn>
      </div>
    </div>
  );
}

// ─── Full job description section ───────────────────────────
function CareersJobDetail({ job, alt }) {
  return (
    <section id={`careers-${job.slug}`} style={{ background: alt ? S.cream2 : S.cream, padding: '88px 64px', position: 'relative', scrollMarginTop: 96 }}>
      <div className={`has-grain ${alt ? '' : 'light'}`} style={{ position: 'absolute', inset: 0 }} />
      <div style={{ position: 'relative', maxWidth: 860, margin: '0 auto' }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, color: S.red, letterSpacing: '0.2em', textTransform: 'uppercase' }}>
          ★ Open role · {job.dept} ★
        </div>
        <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 36, lineHeight: 1.08, letterSpacing: '-0.025em', color: S.ink, margin: '14px 0 14px' }}>
          {job.title}
        </h2>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 20 }}>
          {job.meta.map((m, i) => <StubChip key={i} tone="ink" color={S.ink}>{m}</StubChip>)}
        </div>
        <p style={{ fontSize: 16, lineHeight: 1.6, color: S.ink, opacity: 0.78, margin: '0 0 8px' }}>{job.summary}</p>

        {job.sections.map((sec) => (
          <div key={sec.heading} style={{ marginTop: 32 }}>
            <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 22, letterSpacing: '-0.02em', color: S.ink, margin: '0 0 14px' }}>
              {sec.heading}
            </h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {sec.items.map((item, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                  <span style={{ flexShrink: 0, width: 22, height: 22, borderRadius: 7, background: S.red, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginTop: 1 }}>
                    <Ico name="check" size={12} color={S.cream} strokeWidth={2.6} />
                  </span>
                  <span style={{ fontSize: 16, lineHeight: 1.55, color: S.ink, opacity: 0.82 }}>{item}</span>
                </div>
              ))}
            </div>
          </div>
        ))}

        <div style={{ marginTop: 36, display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
          <CareersApplyBtn job={job} size="lg">Apply — {job.title}</CareersApplyBtn>
          <span style={{ fontSize: 16, color: S.ink, opacity: 0.65 }}>We read every application.</span>
        </div>
      </div>
    </section>
  );
}

// ─── Page ───────────────────────────────────────────────────
function PageCareers({ onNav }) {
  // Deep links: fairs.com/careers#<slug>, #careers/<slug>, or …/apply scroll
  // to the matching section once the page has painted.
  React.useEffect(() => {
    const scrollFromHash = () => {
      const h = (location.hash || '').replace(/^#/, '');
      const sub = h.indexOf('careers/') === 0 ? h.slice('careers/'.length) : h;
      if (!sub || sub === 'careers') return;
      if (sub === 'apply') { setTimeout(() => careersScrollTo('careers-apply'), 150); return; }
      if (CAREERS_JOBS.some((j) => j.slug === sub)) {
        setTimeout(() => careersScrollTo(`careers-${sub}`), 150);
      }
    };
    scrollFromHash();
    window.addEventListener('hashchange', scrollFromHash);
    return () => window.removeEventListener('hashchange', scrollFromHash);
  }, []);

  const workingHere = [
    { label: 'Real stakes', title: 'Your work ships to real fairs', body: '180+ fairs run their biggest week of the year on what we build and support. You’ll see your impact from the midway, not just a dashboard.' },
    { label: 'Remote-first', title: 'Work from anywhere in the US', body: 'We’re a small team spread across the country. We hire for ownership, not hours in a chair.' },
    { label: 'Fair season', title: 'Summers with showtime energy', body: 'When the gates open, we’re all in — some of us literally on the fairgrounds. Ask about the RV tour.' },
    { label: 'Growing fast', title: 'Get in early', body: 'We launched in 2023 and haven’t slowed down since. Early hires shape how this company works.' },
  ];

  return (
    <div>
      {/* Hero — we're growing, come grow with us */}
      <section style={{ background: S.cream, padding: '120px 64px 80px', position: 'relative', overflow: 'hidden' }}>
        <div className="has-grain light" style={{ position: 'absolute', inset: 0 }} />
        <div style={{ position: 'relative', maxWidth: 1320, margin: '0 auto', display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 64, alignItems: 'center' }}>
          <div>
            <SectionEyebrow>Careers</SectionEyebrow>
            <h1 style={{
              fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 56, lineHeight: 0.98,
              letterSpacing: '-0.035em', color: S.ink, margin: '20px 0 20px',
            }}>
              Where tradition meets<br />
              <em style={{ fontStyle: 'italic', color: S.red, fontWeight: 500 }}>your next job.</em>
            </h1>
            <p style={{ fontSize: 22, lineHeight: 1.5, color: S.ink, opacity: 0.78, maxWidth: 580, margin: '0 0 28px' }}>
              We&apos;re growing fast — come join the best team in the fair industry.
            </p>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              <StubBtn size="lg" onClick={() => careersScrollTo('careers-roles')}>See open roles</StubBtn>
              <button onClick={() => onNav?.('who-we-are')} style={{
                position: 'relative', height: 56, padding: '0 24px',
                background: 'transparent', color: S.ink,
                border: `1.5px solid ${S.ink}`, borderRadius: 8,
                fontFamily: 'inherit', fontSize: 16, fontWeight: 700, cursor: 'pointer',
              }}>Who we are →</button>
            </div>
          </div>
          <div style={{ position: 'relative', justifySelf: 'center' }}>
            <div style={{ position: 'absolute', top: -30, right: -8, zIndex: 2 }}>
              <SpeechBubble tail="right" tilt={-3}>We&apos;re <em style={{ fontStyle: 'italic', color: S.red }}>hiring!</em></SpeechBubble>
            </div>
            <FramedPhoto src={PHOTOS.rv} treatment="grained" caption="★ The Fairs.com RV · on tour" tilt={2} style={{ width: 380 }} />
            <div style={{ position: 'absolute', bottom: -36, left: -36 }}>
              <Cow size={140} rotate={-6} />
            </div>
          </div>
        </div>
      </section>

      {/* Working here — four quick reasons */}
      <section style={{ background: S.cream2, padding: '80px 64px', position: 'relative' }}>
        <div className="has-grain" style={{ position: 'absolute', inset: 0 }} />
        <div style={{ position: 'relative', maxWidth: 1320, margin: '0 auto' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20 }}>
            {workingHere.map((w) => (
              <div key={w.label} style={{ background: S.cream, border: `1.5px solid ${S.ink}`, borderRadius: 16, padding: '24px 22px' }}>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, color: S.red, letterSpacing: '0.18em', textTransform: 'uppercase', marginBottom: 10 }}>
                  ★ {w.label}
                </div>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 22, lineHeight: 1.2, letterSpacing: '-0.02em', color: S.ink, marginBottom: 8 }}>{w.title}</div>
                <div style={{ fontSize: 16, lineHeight: 1.5, color: S.ink, opacity: 0.72 }}>{w.body}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Open roles */}
      <section id="careers-roles" style={{ background: S.cream, padding: '96px 64px 80px', position: 'relative', scrollMarginTop: 64 }}>
        <div className="has-grain light" style={{ position: 'absolute', inset: 0 }} />
        <div style={{ position: 'relative', maxWidth: 1320, margin: '0 auto' }}>
          <div style={{ textAlign: 'center', marginBottom: 48 }}>
            <SectionEyebrow>Open roles</SectionEyebrow>
            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 56, lineHeight: 1.05, letterSpacing: '-0.025em', color: S.ink, margin: '16px auto 12px', maxWidth: 720 }}>
              Two seats open <em style={{ fontStyle: 'italic', color: S.red }}>right now.</em>
            </h2>
            <p style={{ fontSize: 16, lineHeight: 1.5, color: S.ink, opacity: 0.7, maxWidth: 620, margin: '0 auto' }}>
              Full descriptions below. Don&apos;t see your role? We still want to hear from you —{' '}
              <a href={`mailto:${CAREERS_APPLY_EMAIL}?subject=${encodeURIComponent('Application — General')}`} style={{ color: S.red, fontWeight: 700 }}>send us a note</a>.
            </p>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28, alignItems: 'stretch' }}>
            {CAREERS_JOBS.map((job) => <CareersRoleCard key={job.slug} job={job} />)}
          </div>
        </div>
      </section>

      {/* Full descriptions */}
      {CAREERS_JOBS.map((job, i) => <CareersJobDetail key={job.slug} job={job} alt={i % 2 === 0} />)}

      {/* What we offer */}
      <section style={{ background: S.cream, padding: '72px 64px', position: 'relative' }}>
        <div className="has-grain light" style={{ position: 'absolute', inset: 0 }} />
        <div style={{ position: 'relative', maxWidth: 860, margin: '0 auto', textAlign: 'center' }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, color: S.red, letterSpacing: '0.2em', textTransform: 'uppercase', marginBottom: 18 }}>
            ★ What we offer ★
          </div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', justifyContent: 'center' }}>
            {CAREERS_OFFER.map((o, i) => <StubChip key={i} tone="ink" color={S.ink}>{o}</StubChip>)}
          </div>
        </div>
      </section>

      {/* Apply */}
      <section id="careers-apply" style={{ background: S.ink, padding: '88px 64px', position: 'relative', overflow: 'hidden', scrollMarginTop: 64 }}>
        <div style={{ position: 'absolute', bottom: -100, right: -100, width: 400, height: 400, borderRadius: '50%', background: S.red, opacity: 0.18, filter: 'blur(60px)' }} />
        <div style={{ position: 'relative', maxWidth: 860, margin: '0 auto' }}>
          <div style={{ textAlign: 'center', marginBottom: 36 }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, color: S.red, letterSpacing: '0.2em', textTransform: 'uppercase' }}>
              ★ Apply ★
            </div>
            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 56, lineHeight: 1.05, letterSpacing: '-0.03em', color: S.cream, margin: '16px 0 12px' }}>
              Throw your hat <em style={{ fontStyle: 'italic', color: S.red }}>in the ring.</em>
            </h2>
            <p style={{ fontSize: 16, lineHeight: 1.55, color: 'rgba(253,249,240,0.72)', maxWidth: 560, margin: '0 auto' }}>
              Applying takes two minutes: tell us who you are, how to reach you, and attach your resume (PDF preferred). We read every application.
            </p>
          </div>

          <div style={{
            background: S.cream, border: `1.5px solid ${S.ink}`, borderRadius: 18, padding: 20,
            boxShadow: `8px 8px 0 0 ${S.red}`,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14, padding: '0 12px', gap: 12, flexWrap: 'wrap' }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: S.red, fontWeight: 700, letterSpacing: '0.18em', textTransform: 'uppercase' }}>
                ★ Admit one · Application
              </div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: S.mute, letterSpacing: '0.14em' }}>№ 0002</div>
            </div>
            {CAREERS_FORM_ID ? (
              <CareersFormEmbed />
            ) : (
              <div style={{ padding: '12px 12px 16px' }}>
                <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                  {CAREERS_JOBS.map((job) => (
                    <StubBtn key={job.slug} href={careersMailto(job)}>Apply — {job.title}</StubBtn>
                  ))}
                </div>
                <div style={{ fontSize: 16, lineHeight: 1.55, color: S.ink, opacity: 0.72, marginTop: 16 }}>
                  The buttons open a pre-addressed email with a short template. Or just email{' '}
                  <a href={`mailto:${CAREERS_APPLY_EMAIL}`} style={{ color: S.red, fontWeight: 700 }}>{CAREERS_APPLY_EMAIL}</a>{' '}
                  with the role in the subject line and your resume attached.
                </div>
              </div>
            )}
          </div>

          <p style={{ fontSize: 12, lineHeight: 1.6, color: 'rgba(253,249,240,0.55)', maxWidth: 720, margin: '28px auto 0', textAlign: 'center' }}>
            Fairs.com is an equal opportunity employer. We consider all applicants without regard to race, color, religion, sex, sexual orientation, gender identity, national origin, age, veteran status, or disability. Anything you send us is used only for hiring and is never shared or sold.
          </p>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { PageCareers });
