/* global React, STEPS, ProgressRail, StepAbout, StepScores, StepPrefs, StepGoals, StepPay,
   IconChevronLeft, IconChevronRight, IconCheck, IconSparkles, IconShieldCheck, IconHeart,
   IconLock, IconClock, IconUser, IconArrowRight, IconStar */

const STORAGE_KEY = 'ce_form_state';

const Summary = ({ form, stepIdx }) => {
  const row = (k, v) => (v && (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, padding: '8px 0' }}>
      <span style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-muted)' }}>{k}</span>
      <span className="mono" style={{ fontSize: 12, color: 'var(--color-ink)', textAlign: 'right', maxWidth: 220, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{v}</span>
    </div>
  ));

  return (
    <aside style={{ position: 'sticky', top: 180 }}>
      <div style={{
        background: 'var(--color-surface-soft)',
        borderRadius: 24,
        padding: 24,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
          <span className="badge">Live preview</span>
        </div>
        <div className="title-md" style={{ fontSize: 16, marginBottom: 14 }}>Your counselling brief</div>

        <div style={{ paddingTop: 6 }}>
          {row('Name', form.name)}
          {row('Phone', form.phone)}
          {row('Email', form.email)}
          {row('JEE Main', form.jeeMainPct ? `${form.jeeMainPct} %ile` : null)}
          {row('Main rank', form.jeeMainRank)}
          {row('Advanced', form.jeeAdvRank)}
          {row('BITSAT', form.bitsat)}
          {row('Category', form.category)}
          {row('State', form.state)}
          {row('Colleges', form.colleges?.length ? form.colleges.join(', ') : null)}
          {row('Budget', form.budget)}
        </div>

        <div style={{
          marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--color-hairline)',
        }}>
          <div className="caption" style={{ marginBottom: 6 }}>What you get</div>
          {[
            '30-min counsellor call',
            'Personalised shortlist for your profile',
            'Round-by-round JoSAA support',
            'WhatsApp follow-up through counselling',
          ].map((b) => (
            <div key={b} style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0',
              fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-ink)',
            }}>
              <span style={{
                width: 14, height: 14, borderRadius: 100,
                background: 'var(--color-primary-soft)', color: 'var(--color-primary)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              }}><IconCheck size={9} /></span>
              {b}
            </div>
          ))}
        </div>

        {(() => {
          const plan = SITE.plans.find(p => p.id === form.plan);
          return (
            <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--color-hairline)' }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
                <span className="caption">Plan</span>
                <span className="mono" style={{ fontSize: 13, color: 'var(--color-ink)' }}>
                  {plan ? plan.name : <span style={{ color: 'var(--color-muted)' }}>not selected</span>}
                </span>
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginTop: 6 }}>
                <span className="caption">Total</span>
                <span className="mono" style={{ fontSize: 20, fontWeight: 500, color: plan ? 'var(--color-ink)' : 'var(--color-muted)' }}>
                  {plan ? `₹${plan.price.toLocaleString('en-IN')}` : '—'}
                </span>
              </div>
            </div>
          );
        })()}
      </div>
    </aside>
  );
};

// ============================================================
// Wizard
// ============================================================
const Wizard = () => {
  const [idx, setIdx] = React.useState(0);
  const [form, setForm] = React.useState(() => {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      return raw ? JSON.parse(raw) : {};
    } catch { return {}; }
  });
  const [done, setDone]           = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);
  const [bookingRef] = React.useState(() => `CE-26-${Math.floor(100000 + Math.random() * 900000)}`);

  React.useEffect(() => {
    try { localStorage.setItem(STORAGE_KEY, JSON.stringify(form)); } catch {}
  }, [form]);

  React.useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [idx, done]);

  const canNext = (() => {
    if (idx === 0) return form.name && form.phone && form.email;
    if (idx === 1) return form.category && form.gender && form.state;
    if (idx === 2) return form.budget;
    if (idx === 3) return true;
    if (idx === 4) return form.plan && form.txnId;
    return true;
  })();

  const handleSubmit = async () => {
    setSubmitting(true);
    setSubmitError(null);
    try {
      const { error } = await window.supabaseClient
        .from('submissions')
        .insert({
          reference:     bookingRef,
          name:          form.name,
          phone:         form.phone,
          email:         form.email,
          parent:        form.parent        || null,
          jee_main_pct:  form.jeeMainPct    || null,
          jee_main_rank: form.jeeMainRank   || null,
          jee_adv_marks: form.jeeAdvMarks   || null,
          jee_adv_rank:  form.jeeAdvRank    || null,
          bitsat:        form.bitsat        || null,
          category:      form.category,
          gender:        form.gender,
          home_state:    form.state,
          colleges:      form.colleges      || [],
          budget:        form.budget,
          notes:         form.notes         || null,
          plan:          form.plan,
          txn_id:        form.txnId,
        });
      if (error) throw error;
      localStorage.removeItem(STORAGE_KEY);
      setDone(true);
    } catch (err) {
      console.error('Submission error:', err);
      setSubmitError('Something went wrong saving your details. Please WhatsApp us directly at +91 94113 06517.');
    } finally {
      setSubmitting(false);
    }
  };

  if (done) return <Success bookingRef={bookingRef} form={form} onReset={() => { setForm({}); setIdx(0); setDone(false); }} />;

  const Body = [StepAbout, StepScores, StepPrefs, StepGoals, StepPay][idx];

  return (
    <div>
      <ProgressRail idx={idx} max={STEPS.length} />

      <section className="section" style={{ padding: '56px 0 96px' }}>
        <div className="container">
          <div className="wizard-grid" style={{
            display: 'grid', gridTemplateColumns: '1.55fr 0.95fr', gap: 56, alignItems: 'start',
          }}>
            <div>
              <div style={{ maxWidth: 720 }}>
                <Body form={form} setForm={setForm} />

                {/* Footer navigation */}
                <div style={{
                  marginTop: 56, paddingTop: 28, borderTop: '1px solid var(--color-hairline)',
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16,
                }}>
                  <button
                    type="button"
                    className="btn btn-secondary btn-lg"
                    onClick={() => setIdx(Math.max(0, idx - 1))}
                    disabled={idx === 0}
                    style={{ visibility: idx === 0 ? 'hidden' : 'visible' }}
                  >
                    <IconChevronLeft size={16} /> Back
                  </button>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                    <span className="caption hide-xs" style={{ fontSize: 12 }}>
                      {canNext ? 'Looking good' : 'Fill the required fields'}
                    </span>
                    {idx < STEPS.length - 1 ? (
                      <button
                        type="button"
                        className="btn btn-primary btn-lg"
                        onClick={() => setIdx(idx + 1)}
                        disabled={!canNext}
                        style={{ opacity: canNext ? 1 : 0.5, cursor: canNext ? 'pointer' : 'not-allowed' }}
                      >
                        Continue <IconChevronRight size={16} />
                      </button>
                    ) : (
                      <button
                        type="button"
                        className="btn btn-accent btn-lg"
                        onClick={handleSubmit}
                        disabled={!canNext || submitting}
                        style={{ opacity: (canNext && !submitting) ? 1 : 0.5, cursor: (canNext && !submitting) ? 'pointer' : 'not-allowed' }}
                      >
                        {submitting ? 'Saving…' : 'Confirm payment'} <IconArrowRight size={16} />
                      </button>
                    )}
                  </div>
                </div>
              </div>
            </div>

            <div>
              <Summary form={form} stepIdx={idx} />
              {submitError && (
                <div style={{
                  marginTop: 16, padding: '14px 18px',
                  background: '#FEF2F2', border: '1px solid #FECACA',
                  borderRadius: 12,
                  fontFamily: 'var(--font-sans)', fontSize: 13, color: '#991B1B', lineHeight: 1.5,
                }}>
                  ⚠️ {submitError}
                </div>
              )}
            </div>
          </div>
        </div>
        <style>{`
          @media (max-width: 1000px) {
            .wizard-grid { grid-template-columns: 1fr !important; gap: 32px !important; }
          }
          @media (max-width: 480px) { .hide-xs { display: none !important; } }
        `}</style>
      </section>
    </div>
  );
};

// ============================================================
// Success
// ============================================================
const Success = ({ form, bookingRef, onReset }) => {

  return (
    <section className="section" style={{ padding: '96px 0 120px' }}>
      <div className="container-narrow">
        <div className="fade-up" style={{ textAlign: 'center' }}>
          <div style={{
            width: 64, height: 64, borderRadius: 100,
            background: 'var(--color-primary-soft)',
            color: 'var(--color-primary)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            marginBottom: 28,
          }}>
            <IconCheck size={26} />
          </div>

          <h1 className="display-lg" style={{ marginBottom: 16, fontSize: 52 }}>
            We&rsquo;ve got it{form.name ? `, ${form.name.split(' ')[0]}` : ''}.
          </h1>
          <p className="body-lg" style={{ maxWidth: 540, margin: '0 auto 40px' }}>
            Your counselling slot is confirmed pending payment verification. We&rsquo;ll WhatsApp you within 60 minutes during business hours to confirm your slot and schedule the call.
          </p>

          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 10,
            padding: '10px 18px',
            background: 'var(--color-surface-soft)',
            border: '1px solid var(--color-hairline)',
            borderRadius: 100,
            marginBottom: 56,
          }}>
            <span className="caption">Reference</span>
            <span style={{ width: 4, height: 4, borderRadius: 100, background: 'var(--color-muted-soft)' }} />
            <span className="mono" style={{ fontSize: 13, color: 'var(--color-ink)' }}>{bookingRef}</span>
          </div>
        </div>

        {/* Contact channels — prominent, above timeline */}
        <div className="eyebrow-accent" style={{ marginBottom: 12, textAlign: 'center' }}>Reach us now</div>
        <div className="success-channels" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16, marginBottom: 40 }}>
          {[
            {
              label: 'WhatsApp',
              title: 'Share your screenshot',
              body: "Send your payment screenshot here and we'll verify within 60 minutes.",
              cta: '+91 94113 06517',
              href: 'https://wa.me/919411306517',
              iconBg: '#25D366',
              icon: (
                <svg width="28" height="28" viewBox="0 0 24 24" fill="white">
                  <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/>
                  <path d="M12 0C5.373 0 0 5.373 0 12c0 2.136.561 4.14 1.535 5.874L.057 23.876a.5.5 0 0 0 .607.61l6.162-1.453A11.945 11.945 0 0 0 12 24c6.627 0 12-5.373 12-12S18.627 0 12 0zm0 22c-1.891 0-3.658-.52-5.166-1.427l-.37-.223-3.827.902.937-3.715-.242-.382A9.944 9.944 0 0 1 2 12C2 6.477 6.477 2 12 2s10 4.477 10 10-4.477 10-10 10z"/>
                </svg>
              ),
            },
            {
              label: 'Instagram',
              title: 'Follow for updates',
              body: 'Cutoff trends, round-by-round news, and counselling tips from our team.',
              cta: '@counselexpert',
              href: 'https://instagram.com/counselexpert',
              iconBg: 'linear-gradient(135deg,#f09433,#e6683c,#dc2743,#cc2366,#bc1888)',
              icon: (
                <svg width="26" height="26" viewBox="0 0 24 24" fill="white">
                  <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z"/>
                </svg>
              ),
            },
            {
              label: 'Email',
              title: 'Write to us',
              body: 'For detailed queries or if you prefer email over WhatsApp.',
              cta: 'counsel.expert.1@gmail.com',
              href: 'mailto:counsel.expert.1@gmail.com',
              iconBg: 'var(--color-primary)',
              icon: (
                <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>
                  <polyline points="22,6 12,13 2,6"/>
                </svg>
              ),
            },
          ].map((c) => (
            <a key={c.label} href={c.href} target="_blank" rel="noopener noreferrer" className="card" style={{
              padding: '32px 28px', display: 'flex', flexDirection: 'column', gap: 0, color: 'var(--color-ink)',
              border: '1px solid var(--color-hairline)',
            }}>
              <div style={{
                width: 56, height: 56, borderRadius: 16,
                background: c.iconBg,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                marginBottom: 20, flexShrink: 0,
              }}>{c.icon}</div>
              <div className="eyebrow-accent" style={{ marginBottom: 8 }}>{c.label}</div>
              <div className="title-md" style={{ fontSize: 19, marginBottom: 8, lineHeight: 1.3 }}>{c.title}</div>
              <p className="body-sm" style={{ marginBottom: 24, marginTop: 0, fontSize: 14, lineHeight: 1.55, flexGrow: 1 }}>{c.body}</p>
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 600,
                color: 'var(--color-primary)',
              }}>
                {c.cta} <IconArrowRight size={14} />
              </span>
            </a>
          ))}
        </div>

        {/* Timeline */}
        <div className="card" style={{ padding: 40, marginBottom: 24, background: 'var(--color-canvas)' }}>
          <div className="eyebrow-accent" style={{ marginBottom: 6 }}>What happens next</div>
          <h2 className="display-sm" style={{ marginBottom: 32, fontSize: 24 }}>The next 24 hours.</h2>

          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {[
              { time: 'Within 60 minutes', title: 'Payment verification',  body: 'Our team confirms your UPI transaction and sends a WhatsApp confirmation.',             icon: <IconShieldCheck size={16} /> },
              { time: 'On your call',      title: '30-minute counselling', body: 'We walk through your options together and answer every question. Bring your parents.', icon: <IconHeart size={16} /> },
            ].map((t, i, arr) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '40px 1fr', gap: 20, position: 'relative' }}>
                <div style={{ width: 40, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                  <div style={{
                    width: 32, height: 32, borderRadius: 100,
                    background: i === 0 ? 'var(--color-primary)' : 'var(--color-canvas)',
                    color: i === 0 ? 'var(--color-on-primary)' : 'var(--color-ink)',
                    border: i === 0 ? 'none' : '1px solid var(--color-hairline)',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0, zIndex: 2,
                  }}>{t.icon}</div>
                  {i < arr.length - 1 && (
                    <div style={{ width: 1, flex: 1, background: 'var(--color-hairline)', marginTop: 4 }} />
                  )}
                </div>
                <div style={{ paddingBottom: i < arr.length - 1 ? 32 : 0 }}>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--color-primary)', letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 6 }}>
                    {t.time}
                  </div>
                  <div className="title-md" style={{ fontSize: 16, marginBottom: 6 }}>{t.title}</div>
                  <p className="body-sm" style={{ maxWidth: 520, margin: 0 }}>{t.body}</p>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={{ textAlign: 'center' }}>
          <a href="#/" className="caption" style={{ textDecoration: 'underline', textUnderlineOffset: 4 }} onClick={onReset}>
            Back to home
          </a>
        </div>
      </div>
      <style>{`
        @media (max-width: 780px) {
          .success-channels { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
};

window.Wizard = Wizard;
