/* eslint-disable */
// Course Library — on-demand business courses people can buy or subscribe to.
// State machine: catalog → detail → checkout.

const COURSES = [
  {
    id: 1, slug: 'starting-a-business-in-curacao',
    title: 'Starting a Business in Curaçao',
    short: 'From idea to incorporated — the legal, financial and operational steps for founders.',
    full: 'A practical, 10-module bootcamp covering everything from picking the right entity (NV / BV / sole prop) to opening a corporate bank account, registering with the KvK, and your first hire. Built around real Curaçao paperwork, real timelines, and the questions every first-time founder asks.',
    instructor: 'Mireille de Windt',
    instructorRole: 'Editor-in-Chief, Curaçao Business Magazine',
    duration: '6h 20m', modules: 10, level: 'Beginner',
    category: 'Entrepreneurship',
    price: 295, color: '#08345E', featured: true,
    curriculum: [
      'Choosing the right legal entity',
      'Registering with the Chamber of Commerce (KvK)',
      'Opening a corporate bank account',
      'Tax basics — what you owe and when',
      'Hiring your first employee',
      'Workplace contracts and payroll',
      'Government grants and SME programmes',
      'Setting up bookkeeping and invoicing',
      'Year-one cash-flow planning',
      'Closing the first year — what to file',
    ],
  },
  {
    id: 2, slug: 'cfo-toolkit',
    title: 'The CFO Toolkit',
    short: 'Financial planning, scenario modelling and board reporting — for senior finance leaders.',
    full: 'Eight modules covering the practical work of a modern CFO in a small-economy context: scenario modelling, debt structuring, regulator interactions, board reporting, and how to think about local currency exposure.',
    instructor: 'Ronald Pourier',
    instructorRole: 'Former CFO, Aqualectra',
    duration: '8h 40m', modules: 8, level: 'Advanced',
    category: 'Finance',
    price: 495, color: '#1A2333',
    curriculum: [
      'Building a 36-month plan',
      'Scenario and sensitivity modelling',
      'Debt and capital structuring for small caps',
      'Engaging with the central bank',
      'Board reporting and audit committee work',
      'FX exposure in a guilder economy',
      'M&A diligence on the buy side',
      'CFO transitions — the first 90 days',
    ],
  },
  {
    id: 3, slug: 'digital-marketing-caribbean',
    title: 'Digital Marketing for the Caribbean',
    short: 'Run paid social, SEO and email programmes that work for a Caribbean audience.',
    full: 'A hands-on course on what actually moves the needle for Caribbean brands — paid social, search, email and attribution. Includes a complete playbook for Curaçao-specific media buying and a working template kit.',
    instructor: 'Anouk Martijn',
    instructorRole: 'Head of Growth, Curaçao Tourism Board',
    duration: '4h 50m', modules: 7, level: 'Intermediate',
    category: 'Marketing',
    price: 245, color: '#00A99D',
    curriculum: [
      'Audience research and segmentation',
      'Paid social — Meta, TikTok, LinkedIn',
      'Search — SEO and Google Ads',
      'Email and newsletter programmes',
      'Influencer and creator partnerships',
      'Analytics and attribution that work',
      'Budget allocation and reporting',
    ],
  },
  {
    id: 4, slug: 'leadership-island-business',
    title: 'Leadership in Island Business',
    short: 'Managing people, performance and culture in a small, tight-knit market.',
    full: 'Curaçao is small. Your top managers know each other socially, your hires know your last hire, and reputational signal travels in days. This course is about how to lead well in exactly that environment.',
    instructor: 'Glenn Camelia',
    instructorRole: 'Hotel General Manager, Renaissance',
    duration: '5h 15m', modules: 9, level: 'Intermediate',
    category: 'Leadership',
    price: 345, color: '#08345E',
    curriculum: [
      'Hiring in a small market',
      'Performance conversations',
      'Building a culture deliberately',
      'Conflict and confidentiality',
      'Compensation in small markets',
      'Managing succession',
      'Working across multiple languages',
      'When to promote vs hire externally',
      'Building bench strength',
    ],
  },
  {
    id: 5, slug: 'sme-finance-fundamentals',
    title: 'SME Finance Fundamentals',
    short: 'Cash flow, banking, debt and tax — the survival kit for small-business owners.',
    full: 'A six-week, self-paced curriculum for owner-operators: building a basic cash-flow forecast, opening lines of credit, choosing a bookkeeper, and reading your own P&L.',
    instructor: 'Sharine Rojer',
    instructorRole: 'SME Banking Lead, Banco di Caribe',
    duration: '3h 40m', modules: 6, level: 'Beginner',
    category: 'Finance',
    price: 195, color: '#08345E',
    curriculum: [
      'Reading your P&L and balance sheet',
      'Building a 13-week cash forecast',
      'Working with banks — what they want',
      'Lines of credit and SME loans',
      'Tax: the basics for SMEs',
      'When to hire a bookkeeper',
    ],
  },
  {
    id: 6, slug: 'sustainability-strategy',
    title: 'Sustainability Strategy for Caribbean Businesses',
    short: 'Translate ESG and energy-transition pressure into a credible business roadmap.',
    full: 'Practical guidance on building a sustainability strategy that survives audit, investor scrutiny and customer expectations — calibrated for Caribbean realities (energy, water, supply chain, climate exposure).',
    instructor: 'Alex de Boer',
    instructorRole: 'Sustainability Director, Curoil',
    duration: '5h 50m', modules: 8, level: 'Intermediate',
    category: 'Strategy',
    price: 395, color: '#00A99D',
    curriculum: [
      'The ESG landscape, demystified',
      'Materiality — what to measure',
      'Energy transition for SMEs',
      'Water and waste',
      'Supply-chain due diligence',
      'Climate risk and resilience',
      'Reporting frameworks (CSRD, GRI)',
      'Building a 5-year roadmap',
    ],
  },
  {
    id: 7, slug: 'tax-curacao',
    title: 'Curaçao Tax for Business Owners',
    short: 'Corporate tax, profit tax, sales tax and the e-zone — a 2026 walkthrough.',
    full: 'A current, plain-language walkthrough of Curaçao\u0027s tax framework: profit tax brackets, omzetbelasting, wage tax, the e-zone, and what international owners actually pay in practice.',
    instructor: 'Eric Brouwer',
    instructorRole: 'Partner, KPMG Dutch Caribbean',
    duration: '4h 10m', modules: 6, level: 'Intermediate',
    category: 'Finance',
    price: 295, color: '#1A2333', featured: true,
    curriculum: [
      'The tax stack overview',
      'Profit tax — brackets and reliefs',
      'Sales tax (omzetbelasting / OB)',
      'Wage tax and social premiums',
      'The Curaçao e-zone explained',
      'Cross-border structuring',
    ],
  },
  {
    id: 8, slug: 'public-speaking',
    title: 'Public Speaking for Executives',
    short: 'Keynotes, panels and press — how to show up well when the cameras are on.',
    full: 'A short, intensive course on speaking with authority in business settings: shareholder meetings, panel discussions, press interviews and conference keynotes. Includes voice work and on-camera drills.',
    instructor: 'Linda Boertien',
    instructorRole: 'Communications Coach',
    duration: '3h 20m', modules: 5, level: 'Beginner',
    category: 'Leadership',
    price: 195, color: '#E97451',
    curriculum: [
      'Structuring a 7-minute talk',
      'Voice, pace and presence',
      'Q&A and difficult questions',
      'On-camera technique',
      'Press interviews',
    ],
  },
  {
    id: 9, slug: 'hr-fundamentals',
    title: 'HR Fundamentals for Curaçao Employers',
    short: 'Hiring, contracts, payroll and termination — under Curaçao employment law.',
    full: 'A complete primer on the practical side of being an employer in Curaçao: contracts, probation, payroll, sick pay, and the surprisingly nuanced rules around termination.',
    instructor: 'Marlene Sluis',
    instructorRole: 'HR Partner, KPMG',
    duration: '4h 40m', modules: 7, level: 'Beginner',
    category: 'Operations',
    price: 245, color: '#08345E',
    curriculum: [
      'Employment contracts — fixed vs indefinite',
      'Probation and trial periods',
      'Payroll and payslips',
      'Sick pay and absence',
      'Holiday entitlement',
      'Performance management',
      'Termination — the right way',
    ],
  },
];

const CATEGORIES = ['All', 'Entrepreneurship', 'Finance', 'Marketing', 'Leadership', 'Strategy', 'Operations'];

// Plans for the membership subscription tier
const PLANS = [
  { id: 'monthly', label: 'Monthly', price: 95, per: '/ month', sub: 'Cancel anytime' },
  { id: 'yearly',  label: 'Yearly',  price: 950, per: '/ year', sub: 'Save 17% — two months free', featured: true },
  { id: 'team',    label: 'Team',    price: 850, per: '/ user / yr', sub: 'For 5+ seats · invoice billing' },
];

// -------------------------------------------------------------
// Course card
// -------------------------------------------------------------
const CourseCard = ({ course, onOpen, t }) => (
  <article className="cbm-course" onClick={() => onOpen(course)}>
    <div className="cbm-course__media" style={{background: course.color}}>
      <div className="cbm-course__media-inner">
        <span className="cbm-course__cat">{course.category}</span>
        <h3 className="cbm-course__title-media">{course.title}</h3>
      </div>
      {course.featured && <span className="cbm-course__featured">{t('featured')}</span>}
    </div>
    <div className="cbm-course__body">
      <p className="cbm-course__short">{course.short}</p>
      <div className="cbm-course__meta">
        <span><i data-lucide="clock"></i>{course.duration}</span>
        <span><i data-lucide="layers"></i>{course.modules} {t('modules')}</span>
        <span><i data-lucide="trending-up"></i>{course.level}</span>
      </div>
      <div className="cbm-course__foot">
        <div className="cbm-course__instructor">
          <div className="cbm-course__avatar">{course.instructor.split(' ').map(n => n[0]).join('').slice(0,2)}</div>
          <div>
            <div className="cbm-course__author">{course.instructor}</div>
            <div className="cbm-course__role">{course.instructorRole}</div>
          </div>
        </div>
        <div className="cbm-course__price">{window.formatPrice ? window.formatPrice(course.price) : ('XCG ' + course.price)}</div>
      </div>
    </div>
  </article>
);

// -------------------------------------------------------------
// Filter bar
// -------------------------------------------------------------
const CoursesFilterBar = ({ filter, setFilter, q, setQ, t }) => (
  <div className="cbm-jobs-filter">
    <div className="cbm-jobs-filter__search">
      <i data-lucide="search"></i>
      <input
        placeholder={t('searchCourses')}
        value={q}
        onChange={(e) => setQ(e.target.value)}
      />
    </div>
    <div className="cbm-jobs-filter__chips">
      {CATEGORIES.map(c => (
        <button
          key={c}
          className={'cbm-pill ' + (filter === c ? 'is-active' : '')}
          onClick={() => setFilter(c)}
        >
          {c === 'All' ? t('all') : c}
        </button>
      ))}
    </div>
  </div>
);

// -------------------------------------------------------------
// Plans / subscription strip
// -------------------------------------------------------------
const CoursesPlans = ({ onChoose, t }) => (
  <section className="cbm-section cbm-section--tint">
    <div className="cbm-section__inner">
      <div className="cbm-section__head" style={{textAlign:'center'}}>
        <span className="cbm-eyebrow">{t('membershipEyebrow')}</span>
        <div className="cbm-section-rule" style={{margin: '12px auto 14px'}} />
        <h2 className="cbm-section__title" style={{textAlign:'center'}}>{t('membershipTitle')}</h2>
        <p className="cbm-section__lede" style={{margin: '14px auto 0'}}>
          {t('membershipLede')}
        </p>
      </div>
      <div className="cbm-plans">
        {PLANS.map(p => (
          <div key={p.id} className={'cbm-plan-card' + (p.featured ? ' is-featured' : '')}>
            {p.featured && <div className="cbm-plan-card__ribbon">{t('mostPopular')}</div>}
            <h4>{t('plan_' + p.id) || p.label}</h4>
            <div className="cbm-plan-card__price">
              <span className="cbm-plan-card__cur">XCG</span>
              <span className="cbm-plan-card__num">{window.fmtNum ? window.fmtNum(p.price) : p.price}</span>
            </div>
            <div className="cbm-plan-card__per">
              <span className="cbm-plan-card__usd">{window.usdLine ? window.usdLine(p.price) : ''}</span> · {p.per}
            </div>
            <p className="cbm-plan-card__sub">{p.sub}</p>
            <ul>
              <li>{t('plan_feat_all_courses')}</li>
              <li>{t('plan_feat_new_courses')}</li>
              <li>{t('plan_feat_certificates')}</li>
              {p.id === 'team' && <li>{t('plan_feat_team')}</li>}
              {p.id !== 'team' && <li>{t('plan_feat_offline')}</li>}
            </ul>
            <button
              className={'cbm-btn ' + (p.featured ? 'cbm-btn--gold' : 'cbm-btn--ghost')}
              onClick={() => onChoose(p)}
            >
              {p.id === 'team' ? t('contactSales') : t('startMembership')}
            </button>
          </div>
        ))}
      </div>
      <p style={{textAlign:'center', marginTop: 24, fontSize: 12, color: 'var(--cbm-muted)'}}>
        {t('pricingFootnote')}
      </p>
    </div>
  </section>
);

// -------------------------------------------------------------
// Detail view
// -------------------------------------------------------------
const CourseDetail = ({ course, onBack, onBuy, t }) => (
  <div className="cbm-course-detail">
    <button className="cbm-link-back" onClick={onBack}>
      <i data-lucide="arrow-left"></i> {t('allCourses')}
    </button>
    <div className="cbm-course-detail__head">
      <div className="cbm-course-detail__hero" style={{background: course.color}}>
        <span className="cbm-chip cbm-chip--gold">{course.category}</span>
        <h1>{course.title}</h1>
        <p>{course.short}</p>
        <div className="cbm-course__meta">
          <span><i data-lucide="clock"></i>{course.duration}</span>
          <span><i data-lucide="layers"></i>{course.modules} {t('modules')}</span>
          <span><i data-lucide="trending-up"></i>{course.level}</span>
          <span><i data-lucide="video"></i>{t('onDemand')}</span>
        </div>
      </div>
    </div>

    <div className="cbm-course-detail__body">
      <div>
        <section>
          <h2>{t('aboutCourse')}</h2>
          <p>{course.full}</p>
        </section>
        <section>
          <h2>{t('curriculum')}</h2>
          <ol className="cbm-curriculum">
            {course.curriculum.map((m, i) => (
              <li key={m}>
                <span className="cbm-curriculum__num">{String(i + 1).padStart(2, '0')}</span>
                <span>{m}</span>
              </li>
            ))}
          </ol>
        </section>
        <section>
          <h2>{t('instructor')}</h2>
          <div className="cbm-instructor">
            <div className="cbm-instructor__avatar">{course.instructor.split(' ').map(n => n[0]).join('').slice(0,2)}</div>
            <div>
              <div className="cbm-instructor__name">{course.instructor}</div>
              <div className="cbm-instructor__role">{course.instructorRole}</div>
            </div>
          </div>
        </section>
      </div>
      <aside className="cbm-course-detail__buy">
        <div className="cbm-course-detail__buy-price">
          <span className="cbm-course-detail__cur">XCG</span>
          <span className="cbm-course-detail__num">{window.fmtNum ? window.fmtNum(course.price) : course.price}</span>
        </div>
        <div className="cbm-course-detail__per">
          {window.usdLine ? window.usdLine(course.price) : ''} · {t('oneTimePurchase')}
        </div>
        <button className="cbm-btn cbm-btn--gold" onClick={() => onBuy(course, 'buy')} style={{width: '100%', marginTop: 14}}>
          {t('buyNow')}
        </button>
        <div className="cbm-course-detail__or">{t('or')}</div>
        <button className="cbm-btn cbm-btn--ghost" onClick={() => onBuy(course, 'subscribe')} style={{width: '100%'}}>
          {t('includedInMembership')}
        </button>
        <ul className="cbm-course-detail__incl">
          <li><i data-lucide="check"></i>{t('lifetimeAccess')}</li>
          <li><i data-lucide="check"></i>{t('downloadableResources')}</li>
          <li><i data-lucide="check"></i>{t('certificateOnCompletion')}</li>
          <li><i data-lucide="check"></i>{t('mobileAndOffline')}</li>
        </ul>
      </aside>
    </div>
  </div>
);

// -------------------------------------------------------------
// Checkout
// -------------------------------------------------------------
const Checkout = ({ context, onBack, t }) => {
  const [done, setDone] = React.useState(false);
  const isSubscribe = context.mode === 'subscribe' || context.mode === 'plan';
  const amount = context.mode === 'plan' ? context.plan.price :
                 context.mode === 'buy'  ? context.course.price :
                 PLANS[1].price; // default yearly
  return (
    <div className="cbm-apply">
      <button className="cbm-link-back" onClick={onBack}>
        <i data-lucide="arrow-left"></i> {t('back')}
      </button>
      <div className="cbm-apply__inner">
        {done ? (
          <div className="cbm-apply__done">
            <i data-lucide="check-circle"></i>
            <h2>{isSubscribe ? t('membershipActive') : t('purchaseComplete')}</h2>
            <p>{isSubscribe ? t('subscribeSuccessBody') : t('buySuccessBody')}</p>
            <button className="cbm-btn cbm-btn--ghost" onClick={onBack}>
              {isSubscribe ? t('browseCatalog') : t('startCourse')}
            </button>
          </div>
        ) : (
          <>
            <span className="cbm-eyebrow">{isSubscribe ? t('startMembership') : t('checkout')}</span>
            <h1 className="cbm-section__title" style={{color: 'var(--cbm-blue)', margin: '6px 0 16px'}}>
              {context.mode === 'plan' && (t('plan_' + context.plan.id) + ' — ' + window.formatPrice(context.plan.price) + ' ' + context.plan.per)}
              {context.mode === 'buy' && context.course.title}
              {context.mode === 'subscribe' && t('membershipTitle')}
            </h1>
            <form onSubmit={async e => {
              e.preventDefault();
              const courseTitle = context.mode === 'buy' ? context.course.title : '';
              const planLabel   = context.mode === 'plan' ? (t('plan_' + context.plan.id) + ' (' + context.plan.id + ')') : '';
              const ok = await window.submitFormspree(window.FORMSPREE.courseCheckout, e.currentTarget, {
                _subject: 'Course/membership lead — ' + (courseTitle || planLabel || t('membershipTitle')),
                mode: context.mode,
                course: courseTitle,
                plan: planLabel,
                amount_xcg: amount,
              });
              if (ok) setDone(true);
            }} className="cbm-apply__form">
              <div className="cbm-apply__row">
                <div>
                  <label className="cbm-label">{t('firstName')}</label>
                  <input className="cbm-field" name="first_name" required placeholder="Maya" />
                </div>
                <div>
                  <label className="cbm-label">{t('lastName')}</label>
                  <input className="cbm-field" name="last_name" required placeholder="de Windt" />
                </div>
              </div>
              <div>
                <label className="cbm-label">{t('email')}</label>
                <input className="cbm-field" type="email" name="email" required placeholder="you@business.cw" />
              </div>
              <div>
                <label className="cbm-label">{t('cardNumber')}</label>
                <input className="cbm-field" required placeholder="4242 4242 4242 4242" />
              </div>
              <div className="cbm-apply__row">
                <div>
                  <label className="cbm-label">{t('expiry')}</label>
                  <input className="cbm-field" required placeholder="MM / YY" />
                </div>
                <div>
                  <label className="cbm-label">{t('cvc')}</label>
                  <input className="cbm-field" required placeholder="123" />
                </div>
              </div>
              <div className="cbm-checkout-total">
                <span>{t('totalToday')}</span>
                <strong>{window.formatPrice ? window.formatPrice(amount) : ('XCG ' + amount)}</strong>
              </div>
              {isSubscribe && (
                <p style={{fontSize: 12, color: 'var(--cbm-muted)', margin: 0}}>
                  {t('subscriptionFinePrint')}
                </p>
              )}
              <button className="cbm-btn cbm-btn--gold" type="submit" style={{width: '100%', marginTop: 6}}>
                {(isSubscribe ? t('startMembership') : t('payNow')) + ' · ' + (window.formatPrice ? window.formatPrice(amount) : ('XCG ' + amount))}
              </button>
            </form>
          </>
        )}
      </div>
    </div>
  );
};

// -------------------------------------------------------------
// Catalog
// -------------------------------------------------------------
const CourseCatalog = ({ onOpen, onChoosePlan, t }) => {
  const [filter, setFilter] = React.useState('All');
  const [q, setQ] = React.useState('');
  const list = COURSES
    .filter(c => filter === 'All' || c.category === filter)
    .filter(c => !q || (c.title + ' ' + c.short + ' ' + c.category + ' ' + c.instructor).toLowerCase().includes(q.toLowerCase()));
  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">{t('coursesEyebrow')}</span>
            <div className="cbm-section-rule" />
            <h1 className="cbm-section__title">{t('coursesHeroTitle')}</h1>
            <p className="cbm-section__lede" style={{marginTop: 14}}>{t('coursesHeroLede')}</p>
          </div>
          <div className="cbm-jobs-cta">
            <p className="cbm-eyebrow cbm-eyebrow--gold" style={{margin: 0}}>{t('membershipEyebrow')}</p>
            <h3 style={{fontFamily:'var(--font-display)', fontWeight: 800, fontSize: 28, lineHeight: 1.1, margin: '8px 0 12px', color:'#fff'}}>
              {t('membershipPitch')}
            </h3>
            <p style={{color:'rgba(255,255,255,0.85)', margin:'0 0 18px'}}>
              {t('membershipPitchBody')}
            </p>
            <button className="cbm-btn cbm-btn--gold" onClick={() => onChoosePlan(PLANS[1])}>
              {t('startMembership') + ' — ' + (window.formatPrice ? window.formatPrice(PLANS[1].price) : ('XCG ' + PLANS[1].price)) + ' ' + PLANS[1].per}
            </button>
          </div>
        </div>
      </section>

      <section className="cbm-section" style={{paddingTop: 32}}>
        <div className="cbm-section__inner">
          <CoursesFilterBar filter={filter} setFilter={setFilter} q={q} setQ={setQ} t={t} />
          <div className="cbm-jobs-stats">
            <span><strong>{list.length}</strong> {t('coursesAvailable')}</span>
            <span>{t('onDemand')}</span>
            <span>{t('avgDuration')}</span>
          </div>
          <div className="cbm-course-grid">
            {list.length === 0 ? (
              <div style={{padding: '48px 0', textAlign: 'center', color: 'var(--cbm-muted)', gridColumn: '1 / -1'}}>
                {t('noCoursesFound')}
              </div>
            ) : list.map(c => <CourseCard key={c.id} course={c} onOpen={onOpen} t={t} />)}
          </div>
        </div>
      </section>

      <CoursesPlans onChoose={onChoosePlan} t={t} />
    </>
  );
};

// -------------------------------------------------------------
// Top-level screen
// -------------------------------------------------------------
const CoursesScreen = () => {
  const [view, setView] = React.useState({ mode: 'catalog' });
  const t = (window.useT && window.useT()) || ((k) => k);
  React.useEffect(() => {
    if (window.lucide && window.lucide.createIcons) window.lucide.createIcons();
  }, [view]);
  return (
    <div data-screen-label="Courses">
      {view.mode === 'catalog' && (
        <CourseCatalog
          t={t}
          onOpen={(course) => setView({ mode: 'detail', course })}
          onChoosePlan={(plan) => setView({ mode: 'checkout', context: { mode: 'plan', plan } })}
        />
      )}
      {view.mode === 'detail' && (
        <section className="cbm-section">
          <div className="cbm-section__inner">
            <CourseDetail
              t={t}
              course={view.course}
              onBack={() => setView({ mode: 'catalog' })}
              onBuy={(course, mode) => setView({ mode: 'checkout', context: { mode, course } })}
            />
          </div>
        </section>
      )}
      {view.mode === 'checkout' && (
        <section className="cbm-section cbm-section--tint">
          <div className="cbm-section__inner">
            <Checkout
              t={t}
              context={view.context}
              onBack={() => setView({ mode: 'catalog' })}
            />
          </div>
        </section>
      )}
    </div>
  );
};

Object.assign(window, { CoursesScreen });
