/* global React */
/* American Dream Motors — one-click quick capture widgets.
   Built for a 2-minute attention window: phone number + one tap. */
const { useState, useMemo } = React;

const QP_CFG = window.ADM_LEAD_CONFIG || {};

function qpFormatPhone(raw) {
  const d = raw.replace(/\D/g, '').slice(0, 10);
  if (d.length < 4) return d;
  if (d.length < 7) return `(${d.slice(0, 3)}) ${d.slice(3)}`;
  return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}`;
}

/* Next 4 open time slots from lot hours: Mon–Sat 10–6, Sun closed */
function nextSlots() {
  const out = [];
  const now = new Date();
  let d = new Date(now);
  const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  for (let i = 0; i < 10 && out.length < 4; i++) {
    const dow = d.getDay();
    const close = dow === 0 ? 0 : 18;
    const hours = dow === 0 ? [] : [10, 12, 15, 17].filter(h => h < close);
    for (const h of hours) {
      if (out.length >= 4) break;
      const slot = new Date(d); slot.setHours(h, 0, 0, 0);
      if (slot.getTime() < now.getTime() + 90 * 60000) continue;
      const isToday = slot.toDateString() === now.toDateString();
      const tom = new Date(now); tom.setDate(now.getDate() + 1);
      const isTom = slot.toDateString() === tom.toDateString();
      const day = isToday ? 'Today' : isTom ? 'Tomorrow' : dayNames[dow];
      const hr = h >= 12 ? (h === 12 ? 'Noon' : (h - 12) + ' PM') : h + ' AM';
      out.push({ label: `${day} ${hr}`, iso: slot.toISOString() });
    }
    d.setDate(d.getDate() + 1);
    d.setHours(0, 0, 0, 0);
  }
  return out;
}

/* ============ ONE-FIELD PHONE CAPTURE ============ */
function QuickPhone({ intent = 'general', vehicle = null, cta = 'Text me about this one', placeholder = 'Your phone number' }) {
  const [phone, setPhone] = useState('');
  const [state, setState] = useState('idle');
  const valid = phone.replace(/\D/g, '').length >= 10;

  async function go(e) {
    e.preventDefault();
    if (!valid || state !== 'idle') return;
    setState('sending');
    await window.adm.submitLead({
      intent, phone, name: '', channel: 'quick-phone',
      vehicleId: vehicle ? vehicle.id : null,
      vehicleLabel: vehicle ? `${vehicle.year} ${vehicle.make} ${vehicle.model} ${vehicle.trim}` : null,
      vehicleStock: vehicle ? vehicle.stock : null,
    });
    setTimeout(() => setState('done'), 500);
  }

  if (state === 'done') {
    return (
      <div className="qp qp-done">
        <span className="qp-check">✓</span>
        <span>Done — we&apos;ll text you shortly.</span>
      </div>
    );
  }
  return (
    <form className="qp" onSubmit={go}>
      <input className="qp-input" type="tel" inputMode="tel" autoComplete="tel" placeholder={placeholder}
        value={phone} onChange={e => setPhone(qpFormatPhone(e.target.value))} />
      <button type="submit" className={'btn btn-primary qp-btn' + (valid ? '' : ' qp-off')} disabled={state === 'sending'}>
        {state === 'sending' ? '…' : cta}
      </button>
    </form>
  );
}

/* ============ TAP-A-SLOT TEST DRIVE ============ */
function TestDriveQuick({ vehicle }) {
  const slots = useMemo(nextSlots, []);
  const [slot, setSlot] = useState(null);
  const [phone, setPhone] = useState('');
  const [state, setState] = useState('idle');
  const valid = slot && phone.replace(/\D/g, '').length >= 10;

  async function go(e) {
    e.preventDefault();
    if (!valid || state !== 'idle') return;
    setState('sending');
    await window.adm.submitLead({
      intent: 'testdrive', phone, name: '', channel: 'quick-slot',
      slot: slot.label, slotIso: slot.iso,
      vehicleId: vehicle ? vehicle.id : null,
      vehicleLabel: vehicle ? `${vehicle.year} ${vehicle.make} ${vehicle.model} ${vehicle.trim}` : null,
      vehicleStock: vehicle ? vehicle.stock : null,
    });
    setTimeout(() => setState('done'), 500);
  }

  if (state === 'done') {
    return (
      <div className="tdq">
        <div className="qp qp-done" style={{ border: 0, padding: '6px 0' }}>
          <span className="qp-check">✓</span>
          <div>
            <div style={{ fontFamily: 'var(--display)', fontSize: 19 }}>{slot.label} — it&apos;s yours.</div>
            <div className="tdq-sub">We&apos;ll text to confirm and have it pulled up front, keys on the dash.</div>
          </div>
        </div>
      </div>
    );
  }
  return (
    <form className="tdq" onSubmit={go}>
      <div className="tdq-head">
        <span className="tdq-t">Drive it — pick a time</span>
        <span className="tdq-sub">2 taps · no account · free</span>
      </div>
      <div className="tdq-slots">
        {slots.map(s => (
          <button type="button" key={s.iso} className={'tdq-slot' + (slot && slot.iso === s.iso ? ' active' : '')}
            onClick={() => { setSlot(s); window.dd && window.dd.track('slot_pick', { slot: s.label }); }}>
            {s.label}
          </button>
        ))}
      </div>
      <div className="qp" style={{ border: 0, padding: 0 }}>
        <input className="qp-input" type="tel" inputMode="tel" autoComplete="tel" placeholder="Phone — we text you the confirmation"
          value={phone} onChange={e => setPhone(qpFormatPhone(e.target.value))} />
        <button type="submit" className={'btn btn-primary qp-btn' + (valid ? '' : ' qp-off')} disabled={state === 'sending'}>
          {state === 'sending' ? '…' : 'Book it →'}
        </button>
      </div>
    </form>
  );
}

/* ============ ONE-TAP ACTION ROW ============ */
function QuickActions({ vehicle }) {
  const phone = QP_CFG.phone || '540-450-5373';
  const items = [
    { l: 'Call', d: 'Rings the lot', href: 'tel:' + phone, ic: '☎' },
    { l: 'Text', d: 'The lot replies', href: 'sms:' + phone + (vehicle ? '?body=' + encodeURIComponent(`Hi — asking about the ${vehicle.year} ${vehicle.make} ${vehicle.model}, stock ${vehicle.stock}.`) : ''), ic: '💬' },
    { l: 'Directions', d: '691 N. Loudoun St', href: 'https://maps.google.com/?q=691+N+Loudoun+St,+Winchester,+VA+22601', blank: true, ic: '➤' },
    { l: 'I want it', d: 'Send your info', onClick: () => window.openLead && window.openLead('hold', vehicle), ic: '✋' },
  ];
  return (
    <div className="qa-row">
      {items.map(a => (
        <a key={a.l} className="qa" href={a.href} target={a.blank ? '_blank' : undefined} rel={a.blank ? 'noopener noreferrer' : undefined}
          onClick={() => { a.onClick && a.onClick(); window.dd && window.dd.track('quick_action', { action: a.l, id: vehicle && vehicle.id }); }}
          role={a.href ? undefined : 'button'}>
          <span className="qa-l">{a.l}</span>
          <span className="qa-d">{a.d}</span>
        </a>
      ))}
    </div>
  );
}

Object.assign(window, { QuickPhone, TestDriveQuick, QuickActions, nextSlots });
