/* Quiz — Find Your Fit. ICP-grounded triggers. */
const QUIZ_STRINGS = {
  en: {
    q1: "What's happening right now?",
    q1opts: [
      { id: 'no-leads', text: "I'm not getting enough qualified appointments" },
      { id: 'losing-leads', text: 'Leads come in but slip through the cracks' },
      { id: 'wearing-hats', text: "I'm wearing all the hats — no time for sales" },
      { id: 'starting', text: "I'm starting fresh — need the system from scratch" },
    ],
    q2: 'How involved do you want to be?',
    q2opts: [
      { id: 'hands-off', text: 'Hands off — just send qualified appointments' },
      { id: 'partner', text: 'Build it together — my team takes over after' },
      { id: 'self', text: "Give me the tools and training — I'll run it" },
      { id: 'unsure', text: 'Honestly, not sure yet' },
    ],
    q3: "What's realistic this quarter?",
    q3opts: [
      { id: 'under-500', text: 'Under $500 / month' },
      { id: 'mid', text: '$500 – $1,500 / month' },
      { id: 'high', text: '$1,500 – $3,000 / month' },
      { id: 'enterprise', text: "$3,000+ — let's go" },
    ],
    eyebrow: 'Find your fit · 30 seconds',
    sub: 'No emails. No call. Just a recommendation in your hand.',
    done: "Here's where to start.",
    yourFit: '★ Your fit',
    cta: 'See full breakdown',
    startOver: 'Start over',
    questionOf: (a, b) => `Question ${a} of ${b}`,
    back: '← Back',
    reasons: {
      'no-leads_hands-off': "You need appointments — not infrastructure. Pay per qualified proposal.",
      'no-leads_partner': "Build a calling team that's yours. We hire and train, you run it after month 4.",
      'no-leads_self': "Get the full system + training. Run scraping, calling, and booking yourself.",
      'losing-leads_hands-off': "Your leads exist. The follow-up system doesn't. We build it together.",
      'losing-leads_partner': "Your leads exist. The follow-up system doesn't. We build it together.",
      'losing-leads_self': "Start with a clean CRM seat. Upgrade to NLLB when you're ready.",
      'wearing-hats_hands-off': "Stop doing sales yourself. We put qualified appointments on your calendar.",
      'wearing-hats_partner': "Train your existing team on our system. 4 months and they're autonomous.",
      'wearing-hats_self': "Build the follow-up engine that runs without you in the seat all day.",
      'starting_hands-off': "Start with visibility. You can't close what doesn't find you.",
      'starting_partner': "Get our calling system + training installed. 4 months to autonomy.",
      'starting_self': "Get the tools — scraper + dialer. Add the CRM and coaching when ready.",
      fallbackHO: 'Our flagship — best starting point if you want hands-off impact.',
      fallbackPT: 'Build the follow-up engine together. You own it after month 4.',
      fallbackSF: 'Full DIY system — onboarding, training, masterminds, all the tools.',
      fallback: 'Most teams start here — flagship CRM build with coaching.'
    }
  },
  es: {
    q1: '¿Qué está pasando ahora mismo?',
    q1opts: [
      { id: 'no-leads', text: 'No recibo suficientes citas calificadas' },
      { id: 'losing-leads', text: 'Llegan leads pero se pierden en el camino' },
      { id: 'wearing-hats', text: 'Estoy con todos los sombreros puestos — no hay tiempo para ventas' },
      { id: 'starting', text: 'Empiezo de cero — necesito el sistema completo' },
    ],
    q2: '¿Qué tan involucrado quieres estar?',
    q2opts: [
      { id: 'hands-off', text: 'Sin mover un dedo — solo envíame citas calificadas' },
      { id: 'partner', text: 'Construyámoslo juntos — mi equipo lo opera después' },
      { id: 'self', text: 'Dame las herramientas y entrenamiento — yo lo manejo' },
      { id: 'unsure', text: 'Honestamente, todavía no estoy seguro' },
    ],
    q3: '¿Qué es realista este trimestre?',
    q3opts: [
      { id: 'under-500', text: 'Menos de $500 / mes' },
      { id: 'mid', text: '$500 – $1,500 / mes' },
      { id: 'high', text: '$1,500 – $3,000 / mes' },
      { id: 'enterprise', text: '$3,000+ — vamos' },
    ],
    eyebrow: 'Encuentra tu plan · 30 segundos',
    sub: 'Sin emails. Sin llamadas. Solo una recomendación en tus manos.',
    done: 'Aquí es donde empezar.',
    yourFit: '★ Tu plan',
    cta: 'Ver detalle completo',
    startOver: 'Empezar de nuevo',
    questionOf: (a, b) => `Pregunta ${a} de ${b}`,
    back: '← Atrás',
    reasons: {
      'no-leads_hands-off': "Necesitas citas — no infraestructura. Paga por propuesta calificada.",
      'no-leads_partner': "Construye un equipo de llamadas que es tuyo. Nosotros contratamos y entrenamos, tú lo operas en mes 4.",
      'no-leads_self': "Obtén el sistema completo + entrenamiento. Tú corres scraping, llamadas y agendamiento.",
      'losing-leads_hands-off': "Los leads existen. El sistema de seguimiento no. Lo construimos juntos.",
      'losing-leads_partner': "Los leads existen. El sistema de seguimiento no. Lo construimos juntos.",
      'losing-leads_self': "Empieza con un CRM limpio. Sube a NLLB cuando estés listo.",
      'wearing-hats_hands-off': "Deja de hacer ventas tú mismo. Ponemos citas calificadas en tu calendario.",
      'wearing-hats_partner': "Entrena a tu equipo en nuestro sistema. 4 meses y son autónomos.",
      'wearing-hats_self': "Construye el motor de seguimiento que corre sin ti en la silla todo el día.",
      'starting_hands-off': "Empieza con visibilidad. No puedes cerrar lo que no te encuentra.",
      'starting_partner': "Instala nuestro sistema de llamadas + entrenamiento. 4 meses a la autonomía.",
      'starting_self': "Obtén las herramientas — scraper + dialer. Agrega CRM y coaching cuando estés listo.",
      fallbackHO: 'Nuestro flagship — el mejor punto de partida si quieres impacto sin intervención.',
      fallbackPT: 'Construye el motor de seguimiento juntos. Lo posees en mes 4.',
      fallbackSF: 'Sistema DIY completo — onboarding, entrenamiento, masterminds, todas las herramientas.',
      fallback: 'La mayoría de equipos empieza aquí — construcción flagship de CRM con coaching.'
    }
  }
};

function quizPick(answers, lang) {
  const key = `${answers.situation}_${answers.involvement}`;
  const reasons = QUIZ_STRINGS[lang].reasons;
  const RECS = {
    'no-leads_hands-off': 'everlines',
    'no-leads_partner': 'pipeline-recruit',
    'no-leads_self': 'diy-training',
    'losing-leads_hands-off': 'nllb',
    'losing-leads_partner': 'nllb',
    'losing-leads_self': 'diy-crm',
    'wearing-hats_hands-off': 'everlines',
    'wearing-hats_partner': 'pipeline-no-recruit',
    'wearing-hats_self': 'nllb',
    'starting_hands-off': 'local-visibility',
    'starting_partner': 'pipeline-no-recruit',
    'starting_self': 'diy-tech',
  };
  if (RECS[key]) return { svc: RECS[key], reason: reasons[key] };
  if (answers.involvement === 'hands-off') return { svc: 'nllb', reason: reasons.fallbackHO };
  if (answers.involvement === 'partner') return { svc: 'nllb', reason: reasons.fallbackPT };
  if (answers.involvement === 'self') return { svc: 'diy-training', reason: reasons.fallbackSF };
  return { svc: 'nllb', reason: reasons.fallback };
}

const Quiz = ({ services, onPick, lang }) => {
  lang = lang || (window.CIM_GET_LANG ? window.CIM_GET_LANG() : 'en');
  const S = QUIZ_STRINGS[lang];

  const QUIZ_QUESTIONS = [
    { id: 'situation', label: S.q1, options: S.q1opts },
    { id: 'involvement', label: S.q2, options: S.q2opts },
    { id: 'budget', label: S.q3, options: S.q3opts },
  ];

  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const total = QUIZ_QUESTIONS.length;

  const handlePick = (qid, optId) => {
    const next = { ...answers, [qid]: optId };
    setAnswers(next);
    if (step < total - 1) {
      setTimeout(() => setStep(step + 1), 220);
    }
  };

  const reset = () => { setStep(0); setAnswers({}); };

  const isDone = Object.keys(answers).length >= total;
  const rec = isDone ? quizPick(answers, lang) : null;
  const recService = rec ? services.find(s => s.id === rec.svc) : null;

  return (
    <div className="hero-right">
      <div className="quiz-eyebrow"><span className="dot"></span> {S.eyebrow}</div>
      <div className="quiz-title">{isDone ? S.done : QUIZ_QUESTIONS[step].label}</div>
      {!isDone && (
        <div className="quiz-sub">{S.sub}</div>
      )}

      <div className="quiz-progress">
        {QUIZ_QUESTIONS.map((q, i) => (
          <div key={q.id} className={`seg ${i <= step || isDone ? 'is-done' : ''}`}></div>
        ))}
      </div>

      <div className="quiz-spine">
        {!isDone && (
          <div className="quiz-options">
            {QUIZ_QUESTIONS[step].options.map((opt, i) => (
              <button key={opt.id} className="quiz-opt" onClick={() => handlePick(QUIZ_QUESTIONS[step].id, opt.id)}>
                <span className="num">{i + 1}</span>
                <span>{opt.text}</span>
              </button>
            ))}
          </div>
        )}

        {isDone && recService && (
          <div className="quiz-result">
            <div className="quiz-result-eyebrow">{S.yourFit}</div>
            <div className="quiz-result-title">{recService.name}</div>
            <div className="quiz-result-desc">{rec.reason}</div>
            <button className="quiz-result-cta" onClick={() => onPick(recService.id)}>
              {S.cta} <span>→</span>
            </button>
            <button onClick={reset} style={{ marginLeft: 10, color: 'rgba(255,255,255,0.6)', fontSize: 12, fontWeight: 600 }}>{S.startOver}</button>
          </div>
        )}
      </div>

      {!isDone && (
        <div style={{ marginTop: 16, fontSize: 11.5, color: 'rgba(255,255,255,0.5)', display: 'flex', justifyContent: 'space-between' }}>
          <span>{S.questionOf(step + 1, total)}</span>
          {step > 0 && <button onClick={() => setStep(step - 1)} style={{ color: 'rgba(255,255,255,0.55)', fontSize: 11.5, fontWeight: 600 }}>{S.back}</button>}
        </div>
      )}
    </div>
  );
};

window.Quiz = Quiz;
