/* global React, fmt$ */
/* American Dream Motors — lead form + modal system.
   Every CTA on the site funnels here → window.adm.submitLead(). */
const { useState, useEffect, useRef } = React;

const LEAD_INTENTS = {
  general: {
    tag: 'Contact the lot',
    title: <>Talk to a human.</>,
    sub: 'Tell us what you\u2019re after. We answer during open hours — usually within the hour.',
    cta: 'Send it',
    success: 'Got it. We\u2019ll get back to you within the hour during open hours.',
  },
  finance: {
    tag: 'Financing',
    title: <>Start your <em style={{ color: 'var(--accent)' }}>approval.</em></>,
    sub: 'No SSN in this first step. Send your name and phone, then the lot will call to finish the real application.',
    cta: 'Start my approval',
    success: 'Application started. We\u2019ll call to finish the next step during open hours.',
  },
  hold: {
    tag: 'Interested',
    title: <>Put your name <em style={{ color: 'var(--accent)' }}>on this one.</em></>,
    sub: 'Tell us which vehicle you want. We\u2019ll confirm availability and set up the next step.',
    cta: 'Send my info',
    success: 'Got it. We\u2019ll text or call to confirm availability.',
  },
  testdrive: {
    tag: 'Test drive',
    title: <>Pick a time, <em style={{ color: 'var(--accent)' }}>drive it.</em></>,
    sub: 'Take it on 81 and the back roads. Bring your mechanic if you want — we\u2019ll wait.',
    cta: 'Book my drive',
    success: 'You\u2019re booked. We\u2019ll text to confirm a time and have it pulled up front.',
  },
  trade: {
    tag: 'Trade-in',
    title: <>What\u2019s yours <em style={{ color: 'var(--accent)' }}>worth?</em></>,
    sub: 'Tell us what you\u2019re driving. We\u2019ll give you a real number — over the phone, no games.',
    cta: 'Get my number',
    success: 'On it. We\u2019ll call to talk through the trade details during open hours.',
  },
  report: {
    tag: 'Vehicle details',
    title: <>Ask for more <em style={{ color: 'var(--accent)' }}>details.</em></>,
    sub: 'Ask for photos, condition notes, vehicle history, or anything else you need before coming in.',
    cta: 'Send my request',
    success: 'Sent. Check your texts or inbox in the next few minutes.',
  },
};

const TIMEFRAMES = ['This week', 'This month', 'Just looking'];

function formatPhone(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)}`;
}

/* ============ SUCCESS STATE ============ */
function LeadSuccess({ intent }) {
  const copy = LEAD_INTENTS[intent] || LEAD_INTENTS.general;
  const cfg = window.ADM_LEAD_CONFIG || {};
  return (
    <div className="lf-success">
      <svg className="lf-check" viewBox="0 0 64 64" width="64" height="64" aria-hidden="true">
        <circle className="lf-check-ring" cx="32" cy="32" r="29" fill="none" stroke="var(--accent)" strokeWidth="2"></circle>
        <path className="lf-check-mark" d="M20 33 L28.5 41.5 L45 24" fill="none" stroke="var(--accent)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"></path>
      </svg>
      <div className="lf-success-t">You&apos;re in.</div>
      <p className="lf-success-d">{copy.success}</p>
      <a href={'tel:' + (cfg.phone || '540-450-5373')} className="btn btn-sm" style={{ marginTop: 6 }}>
        In a hurry? Call {cfg.phoneDisplay || '(540) 450-5373'}
      </a>
    </div>
  );
}

/* ============ LEAD FORM ============ */
function LeadForm({ intent = 'general', vehicle = null, onDone, compact = false, idPrefix = 'lf' }) {
  const copy = LEAD_INTENTS[intent] || LEAD_INTENTS.general;
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [email, setEmail] = useState('');
  const [message, setMessage] = useState('');
  const [timeframe, setTimeframe] = useState('');
  const [hp, setHp] = useState('');           // honeypot
  const [state, setState] = useState('idle'); // idle | sending | done
  const [errors, setErrors] = useState({});

  const vehicleLabel = vehicle ? `${vehicle.year} ${vehicle.make} ${vehicle.model} ${vehicle.trim}` : null;

  async function submit(e) {
    e.preventDefault();
    if (hp) return; // bot
    const errs = {};
    if (!name.trim()) errs.name = true;
    if (phone.replace(/\D/g, '').length < 10) errs.phone = true;
    setErrors(errs);
    if (Object.keys(errs).length) return;

    setState('sending');
    const payload = {
      intent,
      name: name.trim(),
      phone,
      email: email.trim(),
      message: message.trim(),
      timeframe,
      vehicleId: vehicle ? vehicle.id : null,
      vehicleLabel,
      vehicleStock: vehicle ? vehicle.stock : null,
      vehiclePrice: vehicle ? vehicle.price : null,
    };
    const started = Date.now();
    await window.adm.submitLead(payload);
    // small minimum so the transition reads as deliberate
    const wait = Math.max(0, 650 - (Date.now() - started));
    setTimeout(() => { setState('done'); onDone && onDone(payload); }, wait);
  }

  if (state === 'done') return <LeadSuccess intent={intent} />;

  return (
    <form className={'lf' + (compact ? ' lf-compact' : '')} onSubmit={submit} noValidate>
      {!compact && (
        <header className="lf-head">
          <span className="eyebrow">{copy.tag}</span>
          <h3 className="lf-title">{copy.title}</h3>
          <p className="lf-sub">{copy.sub}</p>
        </header>
      )}

      {vehicleLabel && (
        <div className="lf-vehicle">
          <span className="lf-vehicle-dot"></span>
          <span>{vehicleLabel}</span>
          <span className="lf-vehicle-price">{vehicle.price ? '$' + vehicle.price.toLocaleString() : ''}</span>
        </div>
      )}

      <div className="lf-grid">
        <label className={'lf-field' + (errors.name ? ' err' : '')}>
          <span className="lf-label">Name</span>
          <input className="lf-input" id={idPrefix + '-name'} autoComplete="name" placeholder="First and last"
            value={name} onChange={e => { setName(e.target.value); setErrors(s => ({ ...s, name: false })); }} />
        </label>
        <label className={'lf-field' + (errors.phone ? ' err' : '')}>
          <span className="lf-label">Phone</span>
          <input className="lf-input" id={idPrefix + '-phone'} type="tel" autoComplete="tel" inputMode="tel" placeholder="(540) 000-0000"
            value={phone} onChange={e => { setPhone(formatPhone(e.target.value)); setErrors(s => ({ ...s, phone: false })); }} />
        </label>
      </div>

      <label className="lf-field">
        <span className="lf-label">Email <em className="lf-opt">optional</em></span>
        <input className="lf-input" id={idPrefix + '-email'} type="email" autoComplete="email" placeholder="you@example.com"
          value={email} onChange={e => setEmail(e.target.value)} />
      </label>

      <div className="lf-field">
        <span className="lf-label">When are you buying?</span>
        <div className="lf-chips">
          {TIMEFRAMES.map(t => (
            <button type="button" key={t} className={'fchip' + (timeframe === t ? ' active' : '')}
              onClick={() => setTimeframe(timeframe === t ? '' : t)}>{t}</button>
          ))}
        </div>
      </div>

      {!compact && (
        <label className="lf-field">
          <span className="lf-label">Anything else <em className="lf-opt">optional</em></span>
          <textarea className="lf-input" rows="2" placeholder={intent === 'trade' ? 'Year, make, model, miles\u2026' : 'Budget, must-haves, questions\u2026'}
            value={message} onChange={e => setMessage(e.target.value)}></textarea>
        </label>
      )}

      {/* honeypot — hidden from humans */}
      <input className="lf-hp" tabIndex="-1" autoComplete="off" value={hp} onChange={e => setHp(e.target.value)} aria-hidden="true" />

      <button type="submit" className={'btn btn-primary btn-lg lf-submit' + (state === 'sending' ? ' sending' : '')} disabled={state === 'sending'}>
        {state === 'sending' ? <span className="lf-spinner" aria-hidden="true"></span> : null}
        {state === 'sending' ? 'Sending\u2026' : copy.cta}
        {state !== 'sending' && <span className="btn-arrow">→</span>}
      </button>
      <p className="lf-consent">No spam, no mailing lists. One call or text from a human at the lot.</p>
    </form>
  );
}

/* ============ GLOBAL LEAD MODAL ============ */
function LeadModalHost() {
  const [open, setOpen] = useState(false);
  const [intent, setIntent] = useState('general');
  const [vehicle, setVehicle] = useState(null);

  useEffect(() => {
    function onOpen(e) {
      setIntent((e.detail && e.detail.intent) || 'general');
      setVehicle((e.detail && e.detail.vehicle) || null);
      setOpen(true);
      if (window.dd) window.dd.track('lead_modal_open', { intent: (e.detail && e.detail.intent) || 'general' });
    }
    window.addEventListener('adm:open-lead', onOpen);
    return () => window.removeEventListener('adm:open-lead', onOpen);
  }, []);

  useEffect(() => {
    if (!open) return;
    function onKey(e) { if (e.key === 'Escape') setOpen(false); }
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [open]);

  if (!open) return null;
  return (
    <div className="modal-bg" onClick={e => { if (e.target === e.currentTarget) setOpen(false); }}>
      <div className="modal" style={{ maxWidth: 560 }} role="dialog" aria-modal="true">
        <button className="modal-close" onClick={() => setOpen(false)} aria-label="Close">×</button>
        <div className="modal-body">
          <LeadForm intent={intent} vehicle={vehicle} idPrefix="lm" />
        </div>
      </div>
    </div>
  );
}

window.openLead = function (intent, vehicle) {
  window.dispatchEvent(new CustomEvent('adm:open-lead', { detail: { intent, vehicle } }));
};

/* ============ LEADS LOG (local admin helper) ============ */
function LeadsLog() {
  const [leads, setLeads] = useState(() => (window.adm ? window.adm.leads() : []));
  useEffect(() => {
    if (!window.adm) return;
    return window.adm.subscribe(() => setLeads(window.adm.leads()));
  }, []);
  const endpoint = (window.ADM_LEAD_CONFIG || {}).endpoint;
  return (
    <div>
      <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.12em', color: endpoint ? '#7fa67c' : 'var(--accent-pop)', fontWeight: 600, marginBottom: 8 }}>
        {endpoint ? '● DELIVERING TO ENDPOINT' : '○ LOCAL ONLY — SET ENDPOINT IN leads.js'}
      </div>
      <div style={{ maxHeight: 180, overflowY: 'auto', fontFamily: 'var(--mono)', fontSize: 10, lineHeight: 1.5 }}>
        {leads.length === 0 && <div style={{ color: 'var(--fg-dim)', padding: 4 }}>No leads yet</div>}
        {leads.slice().reverse().map(l => (
          <div key={l.id} style={{ padding: '5px 0', borderTop: '1px solid var(--line)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
              <span style={{ color: 'var(--accent)', fontWeight: 600 }}>{l.intent}</span>
              <span style={{ color: 'var(--fg-dim)' }}>{new Date(l.ts).toLocaleTimeString()}</span>
            </div>
            <div style={{ color: 'var(--fg-mute)' }}>{l.name} · {l.phone}{l.vehicleLabel ? ' · ' + l.vehicleLabel : ''}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { LeadForm, LeadModalHost, LeadSuccess, LeadsLog, LEAD_INTENTS });
