// ============ AI CUSTOMER SERVICE READINESS CHECK ============
// Booth activation lead-gen experience for Global AI Show Riyadh 2026.
// Frontend-only. Shares the design language of the calculator (calculator.css + ai-readiness.css).
const { useState: useAR, useEffect: useARE, useRef: useARR, useMemo: useARM } = React;

// ---- Editable constants ----
const BOOTH_NUMBER = "S21";
const MISLAK_WEBSITE = "https://www.mislakcloud.com";
const WHATSAPP_NUMBER = "966XXXXXXXXX"; // placeholder — replace with the real number
const BOOKING_URL = "https://www.mislakcloud.com/book-demo";

const Ico = (props) => (window.CalcIcon ? <window.CalcIcon {...props} /> : null);

const arToWestern = (s) => String(s == null ? "" : s)
  .replace(/[\u0660-\u0669]/g, (d) => String(d.charCodeAt(0) - 0x0660))
  .replace(/[\u06F0-\u06F9]/g, (d) => String(d.charCodeAt(0) - 0x06F0));

// Animated counter
function useARCount(target, duration = 900) {
  const [val, setVal] = useAR(0);
  const raf = useARR(null);
  useARE(() => {
    const reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) { setVal(target); return; }
    const start = performance.now();
    cancelAnimationFrame(raf.current);
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      setVal(Math.round(target * (1 - Math.pow(1 - t, 3))));
      if (t < 1) raf.current = requestAnimationFrame(tick);
    };
    raf.current = requestAnimationFrame(tick);
    const fb = setTimeout(() => setVal(target), duration + 250);
    return () => { cancelAnimationFrame(raf.current); clearTimeout(fb); };
  }, [target, duration]);
  return val;
}

// ---- Assessment data ----
// score: [full, partial, zero]; priority weight for gap ordering
const QUESTIONS = [
  {
    q: "هل لدى شركتكم رقم أعمال موحد؟",
    qEn: "Does your company have a unified business number?",
    options: ["نعم", "جزئيًا / أكثر من رقم", "لا"],
    optionsEn: ["Yes", "Partially / multiple numbers", "No"],
    scores: [12, 6, 0],
    bot: "إذا كل موظف عنده رقم مختلف، الـ AI بيحتاج خريطة قبل ما يساعدك.",
    botEn: "If every employee has a different number, the AI needs a map before it can help you.",
    gap: "لا يوجد رقم أعمال موحد", gapEn: "No unified business number",
    priority: 2, icon: "phone",
  },
  {
    q: "هل تعرفون كم مكالمة فائتة تصير عندكم يوميًا أو أسبوعيًا؟",
    qEn: "Do you know how many missed calls you get daily or weekly?",
    options: ["نعم بدقة", "تقريبًا", "لا نعرف"],
    optionsEn: ["Yes, precisely", "Roughly", "We don't know"],
    scores: [13, 6, 0],
    bot: "أول خطوة في تحسين خدمة العملاء أنك تعرف أين تضيع الفرص.",
    botEn: "The first step to improving customer service is knowing where opportunities are lost.",
    gap: "لا يتم تتبع المكالمات الفائتة", gapEn: "Missed calls aren't tracked",
    priority: 3, icon: "phoneMissed",
  },
  {
    q: "هل يتم توزيع المكالمات على الفريق بطريقة منظمة؟",
    qEn: "Are calls distributed to the team in an organized way?",
    options: ["نعم، عندنا توزيع واضح", "يدويًا", "حسب من يرد أول"],
    optionsEn: ["Yes, we have clear routing", "Manually", "Whoever answers first"],
    scores: [12, 6, 0],
    bot: "«حسب من يرد أول» ليست استراتيجية… لكنها منتشرة.",
    botEn: "“Whoever answers first” isn't a strategy… but it's common.",
    gap: "توزيع المكالمات غير منظم", gapEn: "Unstructured call distribution",
    priority: 2, icon: "shuffle",
  },
  {
    q: "هل يتم تسجيل أو توثيق المكالمات المهمة؟",
    qEn: "Are important calls recorded or documented?",
    options: ["نعم", "لبعض المكالمات", "لا"],
    optionsEn: ["Yes", "For some calls", "No"],
    scores: [13, 6, 0],
    bot: "بدون توثيق، صعب تلخص أو تحلل أو تتعلم من المكالمات.",
    botEn: "Without documentation, it's hard to summarize, analyze, or learn from calls.",
    gap: "المكالمات غير موثقة", gapEn: "Calls aren't documented",
    priority: 1, icon: "clipboard",
  },
  {
    q: "هل واتساب العملاء مربوط بفريق أو نظام؟",
    qEn: "Is customer WhatsApp connected to a team or system?",
    options: ["نعم، منظم", "جزئيًا", "لا، على جوالات الموظفين"],
    optionsEn: ["Yes, organized", "Partially", "No, on employees' phones"],
    scores: [13, 6, 0],
    bot: "إذا واتساب العملاء في جوال الموظف، فالـ AI قد يحتاج يستأذن من البطارية أولًا.",
    botEn: "If customer WhatsApp lives on an employee's phone, the AI may need to ask the battery for permission first.",
    gap: "واتساب العملاء غير منظم", gapEn: "Customer WhatsApp isn't organized",
    priority: 3, icon: "chat",
  },
  {
    q: "هل عندكم Dashboard أو تقارير عن المكالمات والمحادثات؟",
    qEn: "Do you have a dashboard or reports for calls and conversations?",
    options: ["نعم", "تقارير محدودة", "لا"],
    optionsEn: ["Yes", "Limited reports", "No"],
    scores: [13, 6, 0],
    bot: "الذكاء الاصطناعي يحب البيانات المنظمة، وليس التخمين.",
    botEn: "AI loves organized data, not guesswork.",
    gap: "لا توجد Dashboard واضحة", gapEn: "No clear dashboard",
    priority: 2, icon: "gauge",
  },
  {
    q: "هل لديكم طريقة واضحة للمتابعة بعد المكالمة الفائتة؟",
    qEn: "Do you have a clear way to follow up after a missed call?",
    options: ["نعم، تلقائية أو منظمة", "يدويًا", "لا يوجد"],
    optionsEn: ["Yes, automated or organized", "Manually", "None"],
    scores: [12, 6, 0],
    bot: "العميل الذي لم يتم الرد عليه لا ينتظر كثيرًا.",
    botEn: "A customer who wasn't answered doesn't wait long.",
    gap: "المتابعة بعد المكالمات الفائتة غير واضحة", gapEn: "No clear missed-call follow-up",
    priority: 3, icon: "target",
  },
  {
    q: "هل تستخدمون CRM أو نظام لتتبع العملاء؟",
    qEn: "Do you use a CRM or customer-tracking system?",
    options: ["نعم", "نستخدم ملفات / Excel", "لا"],
    optionsEn: ["Yes", "We use files / Excel", "No"],
    scores: [12, 6, 0],
    bot: "Excel محترم، بس لا تجعله مدير تجربة العميل الوحيد.",
    botEn: "Excel is respectable, but don't make it your only customer-experience manager.",
    gap: "لا يوجد CRM أو نظام تتبع عملاء", gapEn: "No CRM or customer-tracking system",
    priority: 1, icon: "database",
  },
];

const GAP_HELP = {
  "لا يوجد رقم أعمال موحد": { ico: "phone", desc: "وجود رقم موحد يساعدك على استقبال مكالمات العملاء باسم الشركة بدل تشتت الأرقام.", descEn: "A unified number lets you receive customer calls under the company's name instead of scattered numbers." },
  "لا يتم تتبع المكالمات الفائتة": { ico: "phoneMissed", desc: "ما لا يتم قياسه يصعب تحسينه. تتبع المكالمات الفائتة يوضح أين تضيع الفرص.", descEn: "What isn't measured is hard to improve. Tracking missed calls shows where opportunities are lost." },
  "توزيع المكالمات غير منظم": { ico: "shuffle", desc: "التوجيه المنظم يقلل الانتظار والتحويلات العشوائية.", descEn: "Organized routing reduces waiting and random transfers." },
  "المكالمات غير موثقة": { ico: "clipboard", desc: "التوثيق يساعد على المراجعة، التدريب، الجودة، والتحليل.", descEn: "Documentation supports review, training, quality, and analysis." },
  "واتساب العملاء غير منظم": { ico: "chat", desc: "واتساب يحتاج أن يكون قناة عمل منظمة، وليس محادثات متفرقة على أجهزة الموظفين.", descEn: "WhatsApp needs to be an organized business channel, not scattered chats on employees' devices." },
  "لا توجد Dashboard واضحة": { ico: "gauge", desc: "اللوحات والتقارير تعطي الإدارة رؤية أوضح للأداء.", descEn: "Dashboards and reports give management a clearer view of performance." },
  "المتابعة بعد المكالمات الفائتة غير واضحة": { ico: "target", desc: "المتابعة المنظمة تقلل نسيان العملاء والفرص.", descEn: "Organized follow-up reduces forgotten customers and opportunities." },
  "لا يوجد CRM أو نظام تتبع عملاء": { ico: "database", desc: "ربط العميل بسجل واضح يساعد الفريق على فهم السياق وعدم البدء من الصفر.", descEn: "Linking the customer to a clear record helps the team understand context and not start from scratch." },
};

const LEVELS = [
  { min: 0, max: 30, title: "مرحلة الفوضى اللطيفة", titleEn: "Gentle chaos stage", sub: "عندكم قنوات خدمة عملاء، لكن غير منظمة بما يكفي للاستفادة من AI.", subEn: "You have customer-service channels, but they're not organized enough to benefit from AI.", status: "محتار… لكن فيه أمل.", statusEn: "Confused… but there's hope.", explain: "الذكاء الاصطناعي يقدر يساعدك لاحقًا، لكن قبل ذلك تحتاج تنظيم المكالمات، واتساب، المتابعة، والبيانات.", explainEn: "AI can help you later, but first you need to organize calls, WhatsApp, follow-up, and data.", bot: "الـ AI هنا غالبًا بيطلب اجتماع تعارف مع البيانات أولًا.", botEn: "The AI here usually asks for an introductory meeting with the data first." },
  { min: 31, max: 55, title: "تحتاج ترتيب الأسلاك", titleEn: "Wiring needs tidying", sub: "عندكم أساس جيد، لكن البيانات والمتابعة تحتاج تنظيم.", subEn: "You have a good foundation, but data and follow-up need organizing.", status: "يحاول يفهم الصورة.", statusEn: "Trying to understand the picture.", explain: "بعض قنوات خدمة العملاء موجودة، لكن بدون توحيد وقياس واضح، سيكون من الصعب استخدام AI بكفاءة.", explainEn: "Some customer-service channels exist, but without unification and clear measurement, it'll be hard to use AI efficiently.", bot: "فيه بداية جيدة… بس الأسلاك تحتاج ترتيب قبل التشغيل الذكي.", botEn: "There's a good start… but the wiring needs tidying before smart operation." },
  { min: 56, max: 75, title: "جاهزية متوسطة", titleEn: "Moderate readiness", sub: "أنتم قريبون من الجاهزية، وتحتاجون توحيد وربط أفضل.", subEn: "You're close to ready, and need better unification and integration.", status: "بدأ يستوعب.", statusEn: "Starting to get it.", explain: "لديكم جزء من الأساس، لكن توحيد المكالمات وواتساب والتقارير سيساعدكم على الاستفادة بشكل أفضل من الأتمتة والذكاء الاصطناعي.", explainEn: "You have part of the foundation, but unifying calls, WhatsApp, and reports will help you benefit more from automation and AI.", bot: "الوضع مبشر. التنظيم الإضافي هنا ممكن يفرق كثير.", botEn: "The situation is promising. A bit more organization here can make a big difference." },
  { min: 76, max: 100, title: "AI-Ready Customer Service", titleEn: "AI-Ready Customer Service", sub: "خدمة العملاء عندكم منظمة وقابلة للأتمتة والتحليل.", subEn: "Your customer service is organized and ready for automation and analysis.", status: "جاهز يشتغل.", statusEn: "Ready to go.", explain: "لديكم أساس جيد للاستفادة من AI في خدمة العملاء، خصوصًا إذا تم ربط المكالمات وواتساب والمتابعة داخل نظام واحد.", explainEn: "You have a solid foundation to benefit from AI in customer service, especially if calls, WhatsApp, and follow-up are connected in one system.", bot: "الـ AI هنا يبتسم… البيانات واضحة والطريق ممهد.", botEn: "The AI here is smiling… the data is clear and the path is paved." },
];

const INDUSTRIES = ["عيادة / مركز صحي", "عقار / مقاولات", "مطعم / ضيافة", "متجر إلكتروني", "صيانة وخدمات منزلية", "تعليم وتدريب", "خدمات مهنية", "مبيعات وخدمة عملاء", "أخرى"];
const CHALLENGES = ["مكالمات فائتة", "واتساب غير منظم", "لا يوجد رقم موحد", "ضعف المتابعة", "لا توجد Dashboard", "نحتاج كول سنتر", "نبحث عن AI في خدمة العملاء", "أخرى"];

function getResultLevel(score) { return LEVELS.find((l) => score >= l.min && score <= l.max) || LEVELS[0]; }
function getConfusionLabel(c) {
  if (c <= 25) return window.L("الـ AI مرتاح.", "The AI is comfortable.");
  if (c <= 50) return window.L("الـ AI يحتاج قهوة.", "The AI needs coffee.");
  if (c <= 75) return window.L("الـ AI يسأل: وين البيانات؟", "The AI is asking: where's the data?");
  return window.L("الـ AI دخل اجتماع طارئ.", "The AI just entered an emergency meeting.");
}

async function submitLead(leadPayload) {
  // TODO: Connect to a webhook, Google Sheet, Airtable, or CRM endpoint.
  // e.g. await fetch(YOUR_WEBHOOK_URL, { method: "POST", body: JSON.stringify(leadPayload) });
  console.log("Lead submitted:", leadPayload);
  window.__mislakReadinessLead = leadPayload;
}

// ============================================================
function AIReadinessPage() {
  window.useLang();
  const [started, setStarted] = useAR(false);
  const [cur, setCur] = useAR(0);
  const [answers, setAnswers] = useAR(Array(QUESTIONS.length).fill(null)); // option index per question
  const [showResults, setShowResults] = useAR(false);
  const [submitted, setSubmitted] = useAR(false);
  const assessRef = useARR(null);

  const allAnswered = answers.every((a) => a !== null);

  const score = useARM(() => answers.reduce((sum, a, i) => sum + (a === null ? 0 : QUESTIONS[i].scores[a]), 0), [answers]);
  const confusion = 100 - score;
  const level = getResultLevel(score);

  const topGaps = useARM(() => {
    const gaps = [];
    answers.forEach((a, i) => {
      if (a === null || a === 0) { // a===0 is the full-score option (first)
        if (a !== null && a !== 0) {}
      }
      if (a === null) return;
      const sev = a === 1 ? "partial" : a === 2 ? "weak" : null; // index1 partial, index2 zero
      if (!sev) return;
      gaps.push({ label: QUESTIONS[i].gap, labelEn: QUESTIONS[i].gapEn, severity: sev, priority: QUESTIONS[i].priority, qIndex: i });
    });
    const sevRank = { weak: 0, partial: 1 };
    gaps.sort((x, y) => {
      if (sevRank[x.severity] !== sevRank[y.severity]) return sevRank[x.severity] - sevRank[y.severity];
      if (y.priority !== x.priority) return y.priority - x.priority;
      return x.qIndex - y.qIndex;
    });
    return gaps.slice(0, 3);
  }, [answers]);

  // missed-opportunity hint: weak/partial on tracking(1), follow-up(6), distribution(2)
  const showHint = useARM(() => [1, 6, 2].some((i) => answers[i] === 1 || answers[i] === 2), [answers]);

  const scrollAssess = () => {
    if (assessRef.current) {
      const y = assessRef.current.getBoundingClientRect().top + window.scrollY - 76;
      window.scrollTo({ top: y, behavior: "smooth" });
    }
  };
  const begin = () => { setStarted(true); setTimeout(scrollAssess, 60); };
  const choose = (qi, oi) => setAnswers((prev) => prev.map((v, i) => (i === qi ? oi : v)));
  const next = () => { if (cur < QUESTIONS.length - 1) setCur(cur + 1); else { setShowResults(true); setTimeout(scrollAssess, 60); } };
  const back = () => { if (cur > 0) setCur(cur - 1); };
  const reset = () => { setStarted(false); setCur(0); setAnswers(Array(QUESTIONS.length).fill(null)); setShowResults(false); setSubmitted(false); setTimeout(scrollAssess, 60); };

  return (
    <div className="calc-page">
      <Hero onStart={() => { begin(); }} onHow={() => document.getElementById("ar-how").scrollIntoView({ behavior: "smooth" })} />
      <Strategic />

      <section className="calc-section alt" id="assess" ref={assessRef}>
        <div className="container">
          <div className="calc-wrap">
            {!started && !showResults && <StartCard onStart={begin} />}

            {started && !showResults && (
              <QuestionCard
                idx={cur} total={QUESTIONS.length} data={QUESTIONS[cur]}
                selected={answers[cur]} onChoose={(oi) => choose(cur, oi)}
                onNext={next} onBack={back} canBack={cur > 0}
                isLast={cur === QUESTIONS.length - 1} answered={answers[cur] !== null}
              />
            )}

            {showResults && (
              <Result
                score={score} confusion={confusion} level={level} topGaps={topGaps}
                answers={answers} showHint={showHint} onReset={reset}
              />
            )}
          </div>
        </div>
      </section>

      <div className="calc-foot">
        <div className="cf-brand">Mislak · مسلاك</div>
        <div className="cf-link mono">www.mislakcloud.com</div>
        <div className="cf-tag">{window.L("نحو تواصل أذكى للأعمال", "Toward smarter communication for business")}</div>
      </div>
    </div>
  );
}

// ---------- Hero ----------
function Hero({ onStart, onHow }) {
  return (
    <section className="calc-hero">
      <div className="calc-nodes" aria-hidden="true">
        {[[8,18,5],[22,68,4],[42,28,6],[63,74,5],[78,22,7],[88,58,4],[15,82,5],[55,12,4]].map((n,i)=>(
          <span key={i} style={{ left: n[0]+"%", top: n[1]+"%", width: n[2]+"px", height: n[2]+"px", animationDelay: (i*0.7)+"s" }}></span>
        ))}
      </div>
      <div className="container">
        <div className="calc-hero-grid">
          <div>
            <h1>{window.L("هل خدمة عملاء شركتك جاهزة للذكاء الاصطناعي؟", "Is your customer service ready for AI?")}</h1>
            <p className="lead">{window.L("اختبار سريع خلال 60 ثانية يقيّم جاهزية شركتك لاستخدام AI في خدمة العملاء، بناءً على تنظيم المكالمات، واتساب، المتابعة، والبيانات.", "A quick 60-second test that assesses your company's readiness to use AI in customer service, based on how organized your calls, WhatsApp, follow-up, and data are.")}</p>
            <div className="calc-hero-cta">
              <button className="btn btn-accent" onClick={onStart}>{window.L("ابدأ التقييم", "Start the assessment")} <span className="mono">{window.ARR ? window.ARR() : "←"}</span></button>
              <button className="btn btn-glass" onClick={onHow}>{window.L("كيف يعمل التقييم؟", "How does it work?")}</button>
            </div>
            <div style={{ marginTop: 18, fontSize: 13, color: "rgba(255,255,255,.78)" }}>{window.L("الاختبار يستغرق أقل من دقيقة.", "The test takes less than a minute.")}</div>
          </div>
          <div className="calc-preview">
            <div className="pv-label">{window.L("جاهزية الذكاء الاصطناعي", "AI readiness")}</div>
            <div className="pv-num" style={{ fontSize: "clamp(40px,5vw,58px)" }}>؟؟<span className="cur">/ 100</span></div>
            <div className="pv-sub">{window.L("قيّم جاهزية خدمة عملاء شركتك", "Assess your customer service's readiness")}</div>
            <div className="pv-flow">
              <div className="pv-flow-row"><span>{window.L("المكالمات", "Calls")}</span><span className="v">Calls</span></div>
              <div className="pv-flow-row"><span>{window.L("واتساب العملاء", "Customer WhatsApp")}</span><span className="v">WhatsApp</span></div>
              <div className="pv-flow-row"><span>{window.L("المتابعة والتقارير", "Follow-up & reports")}</span><span className="v">Dashboard</span></div>
              <div className="pv-flow-row"><span>{window.L("الذكاء الاصطناعي", "Artificial intelligence")}</span><span className="v">AI</span></div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Strategic message ----------
function Strategic() {
  return (
    <section className="calc-section" id="ar-how">
      <div className="container">
        <div className="calc-section-head">
          <div className="calc-eyebrow">{window.L("قبل AI… رتّب الأساس", "Before AI… set the foundation")}</div>
          <h2>{window.L("قبل أن تستفيد من AI، رتّب طبقة التواصل", "Before you benefit from AI, organize the communication layer")}</h2>
          <p>{window.L("الذكاء الاصطناعي لا يعمل جيدًا فوق بيانات مشتتة. إذا كانت المكالمات وواتساب والمتابعة غير منظمة، فالخطوة الأولى ليست إضافة AI، بل تنظيم طبقة التواصل مع العملاء.", "AI doesn't work well on scattered data. If calls, WhatsApp, and follow-up aren't organized, the first step isn't adding AI — it's organizing the customer communication layer.")}</p>
        </div>
        <div className="flow-mini">
          <div className="fm-step">{window.L("مكالمات + واتساب + متابعة + بيانات", "Calls + WhatsApp + follow-up + data")}</div>
          <span className="fm-arrow">←</span>
          <div className="fm-step">{window.L("تنظيم وقياس", "Organize & measure")}</div>
          <span className="fm-arrow">←</span>
          <div className="fm-step accent">{window.L("جاهزية أعلى للأتمتة والذكاء الاصطناعي", "Higher readiness for automation and AI")}</div>
        </div>
      </div>
    </section>
  );
}

// ---------- Start card ----------
function StartCard({ onStart }) {
  return (
    <div className="calc-card assess-start">
      <div className="calc-eyebrow">{window.L("التقييم التفاعلي", "Interactive assessment")}</div>
      <h3>{window.L("هل خدمة عملاء شركتك مبنية على بيانات منظمة؟", "Is your customer service built on organized data?")}</h3>
      <p>{window.L("8 أسئلة قصيرة تعطيك مؤشرًا تقريبيًا لجاهزية خدمة عملاء شركتك للذكاء الاصطناعي، مع توصيات عملية. تقييم مبدئي سريع لا يغني عن التشخيص التفصيلي.", "8 short questions give you an approximate indicator of your customer service's AI readiness, with practical recommendations. A quick initial assessment, not a substitute for a detailed diagnosis.")}</p>
      <button className="btn btn-primary" onClick={onStart} style={{ justifyContent: "center" }}>{window.L("ابدأ التقييم", "Start the assessment")} <span className="mono">{window.ARR ? window.ARR() : "←"}</span></button>
      <div className="assess-meta">
        <span className="am"><Ico name="check" size={18} /> {window.L("أقل من دقيقة", "Under a minute")}</span>
        <span className="am"><Ico name="clipboard" size={18} /> {window.L("8 أسئلة", "8 questions")}</span>
        <span className="am"><Ico name="gauge" size={18} /> {window.L("نتيجة فورية", "Instant result")}</span>
      </div>
    </div>
  );
}

// ---------- Question card ----------
function QuestionCard({ idx, total, data, selected, onChoose, onNext, onBack, canBack, isLast, answered }) {
  return (
    <div className="calc-card">
      <div className="step-progress">
        <span className="label">{window.L(`السؤال ${idx + 1} من ${total}`, `Question ${idx + 1} of ${total}`)}</span>
        <div className="track"><div className="fill" style={{ width: ((idx + 1) / total * 100) + "%" }}></div></div>
      </div>
      <div className="q-text">{window.L(data.q, data.qEn)}</div>
      <div className="answer-list">
        {window.L(data.options, data.optionsEn).map((opt, oi) => (
          <button key={oi} type="button" className={"answer-opt" + (selected === oi ? " active" : "")}
            onClick={() => onChoose(oi)} aria-pressed={selected === oi}>
            <span className="ao-radio"><Ico name="check" size={14} /></span>
            <span className="ao-txt"><span className="ao-label">{opt}</span></span>
          </button>
        ))}
      </div>
      <div className="bot-note">
        <span className="bot-ico"><Ico name="robot" size={20} /></span>
        <span className="bot-body"><span className="bot-name">Mislak Bot</span>{window.L(data.bot, data.botEn)}</span>
      </div>
      <div className="step-nav">
        {canBack ? <button className="btn btn-ghost" onClick={onBack}>{window.L("السابق", "Back")}</button> : <span className="spacer"></span>}
        <button className="btn btn-primary" onClick={onNext} disabled={!answered} style={answered ? {} : { opacity: .5, cursor: "not-allowed" }}>
          {isLast ? window.L("عرض النتيجة", "View result") : window.L("التالي", "Next")} <span className="mono">{window.ARR ? window.ARR() : "←"}</span>
        </button>
      </div>
    </div>
  );
}

// ---------- Result ----------
function Result({ score, confusion, level, topGaps, answers, showHint, onReset }) {
  const aScore = useARCount(score);
  const aConf = useARCount(confusion);
  const confPct = Math.max(3, Math.min(97, confusion));
  const downloadReport = () => {
    const isEn = window.__lang === "en";
    const GAP_EN = {
      "لا يوجد رقم أعمال موحد": "No unified business number",
      "لا يتم تتبع المكالمات الفائتة": "Missed calls aren't tracked",
      "توزيع المكالمات غير منظم": "Unstructured call distribution",
      "المكالمات غير موثقة": "Calls aren't documented",
      "واتساب العملاء غير منظم": "Customer WhatsApp isn't organized",
      "لا توجد Dashboard واضحة": "No clear dashboard / reporting",
      "المتابعة بعد المكالمات الفائتة غير واضحة": "No clear missed-call follow-up",
      "لا يوجد CRM أو نظام تتبع عملاء": "No CRM / customer-tracking system",
    };
    const gapName = (g) => (isEn ? (g.labelEn || GAP_EN[g.label] || g.label) : g.label);
    const rows = [
      { heading: window.L("النتيجة", "Result") },
      { label: window.L("النتيجة الإجمالية", "Overall score"), value: `${score} / 100`, big: true },
      { label: window.L("مستوى الجاهزية", "Readiness level"), value: isEn ? (level.titleEn || level.title) : level.title },
      { label: window.L("مؤشر ارتباك الذكاء الاصطناعي", "AI confusion index"), value: `${confusion}%` },
      { heading: window.L("أهم الفجوات", "Top gaps") },
    ];
    if (topGaps.length) {
      topGaps.forEach((g, i) => rows.push({ label: `${String(i + 1).padStart(2, "0")}`, value: gapName(g) }));
    } else {
      rows.push({ label: "—", value: window.L("لا توجد فجوات جوهرية", "No critical gaps") });
    }
    window.MislakReport({
      filename: "mislak-ai-readiness",
      title: window.L("تقرير جاهزية خدمة العملاء للذكاء الاصطناعي", "AI Customer-Service Readiness Report"),
      subtitle: window.L(
        "تقييم مبدئي سريع لمدى جاهزية خدمة عملاء شركتك للأتمتة والذكاء الاصطناعي.",
        "A quick initial assessment of how ready your customer service is for automation and AI."
      ),
      hero: {
        label: window.L("نتيجة الجاهزية", "Readiness score"),
        value: `${score} / 100 · ${isEn ? (level.titleEn || level.title) : level.title}`,
      },
      rows,
      note: window.L(
        "هذا تقييم مبدئي سريع وليس تشخيصًا نهائيًا. الهدف هو معرفة أين تحتاج خدمة عملاء شركتك إلى تنظيم أفضل قبل استخدام الذكاء الاصطناعي.",
        "This is a quick initial assessment, not a final diagnosis. It is meant to highlight where your customer service needs better organization before adopting AI."
      ),
    });
  };
  return (
    <div>
      <div className="calc-section-head" style={{ marginBottom: 26 }}>
        <div className="calc-eyebrow">{window.L("النتيجة", "Result")}</div>
        <h2>{window.L("نتيجة جاهزية خدمة عملاء شركتك", "Your customer service's readiness result")}</h2>
      </div>

      <div className="score-hero">
        <div className="sh-eyebrow">{window.L("جاهزية خدمة العملاء للذكاء الاصطناعي", "Customer-service AI readiness")}</div>
        <div className="sh-score">{aScore}<span className="sh-of">/ 100</span></div>
        <div className="level-badge"><Ico name="sparkle" size={18} /> {window.L(level.title, level.titleEn)}</div>
        <div className="sh-status"><b>{window.L("حالة الـ AI:", "AI status:")}</b> {window.L(level.status, level.statusEn)}</div>
        <p className="sh-explain">{window.L(level.explain, level.explainEn)}</p>
      </div>

      <div className="conf-card">
        <div className="conf-head">
          <span className="conf-title"><Ico name="robot" size={22} /> {window.L("مؤشر ارتباك الذكاء الاصطناعي", "AI confusion index")}</span>
          <span className="conf-pct">{aConf}%</span>
        </div>
        <div className="conf-bar" role="img" aria-label={"AI confusion " + confusion + "%"}>
          <div className="conf-needle" style={{ right: confPct + "%" }}></div>
        </div>
        <div className="conf-label"><span className="dot"></span> {getConfusionLabel(confusion)}</div>
      </div>

      <p className="result-note">{window.L("هذا تقييم مبدئي سريع، وليس تشخيصًا نهائيًا. الهدف هو مساعدتك على معرفة أين تحتاج خدمة عملاء شركتك إلى تنظيم أفضل قبل استخدام AI.", "This is a quick initial assessment, not a final diagnosis. It's meant to help you see where your customer service needs better organization before using AI.")}</p>

      {/* Top gaps */}
      <div className="calc-section-head" style={{ margin: "40px auto 22px" }}>
        <h2 style={{ fontSize: "clamp(22px,2.8vw,30px)" }}>{window.L("أهم الفجوات التي تمنع الاستفادة من AI", "Top gaps preventing you from benefiting from AI")}</h2>
      </div>
      {topGaps.length > 0 ? (
        <div className="gap-list">
          {topGaps.map((g, i) => {
            const info = GAP_HELP[g.label] || {};
            return (
              <div className="gap-card" key={g.label}>
                <div className="gap-ico"><Ico name={info.ico || "alert"} size={24} /></div>
                <div>
                  <div className="gap-rank">{String(i + 1).padStart(2, "0")}</div>
                  <div className="gap-title">{window.L(g.label, g.labelEn)}</div>
                  <div className="gap-desc">{window.L(info.desc, info.descEn)}</div>
                  <div className="gap-help"><b>{window.L("كيف تساعد مسلاك:", "How Mislak helps:")}</b> {window.L("توحيد القناة وقياسها داخل نظام واحد قابل للأتمتة.", "Unify the channel and measure it within one automatable system.")}</div>
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        <div className="results-empty">{window.L("وضعكم جيد. التوصية التالية هي تحسين الربط بين القنوات وتجهيز البيانات لاستخدامات AI أعمق.", "You're in good shape. The next recommendation is to improve channel integration and prepare data for deeper AI use.")}</div>
      )}

      {showHint && (
        <div className="hint-card">
          <span className="hint-ico"><Ico name="alert" size={22} /></span>
          <span className="hint-body">{window.L("قد تكون لديكم فرص مبيعات تضيع دون قياس واضح. أول خطوة ليست AI، بل معرفة أين تضيع المكالمات والمتابعات.", "You may have sales opportunities slipping away without clear measurement. The first step isn't AI — it's knowing where calls and follow-ups are lost.")}</span>
        </div>
      )}

      {/* Value */}
      <div className="calc-section-head" style={{ margin: "40px auto 22px" }}>
        <div className="calc-eyebrow">{window.L("كيف تساعدك مسلاك", "How Mislak helps you")}</div>
        <h2 style={{ fontSize: "clamp(22px,2.8vw,30px)" }}>{window.L("رتّب خدمة عملاء شركتك اليوم، حتى يصبح AI مفيدًا غدًا.", "Organize your customer service today, so AI becomes useful tomorrow.")}</h2>
      </div>
      <div className="val-cards" style={{ marginBottom: 26 }}>
        <div className="val-card"><div className="val-ico"><Ico name="phone" /></div><h4>{window.L("رقم موحد وتنظيم المكالمات", "Unified number & call organization")}</h4></div>
        <div className="val-card"><div className="val-ico"><Ico name="chat" /></div><h4>{window.L("واتساب للأعمال وربط المحادثات", "WhatsApp Business & connected chats")}</h4></div>
        <div className="val-card"><div className="val-ico"><Ico name="barChart" /></div><h4>{window.L("متابعة وتقارير واضحة", "Clear follow-up & reports")}</h4></div>
        <div className="val-card"><div className="val-ico"><Ico name="robot" /></div><h4>{window.L("أتمتة وAI فوق بيانات منظمة", "Automation & AI on organized data")}</h4></div>
      </div>
      <p className="result-note" style={{ maxWidth: 720 }}>{window.L("مسلاك تساعد الشركات على توحيد المكالمات وواتساب ومحادثات العملاء من مكان واحد، حتى تصبح خدمة عملاء شركتك أكثر تنظيمًا وجاهزية للأتمتة والذكاء الاصطناعي.", "Mislak helps companies unify calls, WhatsApp, and customer chats in one place, so your customer service becomes more organized and ready for automation and AI.")}</p>

      <div className="result-actions">
        <button className="btn btn-ghost btn-sm" onClick={downloadReport}><Ico name="download" size={16} /> {window.L("تحميل التقرير", "Download report")}</button>
        <button className="btn btn-ghost btn-sm" onClick={onReset}>{window.L("إعادة الاختبار", "Restart test")}</button>
      </div>
    </div>
  );
}

// ---------- Lead form ----------
function LeadForm({ score, confusion, level, topGaps, answers, onSubmitted }) {
  const dataSectors = INDUSTRIES;
  const [f, setF] = useAR({ name: "", company: "", jobTitle: "", phone: "", email: "", industry: "", challenge: "", consent: false });
  const [errors, setErrors] = useAR({});
  const upd = (k) => (e) => {
    const v = k === "consent" ? e.target.checked : e.target.value;
    setF({ ...f, [k]: v });
    if (errors[k]) setErrors((er) => { const n = { ...er }; delete n[k]; return n; });
  };
  const validate = () => {
    const e = {};
    const soft = "يبدو أن هذا الحقل يحتاج تعديلًا بسيطًا";
    if (!f.name.trim()) e.name = soft;
    if (!f.company.trim()) e.company = soft;
    const phone = arToWestern(f.phone).replace(/[\s()-]/g, "");
    if (!phone) e.phone = soft;
    else if (!/^(\+?\d{8,15})$/.test(phone)) e.phone = "تأكد من كتابة رقم الجوال بشكل صحيح";
    if (!f.email.trim()) e.email = soft;
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f.email.trim())) e.email = "تأكد من كتابة البريد بشكل صحيح";
    if (!f.consent) e.consent = "نحتاج موافقتك للتواصل معك بخصوص النتيجة";
    return e;
  };
  const buildPayload = () => ({
    leadSource: "Global AI Show Riyadh 2026 - QR Assessment",
    boothNumber: BOOTH_NUMBER,
    campaign: "ai_customer_service_readiness_check",
    name: f.name, company: f.company, jobTitle: f.jobTitle, phone: f.phone, email: f.email,
    industry: f.industry, mainChallenge: f.challenge, consent: f.consent,
    score, resultLevel: level.title, aiConfusionPercentage: confusion,
    topGaps: topGaps.map((g) => g.label), answers,
    submittedAt: new Date().toISOString(),
    utm: { source: "event", medium: "qr", campaign: "ai_readiness_check" },
  });
  const onSubmit = (ev) => {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length === 0) { submitLead(buildPayload()); onSubmitted(); }
  };
  const buildWhatsAppMessage = () => {
    const msg =
      `مرحبًا مسلاك،\n` +
      `أكملت اختبار جاهزية خدمة عملاء شركتي للذكاء الاصطناعي.\n` +
      `الشركة: ${f.company || "-"}\n` +
      `القطاع: ${f.industry || "-"}\n` +
      `النتيجة: ${score} / 100\n` +
      `مستوى الجاهزية: ${level.title}\n` +
      `مؤشر ارتباك الذكاء الاصطناعي: ${confusion}%\n` +
      `أهم الفجوات: ${topGaps.map((g) => g.label).join("، ") || "لا يوجد"}\n` +
      `أرغب في الحصول على تشخيص أو جلسة مجانية.`;
    return `https://wa.me/${WHATSAPP_NUMBER}?text=${encodeURIComponent(msg)}`;
  };

  return (
    <div style={{ marginTop: 40 }}>
      <div className="calc-section-head" style={{ marginBottom: 24 }}>
        <div className="calc-eyebrow">تقرير الجاهزية</div>
        <h2 style={{ fontSize: "clamp(22px,2.8vw,30px)" }}>احصل على تقرير جاهزية خدمة عملاء شركتك</h2>
        <p>اترك بياناتك وسنرسل لك ملخص جاهزية خدمة عملاء شركتك، مع توصيات عملية لتحسين المكالمات، واتساب، المتابعة، والبيانات.</p>
      </div>

      <div className="lead-summary">
        <div className="ls-cell"><div className="ls-label">النتيجة</div><div className="ls-val mono">{score} / 100</div></div>
        <div className="ls-cell"><div className="ls-label">مستوى الجاهزية</div><div className="ls-val">{level.title}</div></div>
        <div className="ls-cell"><div className="ls-label">ارتباك الـ AI</div><div className="ls-val mono">{confusion}%</div></div>
      </div>

      <form onSubmit={onSubmit} noValidate>
        <div className="form-grid">
          <label>
            <span>الاسم<span className="req">*</span></span>
            <input className={errors.name ? "invalid" : ""} value={f.name} onChange={upd("name")} placeholder="عبدالله السعيد" />
            {errors.name && <span className="field-error">{errors.name}</span>}
          </label>
          <label>
            <span>الشركة<span className="req">*</span></span>
            <input className={errors.company ? "invalid" : ""} value={f.company} onChange={upd("company")} placeholder="شركة المثال" />
            {errors.company && <span className="field-error">{errors.company}</span>}
          </label>
          <label>
            <span>المنصب</span>
            <input value={f.jobTitle} onChange={upd("jobTitle")} placeholder="مدير العمليات" />
          </label>
          <label>
            <span>رقم الجوال<span className="req">*</span></span>
            <input className={errors.phone ? "invalid" : ""} type="tel" dir="ltr" value={f.phone} onChange={upd("phone")} placeholder="+966 5X XXX XXXX" />
            {errors.phone && <span className="field-error">{errors.phone}</span>}
          </label>
          <label>
            <span>البريد الإلكتروني<span className="req">*</span></span>
            <input className={errors.email ? "invalid" : ""} type="email" value={f.email} onChange={upd("email")} placeholder="you@company.com" />
            {errors.email && <span className="field-error">{errors.email}</span>}
          </label>
          <label>
            <span>القطاع</span>
            <select value={f.industry} onChange={upd("industry")}>
              <option value="">اختر قطاعك</option>
              {dataSectors.map((s) => <option key={s} value={s}>{s}</option>)}
            </select>
          </label>
          <label className="span-2">
            <span>التحدي الرئيسي</span>
            <select value={f.challenge} onChange={upd("challenge")}>
              <option value="">اختر التحدي الأبرز</option>
              {CHALLENGES.map((s) => <option key={s} value={s}>{s}</option>)}
            </select>
          </label>
        </div>

        <label className={"consent-row" + (errors.consent ? " invalid" : "")}>
          <input type="checkbox" checked={f.consent} onChange={upd("consent")} />
          <span>أوافق على تواصل فريق مسلاك معي بخصوص نتيجة التقييم والخدمات ذات الصلة.</span>
        </label>
        {errors.consent && <span className="field-error" style={{ display: "block", marginTop: 6 }}>{errors.consent}</span>}

        <div className="lead-cta-row">
          <button type="submit" className="btn btn-primary">أرسل لي التقرير <span className="mono">{window.ARR ? window.ARR() : "←"}</span></button>
          <a className="btn btn-ghost" href={BOOKING_URL} target="_blank" rel="noopener noreferrer">احجز جلسة مجانية</a>
        </div>
        <div className="lead-cta-row" style={{ marginTop: 12 }}>
          <a className="btn btn-wa2" href={buildWhatsAppMessage()} target="_blank" rel="noopener noreferrer"><Ico name="chat" size={18} /> أرسل النتيجة على واتساب</a>
        </div>
      </form>
    </div>
  );
}

// ---------- Thank you ----------
function ThankYou({ score, level, topGap, onReset }) {
  return (
    <div className="calc-card thanks-card">
      <div className="tck"><Ico name="check" size={32} /></div>
      <h3>تم استلام تقييمك بنجاح</h3>
      <p>شكرًا لك. سيراجع فريق مسلاك نتيجتك ويتواصل معك لمشاركة التوصيات المناسبة.</p>
      <div className="thanks-summary">
        <div className="ts"><div className="ts-label">النتيجة</div><div className="ts-val mono" style={{ fontFamily: "'JetBrains Mono',monospace" }}>{score} / 100</div></div>
        <div className="ts"><div className="ts-label">المستوى</div><div className="ts-val">{level.title}</div></div>
        {topGap && <div className="ts"><div className="ts-label">أهم فجوة</div><div className="ts-val" style={{ fontSize: 15 }}>{topGap.label}</div></div>}
      </div>
      <div className="extra-cta-row">
        <a className="btn btn-primary" href={MISLAK_WEBSITE} target="_blank" rel="noopener noreferrer">زيارة موقع مسلاك</a>
        <button className="btn btn-ghost" onClick={onReset}>العودة للنتيجة</button>
      </div>
      <div style={{ marginTop: 16, fontSize: 12.5, color: "var(--muted)" }}>يمكنك أخذ لقطة شاشة للنتيجة ومشاركتها مع فريقك.</div>
    </div>
  );
}

Object.assign(window, { AIReadinessPage });
