// Pricing and Get Started pages
const { useState: useStateP, useMemo: useMemoP } = React;

// ============ PRICING PAGE ============
function PricingPage({ go }) {
  useReveal();
  const [members, setMembers] = useStateP(1000);
  const [annual, setAnnual] = useStateP(true);
  const memberOptions = [500, 1000, 2000, 3000, 4000, 5000];

  const tiers = useMemoP(() => [
    {
      name: 'Basic', color: 'var(--brand)', tint: 'var(--brand-tint)',
      description: 'The essential bridge between Slack, Circle, and email.',
      features: ['Slack activation & profile sync', 'Post, reply & digest emails', 'Channel & space management', 'Analytics & onboarding workflows'],
      prices: {
        500: [749, 8988, 599, 7188], 1000: [749, 8988, 599, 7188],
        2000: [849, 10188, 699, 8388], 3000: [999, 11988, 799, 9588],
        4000: [1099, 13188, 899, 10788], 5000: [1199, 14388, 999, 11988],
      },
    },
    {
      name: 'Standard', color: 'var(--accent-coral)', tint: 'var(--accent-coral-bg)', popular: true,
      description: 'Advanced operations and AI tools for growing communities.',
      features: ['Everything in Basic', 'Ask AI search', 'Applications & directories', 'Mass messaging & priority support'],
      prices: {
        500: [999, 11988, 799, 9588], 1000: [1199, 14388, 949, 11388],
        2000: [1399, 16788, 1149, 13788], 3000: [1699, 20388, 1349, 16188],
        4000: [1849, 22188, 1499, 17988], 5000: [1999, 23988, 1649, 19788],
      },
    },
    {
      name: 'Pro', color: 'var(--accent-mint)', tint: 'var(--accent-mint-bg)',
      description: 'Enterprise control, delivery, and hands-on support.',
      features: ['Everything in Standard', 'Custom domain & dedicated IP', 'Custom SSO', 'White-glove onboarding & migration'],
      prices: {
        500: [1599, 19188, 1299, 15588], 1000: [1899, 22788, 1549, 18588],
        2000: [2199, 26388, 1799, 21588], 3000: [2599, 31188, 2149, 25788],
        4000: [2999, 35988, 2499, 29988], 5000: [3499, 41988, 2849, 34188],
      },
    },
  ], []);

  const formatMembers = (value) => value >= 1000 ? `${value / 1000}k` : value;
  const formatMoney = (value) => `$${value.toLocaleString()}`;

  return (
    <main>
      <section className="section-tight pricing-hero" style={{ paddingTop: 64 }}>
        <div className="page center">
          <h1 className="display-1" style={{ margin: '0 auto' }}>
            Priced for <em>real communities</em>.
          </h1>
          <p style={{ fontSize: 18, color: 'var(--site-ink-soft)', marginTop: 24, maxWidth: 620, margin: '24px auto 0' }}>
            Straightforward plans that scale with your community.
          </p>
        </div>
      </section>

      <section className="pricing-selector-section">
        <div className="page">
          <div className="pricing-control">
            <div className="pricing-control-group">
              <div className="pricing-control-label">Members <span>(up to)</span></div>
              <div className="member-size-options" role="radiogroup" aria-label="Community size">
                {memberOptions.map(option => (
                  <button key={option} type="button" role="radio" aria-checked={members === option}
                    className={members === option ? 'active' : ''}
                    onClick={() => setMembers(option)}>
                    {formatMembers(option)}
                  </button>
                ))}
              </div>
            </div>
            <div className="pricing-control-group billing-control-group">
              <div className="pricing-control-label">Billing frequency</div>
              <div className="billing-toggle">
                <button onClick={() => setAnnual(true)} className={annual ? 'active' : ''}>Annual</button>
                <button onClick={() => setAnnual(false)} className={!annual ? 'active' : ''}>Monthly</button>
              </div>
            </div>
            <div className="custom-pricing-note">
              More than 5,000 members? <a href="#/get-started" onClick={e=>{e.preventDefault();go('get-started');}}>Contact us for custom pricing <span aria-hidden="true">→</span></a>
            </div>
          </div>
        </div>
      </section>

      <section style={{ paddingBottom: 80 }}>
        <div className="page">
          <div className="pricing-grid">
            {tiers.map(t => {
              const [monthlyCost, monthlyYear, annualMonthly, annualYear] = t.prices[members];
              const displayMonthly = annual ? annualMonthly : monthlyCost;
              const displayYear = annual ? annualYear : monthlyYear;
              const savings = monthlyYear - annualYear;
              return (
                <article key={t.name} className={`pricing-card${t.popular ? ' pricing-card-popular' : ''}`}
                  style={{ '--plan-color': t.color, '--plan-tint': t.tint }}>
                  <div className="pricing-card-accent"/>
                  {t.popular && <div className="pricing-popular">Most popular</div>}
                  <div className="pricing-card-kicker">Synchronize</div>
                  <h3>{t.name}</h3>
                  <p className="pricing-card-description">{t.description}</p>

                  <div className="pricing-card-price">
                    <span className="pricing-currency">$</span>
                    <strong>{displayMonthly.toLocaleString()}</strong>
                    <span className="pricing-period">/ month</span>
                  </div>
                  <div className="pricing-billing-detail">
                    {annual ? `Billed ${formatMoney(displayYear)} annually` : `${formatMoney(displayYear)} total over 12 months`}
                    <span>For up to {members.toLocaleString()} members</span>
                  </div>
                  <div className="pricing-savings" style={{ background: t.tint }}>
                    <span className="pricing-savings-icon" aria-hidden="true">↘</span>
                    <span>{annual ? 'You save' : 'Save with annual billing'} <strong>{formatMoney(savings)}/yr</strong></span>
                  </div>

                  <a href="#/get-started" onClick={e=>{e.preventDefault();go('get-started');}}
                    className={`btn pricing-card-cta${t.popular ? ' pricing-card-cta-primary' : ''}`}>
                    Get started <span aria-hidden="true">→</span>
                  </a>
                  <div className="pricing-includes">Plan highlights</div>
                  <ul className="pricing-feature-list">
                    {t.features.map(f => (
                      <li key={f}>
                        <span className="pricing-feature-check" aria-hidden="true">✓</span>
                        <span>{f}</span>
                      </li>
                    ))}
                  </ul>
                </article>
              );
            })}
          </div>
          <p style={{ textAlign: 'center', marginTop: 32, fontSize: 13, color: 'var(--site-ink-soft)' }}>
            All plans require users to independently purchase a Business license to Circle.
          </p>
        </div>
      </section>

      {/* Feature comparison table */}
      <section className="section" style={{ background: 'var(--site-bg-alt)' }}>
        <div className="page">
          <div className="eyebrow center" style={{ marginBottom: 16 }}>Compare plans</div>
          <h2 className="display-2 center" style={{ marginBottom: 48 }}>Every feature, <em>every plan.</em></h2>
          <FeatureMatrix/>
        </div>
      </section>

    </main>
  );
}

function PricingGroupIcon({ kind }) {
  if (kind !== 'enterprise') return <PlatformIcon kind={kind} size={24}/>;
  return (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <rect width="24" height="24" rx="6" fill="#F2F2FF" stroke="#C5C5E7"/>
      <path d="M12 4.5 18.2 7v4.8c0 3.8-2.5 6.3-6.2 7.7-3.7-1.4-6.2-3.9-6.2-7.7V7L12 4.5Z" fill="#fff" stroke="#4242F0" strokeWidth="1.4" strokeLinejoin="round"/>
      <path d="m9.1 12.1 1.8 1.8 4-4" stroke="#15996C" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function FeatureMatrix() {
  const groups = [
    { group: 'Slack', iconKind: 'slack', items: [
      ['Membership Activation', 'onboarding', 1,1,1],
      ['Profile Sync', 'members', 1,1,1],
      ['Post & Comment Sync', 'sync', 1,1,1],
      ['Channel + Space Management', 'spaces', 1,1,1],
      ['Customizable Welcome Messages', 'messaging', 1,1,1],
      ['Event Channel Syncing', 'events', 0,1,1],
      ['Searchable Member Directory in Slack', 'directory', 0,1,1],
      ['Community Search in Slack', 'ask', 0,1,1],
    ]},
    { group: 'Email', iconKind: 'email', items: [
      ['Post by Email', 'email-post', 1,1,1],
      ['Reply by Email', 'email-reply', 1,1,1],
      ['Weekly Digests', 'digest-weekly', 1,1,1],
      ['Biweekly Digests', 'digest-biweekly', 1,1,1],
      ['Daily Digests', 'digest-daily', 1,1,1],
      ['All Emails', 'email-all', 0,1,1],
      ['Realtime Emails', 'email-realtime', 0,1,1],
      ['Custom Email Domain', 'email-domain', 0,0,1],
      ['Dynamic Email Header Content', 'email-header', 0,0,1],
    ]},
    { group: 'Community Operations', iconKind: 'circle', items: [
      ['Analytics', 'analytics', 1,1,1],
      ['Onboarding Workflows', 'onboarding', 1,1,1],
      ['Ask AI Search', 'ask', 0,1,1],
      ['Application Forms', 'applications', 0,1,1],
      ['Member Directories', 'directory', 0,1,1],
      ['Mass Slack DM', 'broadcast', 0,1,1],
      ['Mass Email', 'email-broadcast', 0,1,1],
    ]},
    { group: 'Enterprise', iconKind: 'enterprise', items: [
      ['Dedicated Email IP', 'dedicated-ip', 0,0,1],
      ['Custom SSO', 'sso', 0,0,1],
      ['Standard Email Support', 'support', 1,0,0],
      ['Priority Email Support', 'priority-support', 0,1,1],
      ['White Glove Onboarding', 'white-glove', 0,0,1],
      ['Community Migration Support', 'migration', 0,0,1],
    ]},
  ];
  const tiers = [
    { name: 'Basic', className: 'basic' },
    { name: 'Standard', className: 'standard' },
    { name: 'Pro', className: 'pro' },
  ];
  return (
    <div className="feature-matrix-scroll">
      <div className="feature-matrix">
        <div className="feature-matrix-header">
          <div className="feature-matrix-feature-label">Feature</div>
          {tiers.map(t => (
            <div key={t.name} className={`feature-matrix-plan feature-matrix-plan-${t.className}`}>
              <span>Synchronize</span>
              <strong>{t.name}</strong>
            </div>
          ))}
        </div>
        {groups.map(g => (
          <div key={g.group} className="feature-matrix-group">
            <div className="feature-matrix-group-label"><span className="feature-matrix-platform" aria-hidden="true"><PricingGroupIcon kind={g.iconKind}/></span>{g.group}</div>
            {g.items.map(([label, iconKind, ...checks]) => (
              <div key={label} className="feature-matrix-row">
                <div className="feature-name">
                  <FeatureIcon kind={iconKind} compact/>
                  <span className="feature-name-copy">
                    <span>{label}</span>
                    {label === 'Ask AI Search' && <small>Token Limits Apply</small>}
                  </span>
                </div>
                {checks.map((c, i) => (
                  <div key={i} className="feature-availability">
                    {c
                      ? <span className="feature-check" aria-label={`Included in ${tiers[i].name}`}>✓</span>
                      : <span className="feature-dash" aria-label={`Not included in ${tiers[i].name}`}>−</span>}
                  </div>
                ))}
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}

// ============ GET STARTED PAGE ============
function GetStartedPage() {
  useReveal();
  const [form, setForm] = useStateP({ name: '', email: '', size: '', tools: [], otherTools: '', message: '', website: '' });
  const [status, setStatus] = useStateP('idle');
  const [error, setError] = useStateP('');

  const toggle = (t) => setForm(f => {
    const isSelected = f.tools.includes(t);
    return {
      ...f,
      tools: isSelected ? f.tools.filter(x => x !== t) : [...f.tools, t],
      otherTools: t === 'Other' && isSelected ? '' : f.otherTools,
    };
  });

  const submitDemoRequest = async (event) => {
    event.preventDefault();
    setStatus('sending');
    setError('');

    try {
      const response = await fetch('/api/book-demo', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });

      if (!response.ok) throw new Error('The request could not be sent.');
      setStatus('success');
    } catch (submissionError) {
      console.error(submissionError);
      setError('We couldn’t send your request just now. Please try again, or email cory@synchronize.so.');
      setStatus('error');
    }
  };

  const tools = [
    'Slack', 'Circle', 'Email', 'Discord', 'Mighty Networks',
    'Forj', 'Hivebrite', 'Bettermode', "We don’t have a community yet", 'Other',
  ];

  return (
    <main className="get-started-page">
      <section className="get-started-hero">
        <div className="page get-started-grid">
          <div className="get-started-copy reveal">
            <h1 className="display-1">
              Let’s meet your members <em>where they already are.</em>
            </h1>
            <p>
              We’re excited to set up a demo tailored to your community’s size and needs.
            </p>
          </div>

          <form className="demo-form reveal" onSubmit={submitDemoRequest}>
            {status === 'success' ? (
              <div className="demo-form-success" role="status">
                <span aria-hidden="true">✓</span>
                <h2>Thanks, {form.name.split(' ')[0] || 'there'}.</h2>
                <p>Your request is on its way. We’ll be in touch to find a time and learn more about your community.</p>
              </div>
            ) : (
              <>
                <div className="demo-form-heading">
                  <span>Book a demo</span>
                  <h2>Tell us about your community.</h2>
                </div>
                <Field label="Your name" htmlFor="demo-name">
                  <input id="demo-name" name="name" autoComplete="name" required value={form.name} onChange={e => setForm({...form, name: e.target.value})} placeholder="Alex Morgan" style={inputStyle}/>
                </Field>
                <Field label="Work email" htmlFor="demo-email">
                  <input id="demo-email" name="email" autoComplete="email" required type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} placeholder="alex@community.org" style={inputStyle}/>
                </Field>
                <Field label="Community size" htmlFor="demo-size">
                  <select id="demo-size" name="size" required value={form.size} onChange={e => setForm({...form, size: e.target.value})} style={inputStyle}>
                    <option value="">Pick a range…</option>
                    <option>Up to 500 members</option>
                    <option>500 – 1,000 members</option>
                    <option>1,000 – 2,000 members</option>
                    <option>2,000 – 3,000 members</option>
                    <option>3,000 – 4,000 members</option>
                    <option>4,000 – 5,000 members</option>
                    <option>5,000 – 7,500 members</option>
                    <option>7,500 – 10,000 members</option>
                    <option>10,000+ members</option>
                  </select>
                </Field>
                <Field label="Which tools does your community use today?">
                  <div className="demo-tool-options">
                    {tools.map(t => (
                      <button type="button" key={t} aria-pressed={form.tools.includes(t)} onClick={() => toggle(t)}>
                        {t}
                      </button>
                    ))}
                  </div>
                  {form.tools.includes('Other') && (
                    <div className="demo-other-tools">
                      <label htmlFor="demo-other-tools">What other tools do you use?</label>
                      <input id="demo-other-tools" name="otherTools" required value={form.otherTools}
                        onChange={e => setForm({...form, otherTools: e.target.value})}
                        placeholder="Tell us which tools…" style={inputStyle}/>
                    </div>
                  )}
                </Field>
                <Field label="What would you like to solve?" htmlFor="demo-message">
                  <textarea id="demo-message" name="message" value={form.message} onChange={e => setForm({...form, message: e.target.value})} rows={4}
                    placeholder="Tell us about your community and what you’d like to make easier for your members…"
                    style={{...inputStyle, resize: 'vertical', minHeight: 96, fontFamily: 'inherit' }}/>
                </Field>
                <div className="demo-honeypot" aria-hidden="true">
                  <label htmlFor="demo-website">Website</label>
                  <input id="demo-website" name="website" tabIndex="-1" autoComplete="off" value={form.website} onChange={e => setForm({...form, website: e.target.value})}/>
                </div>
                {error && <p className="demo-form-error" role="alert">{error}</p>}
                <button type="submit" className="btn btn-primary btn-lg demo-form-submit" disabled={status === 'sending'}>
                  {status === 'sending' ? 'Sending…' : 'Book my demo →'}
                </button>
                <p className="demo-form-privacy">
                  By submitting, you agree to our <a href="#/privacy-policy">privacy policy</a>.
                </p>
              </>
            )}
          </form>
        </div>
      </section>
    </main>
  );
}

function Field({ label, htmlFor, children }) {
  return (
    <div className="demo-field">
      <label htmlFor={htmlFor}>{label}</label>
      {children}
    </div>
  );
}

const inputStyle = {
  width: '100%', padding: '10px 14px', fontSize: 14,
  background: '#fff', border: '1px solid var(--site-line)', borderRadius: 2,
  fontFamily: 'inherit', color: 'var(--site-ink)', outline: 'none',
};

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