/* global React */
// Pricing page sections.

const fmtZAR = (n) => {
  // SA convention: non-breaking space separator, e.g. R1 000
  if (typeof n !== 'number') return n;
  return 'R' + n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '\u00A0');
};

const PricingHero = () => (
  <section className="section site-grid-bg" style={{ paddingTop: 72, paddingBottom: 32 }}>
    <div className="container" style={{ maxWidth: 880, textAlign: 'center' }}>
      <span className="t-eyebrow t-eyebrow--accent" style={{ display: 'inline-block' }}>Pricing</span>
      <h1 className="t-display" style={{ marginTop: 18, marginBottom: 18, fontSize: 'clamp(34px, 4.6vw, 54px)' }}>
        Site-first pricing for South African industrial sites.
      </h1>
      <p className="t-lead" style={{ maxWidth: 680, margin: '0 auto' }}>
        Pay per site, not per employee. Multi-site bundle in the base. No hardware to buy.
      </p>
    </div>
  </section>
);

const PricingTiers = () => {
  const [annual, setAnnual] = React.useState(false);

  const sitePrice = annual ? 900 : 1000;
  const extraSite = annual ? 450 : 500;
  const extraWorker = annual ? 18 : 20;

  const tiers = [
    {
      name: 'Pilot',
      priceLabel: 'R0',
      unit: '/ 30 days',
      tagline: 'Test SiteSign on one site. We help you set it up.',
      bullets: [
        'Full feature access',
        '1 site',
        'Up to 100 workers',
        'Setup support included',
        'No credit card',
      ],
      cta: 'Start free pilot',
      ctaStyle: 'btn--secondary',
      ctaDisabled: true,
      ctaNote: 'Pilot programme launching soon — book a demo for early access.',
    },
    {
      name: 'Site',
      priceLabel: fmtZAR(sitePrice),
      unit: '/ month',
      tagline: 'Two sites. Up to 100 workers. Everything you need for verified attendance.',
      bullets: [
        '2 sites included',
        '50 workers per site (up to 100 workers total)',
        'Face + GPS verification',
        'BCEA-safe corrections',
        'Auto-close',
        'Offline mode',
        'Payroll-neutral CSV export',
        'Email support',
      ],
      beyond: `Need more? ${fmtZAR(extraSite)} per extra site / month. ${fmtZAR(extraWorker)} per extra worker / month.`,
      cta: 'Book a 15-min demo',
      ctaStyle: 'btn--cta',
      featured: true,
    },
    {
      name: 'Enterprise',
      priceLabel: 'Talk to us',
      unit: '',
      tagline: 'Multi-region operations, custom integrations, dedicated success manager.',
      bullets: [
        'Unlimited sites',
        'Custom worker volumes',
        'Priority support with named contact',
        'SSO',
        'Custom SLAs',
        'On-site onboarding',
      ],
      cta: 'Book a 15-min demo',
      ctaStyle: 'btn--secondary',
    },
  ];

  return (
    <section className="section--tight" style={{ paddingTop: 8, paddingBottom: 56 }}>
      <div className="container">
        {/* Toggle */}
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 32 }}>
          <div role="tablist" aria-label="Billing period" style={{
            display: 'inline-flex', padding: 4, borderRadius: 99,
            background: 'var(--ss-bg-grey)', border: '1px solid var(--ss-silver)',
          }}>
            {[
              { key: false, label: 'Monthly' },
              { key: true,  label: 'Annual', tag: 'save 10%' },
            ].map(opt => (
              <button
                key={String(opt.key)}
                role="tab"
                aria-selected={annual === opt.key}
                onClick={() => setAnnual(opt.key)}
                style={{
                  border: 'none',
                  background: annual === opt.key ? 'var(--ss-midnight-blue)' : 'transparent',
                  color: annual === opt.key ? '#fff' : 'var(--ss-dark-text)',
                  padding: '8px 18px',
                  borderRadius: 99,
                  fontWeight: 600,
                  fontSize: 14,
                  cursor: 'pointer',
                  display: 'inline-flex', alignItems: 'center', gap: 8,
                }}>
                {opt.label}
                {opt.tag && <span style={{ fontSize: 11, fontWeight: 700, color: annual === opt.key ? 'var(--ss-safety-yellow)' : 'var(--ss-grey-mid)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{opt.tag}</span>}
              </button>
            ))}
          </div>
        </div>

        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
          gap: 20,
          maxWidth: 1100,
          margin: '0 auto',
          alignItems: 'stretch',
        }}>
          {tiers.map((t, i) => {
            const filled = t.featured;
            return (
              <div key={i} style={{
                position: 'relative',
                background: filled ? 'var(--ss-midnight-blue)' : 'var(--ss-white)',
                color: filled ? '#fff' : 'inherit',
                border: filled ? '1px solid var(--ss-midnight-blue)' : '1px solid var(--ss-silver)',
                borderRadius: 'var(--ss-radius)',
                padding: 28,
                boxShadow: filled ? '0 8px 24px rgba(44,62,80,0.18)' : 'var(--ss-shadow-card)',
                display: 'flex', flexDirection: 'column',
                borderTop: filled ? '4px solid var(--ss-safety-yellow)' : '1px solid var(--ss-silver)',
                paddingTop: filled ? 28 : 28,
              }}>
                {filled && (
                  <span style={{
                    position: 'absolute', top: 16, right: 20,
                    fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
                    color: 'var(--ss-safety-yellow)',
                  }}>Most popular</span>
                )}
                <div style={{
                  fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
                  color: filled ? 'rgba(255,255,255,0.6)' : 'var(--ss-grey-mid)',
                  marginBottom: 14,
                }}>{t.name}</div>

                <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 6, flexWrap: 'wrap' }}>
                  <span style={{
                    fontSize: t.priceLabel.length > 6 ? 28 : 36,
                    fontWeight: 900,
                    color: filled ? '#fff' : 'var(--ss-midnight-blue)',
                    lineHeight: 1,
                  }}>{t.priceLabel}</span>
                  {t.unit && <span style={{ fontSize: 13, color: filled ? 'rgba(255,255,255,0.7)' : 'var(--ss-grey-mid)', fontWeight: 500 }}>{t.unit}</span>}
                </div>

                <p style={{
                  fontSize: 14, lineHeight: 1.55,
                  color: filled ? 'rgba(255,255,255,0.85)' : 'var(--ss-dark-text)',
                  margin: '12px 0 18px',
                }}>{t.tagline}</p>

                <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 18px', display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {t.bullets.map((f, j) => (
                    <li key={j} style={{
                      display: 'flex', gap: 10, alignItems: 'flex-start',
                      fontSize: 13.5,
                      color: filled ? 'rgba(255,255,255,0.92)' : 'var(--ss-dark-text)',
                    }}>
                      <span style={{ flex: '0 0 auto', marginTop: 2, color: filled ? 'var(--ss-safety-yellow)' : 'var(--ss-success)' }}><IconCheck size={14}/></span>
                      <span>{f}</span>
                    </li>
                  ))}
                </ul>

                {t.beyond && (
                  <div style={{
                    fontSize: 12,
                    background: 'rgba(238,210,2,0.12)',
                    borderLeft: '3px solid var(--ss-safety-yellow)',
                    color: filled ? '#fff' : 'var(--ss-dark-text)',
                    padding: '10px 12px',
                    borderRadius: 6,
                    marginBottom: 18,
                    lineHeight: 1.5,
                  }}>{t.beyond}</div>
                )}

                <div style={{ marginTop: 'auto' }}>
                  {t.ctaDisabled ? (
                    <button
                      type="button"
                      disabled
                      aria-disabled="true"
                      className="btn btn--secondary btn--sm"
                      style={{ width: '100%', opacity: 0.55, cursor: 'not-allowed' }}
                    >{t.cta}</button>
                  ) : (
                    <a
                      className={`btn ${t.ctaStyle} btn--sm`}
                      href={t.featured ? 'index.html#book-demo' : 'index.html#book-demo'}
                      style={{ width: '100%' }}
                    >{t.cta}</a>
                  )}
                  {t.ctaNote && (
                    <p style={{
                      fontSize: 11.5,
                      color: filled ? 'rgba(255,255,255,0.7)' : 'var(--ss-grey-mid)',
                      margin: '10px 0 0',
                      lineHeight: 1.5,
                    }}>{t.ctaNote}</p>
                  )}
                </div>
              </div>
            );
          })}
        </div>

        <p className="t-meta" style={{ textAlign: 'center', marginTop: 24, fontSize: 12 }}>
          All prices ex-VAT. Billed in ZAR.
        </p>
      </div>
    </section>
  );
};

/* ---------- Why this pricing (4 pillars) ---------- */

const WhyThisPricing = () => {
  const pillars = [
    {
      title: 'Pure attendance. Keep your payroll.',
      body: 'We do not run your payroll. We give you verified hours — exported clean to whichever payroll system you already use. PaySpace, Sage, Pastel, manual — your call.',
    },
    {
      title: 'BYOD tablet. R0 hardware capex.',
      body: 'Pair any Android or iOS tablet at the gate in 60 seconds. No fingerprint scanner to buy. No proprietary device. No surprise hardware bill at month one.',
    },
    {
      title: 'BCEA-safe corrections, not generic compliance.',
      body: 'Original timestamps are immutable. Corrections are captured separately with the supervisor\u2019s name and reason. Defensible against any labour-court dispute.',
    },
    {
      title: 'Site-first pricing. Two sites in the base.',
      body: 'Multi-site contractors get bundled pricing. Single-site operators pay only for what they use. Built for the way industrial-site businesses actually count.',
    },
  ];

  return (
    <section className="section section--grey">
      <div className="container">
        <div style={{ maxWidth: 720, marginBottom: 40 }}>
          <span className="t-eyebrow t-eyebrow--accent">Why this pricing</span>
          <h2 className="t-h1" style={{ marginTop: 14 }}>Built for the way industrial sites count.</h2>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 20 }}>
          {pillars.map((p, i) => (
            <div key={i} className="card card--accent-left">
              <div style={{
                fontFamily: 'ui-monospace, "SF Mono", Menlo, Consolas, monospace',
                fontSize: 11, color: 'var(--ss-grey-mid)', fontWeight: 700,
                letterSpacing: '0.1em', marginBottom: 10,
              }}>PILLAR {String(i+1).padStart(2,'0')}</div>
              <h3 className="t-h3" style={{ fontSize: 17, marginBottom: 10 }}>{p.title}</h3>
              <p className="t-small" style={{ margin: 0 }}>{p.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ---------- Comparison table ---------- */

const Comparison = () => {
  const cols = [
    'SiteSign',
    'Paper sign-in books',
    'Legacy fingerprint hardware',
    'All-in-one labour bundles',
    'Payroll-suite attendance modules',
  ];
  const rows = [
    { feature: 'BCEA-safe corrections',                     values: [true, false, false, 'partial', 'partial'] },
    { feature: 'BYOD tablet (no proprietary hardware)',     values: [true, true,  false, 'partial', true] },
    { feature: 'Auto-close forgotten shifts',               values: [true, false, false, 'partial', false] },
    { feature: 'Face + GPS verification',                   values: [true, false, false, 'partial', false] },
    { feature: 'Offline mode with face verification',       values: [true, false, 'partial', false, false] },
    { feature: 'Site-first pricing structure',              values: [true, false, false, false, false] },
    { feature: 'Payroll-vendor neutral export',             values: [true, true,  'partial', false, false] },
    { feature: 'POPIA-aware biometric retention',           values: [true, false, false, 'partial', 'partial'] },
    { feature: 'Public pricing on the page',                values: [true, true,  false, false, false] },
  ];

  const Cell = ({ v, isSiteSign }) => {
    if (v === true) {
      return (
        <span style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          width: 28, height: 28, borderRadius: 6,
          background: isSiteSign ? 'var(--ss-safety-yellow)' : 'var(--ss-silver)',
          color: 'var(--ss-midnight-blue)',
        }} aria-label="Yes"><IconCheck size={16} strokeWidth={2.5}/></span>
      );
    }
    if (v === false) {
      return (
        <span style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          width: 28, height: 28, borderRadius: 6,
          background: 'rgba(176,0,32,0.08)',
          color: 'var(--ss-danger)',
        }} aria-label="No"><IconX size={16} strokeWidth={2.5}/></span>
      );
    }
    if (v === 'partial') {
      return (
        <span aria-label="Partial" style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          height: 24, padding: '0 10px', borderRadius: 6,
          background: 'rgba(238,210,2,0.18)',
          color: 'var(--ss-dark-text)',
          fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase',
        }}>Partial</span>
      );
    }
    return v;
  };

  return (
    <section className="section">
      <div className="container">
        <div style={{ maxWidth: 720, marginBottom: 32 }}>
          <span className="t-eyebrow t-eyebrow--accent">Comparison</span>
          <h2 className="t-h1" style={{ marginTop: 14 }}>How SiteSign compares.</h2>
        </div>

        <div style={{ overflowX: 'auto', background: 'var(--ss-white)', borderRadius: 12, border: '1px solid var(--ss-silver)', boxShadow: 'var(--ss-shadow-card)' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 900 }}>
            <thead>
              <tr style={{ background: 'var(--ss-midnight-blue)', color: '#fff' }}>
                <th style={{ textAlign: 'left', padding: '16px 20px', fontWeight: 600, fontSize: 13, borderBottom: '4px solid var(--ss-safety-yellow)' }}>Capability</th>
                {cols.map((c, i) => (
                  <th key={i} style={{
                    padding: '16px 12px', fontWeight: 700, fontSize: 12,
                    background: i === 0 ? 'rgba(238,210,2,0.18)' : undefined,
                    color: i === 0 ? 'var(--ss-safety-yellow)' : '#fff',
                    borderBottom: '4px solid var(--ss-safety-yellow)',
                    textAlign: 'center',
                    minWidth: 110,
                    lineHeight: 1.3,
                  }}>{c}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows.map((r, i) => (
                <tr key={i} style={{ background: i % 2 ? 'var(--ss-bg-grey)' : 'transparent' }}>
                  <td style={{ padding: '14px 20px', fontSize: 14, color: 'var(--ss-dark-text)', fontWeight: 500 }}>{r.feature}</td>
                  {r.values.map((v, j) => (
                    <td key={j} style={{
                      padding: '12px 12px', textAlign: 'center',
                      background: j === 0 ? 'rgba(238,210,2,0.06)' : undefined,
                    }}>
                      <Cell v={v} isSiteSign={j === 0}/>
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <p className="t-meta" style={{ marginTop: 14, fontSize: 12 }}>
          Generic categories only. No named competitors. Based on commonly-available feature sets in each category.
        </p>
      </div>
    </section>
  );
};

/* ---------- Pricing FAQ ---------- */

const PricingFaq = () => {
  const items = [
    { q: 'What counts as a site?',                          a: 'A "site" is one geofenced location — one construction site, one mine shaft, one warehouse, one packhouse. You configure each site separately with its own closing time and geofence radius.' },
    { q: 'What happens when I add the 51st worker at a site?', a: 'From worker 51 you pay R20 per extra worker per month at that site. Workers move freely between sites without extra charge.' },
    { q: 'Can I change my payroll system mid-pilot?',       a: 'Yes. SiteSign is payroll-neutral. We never integrate to your payroll engine — we export clean CSV that you import wherever you want. Change payroll vendors without changing attendance.' },
    { q: 'What hardware do I need?',                        a: 'Any Android tablet (Android 10+) or iPad (iOS 15+) with a camera. No fingerprint scanner. No proprietary device. We recommend a basic R3 000–R5 000 tablet at each site.' },
    { q: 'Is the pilot really free?',                       a: 'Yes — 30 days, full feature access, one site. You only commit to paid pricing if you decide to continue. The pilot programme is launching soon — book a 15-min demo for early access.' },
    { q: 'What is included in support?',                    a: 'Email support during SA business hours (08:00 – 17:00 SAST). Same-day response on Severity 1 issues (production down). Two business days on cosmetic / configuration issues. Enterprise tier includes named contact and SLAs.' },
    { q: 'How does the annual discount work?',              a: 'Annual billing saves 10%. You pay 12 months upfront in one invoice and lock pricing for that year. We do not charge usage uplifts mid-year for the Site tier; uplifts apply at renewal.' },
    { q: 'Can I cancel any time?',                          a: 'Monthly billing: cancel any time, prorated to month-end. Annual billing: cancel any time, no refund on remaining months. Your data exports cleanly on cancellation.' },
  ];

  return (
    <section className="section section--grey">
      <div className="container" style={{ maxWidth: 920 }}>
        <div style={{ marginBottom: 28 }}>
          <span className="t-eyebrow t-eyebrow--accent">Pricing FAQ</span>
          <h2 className="t-h1" style={{ marginTop: 14 }}>Pricing-specific questions.</h2>
        </div>
        {items.map((it, i) => <FaqItem key={i} q={it.q} a={it.a} defaultOpen={i === 0}/>)}
      </div>
    </section>
  );
};

/* ---------- Bottom CTA (deprecated, replaced by shared BottomCTA in chrome.jsx) ---------- */

const PricingCTA = () => (
  <section className="section section--midnight">
    <div className="container" style={{ maxWidth: 840, textAlign: 'center' }}>
      <span className="t-eyebrow t-eyebrow--accent" style={{ color: 'rgba(255,255,255,0.7)' }}>Get started</span>
      <h2 className="t-h1" style={{ color: '#fff', marginTop: 14 }}>Try SiteSign on one site for 30 days, free.</h2>
      <p className="t-lead" style={{ color: 'rgba(255,255,255,0.85)', marginTop: 8, marginBottom: 28 }}>
        We help you set up. You decide if it stays.
      </p>
      <a className="btn btn--cta btn--lg" href="index.html#book-demo">
        Book a 15-min demo
        <IconArrowRight size={18}/>
      </a>
    </div>
  </section>
);

Object.assign(window, { PricingHero, PricingTiers, WhyThisPricing, Comparison, PricingFaq });
