/* eslint-disable */
// Jobs screen — listing, detail and apply / post flows. State machine:
//   list  → detail (clicking a card) → apply  (clicking Apply)
//   list  → post                     (clicking "Post a job")
// Companies use the same surface to publish openings; candidates can apply
// against any listed role.

const JOBS = [
  {
    id: 1, title: 'Chief Financial Officer',
    company: 'Aqualectra', logo: 'A', logoColor: '#08345E',
    location: 'Willemstad', type: 'Full-time', level: 'Executive',
    sector: 'Energy', salary: 'XCG 18,000 – 24,000 · USD 10,100 – 13,400 / mo',
    posted: '2 days ago', featured: true,
    summary: 'Lead the financial strategy of Curaçao\u0027s national utility through a once-in-a-generation energy transition.',
    full: 'Aqualectra is hiring a Chief Financial Officer to partner with the CEO and Board on capital planning, regulatory strategy and the financing of the island\u0027s renewable-energy roadmap. You will manage a team of 40 across treasury, accounting, FP&A and investor relations.',
    requirements: [
      '15+ years of senior finance experience, ideally in regulated utilities or infrastructure',
      'Active CFO, FD or equivalent leadership track record',
      'Experience raising debt and structuring public-private financing',
      'Fluent English; Dutch and/or Papiamentu strongly preferred',
    ],
  },
  {
    id: 2, title: 'Senior Investment Associate',
    company: 'CBCS — Centrale Bank van Curaçao en Sint Maarten', logo: 'CB', logoColor: '#1A2333',
    location: 'Willemstad', type: 'Full-time', level: 'Senior',
    sector: 'Finance', salary: 'XCG 9,500 – 12,000 · USD 5,300 – 6,700 / mo',
    posted: '4 days ago',
    summary: 'Support reserve management and counterparty due-diligence across a global portfolio of sovereign and corporate exposures.',
    full: 'You\u0027ll work in a small, high-trust team responsible for the long-term stewardship of the central bank\u0027s investment portfolio, with direct exposure to fixed-income strategy and counterparty risk.',
    requirements: [
      'Master\u0027s degree in economics, finance or related field',
      'CFA Level II or above',
      '5+ years buy-side or treasury experience',
      'Strong Excel and Bloomberg proficiency',
    ],
  },
  {
    id: 3, title: 'Hotel General Manager',
    company: 'Renaissance Curaçao Resort & Casino', logo: 'R', logoColor: '#FFC20E',
    location: 'Otrobanda', type: 'Full-time', level: 'Senior',
    sector: 'Tourism', salary: 'Competitive + bonus + housing',
    posted: '1 week ago',
    summary: 'Run a flagship 237-key resort directly on the Sint Anna Bay — P&L ownership, brand standards and a 280-person team.',
    full: 'Reporting to the regional VP, you will own commercial, operational and people outcomes for one of the highest-occupancy hotels in the Dutch Caribbean.',
    requirements: [
      '10+ years hospitality leadership; 3+ as Hotel Manager or GM',
      'Track record running large, multi-revenue-center properties',
      'Marriott / international flag experience preferred',
      'Comfort working in a multilingual Caribbean environment',
    ],
  },
  {
    id: 4, title: 'Lead Software Engineer',
    company: 'Banco di Caribe', logo: 'BC', logoColor: '#08345E',
    location: 'Willemstad / Remote (CW)', type: 'Full-time', level: 'Senior',
    sector: 'Banking', salary: 'XCG 11,000 – 14,500 · USD 6,100 – 8,100 / mo',
    posted: '1 week ago',
    summary: 'Modernise our digital-banking stack from the inside — own the platform architecture and the engineering culture that goes with it.',
    full: 'You\u0027ll lead a team of six engineers, set technical direction for our customer-facing apps and core integrations, and partner closely with risk and compliance on every release.',
    requirements: [
      '8+ years building production web/mobile applications',
      'Cloud-native architecture (AWS / Azure)',
      'Experience in regulated industries (banking, insurance, healthcare)',
      'Strong written communication and code review discipline',
    ],
  },
  {
    id: 5, title: 'Marketing Manager — Caribbean',
    company: 'Curaçao Tourism Board', logo: 'CTB', logoColor: '#FFC20E',
    location: 'Willemstad', type: 'Full-time', level: 'Mid',
    sector: 'Tourism', salary: 'XCG 7,500 – 9,500 · USD 4,200 – 5,300 / mo',
    posted: '2 weeks ago',
    summary: 'Own the digital marketing programme that drives travel from North America and the Eurozone to Curaçao.',
    full: 'You will manage external agencies, allocate a 7-figure paid-media budget across channels, and own measurement and attribution for the island\u0027s tourism marketing.',
    requirements: [
      '6+ years of growth or destination-marketing experience',
      'Hands-on with paid social, search and programmatic',
      'Strong analytics — GA4, Looker, attribution modelling',
      'Fluent English; Spanish or Dutch a plus',
    ],
  },
  {
    id: 6, title: 'Operations Coordinator',
    company: 'Curaçao Ports Authority', logo: 'CPA', logoColor: '#1A2333',
    location: 'Willemstad', type: 'Full-time', level: 'Mid',
    sector: 'Logistics', salary: 'XCG 5,500 – 7,000 · USD 3,100 – 3,900 / mo',
    posted: '2 weeks ago',
    summary: 'Coordinate vessel scheduling and shore-side operations for the Caribbean\u0027s busiest cruise homeport.',
    full: 'Day-to-day, you\u0027ll be the operational bridge between cruise lines, government agencies and ground handlers — owning the call-sheet, communications and exception handling.',
    requirements: [
      '3+ years in logistics, ports or supply-chain operations',
      'Calm under pressure; excellent verbal communication',
      'Comfortable on shift work including weekends',
      'Bilingual English/Papiamentu strongly preferred',
    ],
  },
];

// -------------------------------------------------------------
// Job card (used in the list view)
// -------------------------------------------------------------
const JobCard = ({ job, onOpen }) => (
  <article className="cbm-job" onClick={() => onOpen(job)}>
    <div className="cbm-job__logo" style={{background: job.logoColor, color: job.logoColor === '#FFC20E' ? '#08345E' : '#fff'}}>
      {job.logo}
    </div>
    <div className="cbm-job__body">
      <div className="cbm-job__row">
        <span className="cbm-chip">{job.sector}</span>
        {job.featured && <span className="cbm-chip cbm-chip--gold">Featured</span>}
        <span className="cbm-job__posted">{job.posted}</span>
      </div>
      <h3 className="cbm-job__title">{job.title}</h3>
      <p className="cbm-job__company">{job.company}</p>
      <p className="cbm-job__summary">{job.summary}</p>
      <div className="cbm-job__meta">
        <span><i data-lucide="map-pin"></i>{job.location}</span>
        <span><i data-lucide="briefcase"></i>{job.type}</span>
        <span><i data-lucide="trending-up"></i>{job.level}</span>
        <span><i data-lucide="banknote"></i>{job.salary}</span>
      </div>
    </div>
    <button className="cbm-btn cbm-btn--ghost cbm-job__cta">View</button>
  </article>
);

// -------------------------------------------------------------
// Filter bar — purely cosmetic state, the listings don't actually filter
// -------------------------------------------------------------
const JobsFilterBar = ({ filter, setFilter }) => {
  const sectors = ['All', 'Finance', 'Energy', 'Tourism', 'Banking', 'Logistics'];
  return (
    <div className="cbm-jobs-filter">
      <div className="cbm-jobs-filter__search">
        <i data-lucide="search"></i>
        <input placeholder="Job title, company or keyword" />
      </div>
      <div className="cbm-jobs-filter__chips">
        {sectors.map(s => (
          <button
            key={s}
            className={'cbm-pill ' + (filter === s ? 'is-active' : '')}
            onClick={() => setFilter(s)}
          >
            {s}
          </button>
        ))}
      </div>
    </div>
  );
};

// -------------------------------------------------------------
// Job detail (drawer-style, full screen)
// -------------------------------------------------------------
const JobDetail = ({ job, onBack, onApply }) => (
  <div className="cbm-job-detail">
    <button className="cbm-link-back" onClick={onBack}>
      <i data-lucide="arrow-left"></i> All jobs
    </button>
    <div className="cbm-job-detail__head">
      <div className="cbm-job__logo cbm-job__logo--lg" style={{background: job.logoColor, color: job.logoColor === '#FFC20E' ? '#08345E' : '#fff'}}>
        {job.logo}
      </div>
      <div>
        <span className="cbm-chip">{job.sector}</span>
        <h1 className="cbm-job-detail__title">{job.title}</h1>
        <p className="cbm-job-detail__company">{job.company}</p>
        <div className="cbm-job__meta">
          <span><i data-lucide="map-pin"></i>{job.location}</span>
          <span><i data-lucide="briefcase"></i>{job.type}</span>
          <span><i data-lucide="trending-up"></i>{job.level}</span>
          <span><i data-lucide="banknote"></i>{job.salary}</span>
        </div>
      </div>
      <button className="cbm-btn cbm-btn--gold" onClick={() => onApply(job)}>Apply now</button>
    </div>

    <div className="cbm-job-detail__body">
      <section>
        <h2>About the role</h2>
        <p>{job.full}</p>
      </section>
      <section>
        <h2>What we're looking for</h2>
        <ul>{job.requirements.map(r => <li key={r}>{r}</li>)}</ul>
      </section>
      <section>
        <h2>How to apply</h2>
        <p>Submit your CV and a short cover note through the form below — applications are sent directly to the hiring company. CBM does not store applicant data beyond what is needed to forward your application.</p>
        <button className="cbm-btn cbm-btn--primary" onClick={() => onApply(job)}>Apply for this role</button>
      </section>
    </div>
  </div>
);

// -------------------------------------------------------------
// Apply form
// -------------------------------------------------------------
const ApplyForm = ({ job, onBack }) => {
  const [submitted, setSubmitted] = React.useState(false);
  return (
    <div className="cbm-apply">
      <button className="cbm-link-back" onClick={onBack}>
        <i data-lucide="arrow-left"></i> Back to role
      </button>
      <div className="cbm-apply__inner">
        <span className="cbm-eyebrow">Apply</span>
        <h1 className="cbm-section__title" style={{color: 'var(--cbm-blue)', margin: '6px 0 6px'}}>{job.title}</h1>
        <p className="cbm-job-detail__company" style={{marginBottom: 28}}>{job.company} · {job.location}</p>

        {submitted ? (
          <div className="cbm-apply__done">
            <i data-lucide="check-circle"></i>
            <h2>Application submitted.</h2>
            <p>We've sent your details to {job.company}. You'll hear back directly from their hiring team, usually within five business days.</p>
            <button className="cbm-btn cbm-btn--ghost" onClick={onBack}>Browse more roles</button>
          </div>
        ) : (
          <form onSubmit={async e => {
              e.preventDefault();
              const ok = await window.submitFormspree(window.FORMSPREE.jobApply, e.currentTarget, {
                _subject: 'Job application: ' + job.title,
                job_title: job.title,
                job_company: job.company,
                job_location: job.location,
              });
              if (ok) setSubmitted(true);
            }} className="cbm-apply__form">
            <div className="cbm-apply__row">
              <div>
                <label className="cbm-label">First name</label>
                <input className="cbm-field" name="first_name" required placeholder="Maya" />
              </div>
              <div>
                <label className="cbm-label">Last name</label>
                <input className="cbm-field" name="last_name" required placeholder="de Windt" />
              </div>
            </div>
            <div className="cbm-apply__row">
              <div>
                <label className="cbm-label">Email</label>
                <input className="cbm-field" name="email" type="email" required placeholder="you@business.cw" />
              </div>
              <div>
                <label className="cbm-label">Phone</label>
                <input className="cbm-field" name="phone" type="tel" placeholder="+599 9 …" />
              </div>
            </div>
            <div>
              <label className="cbm-label">LinkedIn profile (optional)</label>
              <input className="cbm-field" name="linkedin" placeholder="linkedin.com/in/…" />
            </div>
            <div>
              <label className="cbm-label">Years of relevant experience</label>
              <select className="cbm-field" name="experience">
                <option>0 – 2 years</option>
                <option>3 – 5 years</option>
                <option>6 – 10 years</option>
                <option>10+ years</option>
              </select>
            </div>
            <div>
              <label className="cbm-label">Cover note</label>
              <textarea className="cbm-field" name="cover_note" rows="5" placeholder={'Why ' + job.company + '? Why this role?'} />
            </div>
            <div>
              <label className="cbm-label">CV (PDF)</label>
              <label className="cbm-upload">
                <i data-lucide="upload"></i>
                <span>Click to upload — PDF up to 5 MB</span>
                <input type="file" accept=".pdf" style={{display:'none'}} />
              </label>
            </div>
            <label className="cbm-checkbox">
              <input type="checkbox" required />
              <span>I confirm CBM may forward my application to {job.company} for the purposes of this role.</span>
            </label>
            <button className="cbm-btn cbm-btn--gold" type="submit" style={{width: '100%', marginTop: 8}}>
              Submit application
            </button>
          </form>
        )}
      </div>
    </div>
  );
};

// -------------------------------------------------------------
// Post-a-job form (for companies)
// -------------------------------------------------------------
const PostJobForm = ({ onBack }) => {
  const [submitted, setSubmitted] = React.useState(false);
  return (
    <div className="cbm-apply">
      <button className="cbm-link-back" onClick={onBack}>
        <i data-lucide="arrow-left"></i> Back to jobs
      </button>
      <div className="cbm-apply__inner">
        <span className="cbm-eyebrow">For Employers</span>
        <h1 className="cbm-section__title" style={{color: 'var(--cbm-blue)', margin: '6px 0 6px'}}>Post a job on CBM.</h1>
        <p className="cbm-job-detail__company" style={{marginBottom: 28}}>
          {"Reach 25,000+ monthly readers and 15,000+ social followers across Curaçao's business community."}
        </p>

        {submitted ? (
          <div className="cbm-apply__done">
            <i data-lucide="check-circle"></i>
            <h2>Listing received.</h2>
            <p>Our editorial team reviews every posting before it goes live. You'll receive a confirmation and an invoice within one business day.</p>
            <button className="cbm-btn cbm-btn--ghost" onClick={onBack}>Back to jobs</button>
          </div>
        ) : (
          <form onSubmit={async e => {
              e.preventDefault();
              const ok = await window.submitFormspree(window.FORMSPREE.jobPost, e.currentTarget, {
                _subject: 'Job posting submission',
              });
              if (ok) setSubmitted(true);
            }} className="cbm-apply__form">
            <div className="cbm-apply__row">
              <div>
                <label className="cbm-label">Company</label>
                <input className="cbm-field" name="company" required placeholder="Aqualectra" />
              </div>
              <div>
                <label className="cbm-label">Sector</label>
                <select className="cbm-field" name="sector">
                  <option>Finance</option><option>Energy</option><option>Tourism</option>
                  <option>Banking</option><option>Logistics</option><option>Technology</option>
                  <option>Government</option><option>Other</option>
                </select>
              </div>
            </div>
            <div>
              <label className="cbm-label">Role title</label>
              <input className="cbm-field" name="role_title" required placeholder="Chief Financial Officer" />
            </div>
            <div className="cbm-apply__row">
              <div>
                <label className="cbm-label">Location</label>
                <input className="cbm-field" name="location" required placeholder="Willemstad" />
              </div>
              <div>
                <label className="cbm-label">Employment type</label>
                <select className="cbm-field" name="employment_type">
                  <option>Full-time</option><option>Part-time</option>
                  <option>Contract</option><option>Internship</option>
                </select>
              </div>
            </div>
            <div className="cbm-apply__row">
              <div>
                <label className="cbm-label">Seniority</label>
                <select className="cbm-field" name="seniority">
                  <option>Entry</option><option>Mid</option>
                  <option>Senior</option><option>Executive</option>
                </select>
              </div>
              <div>
                <label className="cbm-label">Salary range (XCG / mo)</label>
                <input className="cbm-field" name="salary_range" placeholder="9,500 – 12,000" />
              </div>
            </div>
            <div>
              <label className="cbm-label">Short summary (1–2 sentences)</label>
              <textarea className="cbm-field" name="short_summary" rows="2" placeholder="What does this role do, in one line?" />
            </div>
            <div>
              <label className="cbm-label">Full description</label>
              <textarea className="cbm-field" name="full_description" rows="6" placeholder="Responsibilities, team, what success looks like…" />
            </div>
            <div>
              <label className="cbm-label">Listing plan</label>
              <div className="cbm-plan-row">
                <label className="cbm-plan"><input type="radio" name="plan" value="Standard" /><div><strong>Standard</strong><span>XCG 350 · USD 196 · 30 days · listed in the feed</span></div></label>
                <label className="cbm-plan"><input type="radio" name="plan" value="Featured" defaultChecked /><div><strong>Featured</strong><span>XCG 750 · USD 419 · 30 days · top of feed + newsletter mention</span></div></label>
                <label className="cbm-plan"><input type="radio" name="plan" value="Headline" /><div><strong>Headline</strong><span>XCG 1,500 · USD 838 · 30 days · social campaign + sponsored article</span></div></label>
              </div>
            </div>
            <button className="cbm-btn cbm-btn--gold" type="submit" style={{width: '100%', marginTop: 8}}>
              Submit for review
            </button>
          </form>
        )}
      </div>
    </div>
  );
};

// -------------------------------------------------------------
// Listing screen — top hero + filters + cards
// -------------------------------------------------------------
const JobsList = ({ onOpen, onPost }) => {
  const [filter, setFilter] = React.useState('All');
  const list = filter === 'All' ? JOBS : JOBS.filter(j => j.sector === filter);
  return (
    <>
      <section className="cbm-section cbm-section--dark" style={{paddingTop: 72, paddingBottom: 48}}>
        <div className="cbm-section__inner" style={{display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 56, alignItems: 'center'}}>
          <div>
            <span className="cbm-eyebrow">Curaçao Jobs Board</span>
            <div className="cbm-section-rule" />
            <h1 className="cbm-section__title">Work that moves <span style={{color:'var(--cbm-gold)'}}>Curaçao</span> forward.</h1>
            <p className="cbm-section__lede" style={{marginTop: 14}}>
              {"Senior and specialist roles from Curaçao's most active employers — banks, energy, tourism, government and the island's fastest-growing companies. Apply directly, or post a role to reach our audience."}
            </p>
          </div>
          <div className="cbm-jobs-cta">
            <div>
              <p className="cbm-eyebrow cbm-eyebrow--gold" style={{margin: 0}}>For Employers</p>
              <h3 style={{fontFamily:'var(--font-display)', fontWeight: 800, fontSize: 28, lineHeight: 1.1, margin: '8px 0 12px', color:'#fff'}}>{"Hire from Curaçao's top business audience."}</h3>
              <p style={{color:'rgba(255,255,255,0.85)', margin:'0 0 18px'}}>Reach 25,000+ monthly readers and a highly engaged business community.</p>
              <button className="cbm-btn cbm-btn--gold" onClick={onPost}>Post a job</button>
            </div>
          </div>
        </div>
      </section>

      <section className="cbm-section" style={{paddingTop: 32}}>
        <div className="cbm-section__inner">
          <JobsFilterBar filter={filter} setFilter={setFilter} />
          <div className="cbm-jobs-stats">
            <span><strong>{list.length}</strong> open roles</span>
            <span>Updated daily</span>
            <span>Average response time · 5 business days</span>
          </div>
          <div className="cbm-jobs-list">
            {list.map(j => <JobCard key={j.id} job={j} onOpen={onOpen} />)}
          </div>
        </div>
      </section>
    </>
  );
};

// -------------------------------------------------------------
// Top-level screen — switches between list / detail / apply / post
// -------------------------------------------------------------
const JobsScreen = () => {
  const [view, setView] = React.useState({ mode: 'list' });
  // Lucide doesn't auto-mount on React renders; re-run after every view change.
  React.useEffect(() => {
    if (window.lucide && window.lucide.createIcons) window.lucide.createIcons();
  }, [view]);
  return (
    <div data-screen-label="Jobs">
      {view.mode === 'list' && (
        <JobsList
          onOpen={(job) => setView({ mode: 'detail', job })}
          onPost={() => setView({ mode: 'post' })}
        />
      )}
      {view.mode === 'detail' && (
        <section className="cbm-section">
          <div className="cbm-section__inner">
            <JobDetail
              job={view.job}
              onBack={() => setView({ mode: 'list' })}
              onApply={(job) => setView({ mode: 'apply', job })}
            />
          </div>
        </section>
      )}
      {view.mode === 'apply' && (
        <section className="cbm-section cbm-section--tint">
          <div className="cbm-section__inner">
            <ApplyForm job={view.job} onBack={() => setView({ mode: 'detail', job: view.job })} />
          </div>
        </section>
      )}
      {view.mode === 'post' && (
        <section className="cbm-section cbm-section--tint">
          <div className="cbm-section__inner">
            <PostJobForm onBack={() => setView({ mode: 'list' })} />
          </div>
        </section>
      )}
    </div>
  );
};

Object.assign(window, { JobsScreen });
