/* Pricing page */

function PricingPage({ setRoute }) {
  const tiers = [
    {
      name: 'Pilot',
      price: '$0',
      per: '/30 days',
      desc: 'Loaner hardware, custom detector, no commitment. Stop anytime.',
      features: [
        '1 Edge device on loan',
        'Custom detector (1 part SKU)',
        'Live + History views',
        'Email + chat support',
        'Stop anytime — we collect the box',
      ],
      cta: 'Start Pilot',
    },
    {
      name: 'Line',
      price: '$249',
      per: '/device/mo',
      desc: 'Per-device subscription. Includes everything in the Edge app and ongoing detector tuning.',
      featured: true,
      features: [
        'All Pilot features',
        'Unlimited part SKUs',
        'Free detector re-training (always)',
        'Cloud Dashboard included',
        '< 4hr support response',
        'PLC + MQTT integration',
      ],
      cta: 'Talk to Sales',
    },
    {
      name: 'Fleet',
      price: 'Custom',
      per: '',
      desc: 'For 20+ device deployments across multiple sites. Volume pricing, dedicated engineer.',
      features: [
        'All Line features',
        'Volume pricing (≥ 20 devices)',
        'Dedicated detector engineer',
        'On-site commissioning',
        'SLA-backed uptime',
        'Custom MES integration',
      ],
      cta: 'Contact Sales',
    },
  ];
  return (
    <React.Fragment>
      <section className="subhero">
        <div className="container">
          <div className="crumb">PRICING</div>
          <h1>Lighter than a single QA shift.</h1>
          <p>Hardware sold at cost. Software per-device. Detector re-training included — every time. No surprise invoices, ever.</p>
        </div>
      </section>

      <section className="section tight">
        <div className="container">
          <div className="pricing-grid">
            {tiers.map(t => (
              <div key={t.name} className={'price-card' + (t.featured ? ' featured' : '')}>
                {t.featured && <div className="badge">Most Popular</div>}
                <div className="name">{t.name}</div>
                <div className="price">{t.price}<span className="per">{t.per}</span></div>
                <div className="desc">{t.desc}</div>
                <ul>
                  {t.features.map(f => (
                    <li key={f}>
                      <span className="check"><Icon name="check" size={11} /></span>
                      {f}
                    </li>
                  ))}
                </ul>
                <button className={'btn ' + (t.featured ? 'btn-primary' : 'btn-outline') + ' btn-lg'}
                        onClick={() => setRoute('demo')}>
                  {t.cta}
                </button>
              </div>
            ))}
          </div>

          <div style={{
            marginTop: 32, padding: 24,
            background: 'var(--color-pass-bg)',
            borderRadius: 12,
            display: 'flex', gap: 14, alignItems: 'flex-start',
            color: 'var(--color-on-surface)',
          }}>
            <Icon name="verified" size={24} style={{ color: 'var(--color-pass)', flexShrink: 0 }} />
            <div>
              <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 4 }}>
                The customization promise
              </div>
              <div style={{ fontSize: 14, color: 'var(--color-on-surface-secondary)', lineHeight: 1.5 }}>
                Whenever your line, SKU, or part changes — we re-train your detector at no extra charge.
                Forever. It's the line in our contract that customers tell us made the difference.
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="section tight">
        <div className="container">
          <Eyebrow>FAQ</Eyebrow>
          <h2 className="section-title">Common questions.</h2>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            {[
              { q: 'What\'s included in the device cost?', a: 'A pre-configured Jetson Orin Nano, an industrial USB3 camera (or we work with yours), the Edge software pre-loaded, and a 1-year hardware warranty.' },
              { q: 'How fast can we go live?', a: 'Most customers go from sample images to live inspection in under a week. We commit to a working detector recording in 4 days.' },
              { q: 'What if the model misses defects?', a: 'During the pilot, if we don\'t hit the defect-catch target you specified, we collect the device and you owe nothing. After that, retraining is included.' },
              { q: 'Do we need cloud connectivity?', a: 'No. The Edge runs fully offline. The Cloud Dashboard is optional and only syncs when you allow it.' },
              { q: 'Can we run on our existing camera?', a: 'Most of the time, yes. We support USB3 and GigE industrial cameras. Send us the model number and we\'ll confirm.' },
              { q: 'Is the model ours or yours?', a: 'You own a perpetual license to the trained model for your part. If you cancel, you keep using it on your hardware.' },
            ].map(f => (
              <div key={f.q} style={{
                background: 'var(--color-surface)',
                border: '1px solid var(--color-border-light)',
                borderRadius: 12, padding: 20,
              }}>
                <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 8 }}>{f.q}</div>
                <div style={{ fontSize: 14, lineHeight: 1.55,
                  color: 'var(--color-on-surface-secondary)' }}>{f.a}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <PriceCalculator />

      <CTA setRoute={setRoute} />
    </React.Fragment>
  );
}

function PriceCalculator() {
  const [devices, setDevices] = React.useState(3);
  const [skus, setSkus] = React.useState(2);
  const [cloud, setCloud] = React.useState(true);
  const [support, setSupport] = React.useState('standard'); // standard | priority
  const [billing, setBilling] = React.useState('monthly');  // monthly | annual

  const hwUnit = 4200;
  const swUnit = 249;
  const cloudFee = cloud ? 99 : 0;
  const supportMult = support === 'priority' ? 1.20 : 1.0;
  const annualDisc = billing === 'annual' ? 0.85 : 1.0;

  const monthlySoftware = (devices * swUnit + cloudFee) * supportMult * annualDisc;
  const oneTimeHardware = devices * hwUnit;
  const yearOne = oneTimeHardware + monthlySoftware * 12;

  const otherVendor = devices * 28000 + (devices * 1800 + 4000) * 12 + 35000; // training fee

  const fmt = (n) => '$' + Math.round(n).toLocaleString();

  return (
    <section className="section tight">
      <div className="container">
        <Eyebrow>Calculator</Eyebrow>
        <h2 className="section-title">Build your quote in 30 seconds.</h2>
        <p className="section-sub">
          Move the sliders. The number on the right is what you'll actually pay — no
          hidden integration fees, no per-image charges, no per-defect billing.
        </p>

        <div style={{
          background: 'var(--color-surface)',
          border: '1px solid var(--color-border-light)',
          borderRadius: 'var(--radius-lg)',
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0,
          overflow: 'hidden',
        }}>
          {/* LEFT: controls */}
          <div style={{ padding: 32, borderRight: '1px solid var(--color-border-light)' }}>
            <PCField label="Edge devices" sub={`${devices} ${devices === 1 ? 'device' : 'devices'}`}>
              <input type="range" min="1" max="50" value={devices}
                     onChange={e => setDevices(+e.target.value)}
                     style={{ width: '100%', accentColor: 'var(--color-primary)' }} />
              <div style={{ display: 'flex', justifyContent: 'space-between',
                  fontSize: 11, color: 'var(--color-on-surface-tertiary)',
                  fontFamily: 'var(--font-mono)' }}>
                <span>1</span><span>25</span><span>50+</span>
              </div>
            </PCField>

            <PCField label="Distinct part SKUs" sub={`${skus} ${skus === 1 ? 'SKU' : 'SKUs'} — retraining included`}>
              <input type="range" min="1" max="20" value={skus}
                     onChange={e => setSkus(+e.target.value)}
                     style={{ width: '100%', accentColor: 'var(--color-primary)' }} />
              <div style={{ display: 'flex', justifyContent: 'space-between',
                  fontSize: 11, color: 'var(--color-on-surface-tertiary)',
                  fontFamily: 'var(--font-mono)' }}>
                <span>1</span><span>10</span><span>20+</span>
              </div>
            </PCField>

            <PCField label="Cloud Dashboard">
              <PCToggle value={cloud} onChange={setCloud}
                onLabel="Enabled · $99/mo flat"
                offLabel="Edge only · $0" />
            </PCField>

            <PCField label="Support tier">
              <div style={{ display: 'flex', gap: 8 }}>
                <PCSeg active={support === 'standard'} onClick={() => setSupport('standard')}>
                  Standard · &lt;4hr
                </PCSeg>
                <PCSeg active={support === 'priority'} onClick={() => setSupport('priority')}>
                  Priority · &lt;1hr (+20%)
                </PCSeg>
              </div>
            </PCField>

            <PCField label="Billing">
              <div style={{ display: 'flex', gap: 8 }}>
                <PCSeg active={billing === 'monthly'} onClick={() => setBilling('monthly')}>
                  Monthly
                </PCSeg>
                <PCSeg active={billing === 'annual'} onClick={() => setBilling('annual')}>
                  Annual · save 15%
                </PCSeg>
              </div>
            </PCField>
          </div>

          {/* RIGHT: total */}
          <div style={{
            padding: 32,
            background: 'var(--color-surface-variant)',
            display: 'flex', flexDirection: 'column',
          }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 0.8,
                textTransform: 'uppercase', color: 'var(--color-on-surface-tertiary)',
                marginBottom: 16 }}>
              Your estimated cost
            </div>

            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 48, fontWeight: 700,
              letterSpacing: -1.5, lineHeight: 1, color: 'var(--color-on-surface)',
            }}>
              {fmt(monthlySoftware)}
              <span style={{ fontSize: 16, color: 'var(--color-on-surface-tertiary)',
                  fontWeight: 400, marginLeft: 8 }}>/mo</span>
            </div>

            <div style={{
              fontSize: 13, color: 'var(--color-on-surface-secondary)',
              marginTop: 6, fontFamily: 'var(--font-mono)',
            }}>
              + {fmt(oneTimeHardware)} hardware (one-time)
            </div>

            <div style={{
              marginTop: 24, padding: '14px 16px',
              background: 'var(--color-surface)',
              borderRadius: 12, border: '1px solid var(--color-border-light)',
              display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            }}>
              <span style={{ fontSize: 12, color: 'var(--color-on-surface-secondary)',
                  fontWeight: 500 }}>YEAR 1 TOTAL</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 22,
                  fontWeight: 700, color: 'var(--color-primary)' }}>
                {fmt(yearOne)}
              </span>
            </div>

            <div style={{
              marginTop: 12, padding: '12px 16px',
              background: 'var(--color-pass-bg)', borderRadius: 12,
              fontSize: 12, color: 'var(--color-on-surface-secondary)',
              lineHeight: 1.5,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span>Year 1 with typical CV vendor</span>
                <span style={{ fontFamily: 'var(--font-mono)', textDecoration: 'line-through',
                    color: 'var(--color-on-surface-tertiary)' }}>
                  {fmt(otherVendor)}
                </span>
              </div>
              <div style={{ marginTop: 6, fontWeight: 600, color: 'var(--color-pass)' }}>
                You save {fmt(otherVendor - yearOne)} vs. typical industrial CV.
              </div>
            </div>

            <button className="btn btn-primary btn-lg" style={{ marginTop: 24, justifyContent: 'center' }}>
              <Icon name="event" size={16} />
              Lock in this quote
            </button>
            <div style={{ fontSize: 11, color: 'var(--color-on-surface-tertiary)',
                marginTop: 10, textAlign: 'center' }}>
              Quotes valid for 30 days · No payment until pilot succeeds
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function PCField({ label, sub, children }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
        <span style={{ fontSize: 13, fontWeight: 600 }}>{label}</span>
        {sub && <span style={{ fontSize: 12, color: 'var(--color-on-surface-tertiary)',
            fontFamily: 'var(--font-mono)' }}>{sub}</span>}
      </div>
      {children}
    </div>
  );
}

function PCToggle({ value, onChange, onLabel, offLabel }) {
  return (
    <button onClick={() => onChange(!value)}
      style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '10px 14px', borderRadius: 9999,
        background: value ? 'var(--color-primary-light)' : 'var(--color-surface-variant)',
        border: '1px solid ' + (value ? 'var(--color-primary)' : 'var(--color-border)'),
        color: value ? 'var(--color-primary)' : 'var(--color-on-surface-secondary)',
        fontSize: 13, fontWeight: 500, cursor: 'pointer',
        width: '100%', textAlign: 'left',
      }}>
      <span style={{
        width: 32, height: 18, borderRadius: 9999,
        background: value ? 'var(--color-primary)' : 'var(--color-on-surface-tertiary)',
        position: 'relative', flexShrink: 0,
      }}>
        <span style={{
          position: 'absolute', top: 2, left: value ? 16 : 2,
          width: 14, height: 14, borderRadius: '50%', background: '#fff',
          transition: 'left 0.15s',
        }}></span>
      </span>
      {value ? onLabel : offLabel}
    </button>
  );
}

function PCSeg({ active, onClick, children }) {
  return (
    <button onClick={onClick}
      style={{
        flex: 1, padding: '10px 12px', borderRadius: 8,
        background: active ? 'var(--color-primary-light)' : 'var(--color-surface-variant)',
        border: '1px solid ' + (active ? 'var(--color-primary)' : 'var(--color-border)'),
        color: active ? 'var(--color-primary)' : 'var(--color-on-surface-secondary)',
        fontSize: 12, fontWeight: 600, cursor: 'pointer',
      }}>
      {children}
    </button>
  );
}

Object.assign(window, { PricingPage });
