// ToolkitBuyForm.jsx — Verigo Global: toolkit purchase inquiry (same pattern as Contact.jsx)
// Replaces the old per-framework custom-quote/PDF builders. No payment is taken here —
// this captures the inquiry into Supabase and triggers the same admin notification email
// as the main Contact form.
const { V: BV, MAXW: BMW, FONT: BFT } = window;

const TIER_OPTIONS = ['Starter', 'Professional', 'Enterprise', 'Not sure yet'];
const TIER_FROM_PARAM = { starter: 'Starter', professional: 'Professional', enterprise: 'Enterprise' };

// Display prices only — the amount actually charged is always resolved
// server-side from server/pricing.js, never trusted from the browser. Keep in
// sync by hand with server/pricing.js and pages/toolkit-*-data.jsx.
const TOOLKIT_PRICING = {
  iso27001: { starter: 1495, professional: 4950 },
  iso42001: { starter: 1595, professional: 5250 },
  cmmc:     { starter: 1495, professional: 4950 },
  cmmi:     { starter: 1495, professional: 4950 },
  hitrust:  { starter: 1495, professional: 4950 },
  nist:     { starter: 1495, professional: 4950 },
  soc2:     { starter: 1495, professional: 4950 },
};

const BuyNowCard = ({ tierKey, tierLabel, price, itemKey, tagline }) => {
  const [open, setOpen] = React.useState(false);
  const [buyer, setBuyer] = React.useState({ name: '', email: '', company: '' });
  const [done, setDone] = React.useState(false);
  const ready = buyer.name.trim().length > 1 && /\S+@\S+\.\S+/.test(buyer.email);

  const cardStyle = { border: `1.5px solid ${BV.g200}`, borderRadius: 12, padding: '16px 18px', background: '#fff' };
  const miniInput = { fontFamily: BFT, fontSize: 13.5, color: BV.black, background: '#fff', border: `1.5px solid ${BV.g200}`, borderRadius: 7, padding: '9px 12px', outline: 'none', width: '100%', boxSizing: 'border-box' };

  if (done) {
    return (
      <div style={{ ...cardStyle, display: 'flex', alignItems: 'center', gap: 12, background: BV.purpleSubtle, border: `1.5px solid ${BV.purple}` }}>
        <window.Icon name="check" size={20} color={BV.purple} />
        <div style={{ fontSize: 13, color: BV.black, lineHeight: 1.5 }}>Payment received for the <strong>{tierLabel}</strong> package — a confirmation and access details are on their way to your email.</div>
      </div>
    );
  }

  return (
    <div style={cardStyle}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
        <div>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: BV.black }}>{tierLabel}</div>
          <div style={{ fontSize: 12, color: BV.g500, marginTop: 2 }}>{tagline}</div>
        </div>
        <div style={{ fontSize: 20, fontWeight: 800, color: BV.black, flexShrink: 0 }}>${price.toLocaleString()}</div>
      </div>
      {!open ? (
        <window.Btn kind="ghost" onClick={() => setOpen(true)} style={{ width: '100%', justifyContent: 'center', marginTop: 14 }}>Buy Now</window.Btn>
      ) : (
        <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <input style={miniInput} placeholder="Full name" value={buyer.name} onChange={(e) => setBuyer((b) => ({ ...b, name: e.target.value }))} />
          <input style={miniInput} type="email" placeholder="Work email" value={buyer.email} onChange={(e) => setBuyer((b) => ({ ...b, email: e.target.value }))} />
          <input style={miniInput} placeholder="Company (optional)" value={buyer.company} onChange={(e) => setBuyer((b) => ({ ...b, company: e.target.value }))} />
          <window.PayPalCheckout
            itemType="toolkit" itemKey={itemKey} tier={tierKey}
            customer={buyer}
            disabled={!ready}
            disabledReason="Enter your name and work email to pay."
            onSuccess={() => setDone(true)}
          />
        </div>
      )}
    </div>
  );
};

const ToolkitBuyForm = ({ framework, standardId, onNav }) => {
  const initialTier = (() => {
    try {
      const tierParam = new URLSearchParams(window.location.search).get('tier');
      return TIER_FROM_PARAM[tierParam] || 'Not sure yet';
    } catch (e) { return 'Not sure yet'; }
  })();

  const [form, setForm] = React.useState({ name: '', email: '', company: '', phone: '', tier: initialTier, message: '' });
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [err, setErr] = React.useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setSubmitting(true);
    setErr(false);
    const { error } = await window.submitInquiry({
      form_type: 'toolkit-purchase',
      name: form.name, email: form.email, company: form.company, phone: form.phone,
      framework,
      service_interest: 'Implementation Toolkits',
      message: form.message,
      metadata: { tier: form.tier },
    });
    setSubmitting(false);
    if (error) { setErr(true); return; }
    setSent(true);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const input = { fontFamily: BFT, fontSize: 14, color: BV.black, background: '#fff', border: `1.5px solid ${BV.g200}`, borderRadius: 8, padding: '11px 14px', outline: 'none', width: '100%' };
  const label = { fontSize: 12.5, fontWeight: 600, color: BV.black, display: 'block', marginBottom: 7 };
  const selectStyle = { ...input, appearance: 'none', backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%239A9AAA' stroke-width='2.5'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E\")", backgroundRepeat: 'no-repeat', backgroundPosition: 'right 12px center', paddingRight: 32, cursor: 'pointer' };

  if (sent) return (
    <div style={{ minHeight: '62vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '80px 32px' }}>
      <div style={{ textAlign: 'center', maxWidth: 460 }}>
        <div style={{ width: 68, height: 68, borderRadius: '50%', background: BV.purpleSubtle, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 24px' }}>
          <window.Icon name="check" size={34} color={BV.purple} />
        </div>
        <h2 style={{ fontSize: 34, fontWeight: 800, letterSpacing: '-0.02em', margin: '0 0 14px', color: BV.black, fontFamily: BFT }}>We'll be in touch.</h2>
        <p style={{ color: BV.g500, lineHeight: 1.65, fontSize: 16, margin: '0 0 28px' }}>Thank you for your interest in the {framework} Toolkit. A senior Verigo practitioner will reach out within one business day with pricing and next steps.</p>
        <window.Btn kind="ghost" onClick={() => onNav('toolkit:' + standardId)}>Back to the {framework} Toolkit</window.Btn>
      </div>
    </div>
  );

  return (
    <div style={{ position: 'relative', overflow: 'hidden' }}>
      <window.HeroWatermark variant="stack" opacity={0.12} style={{ top: -20, right: -10, width: 460, height: 360 }} />
      <div style={{ maxWidth: BMW, margin: '0 auto', padding: '72px 32px', position: 'relative', zIndex: 1 }}>
        <div className="vg-detail-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 500px', gap: 80, alignItems: 'start' }}>
          <div>
            <window.Overline style={{ marginBottom: 14 }}>{framework} Toolkit</window.Overline>
            <h1 className="vg-hero-title" style={{ fontSize: 48, fontWeight: 800, letterSpacing: '-0.03em', margin: '0 0 20px', lineHeight: 1.06, color: BV.black, fontFamily: BFT }}>Get the {framework} Toolkit.</h1>
            <p style={{ fontSize: 18, color: BV.g500, lineHeight: 1.6, marginBottom: 40, maxWidth: 460 }}>Tell us a little about your organization and which package you're interested in — a senior practitioner will follow up with pricing, scope, and next steps.</p>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
              {[
                ['clipboard', '1. Tell us what you need', 'Package interest, company size, and timeline.'],
                ['search', '2. We scope it', 'A practitioner reviews your scope and confirms fixed pricing.'],
                ['shield', '3. Get to work', 'Editable policies, procedures, and control templates — plus support if you want it.'],
              ].map(([icon, t, d]) => (
                <div key={t} style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
                  <div style={{ width: 44, height: 44, borderRadius: 9, background: BV.purpleSubtle, color: BV.purple, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <window.Icon name={icon} size={22} />
                  </div>
                  <div>
                    <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 4, color: BV.black }}>{t}</div>
                    <div style={{ fontSize: 14, color: BV.g500, lineHeight: 1.55 }}>{d}</div>
                  </div>
                </div>
              ))}
            </div>

            {TOOLKIT_PRICING[standardId] && (
              <div style={{ marginTop: 40 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: BV.g500, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 14 }}>Ready now? Buy instantly.</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  <BuyNowCard tierKey="starter" tierLabel="Starter" tagline="Complete document toolkit, ready to deploy." price={TOOLKIT_PRICING[standardId].starter} itemKey={standardId} />
                  <BuyNowCard tierKey="professional" tierLabel="Professional" tagline="Toolkit tailored to you, with practitioner guidance." price={TOOLKIT_PRICING[standardId].professional} itemKey={standardId} />
                </div>
              </div>
            )}
          </div>

          <form onSubmit={handleSubmit} style={{ background: '#fff', border: `1px solid ${BV.g200}`, borderRadius: 16, padding: '36px', display: 'flex', flexDirection: 'column', gap: 18, boxShadow: '0 4px 24px rgba(0,0,0,0.05)' }}>
            <div className="vg-grid-2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <div><label style={label}>Full name</label><input style={input} required value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} placeholder="Jane Smith" /></div>
              <div><label style={label}>Work email</label><input style={input} type="email" required value={form.email} onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))} placeholder="jane@company.com" /></div>
            </div>
            <div className="vg-grid-2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <div><label style={label}>Company</label><input style={input} required value={form.company} onChange={(e) => setForm((f) => ({ ...f, company: e.target.value }))} placeholder="Acme Technologies" /></div>
              <div><label style={label}>Phone number</label><input style={input} type="tel" value={form.phone} onChange={(e) => setForm((f) => ({ ...f, phone: e.target.value }))} placeholder="+1 555 000 1234" /></div>
            </div>
            <div>
              <label style={label}>Package interested in</label>
              <select style={selectStyle} value={form.tier} onChange={(e) => setForm((f) => ({ ...f, tier: e.target.value }))}>
                {TIER_OPTIONS.map((o) => <option key={o}>{o}</option>)}
              </select>
            </div>
            <div><label style={label}>Anything else we should know?</label><textarea style={{ ...input, resize: 'none' }} rows={4} value={form.message} onChange={(e) => setForm((f) => ({ ...f, message: e.target.value }))} placeholder="Scope, timeline, or specific requirements…" /></div>
            {err && <p style={{ fontSize: 13, color: '#D93B3B', background: '#FDEAEA', border: '1px solid #F5C2C2', borderRadius: 8, padding: '10px 14px', margin: 0 }}>Something went wrong sending your inquiry. Please try again, or email us directly.</p>}
            <window.Btn kind="primary" style={{ width: '100%', justifyContent: 'center', opacity: submitting ? 0.7 : 1, cursor: submitting ? 'default' : 'pointer' }}>{submitting ? 'Sending…' : <>Request Pricing <window.Icon name="arrow" size={17} color="#fff" /></>}</window.Btn>
            <p style={{ fontSize: 12, color: BV.g400, textAlign: 'center', margin: 0 }}>We'll only use your details to follow up. No spam. No payment is taken here.</p>
          </form>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ToolkitBuyForm });
