// ============ REVENUE AT RISK CALCULATOR ============
// Frontend-only lead-gen calculator for events / QR. Brand: Mislak.
const { useState: useC, useEffect: useCE, useRef: useCR, useMemo: useCM } = React;

// UTM / source placeholders (edit later)
const CALC_META = {
  leadSource: "QR / Event Calculator",
  utm_source: "event",
  utm_medium: "qr",
  utm_campaign: "revenue_at_risk_calculator",
  whatsappNumber: "966XXXXXXXXX", // placeholder — replace with real number
};

// Convert Arabic-Indic digits to western and strip non-digits
function toWestern(str) {
  if (str == null) return "";
  return String(str)
    .replace(/[\u0660-\u0669]/g, (d) => String(d.charCodeAt(0) - 0x0660))
    .replace(/[\u06F0-\u06F9]/g, (d) => String(d.charCodeAt(0) - 0x06F0));
}
function parseNum(str) {
  const n = parseInt(toWestern(str).replace(/[^\d]/g, ""), 10);
  return isNaN(n) ? 0 : n;
}
const fmt = (n) => Math.round(n).toLocaleString("en-US");

// Animated counter
function useCountUp(target, duration = 700) {
  const [val, setVal] = useC(target);
  const fromRef = useCR(target);
  const rafRef = useCR(null);
  useCE(() => {
    const reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) { setVal(target); fromRef.current = target; return; }
    const from = fromRef.current;
    const start = performance.now();
    cancelAnimationFrame(rafRef.current);
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - t, 3);
      setVal(from + (target - from) * eased);
      if (t < 1) rafRef.current = requestAnimationFrame(tick);
      else fromRef.current = target;
    };
    rafRef.current = requestAnimationFrame(tick);
    // Fallback: if RAF is throttled (e.g. backgrounded tab), force the final value.
    const fallback = setTimeout(() => { setVal(target); fromRef.current = target; }, duration + 250);
    return () => { cancelAnimationFrame(rafRef.current); clearTimeout(fallback); };
  }, [target, duration]);
  return val;
}

const SECTORS_CALC = [
  { id: "clinic", ico: "clinic", label: "عيادة", labelEn: "Clinic" },
  { id: "realestate", ico: "building", label: "عقار", labelEn: "Real estate" },
  { id: "restaurant", ico: "restaurant", label: "مطعم", labelEn: "Restaurant" },
  { id: "ecom", ico: "cart", label: "متجر إلكتروني", labelEn: "E-commerce" },
  { id: "services", ico: "briefcase", label: "خدمات مهنية", labelEn: "Professional services" },
  { id: "maintenance", ico: "wrench", label: "صيانة وخدمات منزلية", labelEn: "Maintenance & home" },
  { id: "education", ico: "cap", label: "تعليم وتدريب", labelEn: "Education & training" },
  { id: "other", ico: "plus", label: "أخرى", labelEn: "Other" },
];

const CALC_DEFAULTS = {
  dailyCalls: 100,
  averageCustomerValue: 1500,
  missedCallRate: 15,
  workingDays: 22,
  salesOpportunityRate: 30,
  conversionRate: 15,
};

function CalcIcon({ name, size = 24 }) {
  
  const paths = {
    phone: <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/>,
    phoneMissed: <g><path d="M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.42 19.42 0 0 1-3.33-2.67m-2.67-3.34A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91"/><line x1="23" y1="1" x2="1" y2="23"/></g>,
    target: <g><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></g>,
    alert: <g><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></g>,
    trendingDown: <g><polyline points="23 18 13.5 8.5 8.5 13.5 1 6"/><polyline points="17 18 23 18 23 12"/></g>,
    barChart: <g><line x1="12" y1="20" x2="12" y2="10"/><line x1="18" y1="20" x2="18" y2="4"/><line x1="6" y1="20" x2="6" y2="16"/></g>,
    robot: <g><rect x="4" y="8" width="16" height="12" rx="3"/><line x1="12" y1="4" x2="12" y2="8"/><circle cx="12" cy="3" r="1.2"/><circle cx="9" cy="14" r="1.3" fill="currentColor" stroke="none"/><circle cx="15" cy="14" r="1.3" fill="currentColor" stroke="none"/><line x1="8" y1="20" x2="8" y2="22"/><line x1="16" y1="20" x2="16" y2="22"/></g>,
    shuffle: <g><polyline points="16 3 21 3 21 8"/><line x1="4" y1="20" x2="21" y2="3"/><polyline points="21 16 21 21 16 21"/><line x1="15" y1="15" x2="21" y2="21"/><line x1="4" y1="4" x2="9" y2="9"/></g>,
    clipboard: <g><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect x="8" y="2" width="8" height="4" rx="1"/><line x1="9" y1="12" x2="15" y2="12"/><line x1="9" y1="16" x2="13" y2="16"/></g>,
    clinic: <g><rect x="4" y="4" width="16" height="16" rx="3"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></g>,
    building: <g><path d="M5 21V5a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v16"/><path d="M15 9h3a1 1 0 0 1 1 1v11"/><line x1="3" y1="21" x2="21" y2="21"/><line x1="8" y1="8" x2="11" y2="8"/><line x1="8" y1="12" x2="11" y2="12"/></g>,
    restaurant: <g><path d="M6 2v8a2 2 0 0 0 4 0V2"/><line x1="8" y1="10" x2="8" y2="22"/><path d="M17 2c-1.5 0-2.5 1.8-2.5 4.5S15.5 11 17 11v11"/></g>,
    cart: <g><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></g>,
    briefcase: <g><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/></g>,
    wrench: <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>,
    cap: <g><path d="M22 10 12 5 2 10l10 5 10-5z"/><path d="M6 12v5c0 1 2.5 3 6 3s6-2 6-3v-5"/></g>,
    plus: <g><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></g>,
    download: <g><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></g>,
    send: <g><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></g>,
    chat: <g><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8z"/></g>,
    gauge: <g><path d="M3 12a9 9 0 1 1 18 0"/><line x1="12" y1="12" x2="16" y2="9"/><circle cx="12" cy="12" r="1.6" fill="currentColor" stroke="none"/></g>,
    database: <g><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14a9 3 0 0 0 18 0V5"/><path d="M3 12a9 3 0 0 0 18 0"/></g>,
    check: <g><polyline points="20 6 9 17 4 12"/></g>,
    calendar: <g><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></g>,
    sparkle: <g><path d="M12 3l1.9 5.8L20 11l-6.1 2.2L12 19l-1.9-5.8L4 11l6.1-2.2z"/></g>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">{paths[name]}</svg>
  );
}

function CalculatorPage() {
  window.useLang();
  const [vals, setVals] = useC(CALC_DEFAULTS);
  const [sector, setSector] = useC("");
  const [step, setStep] = useC(1);
  const [started, setStarted] = useC(false);
  const [advOpen, setAdvOpen] = useC(false);
  const resultsRef = useCR(null);

  const set = (k) => (v) => setVals((s) => ({ ...s, [k]: v }));

  // ---- calculations ----
  const calc = useCM(() => {
    const { dailyCalls, missedCallRate, workingDays, salesOpportunityRate, conversionRate, averageCustomerValue } = vals;
    const monthlyMissedCalls = dailyCalls * (missedCallRate / 100) * workingDays;
    const missedOpportunities = monthlyMissedCalls * (salesOpportunityRate / 100);
    const missedCustomers = missedOpportunities * (conversionRate / 100);
    const revenueAtRisk = missedCustomers * averageCustomerValue;
    const protectedRevenue = revenueAtRisk * 0.5;
    let riskLevel = "low";
    if (revenueAtRisk > 50000) riskLevel = "high";
    else if (revenueAtRisk >= 10000) riskLevel = "medium";
    return { monthlyMissedCalls, missedOpportunities, missedCustomers, revenueAtRisk, protectedRevenue, riskLevel };
  }, [vals]);

  const summary = useCM(() => ({
    sector,
    ...vals,
    ...calc,
  }), [sector, vals, calc]);

  // animated figures
  const aRevenue = useCountUp(started ? calc.revenueAtRisk : 0);
  const aMissedCalls = useCountUp(started ? calc.monthlyMissedCalls : 0);
  const aOpps = useCountUp(started ? calc.missedOpportunities : 0);
  const aCustomers = useCountUp(started ? calc.missedCustomers : 0);
  const aProtected = useCountUp(started ? calc.protectedRevenue : 0);

  const riskPct = Math.max(4, Math.min(96, (calc.revenueAtRisk / 80000) * 100));
  const riskLabel = { low: window.L("منخفض", "Low"), medium: window.L("متوسط", "Medium"), high: window.L("مرتفع", "High") }[calc.riskLevel];

  // ---- actions ----
  const showResult = () => {
    setStarted(true);
    setTimeout(() => {
      if (resultsRef.current) {
        const y = resultsRef.current.getBoundingClientRect().top + window.scrollY - 80;
        window.scrollTo({ top: y, behavior: "smooth" });
      }
    }, 60);
  };
  const resetCalculator = () => {
    setVals(CALC_DEFAULTS);
    setSector("");
    setStep(1);
    setStarted(false);
    setAdvOpen(false);
  };

  const [copied, setCopied] = useC(false);
  const downloadResult = () => {
    const sObj = SECTORS_CALC.find((s) => s.id === sector) || {};
    const sectorLabel = window.L(sObj.label || "غير محدد", sObj.labelEn || sObj.label || "Not specified");
    const cur = window.L("ريال", "SAR");
    window.MislakReport({
      filename: "mislak-revenue-at-risk",
      title: window.L("تقدير الفرص المحتملة المفقودة", "Estimated Potential Lost Opportunities"),
      subtitle: window.L(
        "تقدير تقريبي للإيرادات المحتملة المعرضة للضياع بسبب المكالمات الفائتة.",
        "An approximate estimate of potential revenue at risk due to missed calls."
      ),
      hero: {
        label: window.L("إيرادات محتملة معرضة للضياع شهريًا", "Potential revenue at risk per month"),
        value: `${fmt(calc.revenueAtRisk)} ${cur}`,
      },
      rows: [
        { heading: window.L("المدخلات", "Inputs") },
        { label: window.L("القطاع", "Sector"), value: sectorLabel },
        { label: window.L("المكالمات اليومية", "Daily calls"), value: fmt(vals.dailyCalls) },
        { label: window.L("متوسط قيمة العميل", "Avg. customer value"), value: `${fmt(vals.averageCustomerValue)} ${cur}` },
        { label: window.L("نسبة المكالمات الفائتة", "Missed-call rate"), value: `${vals.missedCallRate}%` },
        { heading: window.L("النتائج", "Results") },
        { label: window.L("المكالمات الفائتة شهريًا", "Missed calls / month"), value: fmt(calc.monthlyMissedCalls) },
        { label: window.L("فرص البيع المحتملة", "Potential sales opportunities"), value: fmt(calc.missedOpportunities) },
        { label: window.L("العملاء المحتملون الضائعون", "Potential lost customers"), value: fmt(calc.missedCustomers) },
        { label: window.L("الإيرادات المحتملة المعرضة للضياع", "Potential revenue at risk"), value: `${fmt(calc.revenueAtRisk)} ${cur}`, big: true },
        { label: window.L("فرص يمكن حمايتها", "Recoverable opportunities"), value: `${fmt(calc.protectedRevenue)} ${cur}` },
      ],
      note: window.L(
        "هذا تقدير تجاري تقريبي وليس رقمًا محاسبيًا مؤكدًا. الهدف هو توضيح حجم الفرص التي قد تضيع، وليس ضمان إيرادات.",
        "This is an approximate commercial estimate, not a guaranteed accounting figure. It illustrates the scale of opportunities at risk, not promised revenue."
      ),
    });
  };

  return (
    <div className="calc-page">
      {/* HERO */}
      <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("كم تكلفك المكالمات الفائتة؟", "What are missed calls costing you?")}</h1>
              <p className="lead">{window.L("كل مكالمة فائتة قد تكون فرصة بيع أو عميل جديد. احصل على تقدير سريع للإيرادات المحتملة المعرضة للضياع خلال 60 ثانية.", "Every missed call could be a sale or a new customer. Get a quick estimate of your potential revenue at risk in 60 seconds.")}</p>
              <div className="calc-hero-cta">
                <button className="btn btn-accent" onClick={() => { document.getElementById("calc-tool").scrollIntoView({ behavior: "smooth" }); }}>{window.L("ابدأ الحساب", "Start calculating")} <span className="mono">{window.ARR ? window.ARR() : "←"}</span></button>
                <button className="btn btn-glass" onClick={() => { document.getElementById("calc-how").scrollIntoView({ behavior: "smooth" }); }}>{window.L("كيف يتم الحساب؟", "How is it calculated?")}</button>
              </div>
            </div>
            <div className="calc-preview">
              <div className="pv-label">{window.L("تقدير مبدئي", "Preliminary estimate")}</div>
              <div className="pv-num">{fmt(started ? calc.revenueAtRisk : 22275)}<span className="cur">{window.L("ريال / شهرياً", "SAR / month")}</span></div>
              <div className="pv-sub">{window.L("إيرادات محتملة معرضة للضياع", "Potential revenue at risk")}</div>
              <div className="pv-flow">
                <div className="pv-flow-row"><span>{window.L("مكالمات واردة", "Incoming calls")}</span><span className="v">Incoming</span></div>
                <div className="pv-flow-row"><span>{window.L("مكالمات فائتة", "Missed calls")}</span><span className="v">Missed</span></div>
                <div className="pv-flow-row"><span>{window.L("فرص بيع محتملة", "Sales opportunities")}</span><span className="v">Opportunities</span></div>
                <div className="pv-flow-row"><span>{window.L("إيرادات معرضة للضياع", "Revenue at risk")}</span><span className="v">At Risk</span></div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* CALCULATOR TOOL */}
      <section className="calc-section" id="calc-tool">
        <div className="container">
          <div className="calc-section-head">
            <div className="calc-eyebrow">{window.L("الحاسبة التفاعلية", "Interactive calculator")}</div>
            <h2>{window.L("قدّر فرصك في 3 خطوات", "Estimate your opportunities in 3 steps")}</h2>
            <p>{window.L("أدخل بيانات بسيطة عن مكالماتك، وسنحسب لك التقدير مباشرة.", "Enter a few simple details about your calls and we'll calculate the estimate instantly.")}</p>
          </div>

          <div className="calc-wrap">
            <div className="calc-card">
              <div className="step-progress">
                <span className="label">{window.L(`الخطوة ${step} من 3`, `Step ${step} of 3`)}</span>
                <div className="track"><div className="fill" style={{ width: (step / 3 * 100) + "%" }}></div></div>
              </div>

              {step === 1 && (
                <div>
                  <div className="step-q">{window.L("كم مكالمة تستقبل شركتك يوميًا؟", "How many calls does your company receive daily?")}</div>
                  <div className="step-micro">{window.L("اكتب متوسط عدد المكالمات الواردة يوميًا من العملاء أو المهتمين.", "Enter the average number of incoming calls per day from customers or prospects.")}</div>
                  <div className="field-big">
                    <div className="field-value-row">
                      <input className="num" type="text" inputMode="numeric" value={vals.dailyCalls}
                        onChange={(e) => set("dailyCalls")(Math.min(500, Math.max(10, parseNum(e.target.value) || 10)))}
                        aria-label="عدد المكالمات اليومية" />
                      <span className="unit">{window.L("مكالمة / يوم", "calls / day")}</span>
                    </div>
                    <input className="slider" type="range" min="10" max="500" step="5" value={vals.dailyCalls}
                      onChange={(e) => set("dailyCalls")(parseNum(e.target.value))} aria-label="شريط عدد المكالمات اليومية" />
                    <div className="range-ends"><span>10</span><span>500</span></div>
                  </div>
                </div>
              )}

              {step === 2 && (
                <div>
                  <div className="step-q">{window.L("كم متوسط قيمة العميل الواحد؟", "What's your average customer value?")}</div>
                  <div className="step-micro">{window.L("يمكن أن تكون قيمة طلب، اشتراك، حجز، أو صفقة متوسطة.", "It could be an average order, subscription, booking, or deal.")}</div>
                  <div className="field-big">
                    <div className="field-value-row">
                      <input className="num" type="text" inputMode="numeric" value={vals.averageCustomerValue}
                        onChange={(e) => set("averageCustomerValue")(Math.min(50000, Math.max(100, parseNum(e.target.value) || 100)))}
                        aria-label="متوسط قيمة العميل" />
                      <span className="unit">{window.L("ريال", "SAR")}</span>
                    </div>
                    <input className="slider" type="range" min="100" max="50000" step="100" value={vals.averageCustomerValue}
                      onChange={(e) => set("averageCustomerValue")(parseNum(e.target.value))} aria-label="شريط متوسط قيمة العميل" />
                    <div className="range-ends"><span>100</span><span>50,000</span></div>
                  </div>
                </div>
              )}

              {step === 3 && (
                <div>
                  <div className="step-q">{window.L("ما نوع نشاطك؟", "What's your business type?")}</div>
                  <div className="step-micro">{window.L("يساعدنا هذا على تجهيز تشخيص أنسب لقطاعك. (لا يغيّر الحساب تلقائيًا)", "This helps us tailor a better diagnosis for your sector. (It doesn't change the calculation automatically.)")}</div>
                  <div className="sector-grid">
                    {SECTORS_CALC.map((s) => (
                      <button key={s.id} type="button"
                        className={"sector-opt" + (sector === s.id ? " active" : "")}
                        onClick={() => setSector(s.id)} aria-pressed={sector === s.id}>
                        <span className="ico"><CalcIcon name={s.ico} size={28} /></span>
                        <span>{window.L(s.label, s.labelEn)}</span>
                      </button>
                    ))}
                  </div>
                </div>
              )}

              <div className="step-nav">
                {step > 1
                  ? <button className="btn btn-ghost" onClick={() => setStep(step - 1)}>{window.L("السابق", "Back")}</button>
                  : <span className="spacer"></span>}
                {step < 3
                  ? <button className="btn btn-primary" onClick={() => setStep(step + 1)}>{window.L("التالي", "Next")} <span className="mono">{window.ARR ? window.ARR() : "←"}</span></button>
                  : <button className="btn btn-primary" onClick={showResult}>{window.L("عرض النتيجة", "View result")} <span className="mono">{window.ARR ? window.ARR() : "←"}</span></button>}
              </div>
            </div>

            {/* Advanced mode */}
            <div className={"advanced" + (advOpen ? " open" : "")}>
              <button className="advanced-toggle" onClick={() => setAdvOpen(!advOpen)} aria-expanded={advOpen}>
                <span>{window.L("تعديل الافتراضات", "Adjust assumptions")}</span>
                <span className="chev">▾</span>
              </button>
              {advOpen && (
                <div className="advanced-body">
                  <div className="adv-field" style={{ gridColumn: "span 2" }}>
                    <span style={{ color: "var(--muted)", fontWeight: 500 }}>{window.L("استخدمنا افتراضات محافظة، ويمكنك تعديلها حسب واقع شركتك. النتيجة تتحدث مباشرة.", "We used conservative assumptions; you can adjust them to match your business. The result updates instantly.")}</span>
                  </div>
                  <AdvSlider label={window.L("نسبة المكالمات الفائتة", "Missed-call rate")} suffix="%" min={1} max={60} value={vals.missedCallRate} onChange={set("missedCallRate")} />
                  <AdvSlider label={window.L("أيام العمل بالشهر", "Working days per month")} suffix="يوم" min={1} max={31} value={vals.workingDays} onChange={set("workingDays")} />
                  <AdvSlider label={window.L("نسبة المكالمات التي تعتبر فرص بيع", "Share of calls that are sales opportunities")} suffix="%" min={1} max={100} value={vals.salesOpportunityRate} onChange={set("salesOpportunityRate")} />
                  <AdvSlider label={window.L("نسبة التحويل من مكالمة إلى عميل", "Call-to-customer conversion rate")} suffix="%" min={1} max={100} value={vals.conversionRate} onChange={set("conversionRate")} />
                  <div className="advanced-reset">
                    <button className="btn btn-ghost btn-sm" onClick={() => setVals((s) => ({ ...s, missedCallRate: 15, workingDays: 22, salesOpportunityRate: 30, conversionRate: 15 }))}>{window.L("إعادة الافتراضات", "Reset assumptions")}</button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </section>

      {/* RESULTS */}
      <section className="calc-section alt" ref={resultsRef}>
        <div className="container">
          {!started ? (
            <div className="results-empty">
              <div className="ico" aria-hidden="true"><CalcIcon name="barChart" size={34} /></div>
              {window.L("ابدأ بإدخال بيانات بسيطة للحصول على تقدير مبدئي للإيرادات المحتملة المعرضة للضياع.", "Enter a few simple details to get a preliminary estimate of your potential revenue at risk.")}
            </div>
          ) : (
            <div>
              <div className="calc-section-head">
                <div className="calc-eyebrow">{window.L("النتيجة", "Result")}</div>
                <h2>{window.L("تقدير الفرص المحتملة المفقودة شهريًا", "Estimated potential lost opportunities per month")}</h2>
              </div>
              <div className="result-cards">
                <div className="result-card hero-num">
                  <div className="rc-label">{window.L("الإيرادات المحتملة المعرضة للضياع", "Potential revenue at risk")}</div>
                  <div className="rc-num">{fmt(aRevenue)}<span className="cur">{window.L("ريال", "SAR")}</span></div>
                  <div className="rc-per">{window.L("شهريًا · Revenue at Risk", "Per month · Revenue at Risk")}</div>
                </div>
                <div className="result-card">
                  <div className="rc-label">{window.L("المكالمات الفائتة شهريًا", "Missed calls per month")}</div>
                  <div className="rc-num">{fmt(aMissedCalls)}</div>
                </div>
                <div className="result-card">
                  <div className="rc-label">{window.L("فرص البيع المحتملة", "Potential sales opportunities")}</div>
                  <div className="rc-num">{fmt(aOpps)}</div>
                </div>
                <div className="result-card">
                  <div className="rc-label">{window.L("العملاء المحتملون الضائعون", "Potential lost customers")}</div>
                  <div className="rc-num">{fmt(aCustomers)}</div>
                </div>
                <div className="result-card accent">
                  <div className="rc-label">{window.L("فرص يمكن حمايتها", "Recoverable opportunities")}</div>
                  <div className="rc-num">{fmt(aProtected)}</div>
                </div>
              </div>

              <div className="risk-meter">
                <div className="risk-bar">
                  <div className="needle" style={{ right: riskPct + "%" }}></div>
                </div>
                <div className="risk-labels"><span>{window.L("منخفض", "Low")}</span><span>{window.L("متوسط", "Medium")}</span><span>{window.L("مرتفع", "High")}</span></div>
                <div style={{ textAlign: "center" }}>
                  <span className={"risk-pill " + calc.riskLevel}><span className="dot"></span> {window.L("مستوى المخاطرة:", "Risk level:")} {riskLabel}</span>
                </div>
              </div>

              <p className="result-note">{window.L("هذا تقدير تجاري تقريبي وليس رقمًا محاسبيًا مؤكدًا. الهدف هو توضيح حجم الفرص التي قد تضيع بسبب المكالمات الفائتة أو ضعف إدارة الاتصالات.", "This is an approximate commercial estimate, not a guaranteed accounting figure. It illustrates the scale of opportunities that may be lost due to missed calls or weak communication management.")}</p>
              <div className="result-actions">
                <button className="btn btn-ghost btn-sm" onClick={downloadResult}><CalcIcon name="download" size={16} /> {window.L("تحميل النتيجة", "Download result")}</button>
                <button className="btn btn-ghost btn-sm" onClick={resetCalculator}>{window.L("إعادة الحساب", "Recalculate")}</button>
              </div>
            </div>
          )}
        </div>
      </section>

      {started && (
        <React.Fragment>
          {/* IMPACT */}
          <section className="calc-section">
            <div className="container">
              <div className="calc-section-head">
                <div className="calc-eyebrow">{window.L("أثر مسلاك", "Mislak's impact")}</div>
                <h2>{window.L("ماذا لو قللت مسلاك المكالمات الفائتة بنسبة 50%؟", "What if Mislak cut missed calls by 50%?")}</h2>
              </div>
              <div className="impact-grid">
                <div className="impact-card now">
                  <div className="ic-label">{window.L("الوضع الحالي", "Current situation")}</div>
                  <div className="ic-num">{fmt(calc.revenueAtRisk)} <span style={{ fontSize: ".5em", color: "var(--muted)" }}>{window.L("ريال", "SAR")}</span></div>
                  <div className="ic-sub">{window.L("إيرادات محتملة معرضة للضياع شهريًا", "Potential revenue at risk per month")}</div>
                </div>
                <div className="impact-arrow" aria-hidden="true">←</div>
                <div className="impact-card after">
                  <div className="ic-label">{window.L("فرص يمكن حمايتها", "Recoverable opportunities")}</div>
                  <div className="ic-num">{fmt(calc.protectedRevenue)} <span style={{ fontSize: ".5em", color: "rgba(255,255,255,.7)" }}>{window.L("ريال", "SAR")}</span></div>
                  <div className="ic-sub">{window.L("بعد تحسين إدارة المكالمات شهريًا", "After improving call management, per month")}</div>
                </div>
              </div>
              <p className="result-note">{window.L("مسلاك لا تضمن الإيرادات، لكنها تساعد الشركات على تقليل ضياع الفرص من خلال الرقم الموحد، توزيع المكالمات، IVR، تسجيل المكالمات، التقارير، وربط قنوات التواصل.", "Mislak doesn't guarantee revenue, but it helps companies reduce lost opportunities through a unified number, call distribution, IVR, call recording, reports, and connected communication channels.")}</p>
            </div>
          </section>

          {/* MINI DIAGRAM */}
          <section className="calc-section alt">
            <div className="container">
              <div className="calc-section-head">
                <div className="calc-eyebrow">{window.L("كيف تتسرّب الفرص", "How opportunities leak")}</div>
                <h2>{window.L("من المكالمة إلى الإيراد المعرّض للضياع", "From call to revenue at risk")}</h2>
              </div>
              <div className="diagram">
                <div className="node"><div className="dn-ico"><CalcIcon name="phone" size={28} /></div><div className="dn-label">{window.L("مكالمات واردة", "Incoming calls")}</div></div>
                <div className="arrow" aria-hidden="true">←</div>
                <div className="node"><div className="dn-ico"><CalcIcon name="phoneMissed" size={28} /></div><div className="dn-label">{window.L("مكالمات فائتة", "Missed calls")}</div></div>
                <div className="arrow" aria-hidden="true">←</div>
                <div className="node"><div className="dn-ico"><CalcIcon name="target" size={28} /></div><div className="dn-label">{window.L("فرص بيع محتملة", "Sales opportunities")}</div></div>
                <div className="arrow" aria-hidden="true">←</div>
                <div className="node danger"><div className="dn-ico"><CalcIcon name="alert" size={28} /></div><div className="dn-label">{window.L("إيرادات معرضة للضياع", "Revenue at risk")}</div></div>
              </div>
            </div>
          </section>

          {/* TRY THE OTHER TEST is rendered below, outside the started block */}
        </React.Fragment>
      )}

      {/* HOW MISLAK HELPS */}
      <section className="calc-section alt" id="calc-how">
        <div className="container">
          <div className="calc-section-head">
            <div className="calc-eyebrow">{window.L("كيف يتم الحساب؟ · كيف تساعدك مسلاك", "How is it calculated? · How Mislak helps")}</div>
            <h2>{window.L("كيف تساعدك مسلاك؟", "How does Mislak help?")}</h2>
          </div>
          <div className="help-grid">
            <div className="help-card"><div className="hc-ico"><CalcIcon name="phone" /></div><h4>{window.L("رقم موحد لاستقبال مكالمات العملاء", "A unified number for customer calls")}</h4></div>
            <div className="help-card"><div className="hc-ico"><CalcIcon name="shuffle" /></div><h4>{window.L("توزيع ذكي للمكالمات على الفريق", "Smart call distribution across the team")}</h4></div>
            <div className="help-card"><div className="hc-ico"><CalcIcon name="clipboard" /></div><h4>{window.L("IVR وتسجيل وتقارير واضحة", "IVR, recording, and clear reports")}</h4></div>
            <div className="help-card"><div className="hc-ico"><CalcIcon name="robot" /></div><h4>{window.L("ربط المكالمات مع واتساب والأتمتة والذكاء الاصطناعي", "Connect calls with WhatsApp, automation, and AI")}</h4></div>
          </div>
        </div>
      </section>

      {/* TRY THE OTHER TEST */}
      <section className="calc-section">
        <div className="container">
          <div className="calc-section-head" style={{ marginBottom: 24 }}>
            <div className="calc-eyebrow">{window.L("اختبار آخر", "Another test")}</div>
            <h2>{window.L("جرّب اختبار الجاهزية للذكاء الاصطناعي", "Try the AI readiness test")}</h2>
          </div>
          <div className="lead-wrap">
            <a className="test-btn" href="#/ai-readiness">
              <span className="tb-ico"><CalcIcon name="robot" size={24} /></span>
              <span className="tb-txt">
                <span className="tb-title">{window.L("اختبار جاهزية خدمة عملاء شركتك للذكاء الاصطناعي", "Your customer service's AI readiness test")}</span>
                <span className="tb-desc">{window.L("قيّم جاهزية فريقك لتبنّي الذكاء الاصطناعي خلال دقيقة.", "Assess your team's readiness to adopt AI in a minute.")}</span>
              </span>
              <span className="tb-arrow mono">{window.ARR ? window.ARR() : "←"}</span>
            </a>
          </div>
        </div>
      </section>

      {/* CALC FOOTER */}
      <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>
  );
}

function AdvSlider({ label, suffix, min, max, value, onChange }) {
  return (
    <div className="adv-field">
      <span>{label}<b>{value}{suffix === "%" ? "%" : ""}</b></span>
      <input className="slider" type="range" min={min} max={max} step="1" value={value}
        onChange={(e) => onChange(parseNum(e.target.value) || min)} aria-label={label} />
      <div className="range-ends"><span>{min}</span><span>{max}{suffix === "%" ? "%" : ""}</span></div>
    </div>
  );
}

function LeadForm({ summary, calc, vals, sector }) {
  const preSector = (SECTORS_CALC.find((s) => s.id === sector) || {}).id || "";
  const [form, setForm] = useC({ name: "", company: "", phone: "", email: "", sector: "" });
  const [errors, setErrors] = useC({});
  const [sent, setSent] = useC(false);
  const dataSectors = (window.getData && window.getData().sectors) || [];
  const sectorLabel = form.sector === "other"
    ? window.L("قطاع آخر", "Other sector")
    : ((dataSectors.find((s) => s.id === form.sector) || {}).tab || window.L("غير محدد", "Not specified"));
  const upd = (k) => (e) => {
    setForm({ ...form, [k]: e.target.value });
    if (errors[k]) setErrors((er) => { const n = { ...er }; delete n[k]; return n; });
  };

  const validate = () => {
    const e = {};
    const soft = "يبدو أن هذا الحقل يحتاج تعديلًا بسيطًا";
    if (!form.name.trim()) e.name = soft;
    else if (!(/^[\u0600-\u06FF\s]+$/.test(form.name.trim()) || /^[A-Za-z\s]+$/.test(form.name.trim())))
      e.name = "يبدو أن الاسم يحتاج تعديلًا بسيطًا (حروف فقط)";
    if (!form.company.trim()) e.company = soft;
    const phone = toWestern(form.phone).replace(/[\s()-]/g, "");
    if (!phone) e.phone = soft;
    else if (!/^(\+9665\d{8}|9665\d{8}|05\d{8})$/.test(phone)) e.phone = "يبدو أن رقم الجوال يحتاج تعديلًا بسيطًا";
    if (!form.email.trim()) e.email = soft;
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) e.email = "يبدو أن البريد يحتاج تعديلًا بسيطًا";
    if (!form.sector) e.sector = "يرجى اختيار القطاع";
    return e;
  };

  const onSubmit = (ev) => {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length === 0) {
      // Frontend only — Result Summary object ready for a backend later:
      window.__mislakLastLead = { ...form, ...summary, leadSource: CALC_META.leadSource };
      setSent(true);
    }
  };

  const downloadResult = () => {
    const cur = window.L("ريال", "SAR");
    const dash = "-";
    window.MislakReport({
      filename: "mislak-revenue-at-risk",
      title: window.L("تقدير الفرص المحتملة المفقودة", "Estimated Potential Lost Opportunities"),
      subtitle: window.L(
        "تقدير تقريبي للإيرادات المحتملة المعرضة للضياع بسبب المكالمات الفائتة.",
        "An approximate estimate of potential revenue at risk due to missed calls."
      ),
      hero: {
        label: window.L("إيرادات محتملة معرضة للضياع شهريًا", "Potential revenue at risk per month"),
        value: `${fmt(calc.revenueAtRisk)} ${cur}`,
      },
      rows: [
        { heading: window.L("بيانات التواصل", "Contact details") },
        { label: window.L("الاسم", "Name"), value: form.name || dash },
        { label: window.L("الشركة", "Company"), value: form.company || dash },
        { label: window.L("رقم الجوال", "Phone"), value: form.phone || dash },
        { label: window.L("البريد الإلكتروني", "Email"), value: form.email || dash },
        { label: window.L("القطاع", "Sector"), value: sectorLabel },
        { heading: window.L("المدخلات والنتائج", "Inputs & results") },
        { label: window.L("المكالمات اليومية", "Daily calls"), value: fmt(vals.dailyCalls) },
        { label: window.L("متوسط قيمة العميل", "Avg. customer value"), value: `${fmt(vals.averageCustomerValue)} ${cur}` },
        { label: window.L("نسبة المكالمات الفائتة", "Missed-call rate"), value: `${vals.missedCallRate}%` },
        { label: window.L("المكالمات الفائتة شهريًا", "Missed calls / month"), value: fmt(calc.monthlyMissedCalls) },
        { label: window.L("فرص البيع المحتملة", "Potential sales opportunities"), value: fmt(calc.missedOpportunities) },
        { label: window.L("العملاء المحتملون الضائعون", "Potential lost customers"), value: fmt(calc.missedCustomers) },
        { label: window.L("الإيرادات المحتملة المعرضة للضياع", "Potential revenue at risk"), value: `${fmt(calc.revenueAtRisk)} ${cur}`, big: true },
        { label: window.L("فرص يمكن حمايتها", "Recoverable opportunities"), value: `${fmt(calc.protectedRevenue)} ${cur}` },
      ],
      note: window.L(
        "هذا تقدير تجاري تقريبي وليس رقمًا محاسبيًا مؤكدًا. الهدف هو توضيح حجم الفرص التي قد تضيع، وليس ضمان إيرادات.",
        "This is an approximate commercial estimate, not a guaranteed accounting figure. It illustrates the scale of opportunities at risk, not promised revenue."
      ),
    });
  };

  return (
    <div className="container">
      <div className="calc-section-head">
        <div className="calc-eyebrow">تشخيص مجاني</div>
        <h2>هل تريد تشخيصًا مجانيًا لمكالمات شركتك؟</h2>
        <p>شاركنا بياناتك وسيقوم فريق مسلاك بمراجعة النتيجة واقتراح طريقة أفضل لتنظيم مكالمات العملاء وتقليل الفرص الضائعة.</p>
      </div>
      <div className="lead-wrap">
        <div className="lead-result-chip">
          <span className="lc-label">إيرادات محتملة معرضة للضياع شهريًا</span>
          <span className="lc-num">{fmt(calc.revenueAtRisk)} ريال</span>
        </div>

        {sent ? (
          <div className="form-success">
            <div className="mono" style={{ fontSize: 12, color: "var(--accent)", letterSpacing: ".1em", marginBottom: 12 }}>✓ تم الاستلام</div>
            <h3>تم استلام طلبك، وسيتم التواصل معك من فريق مسلاك.</h3>
            <button className="btn btn-ghost" style={{ marginTop: 20, display: "inline-flex" }} onClick={downloadResult}><CalcIcon name="download" size={18} /> تحميل النتيجة</button>
          </div>
        ) : (
          <form onSubmit={onSubmit} noValidate>
            <div className="form-grid">
              <label>
                <span>الاسم<span className="req">*</span></span>
                <input className={errors.name ? "invalid" : ""} value={form.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={form.company} onChange={upd("company")} placeholder="شركة المثال" />
                {errors.company && <span className="field-error">{errors.company}</span>}
              </label>
              <label>
                <span>رقم الجوال<span className="req">*</span></span>
                <input className={errors.phone ? "invalid" : ""} type="tel" dir="ltr" value={form.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={form.email} onChange={upd("email")} placeholder="you@company.com" />
                {errors.email && <span className="field-error">{errors.email}</span>}
              </label>
              <label className="span-2">
                <span>القطاع<span className="req">*</span></span>
                <select className={errors.sector ? "invalid" : ""} value={form.sector} onChange={upd("sector")}>
                  <option value="">اختر قطاعك</option>
                  {dataSectors.map((s) => <option key={s.id} value={s.id}>{s.tab}</option>)}
                  <option value="other">قطاع آخر</option>
                </select>
                {errors.sector && <span className="field-error">{errors.sector}</span>}
              </label>
            </div>
            <div className="lead-actions">
              <button type="button" className="btn btn-ghost" onClick={downloadResult}><CalcIcon name="download" size={18} /> تحميل النتيجة</button>
              <button type="submit" className="btn btn-primary">إرسال <span className="mono">{window.ARR ? window.ARR() : "←"}</span></button>
            </div>
            <p className="lead-privacy">باستخدام النموذج، أنت توافق على تواصل فريق مسلاك معك بخصوص التشخيص المطلوب فقط.</p>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { CalculatorPage, CalcIcon });
