// Guided "Get started" page — one yes/no question per screen, booking last.
// URL: #/start (choose), #/start/vehicle, #/start/property, #/start/transporter
// Globals: React, Icon. Opens chat via window event 'jmac:open-chat'.

const START_UI = {
  en: {
    hello: 'How can we help you today?',
    helloSub: 'Choose one and we’ll walk you through it.',
    yes: 'Yes', no: 'No', back: 'Back', startOver: 'Start over',
    other: 'Something else?', chat: 'Chat with our AI agent',
    stepOf: (a, b) => `Step ${a} of ${b}`,
    nextTitle: 'After you book',
    howTitle: 'How to book',
    onPage: 'On the booking page',
    tipVin: 'Tip: if the vehicle info that comes up is wrong, try the full 17-digit VIN.',
    newTab: 'Opens our booking page in a new tab.',
    openAgain: 'Open booking page again', home: 'Back to home',
    bring: 'Bring to your appointment',
    question: 'Have a question?',
  },
  es: {
    hello: '¿Cómo podemos ayudarle hoy?',
    helloSub: 'Elija una opción y le guiaremos paso a paso.',
    yes: 'Sí', no: 'No', back: 'Atrás', startOver: 'Empezar de nuevo',
    other: '¿Algo más?', chat: 'Chatee con nuestro agente de IA',
    stepOf: (a, b) => `Paso ${a} de ${b}`,
    nextTitle: 'Después de reservar',
    howTitle: 'Cómo reservar',
    onPage: 'En la página de reservas',
    tipVin: 'Consejo: si la información del vehículo que aparece es incorrecta, use el VIN completo de 17 dígitos.',
    newTab: 'Abre nuestra página de reservas en una nueva pestaña.',
    openAgain: 'Abrir la página de reservas otra vez', home: 'Volver al inicio',
    bring: 'Traiga a su cita',
    question: '¿Tiene una pregunta?',
  },
};

const START_PATHS = {
  vehicle: {
    icon: 'car', accent: 'var(--amber-400)',
    en: { title: 'Get my car back', sub: 'Make a vehicle redemption appointment' },
    es: { title: 'Recuperar mi vehículo', sub: 'Hacer una cita de redención' },
  },
  property: {
    icon: 'key', accent: '#5AA9FF',
    en: { title: 'Get my belongings', sub: 'Pick up personal items from my vehicle' },
    es: { title: 'Recuperar mis pertenencias', sub: 'Retirar artículos personales de mi vehículo' },
  },
  transporter: {
    icon: 'truck', accent: '#E4E8EE',
    en: { title: 'I’m a transporter', sub: 'Schedule a vehicle pickup' },
    es: { title: 'Soy transportista', sub: 'Programar la recogida de un vehículo' },
  },
};

// ---- Flow content --------------------------------------------------------
// q = yes/no question, stop = "no" answer screen, ready = book screen, done = after booking
const LOAN_Q = (id, nextId, n) => ({
  [id]: { type: 'q', n, yes: nextId, no: id + 'b',
    en: { q: 'Are you the person listed on the loan?', help: 'We can only release to the person on the loan, or someone the lien holder has authorized.' },
    es: { q: '¿Es usted la persona que aparece en el préstamo?', help: 'Solo podemos entregar a la persona del préstamo, o a alguien autorizado por el acreedor prendario.' } },
  [id + 'b']: { type: 'q', n, yes: nextId, no: id + 'x',
    en: { q: 'Do you have authorization from the lien holder to pick up for the person on the loan?' },
    es: { q: '¿Tiene autorización del acreedor prendario para recoger en nombre de la persona del préstamo?' } },
  [id + 'x']: { type: 'stop', n, cont: nextId,
    en: { h: 'Authorization is required', p: 'The person on the loan needs to contact their lien holder and have you authorized. Once you’re authorized, you’ll book the appointment yourself.', cont: 'I have authorization' },
    es: { h: 'Se requiere autorización', p: 'La persona del préstamo debe comunicarse con su acreedor prendario para autorizarle. Una vez autorizado, usted mismo debe reservar la cita.', cont: 'Tengo autorización' } },
});

const ID_Q = (id, nextId, n) => ({
  [id]: { type: 'q', n, yes: nextId, no: id + 'x',
    en: { q: 'Do you have a valid photo ID?', help: 'A driver’s license or government-issued ID.' },
    es: { q: '¿Tiene una identificación con foto válida?', help: 'Licencia de conducir o identificación gubernamental.' } },
  [id + 'x']: { type: 'stop', n, cont: nextId,
    en: { h: 'You’ll need a photo ID', p: 'We can’t release anything without a valid photo ID. Please bring a driver’s license or government-issued ID to your appointment.', cont: 'I’ll have my ID' },
    es: { h: 'Necesitará una identificación con foto', p: 'No podemos entregar nada sin una identificación con foto válida. Traiga su licencia de conducir o identificación gubernamental a su cita.', cont: 'Tendré mi identificación' } },
});

const CASH_Q = (id, nextId, n) => ({
  [id]: { type: 'q', n, yes: nextId, no: id + 'x',
    en: { q: 'Can you bring cash in exact change?', help: 'All JMAC locations are cash only. Your fees will be in your confirmation email.' },
    es: { q: '¿Puede traer efectivo con cambio exacto?', help: 'Todas las ubicaciones de JMAC aceptan solo efectivo. Sus cargos estarán en su correo de confirmación.' } },
  [id + 'x']: { type: 'stop', n, cont: nextId,
    en: { h: 'We accept cash only', p: 'All JMAC locations are cash only, and we ask that you bring exact change. Your fees will be listed in your confirmation email.', cont: 'OK, I’ll bring cash' },
    es: { h: 'Solo aceptamos efectivo', p: 'Todas las ubicaciones de JMAC aceptan solo efectivo, y le pedimos que traiga cambio exacto. Sus cargos estarán en su correo de confirmación.', cont: 'De acuerdo, traeré efectivo' } },
});

const START_FLOWS = {
  vehicle: {
    total: 5, first: 'lien',
    nodes: {
      lien: { type: 'q', n: 1, yes: 'loan', no: 'lienx',
        en: { q: 'Have you spoken to your lien holder and cleared up matters with them?', help: 'Your lien holder has to authorize the release before your appointment can be confirmed.' },
        es: { q: '¿Ha hablado con su acreedor prendario y resuelto los asuntos con ellos?', help: 'Su acreedor prendario debe autorizar la liberación antes de que se confirme su cita.' } },
      lienx: { type: 'stop', n: 1, cont: 'loan',
        en: { h: 'Please call your lien holder first', p: 'Your lien holder needs to authorize the release of your vehicle. Call them, clear things up, and ask them to send JMAC the release paperwork. Then come back here to book.', cont: 'I’ve spoken to them' },
        es: { h: 'Primero llame a su acreedor prendario', p: 'Su acreedor prendario debe autorizar la liberación de su vehículo. Llámelos, resuelva los asuntos y pídales que envíen a JMAC la documentación de liberación. Luego regrese aquí para reservar.', cont: 'Ya hablé con ellos' } },
      ...LOAN_Q('loan', 'id', 2),
      ...ID_Q('id', 'cash', 3),
      ...CASH_Q('cash', 'ready', 4),
      ready: { type: 'ready', n: 5, appt: 'Vehicle Redemption',
        en: { h: 'You’re ready to book', book: 'Book my appointment', steps: [
          'Appointments are processed in the order they are received. Some may take 1 to 3 hours to be confirmed.',
          'Your appointment is confirmed once we receive release paperwork from your lien holder.',
          'Your confirmation will include all fees and the location.'] },
        es: { h: 'Está listo para reservar', book: 'Reservar mi cita', steps: [
          'Las citas se procesan en el orden en que se reciben. Algunas pueden tardar de 1 a 3 horas en confirmarse.',
          'Su cita se confirma cuando recibimos la documentación de liberación de su acreedor prendario.',
          'Su confirmación incluirá todos los cargos y la ubicación.'] } },
      done: { type: 'done', n: 5,
        en: { h: 'Finish booking in the new tab', p: 'Once you book, watch your email. Your confirmation will include all fees and the location.', bring: ['Your confirmation email', 'A valid photo ID', 'Cash in exact change'] },
        es: { h: 'Termine de reservar en la nueva pestaña', p: 'Después de reservar, revise su correo. Su confirmación incluirá todos los cargos y la ubicación.', bring: ['Su correo de confirmación', 'Una identificación con foto válida', 'Efectivo con cambio exacto'] } },
    },
  },
  property: {
    total: 5, first: 'loan',
    nodes: {
      ...LOAN_Q('loan', 'id', 1),
      ...ID_Q('id', 'keys', 2),
      keys: { type: 'q', n: 3, yes: 'cash', no: 'keysx',
        en: { q: 'Will you bring your keys?', help: 'Bringing your keys avoids extra charges from your lender.' },
        es: { q: '¿Traerá sus llaves?', help: 'Traer sus llaves evita cargos adicionales de su prestamista.' } },
      keysx: { type: 'stop', n: 3, cont: 'cash',
        en: { h: 'You can still book', p: 'If you don’t bring your keys, your lender may add extra charges. Bring them if you can.', cont: 'Continue' },
        es: { h: 'Aún puede reservar', p: 'Si no trae sus llaves, su prestamista puede agregar cargos adicionales. Tráigalas si puede.', cont: 'Continuar' } },
      ...CASH_Q('cash', 'ready', 4),
      ready: { type: 'ready', n: 5, appt: 'Property Redemption',
        en: { h: 'You’re ready to book', book: 'Book my appointment', steps: [
          'Appointments are processed in the order they are received. Some may take 1 to 3 hours to be confirmed.',
          'Your confirmation will include all fees and the location.'] },
        es: { h: 'Está listo para reservar', book: 'Reservar mi cita', steps: [
          'Las citas se procesan en el orden en que se reciben. Algunas pueden tardar de 1 a 3 horas en confirmarse.',
          'Su confirmación incluirá todos los cargos y la ubicación.'] } },
      done: { type: 'done', n: 5,
        en: { h: 'Finish booking in the new tab', p: 'Once you book, watch your email. Your confirmation will include all fees and the location.', bring: ['Your confirmation email', 'A valid photo ID', 'Your keys', 'Cash in exact change'] },
        es: { h: 'Termine de reservar en la nueva pestaña', p: 'Después de reservar, revise su correo. Su confirmación incluirá todos los cargos y la ubicación.', bring: ['Su correo de confirmación', 'Una identificación con foto válida', 'Sus llaves', 'Efectivo con cambio exacto'] } },
    },
  },
  transporter: {
    total: 3, first: 'company',
    nodes: {
      company: { type: 'q', n: 1, yes: 'coi', no: 'companyx',
        en: { q: 'Is your company the one physically picking up the vehicle?', help: 'The company that physically picks up the unit must be the one that schedules the appointment.' },
        es: { q: '¿Es su empresa la que recogerá físicamente el vehículo?', help: 'La empresa que recoge físicamente la unidad debe ser la que programe la cita.' } },
      companyx: { type: 'stop', n: 1, cont: 'coi',
        en: { h: 'The pickup company must book', p: 'Whoever is physically picking up the vehicle has to schedule the appointment. Please have the company doing the pickup book it directly.', cont: 'We’re doing the pickup' },
        es: { h: 'La empresa que recoge debe reservar', p: 'Quien recoja físicamente el vehículo debe programar la cita. Pida a la empresa que hará la recogida que la reserve directamente.', cont: 'Nosotros haremos la recogida' } },
      coi: { type: 'q', n: 2, yes: 'ready', no: 'coix',
        en: { q: 'Does JMAC have your COI on file?', help: 'We need a valid certificate of insurance (COI) listing JMAC Asset Recovery on file before the appointment can be made.' },
        es: { q: '¿Tiene JMAC su COI en archivo?', help: 'Necesitamos un certificado de seguro (COI) válido que mencione a JMAC Asset Recovery en archivo antes de poder hacer la cita.' } },
      coix: { type: 'stop', n: 2, cont: 'ready', email: 'transports@jmacrepo.com',
        en: { h: 'Send us your COI first', p: 'Email a copy of your COI listing JMAC Asset Recovery to transports@jmacrepo.com. Once it’s on file, you can book your appointment.', cont: 'I’ve sent our COI', emailBtn: 'Email our COI' },
        es: { h: 'Primero envíenos su COI', p: 'Envíe por correo una copia de su COI que mencione a JMAC Asset Recovery a transports@jmacrepo.com. Una vez en archivo, puede reservar su cita.', cont: 'Ya enviamos nuestro COI', emailBtn: 'Enviar nuestro COI' } },
      ready: { type: 'ready', n: 3, appt: 'Transport Pickup',
        en: { h: 'Schedule your pickup', book: 'Book my pickup', steps: [
          'Appointments are processed in the order they are received. Some may take 1 to 3 hours to be confirmed.',
          'Your confirmation will include the yard address and phone number.'] },
        es: { h: 'Programe su recogida', book: 'Reservar mi recogida', steps: [
          'Las citas se procesan en el orden en que se reciben. Algunas pueden tardar de 1 a 3 horas en confirmarse.',
          'Su confirmación incluirá la dirección del lote y el número de teléfono.'] } },
      done: { type: 'done', n: 3,
        en: { h: 'Finish booking in the new tab', p: 'Once you book, watch your email. Your confirmation will include the yard address and phone number.', bring: ['Your confirmation email', 'The VIN of the unit you’re picking up'] },
        es: { h: 'Termine de reservar en la nueva pestaña', p: 'Después de reservar, revise su correo. Su confirmación incluirá la dirección del lote y el número de teléfono.', bring: ['Su correo de confirmación', 'El VIN de la unidad que recogerá'] } },
    },
  },
};

// ---- Shared bits ---------------------------------------------------------
const startOpenChat = () => window.dispatchEvent(new CustomEvent('jmac:open-chat'));
const startPathFromHash = () => {
  const parts = window.location.hash.replace(/^#\/?/, '').split('/');
  return parts[0] === 'start' && START_PATHS[parts[1]] ? parts[1] : null;
};

const START_CSS = `
  .jmac-start { background: var(--bg-page); min-height: calc(100vh - 68px); padding: 28px 16px 120px; }
  .jmac-start-wrap { max-width: 560px; margin: 0 auto; }
  .jmac-start-card { background: #141922; border: 1.5px solid #2c3a52; border-radius: 12px; box-shadow: var(--shadow-2); padding: 28px 22px; }
  .jmac-start h1, .jmac-start h2 { font-family: var(--font-body); font-weight: 800; color: var(--fg-1); margin: 0;
    letter-spacing: -0.015em; text-transform: none; font-style: normal; font-stretch: 100%; }
  .jmac-start h1 { font-size: clamp(30px, 7.6vw, 40px); line-height: 1.12; }
  .jmac-start h2 { font-size: clamp(24px, 6.4vw, 30px); line-height: 1.22; }
  .jmac-start p { font-size: 19px; font-weight: 500; line-height: 1.55; color: #EEF1F5; margin: 14px 0 0; }
  @media (max-width: 420px) { .jmac-start p { font-size: 18px; } }
  .jmac-start-btn { display: flex; align-items: center; justify-content: center; gap: 10px; width: 100%;
    min-height: 60px; padding: 14px 18px; border-radius: 10px; font-family: var(--font-body);
    font-size: 19px; font-weight: 800; cursor: pointer; border: 2px solid transparent; text-align: center; }
  .jmac-start-btn.yes { background: var(--blue-700); color: #fff; }
  .jmac-start-btn.yes:hover { background: var(--blue-800); }
  .jmac-start-btn.no { background: var(--bg-subtle); color: var(--fg-1); border-color: var(--border-2); }
  .jmac-start-btn.no:hover { border-color: var(--steel-500); }
  .jmac-start-btn.book { background: var(--amber-400); color: #fff; border-color: var(--amber-500); font-size: 20px; min-height: 66px; }
  .jmac-start-btn.book:hover { background: var(--amber-300); }
  .jmac-start-btn:focus-visible, .jmac-start-link:focus-visible, .jmac-start-path:focus-visible { outline: none; box-shadow: var(--shadow-focus); }
  .jmac-start-btns { display: grid; gap: 12px; margin-top: 26px; }
  .jmac-start-link { background: none; border: 0; padding: 8px 0; cursor: pointer; font-family: var(--font-body);
    font-size: 16px; font-weight: 700; color: var(--blue-600); display: inline-flex; align-items: center; gap: 6px; }
  .jmac-start-path { display: flex; align-items: center; gap: 18px; width: 100%; min-height: 96px; text-align: left; cursor: pointer;
    background: linear-gradient(180deg, #19202c 0%, #11161f 100%); border: 1.5px solid #34435c; border-left: 6px solid var(--mk-blue);
    border-radius: 14px; padding: 18px 18px 18px 16px; font-family: var(--font-body); color: #fff;
    box-shadow: 0 6px 20px rgba(0,0,0,.55); transition: border-color 160ms, box-shadow 160ms, transform 120ms; }
  .jmac-start-path:hover { border-color: var(--mk-blue-hi); border-left-color: var(--mk-blue-hi);
    box-shadow: 0 0 0 1px rgba(90,169,255,.45), 0 0 28px rgba(22,115,255,.30); transform: translateY(-1px); }
  .jmac-start-path-icon { width: 56px; height: 56px; border-radius: 12px; flex-shrink: 0; display: grid; place-items: center;
    background: linear-gradient(180deg, #2a88ff 0%, #1673FF 50%, #0A4FD6 100%); box-shadow: 0 0 18px rgba(22,115,255,.35); }
  .jmac-start-path-title { display: block; font-size: 22px; font-weight: 800; line-height: 1.2; color: #fff; }
  .jmac-start-path-sub { display: block; font-size: 17px; font-weight: 500; line-height: 1.4; color: #D6DBE2; margin-top: 4px; }
  .jmac-start-path-go { width: 40px; height: 40px; border-radius: 50%; flex-shrink: 0; display: grid; place-items: center;
    border: 1.5px solid #3d4d68; }
  .jmac-start-path:hover .jmac-start-path-go { background: var(--mk-blue); border-color: var(--mk-blue); }
  @media (max-width: 420px) {
    .jmac-start-path { gap: 14px; padding: 16px 14px 16px 12px; }
    .jmac-start-path-icon { width: 50px; height: 50px; }
    .jmac-start-path-title { font-size: 20px; }
    .jmac-start-path-go { display: none; }
  }
  .jmac-start-list { list-style: none; padding: 0; margin: 14px 0 0; display: grid; gap: 14px; }
  .jmac-start-list li { display: flex; gap: 12px; align-items: flex-start; font-size: 18px; font-weight: 500; line-height: 1.5; color: #EEF1F5; }
  .jmac-chip { display: inline-block; padding: 2px 10px; margin: 2px 0; border-radius: 6px; font-weight: 800;
    background: #0f1a2e; border: 1.5px solid var(--mk-blue-hi); color: #fff; white-space: nowrap; }
  .jmac-chip.orange { background: #f07a2b; border-color: #f07a2b; color: #fff; }
  .jmac-start-sec { margin-top: 22px; font-size: 18px; font-weight: 800; color: #fff; }
  .jmac-start-tip { margin-top: 12px; padding: 12px 14px; border-radius: 10px; background: #0f1a2e;
    border: 1px solid #1d3a66; font-size: 16px; line-height: 1.45; color: #EEF1F5; }
  .jmac-start-num { width: 28px; height: 28px; border-radius: 50%; background: var(--blue-700); color: #fff;
    display: grid; place-items: center; font-weight: 800; font-size: 14px; flex-shrink: 0; margin-top: 1px; }
  @media (prefers-reduced-motion: no-preference) {
    .jmac-start-card { animation: jmacStartIn 220ms cubic-bezier(.2,.7,.2,1); }
    @keyframes jmacStartIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
  }
`;

const StartPathButton = ({ id, lang, onClick }) => {
  const p = START_PATHS[id]; const L = p[lang] || p.en;
  return (
    <button className="jmac-start-path" style={{ '--accent': p.accent }} onClick={onClick}>
      <span className="jmac-start-path-icon"><Icon name={p.icon} size={28} color="#fff" strokeWidth={2}/></span>
      <span style={{ flex: 1 }}>
        <span className="jmac-start-path-title">{L.title}</span>
        <span className="jmac-start-path-sub">{L.sub}</span>
      </span>
      <span className="jmac-start-path-go"><Icon name="arrow" size={20} color="#fff"/></span>
    </button>
  );
};


// Step-by-step instructions for the outside booking page (ClearData scheduler).
const HowToBook = ({ lang, appt, onBookingPage }) => {
  const es = lang === 'es';
  const transport = appt === 'Transport Pickup';
  const Chip = ({ children, orange }) => (
    <span className={'jmac-chip' + (orange ? ' orange' : '')}>{children}</span>
  );
  const items = es ? [
    <>Toque <b>{transport ? 'Reservar mi recogida' : 'Reservar mi cita'}</b> abajo. La página de reservas se abre en una nueva pestaña.</>,
    <>En <b>Appointment Type</b>, abra el menú y elija <Chip>{appt}</Chip></>,
    <>Escriba los <b>últimos 6 dígitos del VIN</b> y toque el botón naranja <Chip orange>VIN Check</Chip></>,
    <>Confirme sus datos e ingrese su <b>correo y teléfono</b>.{transport && <> Escriba también el <b>nombre de su empresa</b>.</>}</>,
    <>Elija cómo quiere recibir su confirmación: <b>texto, correo o llamada</b>.</>,
    <>Elija una <b>fecha y hora</b>. No hay citas para el mismo día.</>,
    <>Revise los detalles y <b>confirme su cita</b>.</>,
  ] : [
    <>Tap <b>{transport ? 'Book my pickup' : 'Book my appointment'}</b> below. Our booking page opens in a new tab.</>,
    <>Under <b>Appointment Type</b>, open the menu and choose <Chip>{appt}</Chip></>,
    <>Enter the <b>last 6 digits of the VIN</b>, then tap the orange <Chip orange>VIN Check</Chip> button.</>,
    <>Confirm your info and enter your <b>email and phone number</b>.{transport && <> Enter your <b>company name</b> too.</>}</>,
    <>Choose how you’d like to get your confirmation: <b>text, email or call</b>.</>,
    <>Pick a <b>date and time</b>. Same-day appointments are not available.</>,
    <>Review the details and <b>book your appointment</b>.</>,
  ];
  return (
    <ol className="jmac-start-list">
      {(onBookingPage ? items.slice(1) : items).map((it, i) => (
        <li key={i}><span className="jmac-start-num">{i + 1}</span><span>{it}</span></li>
      ))}
    </ol>
  );
};

// ---- Page ----------------------------------------------------------------
const StartPage = ({ lang, onNav, onBook }) => {
  const L = lang === 'es' ? 'es' : 'en';
  const ui = START_UI[L];
  const [path, setPath] = React.useState(startPathFromHash);
  const [trail, setTrail] = React.useState(() => {
    const p = startPathFromHash(); return p ? [START_FLOWS[p].first] : [];
  });

  // Follow the URL (browser back/forward, links from the home page).
  React.useEffect(() => {
    const sync = () => {
      const p = startPathFromHash();
      setPath(p); setTrail(p ? [START_FLOWS[p].first] : []);
    };
    window.addEventListener('popstate', sync);
    window.addEventListener('hashchange', sync);
    return () => { window.removeEventListener('popstate', sync); window.removeEventListener('hashchange', sync); };
  }, []);

  const top = () => window.scrollTo({ top: 0, behavior: 'instant' });
  const choose = (id) => {
    window.history.pushState({ page: 'start' }, '', `#/start/${id}`);
    setPath(id); setTrail([START_FLOWS[id].first]); top();
  };
  const goTo = (nodeId) => { setTrail(t => [...t, nodeId]); top(); };
  const back = () => {
    if (trail.length > 1) { setTrail(t => t.slice(0, -1)); top(); }
    else { window.history.pushState({ page: 'start' }, '', '#/start'); setPath(null); setTrail([]); top(); }
  };
  const restart = () => { window.history.pushState({ page: 'start' }, '', '#/start'); setPath(null); setTrail([]); top(); };
  const book = () => { onBook && onBook(); goTo('done'); };

  const chatLine = (
    <div style={{ textAlign: 'center', marginTop: 22, fontSize: 17, color: '#D6DBE2' }}>
      {path ? ui.question : ui.other}{' '}
      <button className="jmac-start-link" onClick={startOpenChat} style={{ padding: 0, textDecoration: 'underline', textUnderlineOffset: 3 }}>
        {ui.chat}
      </button>
    </div>
  );

  // Choose screen
  if (!path) {
    return (
      <main className="jmac-start">
        <style>{START_CSS}</style>
        <div className="jmac-start-wrap">
          <h1>{ui.hello}</h1>
          <p>{ui.helloSub}</p>
          <div style={{ display: 'grid', gap: 14, marginTop: 24 }}>
            {Object.keys(START_PATHS).map(id => (
              <StartPathButton key={id} id={id} lang={L} onClick={() => choose(id)}/>
            ))}
          </div>
          {chatLine}
        </div>
      </main>
    );
  }

  const flow = START_FLOWS[path];
  const nodeId = trail[trail.length - 1];
  const node = flow.nodes[nodeId];
  const t = node[L];
  const P = START_PATHS[path][L];

  return (
    <main className="jmac-start">
      <style>{START_CSS}</style>
      <div className="jmac-start-wrap">
        {/* top bar */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
          <button className="jmac-start-link" onClick={back}>
            <span style={{ display: 'inline-flex', transform: 'scaleX(-1)' }}><Icon name="arrow" size={18}/></span>
            {ui.back}
          </button>
          {flow.total > 1 && node.type !== 'done' && (
            <span style={{ fontSize: 16, fontWeight: 700, color: '#D6DBE2' }}>{ui.stepOf(node.n, flow.total)}</span>
          )}
        </div>
        {flow.total > 1 && (
          <div style={{ display: 'flex', gap: 6, margin: '8px 0 16px' }} aria-hidden="true">
            {Array.from({ length: flow.total }, (_, i) => (
              <span key={i} style={{ flex: 1, height: 6, borderRadius: 3,
                background: i < node.n ? 'var(--blue-700)' : 'var(--border-1)' }}/>
            ))}
          </div>
        )}
        <div style={{ fontSize: 16, fontWeight: 700, color: '#D6DBE2', margin: flow.total > 1 ? '0 0 10px' : '8px 0 12px',
                      display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon name={START_PATHS[path].icon} size={18}/> {P.title}
        </div>

        <div key={nodeId} className="jmac-start-card">
          {node.type === 'q' && (
            <>
              <h2>{t.q}</h2>
              {t.help && <p>{t.help}</p>}
              <div className="jmac-start-btns">
                <button className="jmac-start-btn yes" onClick={() => goTo(node.yes)}>{ui.yes}</button>
                <button className="jmac-start-btn no" onClick={() => goTo(node.no)}>{ui.no}</button>
              </div>
            </>
          )}

          {node.type === 'stop' && (
            <>
              <div style={{ width: 48, height: 48, borderRadius: '50%', background: 'var(--blue-50)', display: 'grid', placeItems: 'center', marginBottom: 14 }}>
                <Icon name="alert" size={26} color="var(--amber-600)"/>
              </div>
              <h2>{t.h}</h2>
              <p>{t.p}</p>
              <div className="jmac-start-btns">
                {node.email && (
                  <a className="jmac-start-btn book" style={{ textDecoration: 'none' }}
                     href={`mailto:${node.email}?subject=${encodeURIComponent('COI for JMAC Asset Recovery')}`}>
                    <Icon name="mail" size={22}/> {t.emailBtn}
                  </a>
                )}
                <button className="jmac-start-btn yes" onClick={() => goTo(node.cont)}>{t.cont}</button>
                <button className="jmac-start-btn no" onClick={restart}>{ui.startOver}</button>
              </div>
            </>
          )}

          {node.type === 'ready' && (
            <>
              <h2>{t.h}</h2>
              <div className="jmac-start-sec">{ui.howTitle}</div>
              <HowToBook lang={L} appt={node.appt}/>
              <div className="jmac-start-tip">{ui.tipVin}</div>
              <div className="jmac-start-btns">
                <button className="jmac-start-btn book" onClick={book}>
                  <Icon name="calendar" size={22}/> {t.book}
                </button>
              </div>
              <div style={{ textAlign: 'center', fontSize: 16, color: '#D6DBE2', marginTop: 12 }}>{ui.newTab}</div>
              <div className="jmac-start-sec">{ui.nextTitle}</div>
              <ul className="jmac-start-list">
                {t.steps.map((x, i) => (
                  <li key={i}>
                    <span style={{ flexShrink: 0, marginTop: 2, display: 'inline-flex' }}><Icon name="clock" size={20} color="var(--mk-blue-hi)"/></span>
                    <span>{x}</span>
                  </li>
                ))}
              </ul>
            </>
          )}

          {node.type === 'done' && (
            <>
              <div style={{ width: 48, height: 48, borderRadius: '50%', background: '#0e2318', display: 'grid', placeItems: 'center', marginBottom: 14 }}>
                <Icon name="check" size={26} color="var(--success-500)" strokeWidth={2.6}/>
              </div>
              <h2>{t.h}</h2>
              <p>{t.p}</p>
              <div className="jmac-start-sec">{ui.onPage}</div>
              <HowToBook lang={L} appt={flow.nodes.ready.appt} onBookingPage/>
              <div style={{ marginTop: 22, fontSize: 17, fontWeight: 800, color: '#fff' }}>{ui.bring}</div>
              <ul className="jmac-start-list">
                {t.bring.map((s, i) => (
                  <li key={i}>
                    <span style={{ flexShrink: 0, marginTop: 2, display: 'inline-flex' }}><Icon name="check" size={20} color="var(--success-500)" strokeWidth={2.6}/></span>
                    <span>{s}</span>
                  </li>
                ))}
              </ul>
              <div className="jmac-start-btns">
                <button className="jmac-start-btn no" onClick={() => onBook && onBook()}>{ui.openAgain}</button>
                <button className="jmac-start-btn no" onClick={() => onNav('home')}>{ui.home}</button>
              </div>
            </>
          )}
        </div>
        {chatLine}
      </div>
    </main>
  );
};

// Home page tiles that open the guided page.
const StartTiles = ({ lang, onNav }) => {
  const L = lang === 'es' ? 'es' : 'en';
  return (
    <div style={{ width: '100%', maxWidth: 560 }}>
      <style>{START_CSS}</style>
      <div style={{ display: 'grid', gap: 16 }}>
        {Object.keys(START_PATHS).map(id => (
          <StartPathButton key={id} id={id} lang={L} onClick={() => onNav('start/' + id)}/>
        ))}
      </div>
      <div style={{ marginTop: 20, fontSize: 18, color: '#D6DBE2', textAlign: 'center' }}>
        {START_UI[L].other}{' '}
        <button onClick={startOpenChat}
          style={{ background: 'none', border: 0, padding: 0, cursor: 'pointer', color: 'var(--mk-blue-hi)',
                   fontWeight: 700, fontSize: 18, textDecoration: 'underline', textUnderlineOffset: 3 }}>
          {START_UI[L].chat}
        </button>
      </div>
    </div>
  );
};
