/* global React, Icon, CtaBand */

const PRICING_SIGNUP = 'https://my.everlasting-memory.com/signup';

const PRICING_PLANS = {
  trial: {
    name: 'Free trial', price: '£0', per: 'for 7 days',
    line: 'Explore everything before you decide.',
    feats: [
      'Try every feature, from the recorder to your family tree',
      'See exactly how your messages will look and feel',
      'No messages are saved or sent during the trial',
      'No card needed',
    ],
    cta: 'Start free',
  },
  monthly: {
    name: 'Monthly', price: '£7', per: 'a month',
    line: 'Everything you need, month by month.',
    feats: [
      'Every feature, with no limits on recording',
      'Schedule messages up to 12 months ahead',
      'Your family tree, photos and stories, all in one place',
      'Cancel any time',
    ],
    cta: 'Choose monthly', href: PRICING_SIGNUP + '?plan=monthly',
  },
  yearly: {
    name: 'Yearly', price: '£60', per: 'a year', badge: 'Save £24',
    line: 'The same plan, for less.',
    feats: ['Everything in Monthly', 'One simple payment each year'],
    cta: 'Choose yearly', href: PRICING_SIGNUP + '?plan=yearly',
  },
  legacy: {
    name: 'Legacy add-on', price: '£150', per: 'one time',
    line: 'For the messages meant for years from now.',
    feats: [
      'Schedule messages for any date, however far ahead',
      'Your messages reach your loved ones after you pass, once your two Guardians confirm',
      'Your legacy video stays on your family tree forever',
      'Still delivered, however far ahead, if your subscription ever ends',
      "Added to a monthly or yearly plan, whenever you're ready",
    ],
    cta: 'Add Legacy', href: PRICING_SIGNUP + '?plan=legacy',
  },
};
const PRICING_ORDER = ['trial', 'monthly', 'yearly', 'legacy'];

// Comparison rows: strings render as text, true/false as a tick or a dash.
const PRICING_COMPARE = [
  ['Price', ['£0 for 7 days', '£7 a month', '£60 a year', '£150 one time']],
  ['How you pay', ['No card needed', 'Monthly', 'Once a year', 'Once, never again']],
  ['Every feature, from the recorder to your family tree', [true, true, true, true]],
  ['Recording', ['Try it out', 'No limits', 'No limits', 'No limits']],
  ['Messages saved and delivered', ['Not during the trial', true, true, true]],
  ['Family tree, photos and stories in one place', ['Try it out', true, true, true]],
  ['How far ahead you can schedule', [false, 'Up to 12 months', 'Up to 12 months', 'Any date']],
  ['Messages delivered after you pass, once your two Guardians confirm', [false, false, false, true]],
  ['Your legacy video stays on your family tree forever', [false, false, false, true]],
  ['Scheduled messages still sent if your subscription ends', [false, 'Within 12 months', 'Within 12 months', 'Any date']],
  ['Cancel any time', ['Nothing to cancel', true, true, 'One-off payment']],
];

const PRICING_FAQ = [
  ['What happens when my free trial ends?', "Subscribe before your trial ends and everything you've set up, like your family tree and profile, stays just as it is. If you don't subscribe, your trial account is deleted when the 7 days are up."],
  ['Why can I only schedule 12 months ahead?', "Monthly and yearly plans are made for the year ahead, like birthdays, anniversaries and the days you'll be away. Legacy removes the limit, so your messages can arrive years from now, or after you've gone."],
  ['Can I add Legacy later?', "Yes. Add it to your monthly or yearly plan whenever you're ready. It's a single payment of £150, and you never pay it again."],
  ['What happens if my subscription ends?', "Messages you've already scheduled are still sent, exactly as you planned. They're never cancelled or paused. On a monthly or yearly plan, that's everything in the next 12 months; with Legacy, it's every date, however far ahead. You just won't be able to add, edit or remove messages until you subscribe again."],
  ['Do the people I send messages to have to pay?', 'Never. Receiving and watching your messages is always free.'],
  ['Can I cancel?', 'Yes, any time from your account.'],
  ['Is my payment secure?', 'Payments are handled by Stripe, a leading payment provider. We never see or store your card details.'],
];

function PricingPage({ navigate }) {
  return (
    <div>
      <section className="page-hero" data-em-surface="ink">
        <div className="page-hero__vignette" />
        <div className="page-hero__inner">
          <h1 className="page-hero__title">Simple plans. A promise that lasts.</h1>
          <p className="page-hero__lede">
            Try everything free for 7 days. Choose monthly or yearly when you're ready, and add
            Legacy whenever you want your messages to reach further. The people who receive your
            messages never pay a penny.
          </p>
        </div>
      </section>

      {/* PLANS */}
      <section className="section section--paper pricing-plans" aria-labelledby="pricing-plans-title">
        <h2 className="pricing-sr" id="pricing-plans-title">Plans</h2>
        <div className="pricing-plans__inner">
          <div className="pricing-plans__grid">
            <PricingCard id="trial" delay={0} />
            <PricingCard id="monthly" delay={80} />
            <PricingCard id="yearly" tone="ink" delay={160} />
            <div className="pricing-plans__join" aria-hidden="true" data-reveal style={{ '--delay': '240ms' }}>
              <span className="pricing-plans__plus"><Icon name="plus" size={18} /></span>
            </div>
            <PricingCard id="legacy" tone="cream" delay={240} />
          </div>
        </div>
      </section>

      {/* COMPARE TABLE */}
      <section className="section pricing-compare-section" aria-labelledby="pricing-compare-title">
        <div className="container">
          <div className="section__head" data-reveal>
            <h2 className="em-h1 pricing-h2" id="pricing-compare-title">Every plan, side by side.</h2>
          </div>
          <PricingCompare />
          <p className="pricing-compare__foot">The people who receive your messages never pay a penny, on any plan.</p>
        </div>
      </section>

      {/* PRICING FAQ */}
      <section className="section section--paper" aria-labelledby="pricing-faq-title">
        <div className="container" style={{ maxWidth: 760 }}>
          <div className="section__head" data-reveal>
            <h2 className="em-h1 pricing-h2" id="pricing-faq-title">Money, fairness, and what happens later.</h2>
          </div>
          <div className="faq">
            {PRICING_FAQ.map(([q, a]) => <FaqItem key={q} q={q} a={a} />)}
          </div>
        </div>
      </section>

      <CtaBand
        title="Start with 7 days free."
        body="Try every feature before you decide. No card needed."
        cta="Start your free trial"
      />
    </div>
  );
}

function PricingCard({ id, tone, delay }) {
  const plan = PRICING_PLANS[id];
  const ink = tone === 'ink';
  return (
    <article
      className={'pricing-card' + (tone ? ' pricing-card--' + tone : '')}
      data-em-surface={ink ? 'ink' : undefined}
      aria-labelledby={'pricing-' + id}
      data-reveal
      style={{ '--delay': delay + 'ms' }}
    >
      {plan.badge && <span className="pricing-card__badge">{plan.badge}</span>}
      <h3 className="pricing-card__name" id={'pricing-' + id}>{plan.name}</h3>
      <div className="pricing-card__price-row">
        <span className="pricing-card__price">{plan.price}</span>
        <span className="pricing-card__per">{plan.per}</span>
      </div>
      <p className="pricing-card__line">{plan.line}</p>
      <ul className="pricing-card__feats">
        {plan.feats.map((f) => (
          <li key={f}><Icon name="check" size={16} /><span>{f}</span></li>
        ))}
      </ul>
      <a className={'btn pricing-card__cta ' + (ink ? 'btn--gold' : 'btn--outline-ink')} href={plan.href || PRICING_SIGNUP}>{plan.cta}</a>
    </article>
  );
}

// A real table. On phones it scrolls sideways with the feature column pinned; the wrapper's
// data-start / data-end drive the edge shadow and fade, so they only show when there's
// more to scroll to in that direction.
function PricingCompare() {
  const ref = React.useRef(null);
  const [edges, setEdges] = React.useState({ start: false, end: false });
  React.useEffect(() => {
    const el = ref.current;
    const update = () => {
      const max = el.scrollWidth - el.clientWidth;
      setEdges({ start: el.scrollLeft > 4, end: el.scrollLeft < max - 4 });
    };
    update();
    el.addEventListener('scroll', update, { passive: true });
    window.addEventListener('resize', update);
    return () => { el.removeEventListener('scroll', update); window.removeEventListener('resize', update); };
  }, []);
  const cell = (v) => {
    if (v === true) return <><span className="pricing-compare__yes" aria-hidden="true"><Icon name="check" size={18} /></span><span className="pricing-sr">Included</span></>;
    if (v === false) return <><span className="pricing-compare__no" aria-hidden="true" /><span className="pricing-sr">Not included</span></>;
    return v;
  };
  return (
    <div className="pricing-compare-wrap" data-start={edges.start} data-end={edges.end} data-reveal>
      <p className="pricing-compare__hint" aria-hidden="true">Swipe to compare all four plans <span>→</span></p>
      <div className="pricing-compare-frame">
        <div className="pricing-compare" ref={ref} role="region" aria-labelledby="pricing-compare-title" tabIndex={0}>
          <table>
            <thead>
              <tr>
                <td className="pricing-compare__corner" />
                {PRICING_ORDER.map((id) => (
                  <th scope="col" key={id} className={id === 'legacy' ? 'is-legacy' : undefined}>
                    <span className="pricing-compare__plan">{PRICING_PLANS[id].name}</span>
                    {id === 'legacy' && <span className="pricing-compare__with">with Monthly or Yearly</span>}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {PRICING_COMPARE.map(([label, cells]) => (
                <tr key={label}>
                  <th scope="row">{label}</th>
                  {cells.map((c, i) => (
                    <td key={i} className={i === 3 ? 'is-legacy' : undefined}>{cell(c)}</td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function FaqItem({ q, a, defaultOpen = false }) {
  const [open, setOpen] = React.useState(defaultOpen);
  const id = React.useId ? React.useId() : Math.random().toString(36).slice(2);
  return (
    <div className={"faq-item" + (open ? " is-open" : "")}>
      <button
        className="faq-item__q"
        onClick={() => setOpen(!open)}
        aria-expanded={open}
        aria-controls={`faq-a-${id}`}
      >
        <span>{q}</span>
        <span className="faq-item__plus" aria-hidden="true"><Icon name="plus" size={20} /></span>
      </button>
      <div id={`faq-a-${id}`} className="faq-item__a" role="region">
        <p>{a}</p>
      </div>
    </div>
  );
}

Object.assign(window, { PricingPage, FaqItem });
