/* global React, IconArrowRight, IconArrowLeft, IconChevronLeft, IconChevronRight, IconCheck,
   IconShieldCheck, IconLock, IconUpload, IconCopy, IconClock, IconSparkles, IconUser, IconPhone,
   IconMail, IconSend, IconTarget, IconCompass, IconHeart, IconStar, SITE */

// ============================================================
// Multi-step counselling form
// ============================================================

const STEPS  = SITE.form.steps;
const STATES = SITE.form.states;

// ============================================================
// Progress rail
// ============================================================
const ProgressRail = ({ idx, max }) => {
  const pct = ((idx + 1) / max) * 100;
  return (
    <div style={{
      position: 'sticky', top: 72, zIndex: 30, background: 'var(--color-canvas)',
      borderBottom: '1px solid var(--color-hairline)',
    }}>
      <div className="container" style={{ padding: '20px 32px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span className="mono" style={{ fontSize: 12, color: 'var(--color-muted)' }}>
              Step {String(idx + 1).padStart(2, '0')} of {String(max).padStart(2, '0')}
            </span>
            <span style={{ width: 4, height: 4, borderRadius: 100, background: 'var(--color-muted-soft)' }} />
            <span style={{ fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600, color: 'var(--color-ink)' }}>
              {STEPS[idx]?.title}
            </span>
            <span style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--color-body)' }} className="hide-sm">
              · {STEPS[idx]?.sub}
            </span>
          </div>
          <div className="caption hide-sm" style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <IconLock size={11} />
            Secured · auto-saved
          </div>
        </div>
        <div style={{ position: 'relative', height: 3, background: 'var(--color-surface-strong)', borderRadius: 100, overflow: 'hidden' }}>
          <div style={{
            position: 'absolute', top: 0, left: 0, bottom: 0,
            width: `${pct}%`,
            background: 'var(--color-primary)',
            borderRadius: 100,
            transition: 'width 400ms cubic-bezier(0.22, 0.61, 0.36, 1)',
          }} />
        </div>
      </div>
      <style>{`@media (max-width: 640px) { .hide-sm { display: none !important; } }`}</style>
    </div>
  );
};

// ============================================================
// Field primitives
// ============================================================
const Field = ({ label, hint, required, children, span = 1 }) => (
  <div style={{ gridColumn: `span ${span}` }}>
    <label className="field-label">
      {label}
      {required && <span style={{ color: 'var(--color-primary)', marginLeft: 4 }}>*</span>}
    </label>
    {children}
    {hint && <div className="field-hint">{hint}</div>}
  </div>
);

const Grid = ({ children, cols = 2 }) => (
  <div className="form-grid" style={{
    display: 'grid', gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 20,
  }}>
    {children}
    <style>{`@media (max-width: 640px) { .form-grid { grid-template-columns: 1fr !important; } }`}</style>
  </div>
);

const ChipGroup = ({ options, value, onChange, multi = true }) => {
  const isSel = (o) => multi ? (value || []).includes(o) : value === o;
  const toggle = (o) => {
    if (multi) {
      const v = value || [];
      onChange(v.includes(o) ? v.filter((x) => x !== o) : [...v, o]);
    } else {
      onChange(o);
    }
  };
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
      {options.map((o) => (
        <button
          key={o}
          type="button"
          className={`chip ${isSel(o) ? 'chip-selected' : ''}`}
          onClick={() => toggle(o)}
        >
          {isSel(o) && <IconCheck size={13} />}
          {o}
        </button>
      ))}
    </div>
  );
};

// ============================================================
// Step bodies
// ============================================================
const StepAbout = ({ form, setForm }) => (
  <div className="fade-up">
    <h2 className="display-md" style={{ marginBottom: 8 }}>Let&rsquo;s start with you.</h2>
    <p className="body-md" style={{ marginBottom: 40, maxWidth: 520 }}>
      We&rsquo;ll use these to send your report and schedule your counselling call. We never share, sell, or call without a reason.
    </p>
    <Grid cols={2}>
      <Field label="Full name" required span={2}>
        <input className="input" placeholder="As on your hall ticket" value={form.name || ''} onChange={(e) => setForm({ ...form, name: e.target.value })} />
      </Field>
      <Field label="Phone (WhatsApp)" required>
        <input className="input" placeholder="+91 ·· ······ ····" value={form.phone || ''} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
      </Field>
      <Field label="Email" required>
        <input className="input" type="email" placeholder="you@example.com" value={form.email || ''} onChange={(e) => setForm({ ...form, email: e.target.value })} />
      </Field>
      <Field label="Parent or guardian name" hint="Optional · we sometimes loop them into the call" span={2}>
        <input className="input" placeholder="Optional" value={form.parent || ''} onChange={(e) => setForm({ ...form, parent: e.target.value })} />
      </Field>
    </Grid>
  </div>
);

const StepScores = ({ form, setForm }) => {
  const [errors, setErrors] = React.useState({});

  const validate = (name, value) => {
    const v = parseFloat(value);
    if (name === 'jeeMainPct' && value !== '') {
      if (isNaN(v) || v < 0 || v > 100)
        return 'Percentile must be between 0 and 100';
    }
    if (name === 'bitsat' && value !== '') {
      if (isNaN(v) || v < 0 || v > 450)
        return 'BITSAT score must be between 0 and 450';
    }
    return null;
  };

  const handle = (name, value) => {
    setForm({ ...form, [name]: value });
    const err = validate(name, value);
    setErrors((prev) => ({ ...prev, [name]: err }));
  };

  const errorStyle = { marginTop: 6, fontSize: 12, color: 'var(--color-critical)', fontFamily: 'var(--font-sans)' };

  return (
  <div className="fade-up">
    <h2 className="display-md" style={{ marginBottom: 8 }}>Where do you stand?</h2>
    <p className="body-md" style={{ marginBottom: 40, maxWidth: 520 }}>
      Fill whichever exams you&rsquo;ve given. If results aren&rsquo;t out yet, enter your best estimate &mdash; we&rsquo;ll re-plan once they are.
    </p>
    <Grid cols={2}>
      <Field label="JEE Main percentile">
        <input
          className="input"
          placeholder="e.g. 99.21"
          value={form.jeeMainPct || ''}
          onChange={(e) => handle('jeeMainPct', e.target.value)}
          style={errors.jeeMainPct ? { borderColor: 'var(--color-critical)' } : {}}
        />
        {errors.jeeMainPct && <div style={errorStyle}>{errors.jeeMainPct}</div>}
      </Field>
      <Field label="JEE Main CRL rank">
        <input className="input" placeholder="e.g. 4,182" value={form.jeeMainRank || ''} onChange={(e) => setForm({ ...form, jeeMainRank: e.target.value })} />
      </Field>
      <Field label="JEE Advanced marks" hint="If qualified">
        <input className="input" placeholder="e.g. 245" value={form.jeeAdvMarks || ''} onChange={(e) => setForm({ ...form, jeeAdvMarks: e.target.value })} />
      </Field>
      <Field label="JEE Advanced CRL rank" hint="If qualified">
        <input className="input" placeholder="e.g. 1,840" value={form.jeeAdvRank || ''} onChange={(e) => setForm({ ...form, jeeAdvRank: e.target.value })} />
      </Field>
      <Field label="BITSAT score" hint="Optional">
        <input
          className="input"
          placeholder="e.g. 342"
          value={form.bitsat || ''}
          onChange={(e) => handle('bitsat', e.target.value)}
          style={errors.bitsat ? { borderColor: 'var(--color-critical)' } : {}}
        />
        {errors.bitsat && <div style={errorStyle}>{errors.bitsat}</div>}
      </Field>
      <Field label="Category" required>
        <select className="input" value={form.category || ''} onChange={(e) => setForm({ ...form, category: e.target.value })}>
          <option value="">Select</option>
          {SITE.form.categories.map((c) => <option key={c}>{c}</option>)}
        </select>
      </Field>
      <Field label="Gender" required>
        <select className="input" value={form.gender || ''} onChange={(e) => setForm({ ...form, gender: e.target.value })}>
          <option value="">Select</option>
          {SITE.form.genders.map((g) => <option key={g}>{g}</option>)}
        </select>
      </Field>
      <Field label="Home state" required>
        <select className="input" value={form.state || ''} onChange={(e) => setForm({ ...form, state: e.target.value })}>
          <option value="">Select your state</option>
          {STATES.map((s) => <option key={s}>{s}</option>)}
        </select>
      </Field>
    </Grid>
  </div>
  );
};

const StepPrefs = ({ form, setForm }) => (
  <div className="fade-up">
    <h2 className="display-md" style={{ marginBottom: 8 }}>What do you want?</h2>
    <p className="body-md" style={{ marginBottom: 40, maxWidth: 520 }}>
      Pick everything that interests you, even loosely. Our counsellors will narrow it down with you.
    </p>

    <div style={{ marginBottom: 32 }}>
      <label className="field-label" style={{ marginBottom: 14 }}>Colleges you&rsquo;d consider <span style={{ color: 'var(--color-muted)', fontWeight: 400 }}>· tap all that apply</span></label>
      <ChipGroup options={SITE.form.colleges} value={form.colleges} onChange={(v) => setForm({ ...form, colleges: v })} />
    </div>

    <Grid cols={1}>
      <Field label="Annual fee comfortable for family" required>
        <select className="input" value={form.budget || ''} onChange={(e) => setForm({ ...form, budget: e.target.value })}>
          <option value="">Select range</option>
          {SITE.form.budgetOptions.map((b) => <option key={b}>{b}</option>)}
        </select>
      </Field>
    </Grid>
  </div>
);

const StepGoals = ({ form, setForm }) => (
  <div className="fade-up">
    <h2 className="display-md" style={{ marginBottom: 8 }}>One last question.</h2>
    <p className="body-md" style={{ marginBottom: 40, maxWidth: 520 }}>
      The more we know about where you want to go, the better we can shape the report.
    </p>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <Field label="Anything else we should know?" hint="Health, family, distance, language, financial constraints &mdash; whatever helps us plan around your real life.">
        <textarea className="input" placeholder="Optional, but read by a human." value={form.notes || ''} onChange={(e) => setForm({ ...form, notes: e.target.value })} />
      </Field>
    </div>
  </div>
);

const StepPay = ({ form, setForm }) => {
  const plans   = SITE.plans;
  const selected = plans.find(p => p.id === form.plan) || null;
  const amount   = selected ? `₹${selected.price.toLocaleString('en-IN')}` : null;

  return (
    <div className="fade-up">
      <h2 className="display-md" style={{ marginBottom: 8 }}>Choose your plan.</h2>
      <p className="body-md" style={{ marginBottom: 32, maxWidth: 540 }}>
        Select the plan that matches your exams, then pay via UPI to lock your counselling slot.
      </p>

      {/* ── Plan picker ── */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 12, marginBottom: 40 }}>
        {plans.map((plan) => {
          const active = form.plan === plan.id;
          return (
            <button
              key={plan.id}
              type="button"
              onClick={() => setForm({ ...form, plan: plan.id })}
              style={{
                position: 'relative',
                textAlign: 'left',
                background: active ? 'var(--color-primary-soft)' : 'var(--color-canvas)',
                border: active ? '2px solid var(--color-primary)' : '1px solid var(--color-hairline)',
                borderRadius: 16,
                padding: '16px 18px',
                cursor: 'pointer',
                transition: 'border 150ms, background 150ms',
              }}
            >
              {plan.popular && (
                <span style={{
                  position: 'absolute', top: -10, right: 14,
                  background: 'var(--color-primary)', color: 'var(--color-on-primary)',
                  fontSize: 10, fontWeight: 700, letterSpacing: '0.06em',
                  textTransform: 'uppercase', padding: '2px 10px', borderRadius: 100,
                  fontFamily: 'var(--font-sans)',
                }}>Popular</span>
              )}
              <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11, color: active ? 'var(--color-primary)' : 'var(--color-muted)', fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 4 }}>
                {plan.tag}
              </div>
              <div style={{ fontFamily: 'var(--font-serif)', fontSize: 16, fontWeight: 700, color: 'var(--color-ink)', marginBottom: 6 }}>
                {plan.name}
              </div>
              <div style={{ fontFamily: 'var(--font-sans)', fontSize: 22, fontWeight: 700, color: active ? 'var(--color-primary)' : 'var(--color-ink)', letterSpacing: '-0.5px' }}>
                ₹{plan.price.toLocaleString('en-IN')}
              </div>
            </button>
          );
        })}
      </div>

      {/* ── Payment section (shown only after plan selected) ── */}
      {selected ? (
        <div className="pay-grid" style={{ display: 'grid', gridTemplateColumns: '1.05fr 1fr', gap: 24 }}>
          {/* QR card */}
          <div style={{
            background: 'var(--color-surface-soft)',
            border: '1px solid var(--color-hairline)',
            borderRadius: 24, padding: 32,
            display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center',
          }}>
            <div className="badge badge-accent" style={{ marginBottom: 20 }}>
              <IconLock size={11} /> UPI · Secure
            </div>
            <div style={{
              width: 240, height: 240,
              background: 'var(--color-canvas)', border: '1px solid var(--color-hairline)',
              borderRadius: 20, padding: 16,
              display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative',
            }}>
              <img src="img/qr_code.jpg" alt="UPI QR code" style={{ width: '100%', height: '100%', objectFit: 'contain', borderRadius: 8 }} />
            </div>
            <div style={{ marginTop: 24, fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--color-body)', marginBottom: 10 }}>
              Scan with any UPI app
            </div>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 10,
              padding: '10px 16px', background: 'var(--color-canvas)',
              border: '1px solid var(--color-hairline)', borderRadius: 100,
            }}>
              <span className="mono" style={{ fontSize: 13, color: 'var(--color-ink)' }}>{SITE.form.pricing.upiId}</span>
              <button
                type="button"
                onClick={() => { navigator.clipboard?.writeText(SITE.form.pricing.upiId); }}
                style={{ background: 'transparent', border: 0, cursor: 'pointer', color: 'var(--color-primary)', padding: 0, display: 'inline-flex', alignItems: 'center' }}
                aria-label="Copy UPI ID"
              ><IconCopy size={14} /></button>
            </div>
          </div>

          {/* Confirmation inputs */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ background: 'var(--color-canvas)', border: '1px solid var(--color-hairline)', borderRadius: 24, padding: 24 }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>Amount due</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 4 }}>
                <span className="mono" style={{ fontSize: 38, fontWeight: 500, letterSpacing: '-1.2px', color: 'var(--color-ink)' }}>
                  {amount}
                </span>
                <span className="caption">one-time</span>
              </div>
              <div className="caption" style={{ fontSize: 12 }}>{selected.name} plan · {selected.tag}</div>
            </div>

            <div style={{ background: 'var(--color-canvas)', border: '1px solid var(--color-hairline)', borderRadius: 24, padding: 24 }}>
              <div className="title-md" style={{ fontSize: 15, marginBottom: 16 }}>After you&rsquo;ve paid</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <Field label="UPI transaction ID" required>
                  <input
                    className="input"
                    placeholder="e.g. 4082746281"
                    value={form.txnId || ''}
                    onChange={(e) => setForm({ ...form, txnId: e.target.value })}
                  />
                </Field>
                <div style={{
                  display: 'flex', alignItems: 'flex-start', gap: 10, padding: '12px 14px',
                  background: 'var(--color-surface-soft)', border: '1px solid var(--color-hairline)', borderRadius: 12,
                }}>
                  <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="var(--color-primary)" strokeWidth="2" strokeLinecap="round" style={{ flexShrink: 0, marginTop: 1 }}><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
                  <p style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-body)', margin: 0, lineHeight: 1.5 }}>
                    Please share your payment screenshot on <strong style={{ color: 'var(--color-ink)' }}>WhatsApp</strong> after submitting — we use it to verify faster.
                  </p>
                </div>
              </div>
            </div>

            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '14px 16px', background: 'var(--color-primary-soft)', borderRadius: 14 }}>
              <IconShieldCheck size={16} style={{ color: 'var(--color-primary)', marginTop: 2, flexShrink: 0 }} />
              <div style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-ink)', lineHeight: 1.5 }}>
                <strong>Your slot is confirmed after payment verification.</strong> We verify within 60 minutes during business hours, then you&rsquo;ll get a WhatsApp confirmation.
              </div>
            </div>
          </div>
        </div>
      ) : (
        <div style={{ padding: '32px', textAlign: 'center', border: '1px dashed var(--color-hairline)', borderRadius: 16 }}>
          <p style={{ fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--color-muted)', margin: 0 }}>
            Select a plan above to see the payment details.
          </p>
        </div>
      )}
      <style>{`@media (max-width: 820px) { .pay-grid { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
};

// ============================================================
// QR placeholder
// ============================================================
const QRPlaceholder = () => {
  const size = 25;
  const grid = React.useMemo(() => {
    const g = [];
    let seed = 7919;
    const rnd = () => { seed = (seed * 9301 + 49297) % 233280; return seed / 233280; };
    for (let y = 0; y < size; y++) {
      const row = [];
      for (let x = 0; x < size; x++) row.push(rnd() < 0.48 ? 1 : 0);
      g.push(row);
    }
    const stamp = (cx, cy) => {
      for (let y = -3; y <= 3; y++) {
        for (let x = -3; x <= 3; x++) {
          if (cx + x < 0 || cx + x >= size || cy + y < 0 || cy + y >= size) continue;
          const inOuter = Math.max(Math.abs(x), Math.abs(y)) === 3;
          const inInner = Math.max(Math.abs(x), Math.abs(y)) <= 1;
          g[cy + y][cx + x] = (inOuter || inInner) ? 1 : 0;
        }
      }
    };
    stamp(3, 3);
    stamp(size - 4, 3);
    stamp(3, size - 4);
    return g;
  }, []);

  const cell = 8;
  return (
    <svg width={size * cell} height={size * cell} viewBox={`0 0 ${size * cell} ${size * cell}`}>
      <rect width={size * cell} height={size * cell} fill="transparent" />
      {grid.flatMap((row, y) =>
        row.map((v, x) => v ? (
          <rect key={`${x}-${y}`} x={x * cell} y={y * cell} width={cell} height={cell} fill="var(--color-ink)" />
        ) : null)
      )}
    </svg>
  );
};

// ============================================================
// File drop
// ============================================================
const FileDrop = ({ value, onChange }) => {
  const [hover, setHover] = React.useState(false);
  const inputRef = React.useRef(null);
  const handle = (f) => {
    if (f && f.type?.startsWith('image/')) onChange({ name: f.name, size: f.size });
  };
  return (
    <div
      onDragOver={(e) => { e.preventDefault(); setHover(true); }}
      onDragLeave={() => setHover(false)}
      onDrop={(e) => { e.preventDefault(); setHover(false); handle(e.dataTransfer.files?.[0]); }}
      onClick={() => inputRef.current?.click()}
      style={{
        border: `1px dashed ${hover ? 'var(--color-primary)' : 'var(--color-hairline)'}`,
        background: hover ? 'var(--color-primary-soft)' : 'var(--color-surface-soft)',
        borderRadius: 14,
        padding: '20px 18px',
        cursor: 'pointer',
        textAlign: 'center',
        transition: 'all 150ms ease-out',
      }}
    >
      <input ref={inputRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={(e) => handle(e.target.files?.[0])} />
      {value ? (
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, justifyContent: 'center' }}>
          <span style={{
            width: 32, height: 32, borderRadius: 100,
            background: 'var(--color-primary)',
            color: 'white',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          }}><IconCheck size={14} /></span>
          <div style={{ textAlign: 'left' }}>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600, color: 'var(--color-ink)' }}>
              {value.name}
            </div>
            <div className="caption" style={{ fontSize: 11 }}>{Math.round(value.size / 1024)} KB · uploaded</div>
          </div>
        </div>
      ) : (
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, justifyContent: 'center' }}>
          <IconUpload size={16} style={{ color: 'var(--color-muted)' }} />
          <div style={{ textAlign: 'left' }}>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--color-ink)', fontWeight: 500 }}>
              Drop your payment screenshot
            </div>
            <div className="caption" style={{ fontSize: 11 }}>or tap to choose · PNG, JPG, up to 5 MB</div>
          </div>
        </div>
      )}
    </div>
  );
};

window.STEPS = STEPS;
window.ProgressRail = ProgressRail;
window.StepAbout = StepAbout;
window.StepScores = StepScores;
window.StepPrefs = StepPrefs;
window.StepGoals = StepGoals;
window.StepPay = StepPay;
