// Monjez — Application funnel app. Data-driven multi-step qualifier with scoring,
// Calendly popup routing, booking confirmation, and Google-Sheet logging.
// Wrapped in an IIFE: on the landing page all babel scripts share global scope,
// so isolating these declarations avoids redeclaration collisions.
(function () {
const { useState, useEffect, useRef, useCallback } = React;

// ---- SCHEMA (language-independent: type, section, scoring) ----
// scored steps map option index → points.
const STEPS = [
  { key: 'contact',        type: 'contact',  section: 'about' },
  { key: 'business',       type: 'single',   section: 'about' },
  { key: 'revenue',        type: 'single',   section: 'financial', scores: [0, 3, 5, 7, 9] },
  { key: 'employees',      type: 'single',   section: 'financial', scores: [1, 2, 4, 5, 6] },
  { key: 'investment',     type: 'single',   section: 'financial', scores: [0, 1, 3, 5, 7] },
  { key: 'bottleneck',     type: 'single',   section: 'problem' },
  { key: 'problemDetails', type: 'longtext', section: 'problem' },
  { key: 'impact',         type: 'longtext', section: 'problem' },
  { key: 'problemCost',    type: 'single',   section: 'problem', scores: [0, 2, 4, 6] },
  { key: 'goal',           type: 'single',   section: 'desire' },
  { key: 'idealOutcome',   type: 'longtext', section: 'desire' },
  { key: 'decisionMaker',  type: 'single',   section: 'serious', scores: [5, 2, 0] },
  { key: 'budget',         type: 'single',   section: 'serious', scores: [5, 0] },
  { key: 'investReady',    type: 'single',   section: 'serious', scores: [0, 2, 5] },
  { key: 'startWhen',      type: 'single',   section: 'serious', scores: [5, 3, 1, 0] },
  { key: 'whyUs',          type: 'longtext', section: 'closing' },
  { key: 'ifNothing',      type: 'longtext', section: 'closing' },
];
const SECTION_ORDER = ['about', 'financial', 'problem', 'desire', 'serious', 'closing'];
const STORE_KEY = 'monjez_apply_v1';
const LETTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];

function uid() { return 'mj_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8); }

function loadState() {
  try { return JSON.parse(localStorage.getItem(STORE_KEY)) || {}; } catch (e) { return {}; }
}
function saveState(s) {
  try { localStorage.setItem(STORE_KEY, JSON.stringify(s)); } catch (e) {}
}

function computeScore(answers) {
  let total = 0;
  for (const st of STEPS) {
    if (!st.scores) continue;
    const v = answers[st.key];
    if (v && typeof v.idx === 'number') total += (st.scores[v.idx] || 0);
  }
  return total;
}

// ---- lead capture ----
function pushLead(payload) {
  const cfg = window.APPLY_CONFIG || {};
  const requests = [];
  try {
    requests.push(fetch('/api/monday-lead', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    }).catch(() => {}));
  } catch (e) {}
  if (cfg.leadWebhookUrl) {
    try {
      requests.push(fetch(cfg.leadWebhookUrl, {
        method: 'POST', mode: 'no-cors',
        headers: { 'Content-Type': 'text/plain;charset=utf-8' },
        body: JSON.stringify(payload),
      }).catch(() => {}));
    } catch (e) {}
  }
  return Promise.all(requests);
}


function App(props) {
  const embed = !!(props && props.embed);
  const CFG = window.APPLY_CONFIG;
  const persisted = loadState();
  const [internalLang, setLang] = useState(persisted.lang || CFG.defaultLang || 'ar');
  const lang = (embed && props.lang) ? props.lang : internalLang;
  const [phase, setPhase] = useState('form'); // form | result | thanks
  const [stepIdx, setStepIdx] = useState(persisted.stepIdx || 0);
  const [answers, setAnswers] = useState(persisted.answers || {});
  const [contact, setContact] = useState(persisted.contact || { name: '', email: '', phone: '', company: '' });
  const [leadId] = useState(persisted.leadId || uid());
  const [err, setErr] = useState('');
  const T = window.APPLY_STRINGS[lang];

  // persist (+ html dir/title only in full-page mode)
  useEffect(() => {
    if (!embed) {
      const el = document.documentElement;
      el.lang = lang; el.dir = T.dir;
      document.title = lang === 'ar' ? 'منجز · طلب انضمام' : 'Monjez · Application';
    }
    saveState({ lang, stepIdx, answers, contact, leadId });
  }, [embed, lang, stepIdx, answers, contact, leadId, T.dir]);

  const score = computeScore(answers);
  const qualified = score >= CFG.qualifiedThreshold;

  // ---- Calendly booking listener ----
  useEffect(() => {
    function onMsg(e) {
      if (!e.data || typeof e.data.event !== 'string') return;
      if (e.data.event === 'calendly.event_scheduled') {
        const p = e.data.payload || {};
        pushLead({
          action: 'booked', leadId, lang,
          callType: qualified ? '45-min strategy' : '30-min discovery',
          eventUri: (p.event && p.event.uri) || '', inviteeUri: (p.invitee && p.invitee.uri) || '',
        });
        try { window.Calendly && window.Calendly.closePopupWidget(); } catch (x) {}
        setPhase('thanks');
        window.scrollTo({ top: 0, behavior: 'smooth' });
      }
    }
    window.addEventListener('message', onMsg);
    return () => window.removeEventListener('message', onMsg);
  }, [leadId, lang, qualified]);

  const setLangSafe = (l) => setLang(l);

  // ---- navigation ----
  const step = STEPS[stepIdx];

  const isAnswered = useCallback(() => {
    if (!step) return true;
    if (step.type === 'contact') {
      return contact.name.trim() && /\S+@\S+\.\S+/.test(contact.email) && contact.phone.trim();
    }
    if (step.type === 'single') return !!answers[step.key];
    if (step.type === 'longtext') return (answers[step.key] && answers[step.key].text || '').trim().length > 0;
    return true;
  }, [step, contact, answers]);

  const goNext = useCallback(() => {
    if (!isAnswered()) { setErr(T.ui.required); return; }
    setErr('');
    if (stepIdx < STEPS.length - 1) {
      setStepIdx(stepIdx + 1);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } else {
      // finish → result
      setPhase('result');
      window.scrollTo({ top: 0, behavior: 'smooth' });
      pushLead({
        action: 'create', leadId, lang,
        status: (score >= CFG.qualifiedThreshold) ? 'QUALIFIED' : 'EARLY_STAGE',
        score, callType: (score >= CFG.qualifiedThreshold) ? '45-min strategy' : '30-min discovery',
        name: contact.name, email: contact.email, phone: contact.phone, company: contact.company,
        answers: serializeAnswers(answers),
      });
    }
  }, [isAnswered, stepIdx, score, leadId, lang, contact, answers, T]);

  const goBack = useCallback(() => {
    setErr('');
    if (stepIdx > 0) setStepIdx(stepIdx - 1);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [stepIdx]);

  function pickSingle(idx, value) {
    setErr('');
    setAnswers((a) => ({ ...a, [step.key]: { idx, value } }));
    // auto-advance for a premium, fast feel
    setTimeout(() => {
      setStepIdx((cur) => (cur < STEPS.length - 1 ? cur + 1 : cur));
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }, 280);
  }
  function setText(text) { setAnswers((a) => ({ ...a, [step.key]: { text } })); }

  // keyboard: Enter to continue (non-contact/longtext handled inline)
  useEffect(() => {
    function onKey(e) {
      if (phase !== 'form') return;
      if (e.key === 'Enter' && (!step || step.type === 'single')) { e.preventDefault(); }
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [phase, step]);

  function restart() {
    setAnswers({}); setContact({ name: '', email: '', phone: '', company: '' });
    setStepIdx(0); setPhase('intro'); setErr('');
    try { localStorage.removeItem(STORE_KEY); } catch (e) {}
  }

  function openCalendly() {
    const url = qualified ? CFG.calendlyQualified : CFG.calendlyEarly;
    const prefill = { name: contact.name, email: contact.email };
    if (window.Calendly && window.Calendly.initPopupWidget) {
      window.Calendly.initPopupWidget({ url, prefill });
    } else {
      window.open(url, '_blank');
    }
  }

  const Shell = embed ? window.ApplyEmbedShell : window.ApplyShell;
  return (
    <Shell lang={lang} setLang={setLangSafe} T={T} phase={phase}
      progress={phase === 'form' ? (stepIdx + 1) / STEPS.length : (phase === 'thanks' || phase === 'result' ? 1 : 0)}
      sectionLabel={phase === 'form' && step ? T.sections[step.section] : ''}
      sectionIndex={phase === 'form' && step ? SECTION_ORDER.indexOf(step.section) + 1 : 0}>
      {phase === 'intro' && <Intro T={T} onStart={() => { setPhase('form'); }} resume={stepIdx > 0 || Object.keys(answers).length > 0} />}
      {phase === 'form' && (
        <StepView
          T={T} step={step} stepIdx={stepIdx} total={STEPS.length}
          answers={answers} contact={contact} setContact={setContact}
          pickSingle={pickSingle} setText={setText} err={err}
          onNext={goNext} onBack={goBack} />
      )}
      {phase === 'result' && (
        <Result T={T} qualified={qualified} score={score} onBook={openCalendly} />
      )}
      {phase === 'thanks' && <Thanks T={T} onRestart={restart} />}
    </Shell>
  );
}

function serializeAnswers(answers) {
  const out = {};
  for (const st of STEPS) {
    const v = answers[st.key];
    if (!v) continue;
    out[st.key] = (st.type === 'longtext') ? (v.text || '') : (v.value || '');
  }
  return out;
}

window.MonjezApply = App;
})();
