/* primitives.jsx — shared UI primitives */
const { useState, useEffect, useRef } = React;

// Inline SVG icons
const Icon = {
  Bolt: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M13 2 3 14h7l-1 8 10-12h-7l1-8z" />
    </svg>
  ),
  Check: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="m5 12 5 5L20 7" />
    </svg>
  ),
  Play: (p) => (
    <svg viewBox="0 0 24 24" fill="currentColor" {...p}>
      <path d="M8 5v14l11-7z" />
    </svg>
  ),
  ArrowRight: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M5 12h14M13 5l7 7-7 7" />
    </svg>
  ),
  Plus: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" {...p}>
      <path d="M12 5v14M5 12h14" />
    </svg>
  ),
  X: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" {...p}>
      <path d="M6 6l12 12M6 18 18 6" />
    </svg>
  ),
  Sparkle: (p) => (
    <svg viewBox="0 0 24 24" fill="currentColor" {...p}>
      <path d="M12 2 14 9l7 2-7 2-2 7-2-7-7-2 7-2 2-7z" />
    </svg>
  ),
  WA: (p) => (
    <svg viewBox="0 0 24 24" fill="currentColor" {...p}>
      <path d="M12.04 2C6.58 2 2.13 6.45 2.13 11.91c0 1.75.46 3.45 1.32 4.95L2 22l5.25-1.38a9.9 9.9 0 0 0 4.79 1.22h.01c5.46 0 9.91-4.45 9.91-9.91 0-2.65-1.03-5.14-2.9-7.01A9.82 9.82 0 0 0 12.04 2zm5.74 14.16c-.24.68-1.42 1.31-1.95 1.36-.5.05-1.13.07-1.81-.11-.42-.13-.96-.31-1.65-.61-2.91-1.26-4.81-4.19-4.96-4.38-.14-.19-1.18-1.57-1.18-3 0-1.42.75-2.13 1.01-2.42.27-.29.58-.36.78-.36.19 0 .39 0 .56.01.18.01.42-.07.66.5.24.59.82 2.02.89 2.17.07.14.12.31.02.5-.1.19-.14.31-.29.48-.14.17-.31.38-.44.51-.14.14-.29.3-.13.59.17.29.74 1.22 1.59 1.98 1.09.97 2.01 1.27 2.3 1.41.29.14.46.12.63-.07.17-.19.73-.85.92-1.14.19-.29.39-.24.65-.14.27.1 1.7.8 1.99.95.29.14.48.22.55.34.07.12.07.71-.17 1.39z" />
    </svg>
  ),
};

// Hook: countdown to a target Date
function useCountdown(target){
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  const diff = Math.max(0, target.getTime() - now.getTime());
  const d = Math.floor(diff / 86400000);
  const h = Math.floor((diff % 86400000) / 3600000);
  const m = Math.floor((diff % 3600000) / 60000);
  const s = Math.floor((diff % 60000) / 1000);
  const pad = (n) => String(n).padStart(2, '0');
  return { d: pad(d), h: pad(h), m: pad(m), s: pad(s), expired: diff <= 0 };
}

// Hook: reveal-on-scroll
function useReveal(){
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if(!el) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if(e.isIntersecting){
          e.target.classList.add('reveal--in');
          obs.unobserve(e.target);
        }
      });
    }, { threshold: 0.12 });
    el.querySelectorAll('.reveal').forEach((n) => obs.observe(n));
    return () => obs.disconnect();
  }, []);
  return ref;
}

function Countdown({ target, compact }){
  const { d, h, m, s } = useCountdown(target);
  return (
    <div className="countdown">
      <span className="countdown__seg">{d}d</span>
      <span className="countdown__sep">:</span>
      <span className="countdown__seg">{h}h</span>
      <span className="countdown__sep">:</span>
      <span className="countdown__seg">{m}m</span>
      {!compact && <>
        <span className="countdown__sep">:</span>
        <span className="countdown__seg">{s}s</span>
      </>}
    </div>
  );
}

// ── Registration config ───────────────────────────────────
const WA_COMMUNITY = 'https://chat.whatsapp.com/KrxiKExv2Au8kXfvBRMfM9';
const REGISTER_API = '/api/register'; // Node server → writes to leads.json

function RegisterModal({ open, onClose }){
  const [step, setStep]     = useState('form'); // 'form' | 'success'
  const [loading, setLoad]  = useState(false);
  const [form, setForm]     = useState({ businessName:'', contact:'', email:'', type:'', terms:false });
  const [errors, setErrors] = useState({});

  // body scroll lock
  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  // reset after close animation
  useEffect(() => {
    if(!open){
      const t = setTimeout(() => {
        setStep('form');
        setForm({ businessName:'', contact:'', email:'', type:'', terms:false });
        setErrors({});
      }, 300);
      return () => clearTimeout(t);
    }
  }, [open]);

  if(!open) return null;

  const set = (k, v) => {
    setForm(f => ({ ...f, [k]: v }));
    setErrors(e => ({ ...e, [k]: undefined }));
  };

  const validate = () => {
    const e = {};
    if(!form.businessName.trim())                                    e.businessName = 'Business name is required';
    if(!/^\d{10}$/.test(form.contact.replace(/[\s\-+() ]/g, ''))) e.contact      = 'Enter a valid 10-digit number';
    if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email))              e.email        = 'Enter a valid email address';
    if(!form.type)                                                    e.type         = 'Please select one';
    if(!form.terms)                                                   e.terms        = 'Please accept the terms to continue';
    return e;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const errs = validate();
    if(Object.keys(errs).length){ setErrors(errs); return; }
    setLoad(true);

    const entry = {
      businessName: form.businessName.trim(),
      contact:      form.contact.replace(/[\s\-+() ]/g, ''),
      email:        form.email.trim().toLowerCase(),
      type:         form.type,
      source:       'webinar-landing',
    };

    try {
      const res = await fetch(REGISTER_API, {
        method:  'POST',
        headers: { 'Content-Type': 'application/json' },
        body:    JSON.stringify(entry),
      });
      if(!res.ok) throw new Error('server error');
    } catch(_) {
      // fallback: save to localStorage if server unreachable
      try {
        const list = JSON.parse(localStorage.getItem('mb_webinar_leads') || '[]');
        list.push({ ...entry, registeredAt: new Date().toISOString(), savedOffline: true });
        localStorage.setItem('mb_webinar_leads', JSON.stringify(list));
      } catch(_) {}
    }

    setLoad(false);
    setStep('success');
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal reg-modal" onClick={e => e.stopPropagation()}>
        <button className="modal__close" onClick={onClose} aria-label="Close">
          <Icon.X width="16" height="16" />
        </button>

        {step === 'form' ? (
          <>
            <div className="reg-modal__head">
              <span className="reg-modal__eyebrow"><Icon.Sparkle width="11" height="11" /> FREE REGISTRATION</span>
              <h3>Reserve Your Free Seat</h3>
              <p>Saturday, May 9 · 5:00 PM IST · Only 100 seats</p>
            </div>

            <form onSubmit={handleSubmit} noValidate>

              <div className={`field${errors.businessName ? ' field--err' : ''}`}>
                <label>Business Name</label>
                <input type="text" placeholder="Your agency or business name"
                  value={form.businessName} onChange={e => set('businessName', e.target.value)} />
                {errors.businessName && <span className="field__msg">{errors.businessName}</span>}
              </div>

              <div className={`field${errors.contact ? ' field--err' : ''}`}>
                <label>WhatsApp Number</label>
                <input type="tel" placeholder="10-digit mobile number"
                  value={form.contact} onChange={e => set('contact', e.target.value)} />
                {errors.contact && <span className="field__msg">{errors.contact}</span>}
              </div>

              <div className={`field${errors.email ? ' field--err' : ''}`}>
                <label>Email ID</label>
                <input type="email" placeholder="you@example.com"
                  value={form.email} onChange={e => set('email', e.target.value)} />
                {errors.email && <span className="field__msg">{errors.email}</span>}
              </div>

              <div className={`field${errors.type ? ' field--err' : ''}`}>
                <label>I am a…</label>
                <div className="type-btns">
                  {[['Business','🏢'],['Agency','🚀'],['Freelancer','💼']].map(([val, icon]) => (
                    <button key={val} type="button"
                      className={`type-btn${form.type === val ? ' type-btn--on' : ''}`}
                      onClick={() => set('type', val)}>
                      <span>{icon}</span>{val}
                    </button>
                  ))}
                </div>
                {errors.type && <span className="field__msg">{errors.type}</span>}
              </div>

              <div className={`field field--check${errors.terms ? ' field--err' : ''}`}>
                <label className="check-label">
                  <input type="checkbox" checked={form.terms} onChange={e => set('terms', e.target.checked)} />
                  <span>I accept the <a href="#" onClick={e => e.stopPropagation()}>Terms &amp; Conditions</a> and consent to receive webinar updates on WhatsApp.</span>
                </label>
                {errors.terms && <span className="field__msg">{errors.terms}</span>}
              </div>

              <button type="submit" className="btn btn--primary reg-submit" disabled={loading}>
                {loading
                  ? <span className="reg-spinner" />
                  : <><Icon.Sparkle width="16" height="16" /> Reserve My Free Seat</>}
              </button>
              <p className="reg-foot">No spam. Unsubscribe anytime.</p>
            </form>
          </>
        ) : (
          <div className="reg-success">
            <div className="reg-success__ring">🎉</div>
            <h3>You're Registered!</h3>
            <p>Your seat is confirmed for <strong>Saturday, May 9 · 5:00 PM IST</strong>. Join the WhatsApp community to get your live link, reminders &amp; ₹47,000 bonus stack.</p>
            <a href={WA_COMMUNITY} target="_blank" rel="noopener noreferrer" className="btn reg-wa-btn">
              <Icon.WA width="20" height="20" /> Join the Community
            </a>
            <p className="reg-foot">The webinar link will be shared in the group 15 min before we go live.</p>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Icon, useCountdown, useReveal, Countdown, RegisterModal });
