/* global React */
/* ============================================================
   WV Smokehouse — Catering section + multi-step inquiry funnel
   "...or we come to you."
   Light inquiry on the site → hands off to HoneyCart at the end.
   ============================================================ */

const { useState: useFunnelState, useRef: useFunnelRef, useEffect: useFunnelEffect } = React;

const EVENT_TYPES = [
  { id: 'wedding',  label: 'Wedding',         note: 'We LOVE catering weddings — and we can travel.' },
  { id: 'corporate',label: 'Company event',   note: 'Receptions, conferences, holiday parties.' },
  { id: 'reunion',  label: 'Reunion',         note: 'Family, class, anniversary — pull up a chair.' },
  { id: 'sporting', label: 'Sporting event',  note: 'Tournaments, tailgates, season openers.' },
  { id: 'party',    label: 'Party',           note: 'Birthdays, retirements, just-because.' },
  { id: 'other',    label: 'Something else',  note: "Tell us — there's a good chance we've done it." },
];

function Catering(){
  return (
    <section id="catering" className="catering" data-screen-label="Catering">
      {/* paper edge transitioning from hero */}
      <div className="paper-edge-top" aria-hidden="true"></div>

      <div className="catering-inner">
        <header className="catering-head">
          <div className="catering-eyebrow">
            <span className="ornament">❦</span>
            <span>Catering</span>
            <span className="ornament">❦</span>
          </div>

          <h2 className="catering-headline">
            <span className="ellipsis">…</span>
            or we come <em>to you.</em>
          </h2>

          <p className="catering-body">
            We happily cater events year-round! Available for receptions, company events,
            reunions, sporting events, parties and more! Our weekends book up fast, so
            contact us soon for a quote!
          </p>

          <div className="catering-weddings">
            <span className="hand-arrow" aria-hidden="true">↬</span>
            <span className="hand-line">We <strong>LOVE</strong> catering weddings — and we can travel.</span>
          </div>
        </header>

        <CateringFunnel />
      </div>
    </section>
  );
}

function CateringFunnel(){
  const [step, setStep]   = useFunnelState(0);          // 0..3 inputs, 4 = success
  const [dir, setDir]     = useFunnelState(1);          // 1 = forward, -1 = back (for transition direction)
  const [data, setData]   = useFunnelState({ type: '', date: '', count: 50, name: '', email: '' });
  const inputRefs         = useFunnelRef({});

  // focus the first interactive element each step.
  // preventScroll: true — keeps keyboard-a11y focus management without yanking the
  // viewport to the funnel on initial mount (was auto-scrolling past the hero on load).
  useFunnelEffect(() => {
    const t = setTimeout(() => {
      const el = inputRefs.current[step];
      el?.focus?.({ preventScroll: true });
    }, 360);
    return () => clearTimeout(t);
  }, [step]);

  const advance = () => { setDir(1);  setStep(s => Math.min(4, s + 1)); };
  const goBack  = () => { setDir(-1); setStep(s => Math.max(0, s - 1)); };

  const set = (key, value) => setData(d => ({ ...d, [key]: value }));

  const canAdvance = (() => {
    switch(step){
      case 0: return !!data.type;
      case 1: return !!data.date;
      case 2: return data.count > 0;
      case 3: return data.name.trim().length > 1 && /\S+@\S+\.\S+/.test(data.email);
      default: return false;
    }
  })();

  const isLast = step === 3;

  const onSubmit = (e) => {
    e?.preventDefault?.();
    if (!canAdvance) return;
    // In a real build this POSTs to /api/catering or mails catering@wvsmokehouse.com
    setDir(1); setStep(4);
  };

  // Smooth slide-and-fade animation by remounting the step view via key
  const Q = (() => {
    if (step === 0) return (
      <FunnelStep key="0" stepNum={1} total={4} label="What kind of event?">
        <div className="event-grid">
          {EVENT_TYPES.map((t, i) => (
            <button
              key={t.id}
              ref={el => { if (i === 0) inputRefs.current[0] = el; }}
              type="button"
              className={`event-card ${data.type === t.id ? 'is-selected' : ''}`}
              onClick={() => { set('type', t.id); setTimeout(advance, 260); }}
            >
              <span className="event-label">{t.label}</span>
              <span className="event-note">{t.note}</span>
            </button>
          ))}
        </div>
      </FunnelStep>
    );
    if (step === 1) return (
      <FunnelStep key="1" stepNum={2} total={4} label="When are you thinking?">
        <div className="date-field">
          <input
            ref={el => { inputRefs.current[1] = el; }}
            type="date"
            className="text-input date-input"
            value={data.date}
            onChange={e => set('date', e.target.value)}
            min={new Date().toISOString().slice(0,10)}
            onKeyDown={e => { if (e.key === 'Enter' && canAdvance) advance(); }}
          />
          <p className="field-note">Weekends book up fast — pick a backup if you have one.</p>
        </div>
      </FunnelStep>
    );
    if (step === 2) return (
      <FunnelStep key="2" stepNum={3} total={4} label="How many folks?">
        <div className="count-field">
          <button
            type="button" className="count-step"
            onClick={() => set('count', Math.max(1, data.count - 5))}
            aria-label="Decrease headcount"
          >–</button>
          <input
            ref={el => { inputRefs.current[2] = el; }}
            type="number"
            className="text-input count-input"
            value={data.count}
            min={1}
            max={1000}
            onChange={e => set('count', Number(e.target.value) || 0)}
            onKeyDown={e => { if (e.key === 'Enter' && canAdvance) advance(); }}
          />
          <button
            type="button" className="count-step"
            onClick={() => set('count', Math.min(1000, data.count + 5))}
            aria-label="Increase headcount"
          >+</button>
        </div>
        <div className="count-chips">
          {[25, 50, 100, 150, 250].map(n => (
            <button
              key={n}
              type="button"
              className={`chip ${data.count === n ? 'is-selected' : ''}`}
              onClick={() => set('count', n)}
            >{n}</button>
          ))}
        </div>
      </FunnelStep>
    );
    if (step === 3) return (
      <FunnelStep key="3" stepNum={4} total={4} label="And who should we get back to?">
        <form className="contact-form" onSubmit={onSubmit}>
          <label className="field">
            <span className="field-label">Your name</span>
            <input
              ref={el => { inputRefs.current[3] = el; }}
              type="text" className="text-input"
              value={data.name}
              onChange={e => set('name', e.target.value)}
              placeholder="Jane Smith"
            />
          </label>
          <label className="field">
            <span className="field-label">Email</span>
            <input
              type="email" className="text-input"
              value={data.email}
              onChange={e => set('email', e.target.value)}
              placeholder="jane@example.com"
            />
          </label>
        </form>
      </FunnelStep>
    );
    if (step === 4) return (
      <FunnelStep key="4" stepNum={4} total={4} label="" success>
        <div className="success-card">
          <div className="success-mark" aria-hidden="true">
            <svg viewBox="0 0 56 56" width="56" height="56" fill="none">
              <circle cx="28" cy="28" r="26" stroke="#7a2a1f" strokeWidth="1.5"/>
              <path d="M16 28 L25 37 L41 19" stroke="#7a2a1f" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <h3 className="success-title">Got it, {data.name.split(' ')[0] || 'friend'}.</h3>
          <p className="success-body">
            We'll be in touch at <strong>{data.email}</strong> about your{' '}
            {EVENT_TYPES.find(t => t.id === data.type)?.label.toLowerCase()} on{' '}
            <strong>{formatDate(data.date)}</strong> for around <strong>{data.count}</strong> guests.
          </p>
          <p className="success-handoff">
            Want to put numbers on it right now? Pick out exact dishes and headcounts on our quote portal.
          </p>
          <a
            className="cta cta-paper"
            href="https://app.honeycart.com/customer/wvsmokehouse"
            target="_blank" rel="noopener noreferrer"
          >
            Continue on HoneyCart
            <span className="cta-arrow" aria-hidden="true"></span>
          </a>
          <button type="button" className="success-restart" onClick={() => { setData({ type:'', date:'', count:50, name:'', email:'' }); setDir(-1); setStep(0); }}>
            Or send another inquiry
          </button>
        </div>
      </FunnelStep>
    );
    return null;
  })();

  return (
    <div className="funnel-card" data-step={step}>
      <div className="funnel-tape" aria-hidden="true"></div>
      <div className="funnel-tape funnel-tape-right" aria-hidden="true"></div>

      <div className="funnel-progress" aria-hidden="true">
        {[0,1,2,3].map(i => (
          <span key={i} className={`pip ${i <= Math.min(step, 3) ? 'is-on' : ''}`}></span>
        ))}
      </div>

      <div className={`funnel-step-shell dir-${dir > 0 ? 'fwd' : 'back'}`}>
        {Q}
      </div>

      {step < 4 && (
        <div className="funnel-actions">
          <button
            type="button"
            className="funnel-back"
            onClick={goBack}
            disabled={step === 0}
            aria-label="Previous step"
          >
            <svg width="16" height="16" viewBox="0 0 22 22" fill="none"><path d="M14 4 L7 11 L14 18" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
            <span>Back</span>
          </button>

          {step > 0 && !isLast && (
            <button
              type="button"
              className="funnel-next"
              onClick={advance}
              disabled={!canAdvance}
            >
              <span>Next</span>
              <svg width="16" height="16" viewBox="0 0 22 22" fill="none"><path d="M8 4 L15 11 L8 18" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
          )}
          {isLast && (
            <button
              type="button"
              className="cta cta-paper"
              onClick={onSubmit}
              disabled={!canAdvance}
            >
              Get a catering quote
              <span className="cta-arrow" aria-hidden="true"></span>
            </button>
          )}
        </div>
      )}
    </div>
  );
}

function FunnelStep({ stepNum, total, label, success, children }){
  return (
    <div className={`funnel-step ${success ? 'is-success' : ''}`}>
      {!success && (
        <div className="step-meta">
          <span className="step-num">Step {stepNum} of {total}</span>
        </div>
      )}
      {label && <h3 className="step-label">{label}</h3>}
      <div className="step-body">{children}</div>
    </div>
  );
}

function formatDate(iso){
  if (!iso) return '—';
  const [y, m, d] = iso.split('-').map(Number);
  const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  return `${months[m-1]} ${d}, ${y}`;
}

Object.assign(window, { Catering });
