/* global React, Icon, Button, Stars, Gallery, PACKS */
const { useState: useBState } = React;

/* benefit bullets under the subheadline (green checks) */
const VALUE_BULLETS = [
  'Eases GLP-1 constipation & bloating',
  'Supports digestion and gut health',
  'Gentle daily fibre — no harsh laxatives',
  'Vegan, UK made & 3rd-party lab tested'
];

/* bottom assurances (HSA/FSA badge removed per request) */
const ASSURANCES = [
  ['shield-check', 'Clinically &', '3rd-party tested'],
  ['rotate-ccw', '60-Day Money-Back', 'Guarantee']
];

const SUB_BULLETS = ['FAST & FREE Shipping On First Order', 'Pause Or Cancel Any Time', '60-Day Money-Back Guarantee'];
const ONCE_BULLETS = ['No Free Shipping', 'Discount on first order only'];

function money(n) { return '$' + n.toFixed(2); }

/* pricing driven by tweaks. 1 bottle = 120 caps = 60 days (2/day). */
function priceFor(bottles, t) {
  const qty = bottles >= 2 ? (1 - t.qtyDiscount / 100) : 1;
  const rrpRaw = t.regularPrice * bottles;           // clean original price
  const rrp = rrpRaw - 0.01;                          // displayed struck, ends in .99
  const sub = rrpRaw * (1 - t.subscribeDiscount / 100) * qty; // subscription price
  const once = sub / (1 - t.subSavings / 100);       // one-time costs more
  const days = bottles * 60;
  return { sub, once, rrp, subDay: sub / days, onceDay: once / days };
}

/* ---------- subscribe / one-time radio card ---------- */
function PurchaseCard({ selected, onSelect, title, sub, price, rrp, perDay, banner, bullets, cross }) {
  return (
    <div onClick={onSelect} style={{ cursor: 'pointer', borderRadius: 14, overflow: 'hidden',
      border: selected ? '2px solid var(--green-600)' : '1.5px solid var(--line)',
      background: selected ? 'var(--green-050)' : '#fff', transition: 'all .12s' }}>
      {banner && selected && (
        <div style={{ background: 'var(--green-900)', color: 'var(--yellow-400)', textAlign: 'center',
          fontWeight: 800, fontSize: 12.5, letterSpacing: '.04em', padding: '7px 10px' }}>{banner}</div>
      )}
      <div style={{ padding: '15px 16px' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 11 }}>
          <span style={{ width: 20, height: 20, borderRadius: 999, flexShrink: 0, marginTop: 2,
            border: selected ? '6px solid var(--green-600)' : '2px solid var(--ink-400)', boxSizing: 'border-box' }} />
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 10 }}>
              <span style={{ fontSize: 16.5, fontWeight: 800, color: 'var(--green-900)', whiteSpace: 'nowrap' }}>{title}</span>
              <span style={{ whiteSpace: 'nowrap' }}>
                <span style={{ fontSize: 18, fontWeight: 800, color: 'var(--green-900)' }}>{money(price)}</span>
                <span style={{ fontSize: 13, color: 'var(--ink-400)', textDecoration: 'line-through', marginLeft: 6 }}>{money(rrp)}</span>
              </span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 2 }}>
              <span style={{ fontSize: 13, color: 'var(--ink-600)' }}>{sub}</span>
              <span style={{ fontSize: 13, color: 'var(--ink-400)' }}>{money(perDay)}/day</span>
            </div>
            {selected && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 7, marginTop: 12 }}>
                {bullets.map(b => (
                  <div key={b} style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 13.5,
                    fontWeight: 600, color: 'var(--green-900)' }}>
                    <Icon name={cross ? 'x' : 'check'} size={16} color={cross ? '#D14343' : 'var(--green-600)'} strokeWidth={2.5} />
                    {b}
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function BuyBox({ onAdd, t }) {
  const [bottles, setBottles] = useBState(2);
  const [mode, setMode] = useBState('sub'); // 'sub' | 'once'
  const pr = priceFor(bottles, t);
  const freq = bottles >= 2 ? `${bottles * 2} weeks` : '8 weeks';
  const popularPct = Math.round((1 - pr.sub / pr.rrp) * 100);
  const price = mode === 'sub' ? pr.sub : pr.once;

  return (
    <div>
      {/* rating */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
        <Stars n={5} size={17} />
        <span style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--green-900)' }}>
          <a href="#reviews" style={{ color: 'var(--green-700)', textDecoration: 'underline' }}>4.8/5.0 (100,000)</a>, 1M+ Customers
        </span>
      </div>

      {/* title */}
      <h2 style={{ margin: '0 0 12px', fontSize: 'clamp(28px, 2.6vw, 36px)', fontWeight: 800,
        letterSpacing: '-.02em', color: 'var(--green-700)', lineHeight: 1.08 }}>
        Psyllium Husk Fibre
      </h2>

      {/* subheadline */}
      <p style={{ margin: '0 0 16px', fontSize: 18, fontWeight: 700, color: '#000', lineHeight: 1.4 }}>
        4000mg psyllium husk + acidophilus to keep you comfortably regular — even on GLP-1s.
      </p>

      {/* value bullets */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9, marginBottom: 20 }}>
        {VALUE_BULLETS.map(b => (
          <div key={b} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 15.5,
            fontWeight: 600, color: 'var(--green-900)' }}>
            <Icon name="check" size={18} color="var(--green-600)" strokeWidth={2.5} />{b}
          </div>
        ))}
      </div>

      <div style={{ borderTop: '1px solid var(--line)', margin: '0 0 18px' }} />

      {/* quantity segmented control */}
      <div style={{ marginBottom: 11, lineHeight: 1 }}>
        <span style={{ fontSize: 16, fontWeight: 800, color: 'var(--green-900)' }}>How many bottles?</span>
        {t.qtyDiscount > 0 && (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, fontWeight: 700,
            color: '#fff', background: 'var(--green-600)', borderRadius: 999, padding: '4px 11px',
            marginLeft: 10, verticalAlign: 'middle', whiteSpace: 'nowrap' }}>
            <Icon name="tag" size={12} color="#fff" />Buy 2 Save {t.qtyDiscount}%
          </span>
        )}
      </div>
      <div style={{ display: 'flex', gap: 6, border: '1.5px solid var(--line)', borderRadius: 999,
        padding: 5, marginBottom: 20 }}>
        {[1, 2].map(n => {
          const on = bottles === n;
          return (
            <button key={n} onClick={() => setBottles(n)} style={{ flex: 1, padding: '13px',
              borderRadius: 999, cursor: 'pointer', fontFamily: 'var(--font-sans)', fontSize: 16, fontWeight: 700,
              color: 'var(--green-900)', transition: 'all .12s',
              background: on ? 'var(--green-100)' : 'transparent',
              border: on ? '1.5px solid var(--green-600)' : '1.5px solid transparent' }}>{n}</button>
          );
        })}
      </div>

      <div style={{ borderTop: '1px solid var(--line)', margin: '0 0 16px' }} />

      {/* purchase options */}
      <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--green-900)', marginBottom: 12 }}>Autoship and Save:</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 18 }}>
        <PurchaseCard selected={mode === 'sub'} onSelect={() => setMode('sub')}
          title="Subscribe & Save" sub={`${bottles * 120} capsules each ${freq}`}
          price={pr.sub} rrp={pr.rrp} perDay={pr.subDay}
          banner={`MOST POPULAR: GET ${popularPct}% OFF`} bullets={SUB_BULLETS} />
        <PurchaseCard selected={mode === 'once'} onSelect={() => setMode('once')}
          title="One Time Purchase" sub={`${bottles * 120} capsules delivered once`}
          price={pr.once} rrp={pr.rrp} perDay={pr.onceDay} bullets={ONCE_BULLETS} cross />
      </div>

      {/* CTA */}
      <Button variant="primary" full style={{ fontSize: 19, padding: '19px' }}
        onClick={() => onAdd({ bottles, mode, price })}>
        Start Now
      </Button>

      {/* auto-applied pill */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, marginTop: 12,
        background: '#FBF3D9', borderRadius: 10, padding: '12px' }}>
        <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--green-900)' }}>Limited Time Discount Auto-Applied</span>
        <Icon name="check-circle" size={17} color="var(--green-600)" />
      </div>

      {/* assurances */}
      <div style={{ display: 'flex', justifyContent: 'center', gap: 56, marginTop: 24,
        paddingTop: 22, borderTop: '1px solid var(--line)' }}>
        {ASSURANCES.map(([ic, l1, l2]) => (
          <div key={l1} style={{ textAlign: 'center' }}>
            <span style={{ width: 42, height: 42, borderRadius: 999, border: '1.5px solid var(--green-600)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 8 }}>
              <Icon name={ic} size={20} color="var(--green-600)" />
            </span>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--green-700)', lineHeight: 1.3 }}>{l1}<br/>{l2}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ProductDetail({ onAdd, t }) {
  return (
    <section id="shop" style={{ maxWidth: 1200, margin: '0 auto', padding: '64px 28px',
      display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48, alignItems: 'start' }}>
      <Gallery showBanner={t.showSaleBanner} />
      <BuyBox onAdd={onAdd} t={t} />
    </section>
  );
}

Object.assign(window, { ProductDetail });
