// Pricing (light region) + Contact / Free-trial modals.
(function () {
  if (document.getElementById('wa-price-styles')) return;
  const s = document.createElement('style');
  s.id = 'wa-price-styles';
  s.textContent = `
  .price-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:22px;margin-top:56px;align-items:stretch;}
  .pcard{position:relative;background:var(--lt-surface);border:1px solid var(--lt-border);border-radius:24px;padding:32px 28px;display:flex;flex-direction:column;}
  .pcard.pop{background:var(--surface-2);border:1.5px solid var(--pink);box-shadow:var(--glow-pink),0 30px 80px -30px rgba(45,140,255,.45);transform:none;}
  .pcard.pop *{color:#fff;}
  .pbadge{position:absolute;top:-13px;left:50%;transform:translateX(-50%);background:var(--grad-primary);color:#fff;
    font-family:'JetBrains Mono';font-size:10px;letter-spacing:.14em;text-transform:uppercase;font-weight:600;padding:6px 16px;border-radius:999px;white-space:nowrap;box-shadow:var(--glow-pink);}
  .pbadge.best{background:var(--surface-3);color:var(--pink);border:1px solid rgba(45,140,255,.4);box-shadow:none;}
  .pname{font-family:'Gabarito';font-weight:800;font-size:22px;color:var(--lt-text);text-align:center;}
  .pprice{font-family:'Gabarito';font-weight:900;font-size:52px;color:var(--lt-text);text-align:center;line-height:1;margin:14px 0 4px;}
  .pprice .per{font-size:15px;font-weight:600;color:var(--lt-muted);font-family:'Hanken Grotesk';}
  .pdesc{text-align:center;color:var(--lt-muted);font-size:13.5px;margin-bottom:22px;min-height:46px;display:flex;align-items:center;justify-content:center;}
  .pcard.pop .pdesc,.pcard.pop .pname{color:#fff;}
  .pcard.pop .pprice{background:var(--grad-warm);-webkit-background-clip:text;background-clip:text;color:transparent;}
  .pcard.pop .pprice .per{-webkit-text-fill-color:rgba(255,255,255,.6);}
  .plist{list-style:none;padding:0;margin:22px 0 0;}
  .plist li{display:flex;gap:11px;align-items:flex-start;font-size:14.5px;color:var(--lt-text);padding:7px 0;}
  .pcard.pop .plist li{color:rgba(255,255,255,.9);}
  .plist .ck{width:18px;height:18px;border-radius:6px;background:rgba(45,140,255,.16);color:var(--pink);display:grid;place-items:center;flex-shrink:0;margin-top:1px;}
  .pcard.pop .plist .ck{background:rgba(45,140,255,.26);}
  .pbtn{width:100%;margin-top:4px;}
  .pay-row{margin-top:22px;padding-top:17px;border-top:1px solid var(--lt-border);display:flex;align-items:center;justify-content:center;gap:15px;}
  .pcard.pop .pay-row,.pay-row.pay-row-dark{border-top-color:rgba(255,255,255,.13);}
  .pay-lock{display:inline-flex;align-items:center;color:rgba(255,255,255,.6);}
  .pay-marks{display:flex;align-items:center;gap:17px;}
  .pay-marks .pm{display:inline-flex;align-items:center;height:20px;opacity:.66;color:#fff;font-family:'Hanken Grotesk',sans-serif;font-weight:800;font-size:14px;letter-spacing:.02em;white-space:nowrap;}
  .pay-marks .pm svg{display:block;}
  .pm-visa{font-style:italic;letter-spacing:.07em;font-size:15.5px;}
  .pm-ap{gap:3px;}
  .pm-ap svg{width:15px;height:18px;}
  .pm-ap span{font-weight:600;}
  .pm-gp{gap:3px;font-weight:700;}
  .pm-gp b{font-weight:800;font-size:15px;}
  .pm-gp span{font-weight:600;}
  .pm-mc svg{width:33px;height:20px;}
  @media(max-width:900px){.price-grid{grid-template-columns:1fr;}.pcard.pop{transform:none;}}
  `;
  document.head.appendChild(s);
})();

function Check() {
  return <span className="ck"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5" /></svg></span>;
}

function PayRow({ dark }) {
  return (
    <div className={'pay-row' + (dark ? ' pay-row-dark' : '')}>
      <span className="pay-lock"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></svg></span>
      <div className="pay-marks">
        <span className="pm pm-visa" title="Visa">VISA</span>
        <span className="pm pm-mc" title="Mastercard"><svg viewBox="0 0 38 24" fill="none"><circle cx="15" cy="12" r="9" fill="#fff" fillOpacity="0.5" /><circle cx="23" cy="12" r="9" fill="#fff" fillOpacity="0.92" /></svg></span>
        <span className="pm pm-ap" title="Apple Pay"><svg viewBox="0 0 24 24" fill="#fff"><path d="M17.05 12.04c-.03-2.6 2.13-3.85 2.22-3.91-1.21-1.77-3.1-2.01-3.77-2.04-1.6-.16-3.13.94-3.94.94-.81 0-2.07-.92-3.4-.89-1.75.03-3.36 1.02-4.26 2.58-1.82 3.16-.47 7.83 1.3 10.4.86 1.25 1.89 2.66 3.23 2.61 1.3-.05 1.79-.84 3.36-.84 1.57 0 2.01.84 3.39.81 1.4-.02 2.29-1.28 3.15-2.54.99-1.45 1.4-2.86 1.42-2.93-.03-.01-2.73-1.05-2.76-4.16zM14.47 4.36c.71-.86 1.19-2.06 1.06-3.25-1.02.04-2.26.68-2.99 1.54-.66.76-1.23 1.98-1.08 3.15 1.14.09 2.3-.58 3.01-1.44z" /></svg><span>Pay</span></span>
        <span className="pm pm-gp" title="Google Pay"><b>G</b><span>Pay</span></span>
      </div>
    </div>);
}

function Pricing({ onBuy, onTrial }) {
  const lifetime = ['All calendars — no limits', 'Any date range', 'Recurring & series events', 'Thousands of events handled', 'Lifetime access — one payment'];
  const year = ['All calendars — no limits', 'Any date range', 'Recurring & series events', 'Thousands of events handled', '365 days of access — one payment'];
  const free = ['1 calendar limit', '30-day date range', '24-hour access'];
  return (
    <section className="section" id="pricing" style={{ paddingTop: 40, paddingBottom: 30 }}>
      <div className="wrap">
        <SectionHead lt eyebrow="Pricing" title="Simple, honest pricing." sub="No subscriptions. No renewals. Pick the licence that suits you." />
        <div className="price-grid">
          <div className="pcard">
            <div className="pbadge best">Best Value</div>
            <div className="pname">Lifetime licence</div>
            <div className="pprice">$19.99</div>
            <div className="pdesc">one-time payment · yours forever</div>
            <button className="btn btn-primary pbtn" onClick={onBuy}>Buy Now — $19.99 <span className="arrow">→</span></button>
            <ul className="plist">{lifetime.map((x) => <li key={x}><Check />{x}</li>)}</ul>
            <PayRow />
          </div>

          <div className="pcard pop">
            <div className="pbadge">Most Popular</div>
            <div className="pname">1-Year Licence</div>
            <div className="pprice">$9.99<span className="per">/yr</span></div>
            <div className="pdesc">one-time payment · unlimited 1-year access</div>
            <button className="btn btn-primary pbtn" onClick={onBuy}>Buy Now — $9.99 <span className="arrow">→</span></button>
            <ul className="plist">{year.map((x) => <li key={x}><Check />{x}</li>)}</ul>
            <PayRow />
          </div>

          <div className="pcard">
            <div className="pname">Trial licence</div>
            <div className="pprice">FREE</div>
            <div className="pdesc">try Wipe Away for free</div>
            <button className="btn btn-lt-ghost pbtn" onClick={onTrial}>Try Now — FREE <span className="arrow">→</span></button>
            <ul className="plist">{free.map((x) => <li key={x}><Check />{x}</li>)}</ul>
          </div>
        </div>
        <TrustBadges center />
      </div>
    </section>
  );
}

// ---------- MODALS ----------
function Modal({ onClose, children }) {
  React.useEffect(() => {
    const k = (e) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', k);
    return () => window.removeEventListener('keydown', k);
  }, []);
  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="x" onClick={onClose}>✕</button>
        {children}
      </div>
    </div>
  );
}

function OkState({ title, sub }) {
  return (
    <div style={{ textAlign: 'center', padding: '8px 0' }}>
      <div className="ok-ico"><svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#8e24aa" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5" /></svg></div>
      <h3>{title}</h3>
      <p className="msub" style={{ marginBottom: 0 }}>{sub}</p>
    </div>
  );
}

function ContactModal({ onClose }) {
  const [sent, setSent]   = React.useState(false);
  const [busy, setBusy]   = React.useState(false);
  const [error, setError] = React.useState('');
  const [name, setName]   = React.useState('');
  const [email, setEmail] = React.useState('');
  const [message, setMessage] = React.useState('');

  function submit(e) {
    e.preventDefault();
    setError('');
    setBusy(true);
    fetch('/api/contact', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name, email, message })
    })
      .then((r) => r.json().then((data) => ({ ok: r.ok, data })))
      .then(({ ok, data }) => {
        setBusy(false);
        if (ok && data && data.success) {
          setSent(true);
        } else {
          setError((data && data.error) || 'Something went wrong. Please try again.');
        }
      })
      .catch(() => {
        setBusy(false);
        setError("Couldn't reach the server. Check your connection and try again.");
      });
  }

  return (
    <Modal onClose={onClose}>
      {sent ? <OkState title="Message sent!" sub="Thanks for reaching out — we'll be in touch shortly." /> : (<>
        <Eyebrow>Get in touch</Eyebrow>
        <h3 style={{ marginTop: 16 }}>Contact us</h3>
        <p className="msub">Questions about licences or your calendar? Drop us a line.</p>
        <form onSubmit={submit}>
          <div className="field"><label>Your name</label><input required placeholder="Jane Doe" value={name} onChange={(e) => setName(e.target.value)} /></div>
          <div className="field"><label>Your email</label><input required type="email" placeholder="jane@gmail.com" value={email} onChange={(e) => setEmail(e.target.value)} /></div>
          <div className="field"><label>Message</label><textarea required rows="3" placeholder="How can we help?" value={message} onChange={(e) => setMessage(e.target.value)}></textarea></div>
          {error ? <div className="modal-note" style={{ color: '#e6536b' }}>{error}</div> : null}
          <button className="btn btn-primary" style={{ width: '100%' }} type="submit" disabled={busy}>{busy ? 'Sending…' : (<>Send message <span className="arrow">→</span></>)}</button>
        </form>
      </>)}
    </Modal>
  );
}

function TrialModal({ onClose }) {
  const [sent, setSent]   = React.useState(false);
  const [busy, setBusy]   = React.useState(false);
  const [error, setError] = React.useState('');
  const [name, setName]   = React.useState('');
  const [email, setEmail] = React.useState('');

  function submit(e) {
    e.preventDefault();
    setError('');
    setBusy(true);
    fetch('/api/free-signup', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name, email })
    })
      .then((r) => r.json().then((data) => ({ ok: r.ok, data })))
      .then(({ ok, data }) => {
        setBusy(false);
        if (ok && data && data.success) {
          setSent(true);
        } else {
          setError((data && data.error) || 'Something went wrong. Please try again.');
        }
      })
      .catch(() => {
        setBusy(false);
        setError("Couldn't reach the server. Check your connection and try again.");
      });
  }

  return (
    <Modal onClose={onClose}>
      {sent ? <OkState title="Check your inbox!" sub="Your free licence key is on its way. Use it in the Wipe Away app." /> : (<>
        <Eyebrow>Free trial</Eyebrow>
        <h3 style={{ marginTop: 16 }}>Try Wipe Away free</h3>
        <p className="msub">Enter your details and we'll email you a free licence key instantly.</p>
        <form onSubmit={submit}>
          <div className="field"><label>Your name</label><input required placeholder="Jane Doe" value={name} onChange={(e) => setName(e.target.value)} /></div>
          <div className="field"><label>Your email</label><input required type="email" placeholder="jane@gmail.com" value={email} onChange={(e) => setEmail(e.target.value)} /></div>
          {error ? <div className="modal-note" style={{ color: '#e6536b' }}>{error}</div> : null}
          <button className="btn btn-primary" style={{ width: '100%' }} type="submit" disabled={busy}>
            {busy ? 'Sending…' : (<>Get my free key <span className="arrow">→</span></>)}
          </button>
          <div className="modal-note">Free trial: 1 calendar · 30-day limit · no card required</div>
        </form>
      </>)}
    </Modal>
  );
}

function BuyModal({ onClose }) {
  const LIFETIME_LINK = 'https://buy.stripe.com/dRm6oH2bwgWB32rdYHgbm01';
  const YEAR_LINK      = 'https://buy.stripe.com/eVq7sLeYi5dT6eD4o7gbm02';
  return (
    <Modal onClose={onClose}>
      <Eyebrow>Checkout</Eyebrow>
      <h3 style={{ marginTop: 16 }}>Choose your licence</h3>
      <p className="msub">One-time payment. No subscriptions, no renewals.</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        <a className="btn btn-ghost" href={LIFETIME_LINK} target="_blank" rel="noopener noreferrer" style={{ justifyContent: 'space-between' }}><span>Lifetime licence</span><span className="grad-text" style={{ fontWeight: 800 }}>$19.99</span></a>
        <a className="btn btn-primary" href={YEAR_LINK} target="_blank" rel="noopener noreferrer" style={{ justifyContent: 'space-between' }}><span>1-Year licence</span><span style={{ fontWeight: 800 }}>$9.99</span></a>
      </div>
      <PayRow dark />
      <div className="modal-note">Secure checkout via Stripe · instant licence key by email</div>
    </Modal>
  );
}

function KeyModal({ onClose }) {
  const [launched, setLaunched]     = React.useState(false);
  const [key, setKey]               = React.useState('');
  const [error, setError]           = React.useState('');
  const [showResend, setShowResend] = React.useState(false);
  const [resendEmail, setResendEmail] = React.useState('');
  const [resendBusy, setResendBusy] = React.useState(false);
  const [resendDone, setResendDone] = React.useState(false);
  const [resendError, setResendError] = React.useState('');

  function submit(e) {
    e.preventDefault();
    setError('');
    const trimmed = key.trim().toUpperCase();
    if (!/^(WIPE|FREE)-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(trimmed)) {
      setError('Keys look like WIPE-XXXX-XXXX-XXXX. Please check and try again.');
      return;
    }
    try { sessionStorage.setItem('wa_pending_key', trimmed); } catch (e) {}
    setLaunched(true);
    setTimeout(() => { window.location.href = '/app.html'; }, 900);
  }

  function submitResend(e) {
    e.preventDefault();
    setResendError('');
    setResendBusy(true);
    fetch('/api/resend-key', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: resendEmail.trim() })
    })
      .then((r) => r.json().then((data) => ({ ok: r.ok, data })))
      .then(({ ok, data }) => {
        setResendBusy(false);
        if (ok && data && data.success) {
          setResendDone(true);
        } else {
          setResendError((data && data.error) || 'Something went wrong. Please try again.');
        }
      })
      .catch(() => {
        setResendBusy(false);
        setResendError("Couldn't reach the server. Check your connection and try again.");
      });
  }

  return (
    <Modal onClose={onClose}>
      {launched ? <OkState title="Opening WipeAway…" sub="Taking you to the app now." /> :
       showResend ? (<>
        <Eyebrow>Lost your key</Eyebrow>
        <h3 style={{ marginTop: 16 }}>Resend my licence key</h3>
        {resendDone
          ? <OkState title="Check your inbox!" sub="If we have a paid licence registered to that address, we've sent your key now." />
          : (<>
            <p className="msub">Enter the email address you used to purchase WipeAway and we'll send your key straight to your inbox.</p>
            <form onSubmit={submitResend}>
              <div className="field"><label>Your email</label><input required type="email" placeholder="jane@gmail.com" value={resendEmail} onChange={(e) => setResendEmail(e.target.value)} /></div>
              {resendError ? <div className="modal-note" style={{ color: '#e6536b' }}>{resendError}</div> : null}
              <button className="btn btn-primary" style={{ width: '100%' }} type="submit" disabled={resendBusy}>{resendBusy ? 'Sending…' : <>Send my key <span className="arrow">→</span></>}</button>
              <div className="modal-note"><a href="#" onClick={(e) => { e.preventDefault(); setShowResend(false); }} style={{ color: 'var(--pink)', fontWeight: 600 }}>← Back</a></div>
            </form>
          </>)
        }
      </>) : (<>
        <Eyebrow>Already a customer</Eyebrow>
        <h3 style={{ marginTop: 16 }}>Enter your licence key</h3>
        <p className="msub">Paste the key from your email — free or paid — to open WipeAway and start cleaning.</p>
        <form onSubmit={submit}>
          <div className="field"><label>Licence key</label><input required placeholder="WIPE-XXXX-XXXX-XXXX" style={{ fontFamily: 'JetBrains Mono', letterSpacing: '.04em' }} value={key} onChange={(e) => setKey(e.target.value)} /></div>
          {error ? <div className="modal-note" style={{ color: '#e6536b' }}>{error}</div> : null}
          <button className="btn btn-primary" style={{ width: '100%' }} type="submit">Open WipeAway <span className="arrow">→</span></button>
          <div className="modal-note">Lost your key? <a href="#" onClick={(e) => { e.preventDefault(); setShowResend(true); }} style={{ color: 'var(--pink)', fontWeight: 600 }}>Resend it</a></div>
        </form>
      </>)}
    </Modal>
  );
}

Object.assign(window, { Pricing, ContactModal, TrialModal, BuyModal, KeyModal });
