// VeloraTech — /consult — Free 30-min consultation, 3-step flow
// NO Stripe, NO payment — completely free
const { useState: useConsult, useMemo: useMemoConsult, useRef: useRefConsult, useEffect: useEffectConsult } = React;

const CONSULT_TOPICS = [
  { id: 'web',     icon: 'Globe',    name: 'Web Design & Ongoing Care' },
  { id: 'wifi',    icon: 'Wifi',     name: 'Home Internet & Wi-Fi Setup' },
  { id: 'cctv',   icon: 'Camera',   name: 'CCTV & Smart Home Installation' },
  { id: 'biz',    icon: 'Building', name: 'Business IT Support' },
  { id: 'compute',icon: 'Tv',       name: 'Computer & Printer Help' },
  { id: 'other',  icon: 'Hand',     name: 'Something Else' },
];

const CONSULT_STEP_NAMES = ["What's on your mind", 'Your details', 'Pick a call time'];

const CONSULT_SLOTS = [
  { id: 'morning',   name: 'Morning',   time: '8:00 AM – 12:00 PM' },
  { id: 'afternoon', name: 'Afternoon', time: '12:00 PM – 5:00 PM' },
  { id: 'evening',   name: 'Evening',   time: '5:00 PM – 7:00 PM' },
  { id: 'flexible',  name: 'Flexible',  time: null },
];

const CONSULT_SLOT_DISPLAY = {
  morning:   'Morning (8:00am – 12:00pm)',
  afternoon: 'Afternoon (12:00pm – 5:00pm)',
  evening:   'Evening (5:00pm – 7:00pm)',
  flexible:  'Flexible',
};

// ── Suburb Autocomplete ───────────────────────────────────────────────────────
// Maps loads async (async defer script) — attach Autocomplete once ready.
// acRef guard (Cause 3/4): prevents double-init if effect re-runs.
// pollTimer (Cause 3): retries every 100ms if Maps not yet ready on Step 2 mount.
function SuburbAutocomplete({ suburb, setSuburb }) {
  const inputRef = useRefConsult(null);
  const acRef    = useRefConsult(null); // Autocomplete instance — set ONCE, never reset mid-session

  useEffectConsult(() => {
    if (!inputRef.current) return;
    if (acRef.current) return; // already initialised — guard against double-init

    let pollTimer = null;

    const tryAttach = () => {
      if (!inputRef.current || acRef.current) return;
      if (!window.google?.maps?.places?.Autocomplete) return; // Maps not ready yet

      const ac = new window.google.maps.places.Autocomplete(inputRef.current, {
        componentRestrictions: { country: 'au' },
        fields: ['address_components', 'name'],
        types: ['(regions)'],
      });
      acRef.current = ac;
      if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }

      ac.addListener('place_changed', () => {
        const place = ac.getPlace();
        if (!place) return;
        let loc = place.name || '';
        if (place.address_components) {
          for (const c of place.address_components) {
            if (c.types.includes('locality') || c.types.includes('sublocality_level_1')) {
              loc = c.long_name; break;
            }
          }
        }
        if (loc) setSuburb(loc);
      });
    };

    // Try immediately — works if Maps already finished loading
    tryAttach();

    // If Maps is still loading (async script), poll until available (max 5 s)
    if (!acRef.current) {
      let polls = 0;
      pollTimer = setInterval(() => {
        polls++;
        tryAttach();
        if (acRef.current || polls >= 50) { clearInterval(pollTimer); pollTimer = null; }
      }, 100);
    }

    return () => {
      if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
      if (acRef.current) {
        try { window.google?.maps?.event?.clearInstanceListeners(acRef.current); } catch (_) {}
        acRef.current = null;
      }
    };
  }, []);

  return (
    <input
      ref={inputRef}
      id="cn-suburb"
      className="big-field__input"
      type="text"
      defaultValue={suburb}
      placeholder="e.g. Burleigh Heads, South Brisbane…"
      autoComplete="off"
      onBlur={e => { if (e.target.value && !suburb) setSuburb(e.target.value); }}
    />
  );
}

// ── Main Component ────────────────────────────────────────────────────────────
function ConsultationBookingPage() {
  const [step,   setStep]   = useConsult(1);
  const [topics, setTopics] = useConsult([]);
  const [name,   setName]   = useConsult('');
  const [phone,  setPhone]  = useConsult('');
  const [email,  setEmail]  = useConsult('');
  const [suburb, setSuburb] = useConsult('');
  const [notes,  setNotes]  = useConsult(() => {
    try {
      const p = new URLSearchParams(window.location.search);
      return decodeURIComponent(p.get('notes') || '');
    } catch (_) { return ''; }
  });
  const [date,       setDate]       = useConsult('');
  const [slot,       setSlot]       = useConsult('');
  const [customTime, setCustomTime] = useConsult('');
  const [submitting, setSubmitting] = useConsult(false);
  const [submitErr,  setSubmitErr]  = useConsult('');
  const [submitted,  setSubmitted]  = useConsult(false);
  const [refId,      setRefId]      = useConsult('');

  const errs = useMemoConsult(() => {
    const e = {};
    if (step === 1) {
      if (!topics.length) e.topics = 'Pick at least one topic so we can match you with the right person.';
    } else if (step === 2) {
      if (!name.trim()) e.name = 'Please tell us your name.';
      const cp = phone.replace(/[\s\-\(\)\.]/g, '');
      if (!cp || !/^\d{10}$/.test(cp) || !cp.startsWith('04'))
        e.phone = 'Please enter a valid Australian mobile number starting with 04 — e.g. 0412 345 678';
      const em = email.trim();
      if (!em || /\s/.test(em) || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(em))
        e.email = 'Please enter a valid email address — e.g. yourname@gmail.com';
    } else if (step === 3) {
      if (!date && !customTime.trim())         e.date = 'Pick a date or type a time below.';
      if (date && !slot && !customTime.trim()) e.slot = 'Pick a time slot, or type your own.';
    }
    return e;
  }, [step, topics, name, phone, email, date, slot, customTime]);

  const toggleTopic = id =>
    setTopics(ts => ts.includes(id) ? ts.filter(x => x !== id) : [...ts, id]);

  const next = () => {
    if (Object.keys(errs).length) return;
    if (step === 3) { submit(); return; }
    setStep(s => Math.min(3, s + 1));
    setTimeout(() => window.scrollTo({ top: 0, behavior: 'smooth' }), 30);
  };
  const back = () => { setStep(s => Math.max(1, s - 1)); setSubmitErr(''); };

  const submit = async () => {
    setSubmitting(true);
    setSubmitErr('');

    const topicNames = topics
      .map(id => (CONSULT_TOPICS.find(t => t.id === id) || {}).name)
      .filter(Boolean).join(', ');
    const SLOT_TIME = { morning: '09:00', afternoon: '13:00', evening: '17:00', flexible: '09:00' };
    const today = new Date().toISOString().split('T')[0];
    const notesStr = [
      topicNames ? 'Topics: ' + topicNames : '',
      notes.trim(),
      customTime ? 'Preferred time: ' + customTime : '',
    ].filter(Boolean).join('\n');

    try {
      const consultRefId = window.vtGenerateRefId('CON');
      const jobId = await window.vtNextJobId();
      await window.vtInsertJob({
        id: jobId, reference_id: consultRefId, source: 'consultation',
        customer: name.trim(), phone: phone.trim(), email: email.trim(),
        service: 'Free Consultation', address: suburb.trim(), suburb: suburb.trim(),
        postcode: '', lat: 0, lng: 0,
        date: date || today, time: SLOT_TIME[slot] || '09:00',
        status: 'Pending', assigned_to: '',
        deposit_paid: false, deposit_amount: 0,
        stripe_payment_id: null, stripe_status: null,
        service_amount: 0, notes: notesStr, amount: 0, created: today,
      });

      const dateLabel = date
        ? new Date(date + 'T00:00:00').toLocaleDateString('en-AU',
            { day: 'numeric', month: 'long', year: 'numeric' })
        : 'Flexible';

      window.vtSendEmail({
        type: 'consult', refId: consultRefId,
        to: email.trim(), name: name.trim(), phone: phone.trim(),
        topics: topicNames, date: dateLabel,
        slot: CONSULT_SLOTS.find(s => s.id === slot)?.name || (customTime || 'Flexible'),
        suburb: suburb.trim(), notes: notes.trim(), customTime: customTime.trim(),
        submittedAt: new Date().toLocaleString('en-AU', { timeZone: 'Australia/Brisbane' }),
      }).catch(e => console.warn('[VT] Email error:', e.message));

      setRefId(consultRefId);
      setSubmitted(true);
      setTimeout(() => window.scrollTo({ top: 0, behavior: 'smooth' }), 30);
    } catch (err) {
      console.error('[VT] consult submit failed', err);
      setSubmitErr('Something went wrong — please try again or call us directly on 0449 991 572.');
    } finally {
      setSubmitting(false);
    }
  };

  // ── Submitted state ────────────────────────────────────────────────────────
  if (submitted) {
    return (
      <div className="success-card">
        <div className="success-card__icon"><Icon.Check/></div>
        <h2 className="success-card__title">Consultation <em>Booked!</em></h2>

        {refId && (
          <div style={{ margin: '18px 0', padding: '18px 24px', background: 'rgba(232,98,26,0.07)',
            borderRadius: '12px', border: '1.5px solid rgba(232,98,26,0.22)', textAlign: 'center' }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#E8621A', marginBottom: 8 }}>
              Your Reference Number
            </div>
            <div style={{ fontSize: 30, fontWeight: 800, color: '#E8621A', letterSpacing: '0.05em', fontFamily: 'monospace' }}>
              {refId}
            </div>
            <div style={{ fontSize: 12, color: 'rgba(10,10,10,0.4)', marginTop: 6 }}>
              Save this — we'll reference it when we call you
            </div>
          </div>
        )}

        <p className="success-card__sub">
          We will call you on <strong>{phone}</strong> at your preferred time to chat through your options.
        </p>
        <p className="success-card__sub" style={{ fontSize: 16, marginTop: -10 }}>
          This call is <strong>100% free</strong> — no payment has been taken, no obligation.
          A confirmation has been sent to <strong>{email}</strong>.
        </p>

        <a className="btn btn--primary btn--lg success-card__cta" href="index.html">
          Back to Home <Icon.Arrow/>
        </a>
        <p className="success-help">
          Need help now? 📞 <a href="tel:0449991572">+61 449 991 572</a>
        </p>
      </div>
    );
  }

  return (
    <>
      <div className="pg-stepper">
        <div className="pg-stepper__label">
          <span>Step <strong style={{color:'var(--ink)'}}>{step}</strong> <span className="of">of 3</span></span>
          <span className="name">— {CONSULT_STEP_NAMES[step - 1]}</span>
        </div>
        <div className="pg-stepper__bar">
          {[1,2,3].map(n => <span key={n} className={step === n ? 'active' : step > n ? 'done' : ''}/>)}
        </div>
      </div>

      <div className="flow">
        {step === 1 && <C_Step1 topics={topics} toggleTopic={toggleTopic} errs={errs}/>}
        {step === 2 && (
          <C_Step2
            name={name} setName={setName} phone={phone} setPhone={setPhone}
            email={email} setEmail={setEmail} suburb={suburb} setSuburb={setSuburb}
            notes={notes} setNotes={setNotes} errs={errs}
          />
        )}
        {step === 3 && (
          <C_Step3
            topics={topics} name={name} phone={phone} email={email} suburb={suburb}
            date={date} setDate={ds => { setDate(ds); setSlot(''); }}
            slot={slot} setSlot={setSlot}
            customTime={customTime} setCustomTime={setCustomTime}
            errs={errs} submitting={submitting} submitErr={submitErr} onSubmit={submit}
          />
        )}

        {step < 3 && (
          <div className="flow__actions">
            {step > 1
              ? <button className="flow__back" onClick={back}><Icon.ChevronL/> Back</button>
              : <span/>}
            <div className="spacer"/>
            <button className="btn btn--ink btn--lg" onClick={next}
              disabled={Object.keys(errs).length > 0}
              style={Object.keys(errs).length ? { opacity: 0.55, cursor: 'not-allowed' } : {}}>
              Continue <Icon.Arrow/>
            </button>
          </div>
        )}
        {step === 3 && (
          <div className="flow__actions" style={{justifyContent:'flex-start', marginTop:24, paddingTop:20}}>
            <button className="flow__back" onClick={back}><Icon.ChevronL/> Back</button>
          </div>
        )}
      </div>
    </>
  );
}

// ----- Step 1 -----
function C_Step1({ topics, toggleTopic, errs }) {
  return (
    <>
      <h2 className="flow__h">What's on your <em>mind?</em></h2>
      <p className="flow__intro">Pick whatever applies — we'll match you with the right person on our team.</p>
      <div className="flow__group">
        <span className="flow__label">What would you like to talk about? <span className="opt">(pick any)</span></span>
        <div className="svc-grid">
          {CONSULT_TOPICS.map(t => {
            const Ico    = Icon[t.icon];
            const active = topics.includes(t.id);
            return (
              <button type="button" key={t.id} className={'svc-pick' + (active ? ' active' : '')} onClick={() => toggleTopic(t.id)}>
                <div className="svc-pick__badge"><Ico/></div>
                <div className="svc-pick__body">
                  <p className="svc-pick__name">{t.name}</p>
                </div>
                <div className="svc-pick__check"><Icon.Check/></div>
              </button>
            );
          })}
        </div>
        {errs.topics && <span className="flow__err">{errs.topics}</span>}
      </div>
    </>
  );
}

// ----- Step 2 -----
function C_Step2({ name, setName, phone, setPhone, email, setEmail, suburb, setSuburb, notes, setNotes, errs }) {
  return (
    <>
      <h2 className="flow__h">Your <em>details</em>.</h2>
      <p className="flow__intro">We'll only use these to set up the call. No mailing lists.</p>

      <div className="big-field">
        <label className="big-field__label" htmlFor="cn-name">Full name</label>
        <input id="cn-name" className="big-field__input" type="text" value={name}
          onChange={e => setName(e.target.value)} placeholder="e.g. Margaret Wilson" autoComplete="name"/>
        {errs.name && <span className="flow__err">{errs.name}</span>}
      </div>

      <div className="big-field__row">
        <div className="big-field">
          <label className="big-field__label" htmlFor="cn-phone">Phone number</label>
          <input id="cn-phone" className="big-field__input" type="tel" value={phone}
            onChange={e => setPhone(e.target.value)} placeholder="04xxxxxxxx" autoComplete="tel"/>
          {errs.phone && <span className="flow__err">{errs.phone}</span>}
        </div>
        <div className="big-field">
          <label className="big-field__label" htmlFor="cn-email">Email address</label>
          <input id="cn-email" className="big-field__input" type="email" value={email}
            onChange={e => setEmail(e.target.value)} placeholder="e.g. yourname@email.com" autoComplete="email"/>
          {errs.email && <span className="flow__err">{errs.email}</span>}
        </div>
      </div>

      <div className="big-field">
        <label className="big-field__label" htmlFor="cn-suburb">Your suburb</label>
        <SuburbAutocomplete suburb={suburb} setSuburb={setSuburb}/>
      </div>

      <div className="big-field">
        <label className="big-field__label" htmlFor="cn-notes">Any extra notes <span className="opt">(optional)</span></label>
        <textarea id="cn-notes" className="big-field__textarea" value={notes}
          onChange={e => setNotes(e.target.value)}
          placeholder="e.g. My internet keeps dropping out, not sure if it's the modem or the provider"></textarea>
      </div>
    </>
  );
}

// ----- Step 3 — NO payment, shows free consultation card -----
function C_Step3({ topics, name, phone, email, suburb,
                   date, setDate, slot, setSlot, customTime, setCustomTime,
                   errs, submitting, submitErr, onSubmit }) {

  const topicNames = topics
    .map(id => (CONSULT_TOPICS.find(t => t.id === id) || {}).name)
    .filter(Boolean).join(', ');

  const dateLabel = date
    ? new Date(date + 'T00:00:00').toLocaleDateString('en-AU',
        { day: 'numeric', month: 'long', year: 'numeric' })
    : null;

  const slotLabel = customTime
    ? (slot ? CONSULT_SLOT_DISPLAY[slot] + ' · ' + customTime : customTime)
    : (slot ? CONSULT_SLOT_DISPLAY[slot] : null);

  return (
    <>
      <h2 className="flow__h">Almost <em>there!</em></h2>
      <p className="flow__intro">Pick a call time and we'll phone you for your free 30-minute consultation.</p>

      <div className="big-field">
        <label className="big-field__label">Preferred date</label>
        <InlineCalendar value={date} onChange={setDate}/>
        {errs.date && <span className="flow__err">{errs.date}</span>}
      </div>

      {date && (
        <div className="big-field">
          <label className="big-field__label">Preferred time slot</label>
          <TimeSlotCards slots={CONSULT_SLOTS} value={slot} onChange={setSlot} selectedDate={date}/>
          {errs.slot && <span className="flow__err">{errs.slot}</span>}
        </div>
      )}

      <div className="big-field">
        <label className="big-field__label" htmlFor="cn-custom">
          None of these work? Type your preferred time <span className="opt">(optional)</span>
        </label>
        <input id="cn-custom" className="big-field__input" type="text" value={customTime}
          onChange={e => setCustomTime(e.target.value)}
          placeholder="e.g. Tuesday after 3pm, or weekend mornings"/>
        <span className="big-field__help">We'll call you to confirm a time that suits.</span>
      </div>

      {/* Consultation summary */}
      <div className="pay4-summary">
        <div className="pay4-summary__head">
          <h3>Your consultation</h3>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--mute)' }}>Free call</span>
        </div>

        {topicNames && (
          <div className="summary-row">
            <span className="summary-label">Topics</span>
            <span className="summary-value">{topicNames}</span>
          </div>
        )}
        {name && (
          <div className="summary-row">
            <span className="summary-label">Name</span>
            <span className="summary-value">{name}</span>
          </div>
        )}
        {phone && (
          <div className="summary-row">
            <span className="summary-label">Phone</span>
            <span className="summary-value">{phone}</span>
          </div>
        )}
        {email && (
          <div className="summary-row">
            <span className="summary-label">Email</span>
            <span className="summary-value">{email}</span>
          </div>
        )}
        {suburb && (
          <div className="summary-row">
            <span className="summary-label">Suburb</span>
            <span className="summary-value">{suburb}</span>
          </div>
        )}
        {dateLabel && (
          <div className="summary-row">
            <span className="summary-label">Date</span>
            <span className="summary-value">{dateLabel}</span>
          </div>
        )}
        {slotLabel && (
          <div className="summary-row">
            <span className="summary-label">Time</span>
            <span className="summary-value">{slotLabel}</span>
          </div>
        )}
      </div>

      {/* Free consultation card */}
      <div className="consult-free-card">
        <p className="consult-free-card__head">📞 Free 30-Minute Consultation</p>
        <p className="consult-free-card__body">This consultation is completely free — no payment required, no obligation.</p>
        <p className="consult-free-card__body">One of our team will call you at your preferred time to understand your needs and explain how we can help. You only pay if you decide to go ahead.</p>
      </div>

      <div className="flow__submit-row">
        <button className="btn btn--ink btn--lg" onClick={onSubmit} disabled={submitting}
          style={submitting ? { opacity: 0.7, cursor: 'wait' } : {}}>
          <Icon.Phone/>
          {submitting ? 'Booking…' : 'Book My Free Call'} {!submitting && <Icon.Arrow/>}
        </button>
        <div className="flow__submit-foot">
          100% free — no card required. Prefer to call us directly? <a href="tel:0449991572">0449 991 572</a>
        </div>
        {submitErr && <span className="flow__err" style={{ marginTop: 4 }}>{submitErr}</span>}
      </div>
    </>
  );
}

Object.assign(window, { ConsultationBookingPage });
