// Inner pages: Services, ServiceDetail, HowItWorks, Sectors, SectorDetail, AIAgents, Pricing, Contact
const { useState: usePS } = React;

// Backend endpoint (Cloudflare Worker -> Google Sheets)
window.MISLAK_FORMS_ENDPOINT = "https://mislak-forms.mislak.workers.dev";
window.submitMislakForm = async function (formName, data) {
  try {
    const res = await fetch(window.MISLAK_FORMS_ENDPOINT, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ form: formName, data }),
    });
    return res.ok;
  } catch (err) {
    return false;
  }
};

// ============ SERVICES OVERVIEW ============
function ServicesPage() {
  return (
    <React.Fragment>
      <PageHero
        eyebrow={window.L("الخدمات", "Services")}
        title={window.L(<>حلول ذكية تُدار<br/>بضغطة زر.</>, <>Smart solutions managed<br/>with one click.</>)}
        sub={window.L("منصة واحدة تجمع المكالمات، الرقم الموحد، التوجيه، التقارير، الواتساب، والذكاء الاصطناعي. اضغط على أي بطاقة لمعرفة تفاصيل أعمق.", "One platform that brings together calls, the unified number, routing, reports, WhatsApp, and AI. Click any card to see deeper details.")}
      />
      <section style={{paddingTop: 8}}>
        <div className="container">
          <div className="feat-grid">
            {window.getData().features.map((f) => (
              <a key={f.num} href={`#/services/${f.viz}`} className={`feat span-${f.span} ${f.dark ? "dark" : ""}`} style={{textDecoration: "none", color: f.dark ? "var(--premium-ink)" : "inherit"}}>
                <div className="feat-num">{f.num} / {String(window.getData().features.length).padStart(2, "0")}</div>
                <h3>{f.title}</h3>
                <p>{f.desc}</p>
                <FeatViz kind={f.viz} dark={f.dark}/>
                <span className="feat-link">{window.L("عرض التفاصيل", "View details")}</span>
              </a>
            ))}
          </div>
        </div>
      </section>
      <section>
        <div className="container">
          <div className="final-cta">
            <h2>{window.L(<>حاب تجرّبه على شركتك؟<br/>خلّنا نوريك كيف يشتغل.</>, <>Want to try it on your business?<br/>Let us show you how it works.</>)}</h2>
            <p>{window.L("إذا حاب تجرّب وتشوف إذا مسلاك يناسب طبيعة شغلك، احجز عرضك التجريبي المجاني — نوقّفك على المنصة خطوة بخطوة، وتقرّر بنفسك بدون أي التزام.", "If you'd like to try it and see whether Mislak fits the way you work, just book your free demo — we'll walk you through the platform step by step, and you decide for yourself, no commitment.")}</p>
            <div style={{display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap"}}>
              <a className="btn btn-accent" href="#/contact">{window.L("احجز عرضك التجريبي المجاني", "Book your free demo")}<span className="mono">{window.ARR()}</span></a>
            </div>
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

// ============ SERVICE DETAIL ============
function ServiceDetailPage({ id }) {
  const s = window.getDetails().serviceDetails[id];
  if (!s) return <NotFound/>;
  return (
    <React.Fragment>
      <PageHero
        eyebrow={s.tab}
        title={s.hero}
        sub={s.intro}
        breadcrumbs={[
          { label: window.L("الرئيسية", "Home"), href: "#/" },
          { label: window.L("الخدمات", "Services"), href: "#/services" },
          { label: s.tab },
        ]}
      />
      <section style={{paddingTop: 16}}>
        <div className="container">
          <div className="detail-board">
            <div className="detail-viz">
              <FeatViz kind={s.id}/>
            </div>
            <div className="detail-quick">
              <div className="sec-eyebrow">{window.L("لمحة سريعة", "Quick glance")}</div>
              <ul className="quick-list">
                {s.sections[0].items.slice(0, 3).map((it, i) => (
                  <li key={i}>
                    <span className="quick-num mono">{`0${i+1}`}</span>
                    <div>
                      <div className="quick-h">{it.h}</div>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </div>
      </section>

      {s.sections.map((sec, i) => (
        <section key={i} style={{paddingTop: 56, paddingBottom: 0}}>
          <div className="container">
            <div className="detail-section">
              <div className="detail-section-h">
                <span className="mono">{`0${i+1}`}</span>
                <h2>{sec.title}</h2>
              </div>
              <div className="detail-items">
                {sec.items.map((it, j) => (
                  <div key={j} className="detail-item">
                    <h4>{it.h}</h4>
                    <p>{it.p}</p>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </section>
      ))}

      {id === "unified" && <UnifiedInfographic/>}

      <PageCTA h={s.cta.h} btn={s.cta.btn} />

      <section style={{paddingTop: 0}}>
        <div className="container">
          <div className="sec-eyebrow">{window.L("خدمات أخرى", "Other services")}</div>
          <h2 style={{marginBottom: 28}}>{window.L("تعرّف على باقي خدمات مسلاك.", "Explore the rest of Mislak's services.")}</h2>
          <div className="related-grid">
            {Object.values(window.getDetails().serviceDetails).filter(o => o.id !== id).slice(0, 3).map((o) => (
              <a key={o.id} href={`#/services/${o.id}`} className="related-card">
                <div className="mono" style={{fontSize: 11, color: "var(--accent)", letterSpacing: ".1em", textTransform: "uppercase"}}>{o.tab}</div>
                <h4>{o.hero}</h4>
                <span className="feat-link">{window.L("عرض التفاصيل", "View details")}</span>
              </a>
            ))}
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

// ============ HOW IT WORKS ============
function HowItWorksPage() {
  return (
    <React.Fragment>
      <PageHero
        eyebrow={window.L("كيف يعمل مسلاك", "How Mislak Works")}
        title={window.L(<>رحلة عميلك مع مسلاك،<br/>ذكاء في كل خطوة.</>, <>Your customer's journey with Mislak,<br/>intelligence at every step.</>)}
        sub={window.L("من اللحظة التي يقرر فيها العميل التواصل، وحتى ظهور النتائج في تقاريرك. مسلاك يدير كل التفاصيل آلياً وباحترافية.", "From the moment a customer decides to reach out, to the results appearing in your reports. Mislak handles every detail automatically and professionally.")}
      />
      <section style={{paddingTop: 16}}>
        <div className="container">
          <div className="how-vert">
            {window.getData().journey.map((s, i) => (
              <div key={s.n} className="how-step">
                <div className="how-step-rail">
                  <div className="how-bub">{s.n}</div>
                  {i < window.getData().journey.length - 1 && <div className="how-line"></div>}
                </div>
                <div className="how-step-body">
                  <div className="how-tag mono">{window.L("المحطة", "Station")} {s.n}</div>
                  <h3>{s.title}</h3>
                  <p>{s.desc}</p>
                  <div className="how-detail">
                    {HowDetail(s.n)}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>
      <PageCTA h={window.L("ابدأ رحلة النمو الآن، ودع الذكاء الاصطناعي يدير اتصالاتك.", "Start your growth journey now, and let AI run your communications.")} btn={window.L("ابدأ رحلتك مع مسلاك", "Start your journey with Mislak")} />
    </React.Fragment>
  );
}

function HowDetail(n) {
  // small mock visualizations per station
  if (n === "01") return (
    <div className="how-mock">
      <div className="how-mock-row"><span className="how-pill">📞 {window.L("مكالمة من الرياض", "Call from Riyadh")}</span><span className="how-pill alt">💬 {window.L("واتساب من جدة", "WhatsApp from Jeddah")}</span><span className="how-pill alt">📞 {window.L("مكالمة دولية", "International call")}</span></div>
      <div className="how-mock-row"><span className="mono" style={{color: "var(--muted)", fontSize: 12}}>{window.ARR()} {window.L("واجهة موحدة + التعرف الفوري على هوية العميل", "Unified interface + instant customer identity recognition")}</span></div>
    </div>
  );
  if (n === "02") return (
    <div className="how-mock">
      <div className="how-mock-row"><span className="how-pill">{window.L("سؤال متكرر", "Recurring question")}</span><span className="mono" style={{color: "var(--muted)"}}>{window.ARR()}</span><span className="how-pill alt">{window.L("وكيل ذكي · فوري", "AI Agent · instant")}</span></div>
      <div className="how-mock-row"><span className="how-pill">{window.L("طلب مهم", "Important request")}</span><span className="mono" style={{color: "var(--muted)"}}>{window.ARR()}</span><span className="how-pill alt">{window.L("أفضل موظف متاح", "Best available agent")}</span></div>
    </div>
  );
  if (n === "03") return (
    <div className="how-mock">
      <Wave bars={36} hi={[14,15,16,17,18]}/>
      <div className="how-mock-row" style={{marginTop: 6}}><span className="how-pill">{window.L("هادئ", "Calm")}</span><span className="how-pill">{window.L("محايد", "Neutral")}</span><span className="how-pill on">{window.L("● مستاء — تنبيه المشرف", "● Upset — supervisor alert")}</span></div>
    </div>
  );
  if (n === "04") return (
    <div className="how-mock">
      <div className="how-mock-row"><span className="how-pill">{window.L("✓ ملخّص المكالمة", "✓ Call summary")}</span><span className="how-pill">{window.L("✓ تحديث CRM", "✓ CRM update")}</span><span className="how-pill">{window.L("✓ رسالة متابعة", "✓ Follow-up message")}</span></div>
      <div className="how-mock-row"><span className="mono" style={{color: "var(--muted)", fontSize: 12}}>{window.L("~0.3s · بدون تدخل بشري", "~0.3s · no human involvement")}</span></div>
    </div>
  );
  if (n === "05") return (
    <div className="how-mock">
      <div className="how-mock-row" style={{gap: 16}}>
        <div><div className="mono" style={{fontSize: 11, color: "var(--muted)"}}>{window.L("الأداء", "Performance")}</div><div style={{fontSize: 22, fontWeight: 800}}>+34%</div></div>
        <div><div className="mono" style={{fontSize: 11, color: "var(--muted)"}}>{window.L("الرضا", "Satisfaction")}</div><div style={{fontSize: 22, fontWeight: 800}}>94%</div></div>
        <div><div className="mono" style={{fontSize: 11, color: "var(--muted)"}}>{window.L("التحويل", "Conversion")}</div><div style={{fontSize: 22, fontWeight: 800}}>2.1x</div></div>
      </div>
    </div>
  );
  return null;
}

// ============ SECTORS OVERVIEW ============
function getSectorSystem(id) {
  const T = {
    ecom: {
      intro: window.L(
        "مهما كان حجم متجرك، يساعدك مسلاك على تحويل تواصلك اليومي مع المتسوقين إلى عملية منظمة وقابلة للمتابعة. بدل أن تضيع استفسارات الطلبات والشحن بين الموظفين والقنوات، يمنحك مسلاك رؤية أوضح لرحلة العميل الشرائية وأداء فريق المبيعات.",
        "Whatever the size of your store, Mislak turns your daily communication with shoppers into an organized, trackable process. Instead of order and shipping inquiries getting lost between staff and channels, Mislak gives you a clearer view of the buying journey and your sales team's performance."
      ),
      bullets: [
        window.L("استقبال استفسارات الطلبات والشحن من مكان واحد.", "Receive order and shipping inquiries from one place."),
        window.L("توجيه العميل لقسم المبيعات أو خدمة ما بعد البيع بسرعة.", "Route the customer to sales or after-sales service quickly."),
        window.L("تقليل الطلبات الفائتة والسلات المتروكة.", "Reduce lost orders and abandoned carts."),
        window.L("متابعة أداء فريق المبيعات من خلال لوحة تحكم واضحة.", "Track sales-team performance through a clear dashboard."),
        window.L("تحسين تجربة المتسوق من أول استفسار حتى إعادة الشراء.", "Improve the shopper experience from first inquiry to repeat purchase."),
      ],
      close: window.L(
        "لا تجعل استفسارًا غير مُجاب أو سلة متروكة سببًا في خسارة عملية بيع. مع مسلاك، يصبح تواصل متجرك أكثر تنظيمًا وسرعة واحترافية.",
        "Don't let an unanswered inquiry or an abandoned cart cost you a sale. With Mislak, your store's communication becomes more organized, faster, and more professional."
      ),
    },
    health: {
      intro: window.L(
        "مهما كان حجم عيادتك أو مركزك، يساعدك مسلاك على تحويل تواصلك اليومي مع المرضى إلى عملية منظمة وقابلة للمتابعة. بدل أن تضيع طلبات المواعيد والاستفسارات بين الموظفين والقنوات، يمنحك مسلاك رؤية أوضح لتواصل المرضى وأداء فريق الاستقبال.",
        "Whatever the size of your clinic or center, Mislak turns your daily communication with patients into an organized, trackable process. Instead of appointment requests and inquiries getting lost between staff and channels, Mislak gives you a clearer view of patient communication and your reception team's performance."
      ),
      bullets: [
        window.L("استقبال طلبات الحجز والاستفسارات من مكان واحد.", "Receive booking requests and inquiries from one place."),
        window.L("توجيه المريض للقسم أو الطبيب المناسب بسرعة.", "Route the patient to the right department or doctor quickly."),
        window.L("تقليل المكالمات الفائتة والمواعيد المنسية.", "Reduce missed calls and forgotten appointments."),
        window.L("متابعة أداء فريق الاستقبال من خلال لوحة تحكم واضحة.", "Track reception-team performance through a clear dashboard."),
        window.L("تحسين تجربة المريض من أول اتصال حتى المتابعة بعد الزيارة.", "Improve the patient experience from first contact to post-visit follow-up."),
      ],
      close: window.L(
        "لا تجعل مكالمة فائتة أو موعدًا ضائعًا سببًا في فقدان مريض. مع مسلاك، يصبح تواصل منشأتك الصحية أكثر تنظيمًا وسرعة واحترافية.",
        "Don't let a missed call or a lost appointment cost you a patient. With Mislak, your healthcare facility's communication becomes more organized, faster, and more professional."
      ),
    },
    realestate: {
      intro: window.L(
        "مهما كان حجم محفظتك العقارية، يساعدك مسلاك على تحويل تواصلك اليومي مع العملاء المحتملين إلى عملية منظمة وقابلة للمتابعة. بدل أن تضيع الاستفسارات والفرص بين أعضاء فريق المبيعات، يمنحك مسلاك رؤية أوضح لرحلة العميل وأداء الفريق.",
        "Whatever the size of your portfolio, Mislak turns your daily communication with prospects into an organized, trackable process. Instead of inquiries and opportunities getting lost between sales-team members, Mislak gives you a clearer view of the customer journey and team performance."
      ),
      bullets: [
        window.L("استقبال استفسارات المشاريع والوحدات من مكان واحد.", "Receive project and unit inquiries from one place."),
        window.L("توجيه العميل المحتمل لمندوب المبيعات المناسب بسرعة.", "Route the prospect to the right sales rep quickly."),
        window.L("تقليل الفرص الضائعة والمكالمات الفائتة.", "Reduce lost opportunities and missed calls."),
        window.L("متابعة أداء فريق المبيعات من خلال لوحة تحكم واضحة.", "Track sales-team performance through a clear dashboard."),
        window.L("تحسين رحلة العميل من أول تواصل حتى إغلاق الصفقة.", "Improve the customer journey from first contact to closing."),
      ],
      close: window.L(
        "لا تجعل «ليد» مهملة أو مكالمة فائتة سببًا في خسارة صفقة. مع مسلاك، يصبح تواصل شركتك العقارية أكثر تنظيمًا وسرعة واحترافية.",
        "Don't let a neglected lead or a missed call cost you a deal. With Mislak, your real estate company's communication becomes more organized, faster, and more professional."
      ),
    },
    edu: {
      intro: window.L(
        "مهما كان حجم منشأتك التعليمية، يساعدك مسلاك على تحويل تواصلك اليومي مع الطلاب وأولياء الأمور إلى عملية منظمة وقابلة للمتابعة. بدل أن تضيع استفسارات التسجيل بين الأقسام والقنوات، يمنحك مسلاك رؤية أوضح للتواصل وأداء الفريق الإداري.",
        "Whatever the size of your institution, Mislak turns your daily communication with students and parents into an organized, trackable process. Instead of enrollment inquiries getting lost between departments and channels, Mislak gives you a clearer view of communication and your administrative team's performance."
      ),
      bullets: [
        window.L("استقبال استفسارات التسجيل والرسوم من مكان واحد.", "Receive enrollment and fee inquiries from one place."),
        window.L("توجيه الطالب أو ولي الأمر للقسم المناسب بسرعة.", "Route the student or parent to the right department quickly."),
        window.L("تقليل المكالمات الفائتة خلال مواسم التسجيل.", "Reduce missed calls during enrollment seasons."),
        window.L("متابعة أداء الفريق الإداري من خلال لوحة تحكم واضحة.", "Track administrative-team performance through a clear dashboard."),
        window.L("تحسين تجربة الطالب من أول استفسار حتى المتابعة.", "Improve the student experience from first inquiry through follow-up."),
      ],
      close: window.L(
        "لا تجعل استفسارًا غير مُجاب سببًا في فقدان طالب محتمل. مع مسلاك، يصبح تواصل منشأتك التعليمية أكثر تنظيمًا وسرعة واحترافية.",
        "Don't let an unanswered inquiry cost you a potential student. With Mislak, your institution's communication becomes more organized, faster, and more professional."
      ),
    },
    hospitality: {
      intro: window.L(
        "مهما كان حجم منشأتك، يساعدك مسلاك على تحويل تواصلك اليومي مع الضيوف إلى عملية منظمة وقابلة للمتابعة. بدل أن تضيع الحجوزات والطلبات بين الموظفين والقنوات، يمنحك مسلاك رؤية أوضح لتواصل الضيوف وأداء الفريق.",
        "Whatever the size of your venue, Mislak turns your daily communication with guests into an organized, trackable process. Instead of reservations and requests getting lost between staff and channels, Mislak gives you a clearer view of guest communication and team performance."
      ),
      bullets: [
        window.L("استقبال الحجوزات والطلبات من مكان واحد.", "Receive reservations and requests from one place."),
        window.L("توجيه الضيف للقسم المناسب بسرعة.", "Route the guest to the right department quickly."),
        window.L("تقليل المكالمات الفائتة والحجوزات الضائعة.", "Reduce missed calls and lost reservations."),
        window.L("متابعة أداء الفريق من خلال لوحة تحكم واضحة.", "Track team performance through a clear dashboard."),
        window.L("تحسين تجربة الضيف قبل الزيارة وأثناءها وبعدها.", "Improve the guest experience before, during, and after the visit."),
      ],
      close: window.L(
        "لا تجعل مكالمة فائتة أو حجزًا ضائعًا سببًا في فقدان ضيف. مع مسلاك، يصبح تواصل منشأتك أكثر تنظيمًا وسرعة واحترافية.",
        "Don't let a missed call or a lost reservation cost you a guest. With Mislak, your venue's communication becomes more organized, faster, and more professional."
      ),
    },
    professional: {
      intro: window.L(
        "مهما كان مجال خدماتك، يساعدك مسلاك على تحويل تواصلك اليومي مع العملاء إلى عملية منظمة وقابلة للمتابعة. بدل أن تضيع الطلبات والمتابعات بين الموظفين والقنوات، يمنحك مسلاك رؤية أوضح لتواصل العملاء وأداء الفريق.",
        "Whatever your line of service, Mislak turns your daily communication with customers into an organized, trackable process. Instead of requests and follow-ups getting lost between staff and channels, Mislak gives you a clearer view of customer communication and team performance."
      ),
      bullets: [
        window.L("استقبال طلبات العملاء والمتابعات من مكان واحد.", "Receive customer requests and follow-ups from one place."),
        window.L("توجيه الطلب للفريق أو الموظف المناسب بسرعة.", "Route the request to the right team or employee quickly."),
        window.L("تقليل الطلبات الفائتة والفرص الضائعة.", "Reduce missed requests and lost opportunities."),
        window.L("متابعة جودة الرد وأداء الفريق من خلال لوحة تحكم واضحة.", "Track response quality and team performance through a clear dashboard."),
        window.L("تحسين تجربة العميل من أول طلب حتى الإنجاز.", "Improve the customer experience from first request to completion."),
      ],
      close: window.L(
        "لا تجعل طلبًا مهملًا أو مكالمة فائتة سببًا في خسارة عميل. مع مسلاك، يصبح تواصل شركتك أكثر تنظيمًا وسرعة واحترافية.",
        "Don't let a neglected request or a missed call cost you a customer. With Mislak, your company's communication becomes more organized, faster, and more professional."
      ),
    },
  };
  return T[id];
}

function getSectors() {
  return [
    {
      id: "ecom", hasDetail: true,
      tab: window.L("التجزئة والتجارة الإلكترونية", "Retail & E-Commerce"),
      desc: window.L(
        "يساعد مسلاك المتاجر وشركات التجارة الإلكترونية على إدارة استفسارات العملاء المرتبطة بالطلبات، الشحن، الاستبدال، العروض، وخدمة ما بعد البيع. من خلال تنظيم المكالمات والرسائل وتوزيعها على الفريق المناسب، يصبح التواصل أسرع وأكثر وضوحًا، مما يحسن تجربة العميل ويقلل ضياع الطلبات والفرص البيعية.",
        "Mislak helps stores and e-commerce companies manage customer inquiries around orders, shipping, returns, offers, and after-sales service. By organizing calls and messages and routing them to the right team, communication becomes faster and clearer — improving the customer experience and reducing lost orders and sales opportunities."
      ),
    },
    {
      id: "health", hasDetail: true,
      tab: window.L("الصحة والرعاية", "Health & Care"),
      desc: window.L(
        "يوفر مسلاك للعيادات والمراكز الصحية طريقة أكثر احترافية لتنظيم تواصل المرضى، سواء لحجز المواعيد، تعديل الزيارات، الاستفسار عن الخدمات، أو المتابعة بعد المراجعة. يساعد النظام على توجيه المكالمات للقسم المناسب، تقليل الضغط على الاستقبال، وتحسين سرعة الاستجابة للمرضى والمراجعين.",
        "Mislak gives clinics and health centers a more professional way to organize patient communication — whether booking appointments, rescheduling visits, inquiring about services, or following up after a visit. The system routes calls to the right department, eases pressure on reception, and improves response speed for patients and visitors."
      ),
    },
    {
      id: "realestate", hasDetail: true,
      tab: window.L("العقار والمقاولات", "Real Estate & Contracting"),
      desc: window.L(
        "في قطاع العقار والمقاولات، كل مكالمة قد تكون فرصة بيع أو عميلًا مهتمًا بمشروع. يساعد مسلاك فرق المبيعات والمشاريع على استقبال الاستفسارات، توزيع المكالمات، توثيق المحادثات، ومتابعة العملاء المحتملين بوضوح، مما يقلل ضياع الفرص ويحسن رحلة العميل من أول تواصل حتى الإغلاق.",
        "In real estate and contracting, every call could be a sales opportunity or a client interested in a project. Mislak helps sales and project teams receive inquiries, distribute calls, document conversations, and follow up with prospects clearly — reducing lost opportunities and improving the journey from first contact to closing."
      ),
    },
    {
      id: "edu", hasDetail: true,
      tab: window.L("التعليم والتدريب", "Education & Training"),
      desc: window.L(
        "يساعد مسلاك المدارس، المعاهد، ومراكز التدريب على تنظيم التواصل مع الطلاب، أولياء الأمور، والمتدربين. يمكن استخدامه لإدارة استفسارات التسجيل، الجداول، الرسوم، البرامج، الدعم الإداري، والمتابعة، مع توجيه كل مكالمة أو رسالة للقسم المناسب بسرعة ووضوح.",
        "Mislak helps schools, institutes, and training centers organize communication with students, parents, and trainees. It manages inquiries about enrollment, schedules, fees, programs, administrative support, and follow-ups — routing every call or message to the right department quickly and clearly."
      ),
    },
    {
      id: "hospitality", hasDetail: true,
      tab: window.L("الضيافة والمطاعم", "Hospitality & Restaurants"),
      desc: window.L(
        "يساعد مسلاك الفنادق، المطاعم، والمقاهي على إدارة الحجوزات، الاستفسارات، الطلبات، الشكاوى، وخدمة العملاء بطريقة أكثر تنظيمًا. من خلال توزيع المكالمات ومتابعة الأداء، يستطيع الفريق الرد بسرعة أعلى، تقليل التأخير، وتحسين تجربة العميل قبل الزيارة وأثناءها وبعدها.",
        "Mislak helps hotels, restaurants, and cafés manage reservations, inquiries, orders, complaints, and customer service in a more organized way. By distributing calls and tracking performance, the team responds faster, reduces delays, and improves the customer experience before, during, and after the visit."
      ),
    },
    {
      id: "professional", hasDetail: false,
      tab: window.L("الخدمات المهنية والتشغيلية", "Professional & Operational Services"),
      desc: window.L(
        "يساعد مسلاك شركات الخدمات المهنية والتشغيلية مثل الصيانة، النظافة، إدارة المرافق، الاستشارات، المكاتب، وشركات الخدمات الميدانية على تنظيم طلبات العملاء والمتابعات اليومية. من خلال رقم موحد ولوحة تحكم واضحة، يمكن توزيع الطلبات على الفريق المناسب، متابعة جودة الرد، وضمان عدم ضياع أي عميل بسبب التشتت أو التأخير.",
        "Mislak helps professional and operational services companies — maintenance, cleaning, facility management, consulting, offices, and field-service firms — organize customer requests and daily follow-ups. Through a unified number and a clear dashboard, requests are distributed to the right team, response quality is tracked, and no customer is lost to scatter or delay."
      ),
    },
  ];
}

function SectorsPage() {
  const SECTORS = getSectors();
  const BENEFITS = [
    window.L("استقبال مكالمات العملاء ورسائلهم من مكان واحد.", "Receive customer calls and messages from one place."),
    window.L("توجيه العميل للقسم أو الموظف المناسب بسرعة.", "Route the customer to the right department or employee quickly."),
    window.L("تقليل المكالمات الفائتة والفرص الضائعة.", "Reduce missed calls and lost opportunities."),
    window.L("متابعة أداء الفريق من خلال لوحة تحكم واضحة.", "Track team performance through a clear dashboard."),
    window.L("تحسين تجربة العميل من أول تواصل حتى المتابعة.", "Improve the customer experience from first contact through follow-up."),
  ];

  return (
    <React.Fragment>
      <section className="page-hero">
        <div className="container">
          <div className="crumbs">
            <a href="#/">{window.L("الرئيسية", "Home")}</a>
            <span className="crumb-sep">{window.ARR()}</span>
            <span>{window.L("القطاعات", "Sectors")}</span>
          </div>
          <h1 className="page-h1">{window.L("حلول اتصالات تناسب مختلف القطاعات.", "Communication solutions for every sector.")}</h1>
        </div>
      </section>

      <section style={{paddingTop: 16, paddingBottom: 96}}>
        <div className="container">
          <div className="sectors-article">
            <p className="sectors-article-lead">{window.L("كل قطاع له طريقة مختلفة في استقبال العملاء، إدارة الاستفسارات، متابعة الطلبات، وخدمة المستفيدين. لذلك صُمم مسلاك ليمنح الشركات نظام تواصل مرن يساعدها على تنظيم المكالمات والرسائل، توجيه العملاء للفريق المناسب، وتقليل الفرص الضائعة من مكان واحد.", "Every sector has its own way of receiving customers, managing inquiries, following up on requests, and serving beneficiaries. That's why Mislak was built to give companies a flexible communication system that organizes calls and messages, routes customers to the right team, and reduces lost opportunities — all from one place.")}</p>
            <p>{window.L("سواء كنت تدير متجرًا، عيادة، شركة عقارية، مركز تدريب، مطعمًا، أو شركة خدمات — مسلاك يساعدك على جعل تواصل عملائك أكثر وضوحًا واحترافية.", "Whether you run a store, a clinic, a real estate company, a training center, a restaurant, or a services company — Mislak helps you make your customer communication clearer and more professional.")}</p>

            <h2>{window.L("القطاعات التي يخدمها مسلاك", "The sectors Mislak serves")}</h2>
            <div className="sectors-list">
              {SECTORS.map((s) => (
                <div key={s.id} className="sector-block">
                  <h3>{s.tab}</h3>
                  <p>{s.desc}</p>
                </div>
              ))}
            </div>

            <h2>{window.L("نظام واحد يناسب طريقة عملك", "One system that fits the way you work")}</h2>
            <p>{window.L("مهما كان قطاعك، يساعدك مسلاك على تحويل التواصل اليومي مع العملاء إلى عملية منظمة وقابلة للمتابعة. بدل أن تضيع المكالمات والرسائل بين الموظفين والقنوات المختلفة، يمنحك مسلاك رؤية أوضح لتواصل العملاء وأداء الفريق.", "Whatever your sector, Mislak turns daily customer communication into an organized, trackable process. Instead of calls and messages getting lost between employees and channels, Mislak gives you a clearer view of customer communication and team performance.")}</p>
            <p>{window.L("مع مسلاك يمكنك:", "With Mislak you can:")}</p>
            <ul>
              {BENEFITS.map((b, i) => <li key={i}>{b}</li>)}
            </ul>

            <h2>{window.L("كل تواصل مع عميلك فرصة", "Every interaction is an opportunity")}</h2>
            <p>{window.L("لا تجعل المكالمات الفائتة أو الرسائل المتفرقة سببًا في ضياع العملاء. مع مسلاك، يصبح تواصل شركتك أكثر تنظيمًا، سرعة، واحترافية.", "Don't let missed calls or scattered messages cost you customers. With Mislak, your company's communication becomes more organized, faster, and more professional.")}</p>
            <a className="btn btn-primary" href="#/contact" style={{marginTop: 12}}>{window.L("تحدّث مع فريق مسلاك", "Talk to the Mislak team")}</a>
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

// ============ SECTOR DETAIL ============
function SectorDetailPage({ id }) {
  window.useLang();
  const s = getSectors().find((x) => x.id === id);
  if (!s) return <NotFound/>;
  const sys = getSectorSystem(id);
  return (
    <React.Fragment>
      <section className="page-hero">
        <div className="container">
          <div className="crumbs">
            <a href="#/">{window.L("الرئيسية", "Home")}</a>
            <span className="crumb-sep">{window.ARR()}</span>
            <a href="#/sectors">{window.L("القطاعات", "Sectors")}</a>
            <span className="crumb-sep">{window.ARR()}</span>
            <span>{s.tab}</span>
          </div>
          <h1 className="page-h1">{s.tab}</h1>
        </div>
      </section>

      <section style={{paddingTop: 16, paddingBottom: 96}}>
        <div className="container">
          <div className="sectors-article">
            <p className="sectors-article-lead">{s.desc}</p>

            <h2>{window.L("نظام واحد يناسب طريقة عملك", "One system that fits the way you work")}</h2>
            <p>{sys.intro}</p>
            <p>{window.L("مع مسلاك يمكنك:", "With Mislak you can:")}</p>
            <ul>
              {sys.bullets.map((b, i) => <li key={i}>{b}</li>)}
            </ul>

            <h2>{window.L("كل تواصل مع عميلك فرصة", "Every interaction is an opportunity")}</h2>
            <p>{sys.close}</p>
            <a className="btn btn-primary" href="#/contact" style={{marginTop: 12}}>{window.L("تحدّث مع فريق مسلاك", "Talk to the Mislak team")}</a>
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

// ============ AI AGENTS ============
function AIAgentsPage() {
  return (
    <React.Fragment>
      <PageHero
        eyebrow={window.L("وكلاء الذكاء الاصطناعي", "AI Agents")}
        title={window.L(<>وظّف «عقلاً ذكياً» لا ينام،<br/>اكتشف وكلاء مسلاك الافتراضيين.</>, <>Hire a "smart mind" that never sleeps,<br/>discover Mislak's virtual agents.</>)}
        sub={window.L("ليس مجرد برنامج يجيب على الأسئلة، بل وكلاء أذكياء يديرون مكالماتك ومحادثاتك، يحللون المشاعر، وينجزون أعقد المهام التشغيلية في ثوانٍ.", "Not just software that answers questions — smart agents that run your calls and conversations, analyze sentiment, and complete the most complex operational tasks in seconds.")}
      />
      <section style={{paddingTop: 16}}>
        <div className="container">
          <div className="ai-grid">
            {window.getDetails().aiCapabilities.map((c, i) => (
              <div key={c.num} className={`ai-card ${i === 0 ? "wide dark" : ""}`}>
                <div className="ai-num mono">{c.num} / 05</div>
                <div className="ai-tag mono">{c.tag}</div>
                <h3>{c.title}</h3>
                <p>{c.desc}</p>
                {i === 0 && (
                  <div className="ai-card-viz">
                    <Wave bars={40} hi={[18,19,20,21,22]}/>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </section>

      <section>
        <div className="container">
          <div className="sec-head" style={{justifyContent: "center", textAlign: "center", flexDirection: "column", alignItems: "center"}}>
            <div className="sec-eyebrow" style={{justifyContent: "center"}}>{window.L("كيف يعمل وكيلك الذكي", "How your smart agent works")}</div>
            <h2>{window.L(<>من نية العميل، إلى صفقة مغلقة،<br/>في أقل من 90 ثانية.</>, <>From customer intent to a closed deal,<br/>in less than 90 seconds.</>)}</h2>
          </div>
          <div className="ai-flow">
            {[
              { t: "01", l: window.L("يرد فوراً", "Responds instantly"), d: window.L("خلال 0.3 ثانية من بدء المحادثة", "Within 0.3s of the conversation starting") },
              { t: "02", l: window.L("يفهم النية", "Understands intent"), d: window.L("يحلل القصد ويرصد نبرة الصوت", "Analyzes intent and reads tone of voice") },
              { t: "03", l: window.L("ينفّذ المهمة", "Executes the task"), d: window.L("حجز، دفع، استرجاع، أو تحويل", "Booking, payment, recovery, or transfer") },
              { t: "04", l: window.L("يلخّص ويرفع", "Summarizes and uploads"), d: window.L("تحديث الـCRM وإرسال المتابعة", "Updates the CRM and sends follow-up") },
            ].map((s, i) => (
              <div key={s.t} className="ai-flow-step">
                <div className="mono" style={{color: "var(--accent)", fontSize: 12, letterSpacing: ".1em"}}>{s.t}</div>
                <div style={{fontSize: 20, fontWeight: 700, marginTop: 6, letterSpacing: "-.01em"}}>{s.l}</div>
                <div style={{color: "var(--muted)", fontSize: 14, marginTop: 4}}>{s.d}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <PageCTA h={window.L("جرّب وكيل مسلاك الذكي مخصصاً لقطاعك.", "Try Mislak's smart agent tailored to your sector.")} btn={window.L("احجز تجربة الوكيل الذكي", "Book a smart agent demo")} />
    </React.Fragment>
  );
}

// ============ PRICING ============
function PricingPage() {
  const [open, setOpen] = usePS(0);
  return (
    <React.Fragment>
      <PageHero
        eyebrow={window.L("الباقات", "Pricing")}
        title={window.L(<>خطط مرنة مصممة<br/>لتواكب نمو أعمالك.</>, <>Flexible plans designed<br/>to keep pace with your growth.</>)}
        sub={window.L("بدون تكاليف مخفية. حلول تناسب المتاجر الناشئة والشركات الكبرى على حد سواء، مع إمكانية الترقية في أي وقت.", "No hidden costs. Solutions that suit both emerging stores and large enterprises, with the ability to upgrade at any time.")}
      />
      <section style={{paddingTop: 16}}>
        <div className="container">
          <div className="price-grid">
            {window.getData().plans.map((p) => (
              <div key={p.name} className={`plan ${p.featured ? "featured" : ""}`}>
                {p.badge && <span className="plan-badge">{p.badge}</span>}
                <div className="plan-name">{p.name}</div>
                <h3>{p.title}</h3>
                <p className="plan-sub">{p.sub}</p>
                <div className="plan-price">
                  <span className="mono">{p.price}</span>
                  {p.currency && <small>{p.currency}</small>}
                </div>
                <div className="plan-period">{p.period}</div>
                <ul className="plan-feats">
                  {p.feats.map((f, i) => <li key={i} className="plan-feat">{f}</li>)}
                </ul>
                <a className={`btn btn-${p.ctaStyle}`} href="#/contact">{p.cta}</a>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section>
        <div className="container">
          <div className="compare">
            <div className="sec-eyebrow">{window.L("مقارنة الباقات", "Plan comparison")}</div>
            <h2 style={{marginBottom: 28}}>{window.L("قارن المميزات تفصيلياً.", "Compare features in detail.")}</h2>
            <div className="compare-table">
              <div className="compare-row compare-head">
                <div>{window.L("الميزة", "Feature")}</div>
                <div>WhatsApp API</div>
                <div className="hl">AI Agent</div>
                <div>Enterprise</div>
              </div>
              {[
                [window.L("توثيق Meta والعلامة الخضراء", "Meta verification & green tick"), true, true, true],
                [window.L("محادثات لعدد غير محدود من الموظفين", "Conversations for unlimited agents"), true, true, true],
                [window.L("قوالب رسائل وردود سريعة", "Message templates & quick replies"), true, true, true],
                [window.L("وكيل ذكاء اصطناعي مخصص", "Custom AI agent"), false, true, true],
                [window.L("تحليل المشاعر بالذكاء الاصطناعي", "AI sentiment analysis"), false, true, true],
                [window.L("تلخيص آلي للمكالمات", "Automatic call summaries"), false, true, true],
                [window.L("ربط مع HIS / LMS / PMS", "Integration with HIS / LMS / PMS"), false, false, true],
                [window.L("مدير حساب خاص", "Dedicated account manager"), false, false, true],
                [window.L("SLA مضمون 99.99%", "Guaranteed 99.99% SLA"), false, false, true],
              ].map((row, i) => (
                <div key={i} className="compare-row">
                  <div>{row[0]}</div>
                  <div className="mono">{row[1] ? "✓" : "—"}</div>
                  <div className="mono hl">{row[2] ? "✓" : "—"}</div>
                  <div className="mono">{row[3] ? "✓" : "—"}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      <section>
        <div className="container">
          <div className="sec-head" style={{justifyContent: "center", textAlign: "center", flexDirection: "column", alignItems: "center"}}>
            <div className="sec-eyebrow" style={{justifyContent: "center"}}>{window.L("الأسئلة الشائعة", "FAQ")}</div>
            <h2>{window.L(<>أجوبة سريعة قبل<br/>أن تضغط أي زرّ.</>, <>Quick answers before<br/>you press any button.</>)}</h2>
          </div>
          <div className="faq-list">
            {window.getData().faqs.map((f, i) => (
              <div key={i} className={`faq-item ${open === i ? "open" : ""}`}>
                <div className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                  <span>{f.q}</span>
                  <span className="faq-toggle">+</span>
                </div>
                <div className="faq-a">{f.a}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <PageCTA h={window.L("لست متأكداً من الباقة المناسبة؟ تحدّث مع فريقنا.", "Not sure which plan is right? Talk to our team.")} btn={window.L("تحدّث مع المبيعات", "Talk to sales")} />
    </React.Fragment>
  );
}

// ============ CONTACT ============
function ContactPage() {
  const [form, setForm] = usePS({ name: "", company: "", email: "", phone: "", sector: "", msg: "" });
  const [sent, setSent] = usePS(false);
  const [sending, setSending] = usePS(false);
  const [error, setError] = usePS(false);

  const c = window.getDetails().contact;
  const update = (k) => (e) => setForm({...form, [k]: e.target.value});

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (sending) return;
    setSending(true);
    setError(false);
    const ok = await window.submitMislakForm("contact", {
      fullName: form.name,
      company: form.company,
      email: form.email,
      phone: form.phone,
      sector: form.sector,
      message: form.msg,
    });
    setSending(false);
    if (ok) setSent(true);
    else setError(true);
  };

  return (
    <React.Fragment>
      <PageHero
        eyebrow={window.L("تواصل معنا", "Contact Us")}
        title={c.title}
        sub={c.sub}
      />
      <section style={{paddingTop: 16, paddingBottom: 48}}>
        <div className="container">
          <div className="contact-board">
            <div className="contact-form">
              {sent ? (
                <div className="form-success">
                  <div className="mono" style={{fontSize: 12, color: "var(--accent)", letterSpacing: ".1em", marginBottom: 12}}>{window.L("✓ تم الاستلام", "✓ Received")}</div>
                  <h3>{window.L("شكراً لك. سنتواصل معك خلال 24 ساعة.", "Thank you. We'll be in touch within 24 hours.")}</h3>
                  <p style={{color: "var(--muted)", marginTop: 14}}>{window.L("سيتولى أحد متخصصي مسلاك تجهيز عرض مخصص لقطاعك والتواصل معك مباشرة.", "One of Mislak's specialists will prepare a tailored demo for your sector and contact you directly.")}</p>
                  <button className="btn btn-ghost" style={{marginTop: 18}} onClick={() => { setSent(false); setForm({ name: "", company: "", email: "", phone: "", sector: "", msg: "" }); }}>{window.L("إرسال طلب آخر", "Send another request")}</button>
                </div>
              ) : (
                <form onSubmit={handleSubmit}>
                  <div className="sec-eyebrow">{window.L("نموذج العرض التجريبي", "Demo request form")}</div>
                  <h3 style={{marginTop: 6, marginBottom: 24}}>{window.L("أخبرنا عنك، وعن شركتك.", "Tell us about you and your company.")}</h3>
                  <div className="form-grid">
                    <label>
                      <span>{window.L("الاسم الكامل", "Full name")}</span>
                      <input value={form.name} onChange={update("name")} required placeholder={window.L("عبدالله السعيد", "Abdullah Al-Saeed")}/>
                    </label>
                    <label>
                      <span>{window.L("اسم الشركة", "Company name")}</span>
                      <input value={form.company} onChange={update("company")} required placeholder={window.L("شركة المثال", "Example Co.")}/>
                    </label>
                    <label>
                      <span>{window.L("البريد الإلكتروني", "Email")}</span>
                      <input type="email" value={form.email} onChange={update("email")} required placeholder="you@company.com"/>
                    </label>
                    <label>
                      <span>{window.L("رقم الجوال", "Mobile number")}</span>
                      <input type="tel" dir="ltr" value={form.phone} onChange={update("phone")} required placeholder="+966 5X XXX XXXX"/>
                    </label>
                    <label className="span-2">
                      <span>{window.L("القطاع", "Sector")}</span>
                      <select value={form.sector} onChange={update("sector")} required>
                        <option value="">{window.L("اختر قطاعك", "Choose your sector")}</option>
                        {window.getData().sectors.map((s) => <option key={s.id} value={s.id}>{s.tab}</option>)}
                        <option value="other">{window.L("قطاع آخر", "Other sector")}</option>
                      </select>
                    </label>
                    <label className="span-2">
                      <span>{window.L("كيف يمكننا مساعدتك؟ (اختياري)", "How can we help you? (optional)")}</span>
                      <textarea value={form.msg} onChange={update("msg")} rows="4" placeholder={window.L("مثلاً: نحتاج لرقم موحد ووكيل ذكي لـ50 موظف…", "E.g.: We need a unified number and a smart agent for 50 employees…")}/>
                    </label>
                  </div>
                  <button type="submit" disabled={sending} className="btn btn-primary" style={{marginTop: 8, width: "100%", justifyContent: "center", opacity: sending ? 0.6 : 1}}>{sending ? window.L("جارٍ الإرسال…", "Sending…") : <>{window.L("أرسل الطلب", "Send request")} <span className="mono">{window.ARR()}</span></>}</button>
                  {error && <p style={{fontSize: 13, color: "#d33", marginTop: 12, textAlign: "center"}}>{window.L("حدث خطأ أثناء الإرسال. حاول مرة أخرى.", "Something went wrong. Please try again.")}</p>}
                  <p className="mono" style={{fontSize: 11, color: "var(--muted)", marginTop: 14, textAlign: "center"}}>{window.L("بإرسال هذا النموذج فإنك توافق على سياسة الخصوصية الخاصة بمسلاك.", "By submitting this form you agree to Mislak's Privacy Policy.")}</p>
                </form>
              )}
            </div>
            <aside className="contact-side">
              <div className="sec-eyebrow">{window.L("قنوات التواصل المباشر", "Direct contact channels")}</div>
              <div className="contact-channels">
                {c.channels.filter((ch) => ch.l !== "واتساب" && ch.l !== "WhatsApp").map((ch, i) => (
                  <div key={i} className="contact-channel">
                    <div className="mono" style={{fontSize: 11, color: "var(--muted)", letterSpacing: ".1em", textTransform: "uppercase"}}>{ch.l}</div>
                    <div style={{fontSize: 20, fontWeight: 700, letterSpacing: "-.01em", margin: "4px 0"}} dir={ch.v.match(/^[\u0600-\u06FF]/) ? "rtl" : "ltr"}>{ch.v}</div>
                    <div style={{fontSize: 13, color: "var(--muted)"}}>{ch.sub}</div>
                  </div>
                ))}
              </div>
            </aside>
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

// Before/After infographic for Unified Number page — per PDF spec
function UnifiedInfographic() {
  return (
    <section style={{paddingTop: 56}}>
      <div className="container">
        <div className="sec-eyebrow" style={{justifyContent: "center", textAlign: "center"}}>{window.L("الفرق الذي يصنعه الرقم الموحد", "The difference a unified number makes")}</div>
        <h2 style={{textAlign: "center", maxWidth: 760, margin: "0 auto 40px"}}>{window.L("قبل مسلاك، وبعد مسلاك.", "Before Mislak, and after Mislak.")}</h2>
        <div className="infogr">
          <div className="infogr-side before">
            <div className="infogr-tag mono">{window.L("قبل مسلاك", "Before Mislak")}</div>
            <h3>{window.L("أرقام عادية، فوضى تشغيلية.", "Ordinary numbers, operational chaos.")}</h3>
            <ul>
              <li><span className="infogr-x">✕</span> {window.L("أرقام جوالات مبعثرة لكل موظف", "Scattered mobile numbers for each employee")}</li>
              <li><span className="infogr-x">✕</span> {window.L("نغمة «الخط مشغول» في أوقات الذروة", "\"Line busy\" tone during peak hours")}</li>
              <li><span className="infogr-x">✕</span> {window.L("مكالمات ضائعة وفرص مهدورة", "Lost calls and wasted opportunities")}</li>
              <li><span className="infogr-x">✕</span> {window.L("لا تعرف من رد، ومتى، وما الذي قيل", "You don't know who answered, when, or what was said")}</li>
              <li><span className="infogr-x">✕</span> {window.L("أجهزة سنترال غالية وصيانة دورية", "Expensive PBX hardware and routine maintenance")}</li>
            </ul>
            <div className="infogr-stat">
              <span className="mono v">−42%</span>
              <span className="l">{window.L("من المكالمات تضيع في الذروة", "of calls are lost during peak")}</span>
            </div>
          </div>
          <div className="infogr-side after">
            <div className="infogr-tag mono">{window.L("بعد مسلاك", "After Mislak")}</div>
            <h3>{window.L("رقم موحد، نظام وهدوء.", "A unified number, order and calm.")}</h3>
            <ul>
              <li><span className="infogr-ok">✓</span> {window.L("رقم 9200 موحد يجمع كل الفروع", "A unified 9200 number that unites all branches")}</li>
              <li><span className="infogr-ok">✓</span> {window.L("مكالمات متزامنة بلا حد، بلا نغمة مشغول", "Unlimited simultaneous calls, no busy tone")}</li>
              <li><span className="infogr-ok">✓</span> {window.L("توجيه ذكي + تسجيل كامل لكل مكالمة", "Smart routing + full recording of every call")}</li>
              <li><span className="infogr-ok">✓</span> {window.L("تقارير لحظية لأداء كل موظف", "Real-time reports on every agent's performance")}</li>
              <li><span className="infogr-ok">✓</span> {window.L("سحابي بالكامل، اشتراك شهري مرن", "Fully cloud-based, flexible monthly subscription")}</li>
            </ul>
            <div className="infogr-stat">
              <span className="mono v">+100%</span>
              <span className="l">{window.L("من المكالمات يتم الرد عليها", "of calls are answered")}</span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function NotFound() {
  return (
    <section style={{paddingTop: 120, paddingBottom: 120, textAlign: "center"}}>
      <div className="container">
        <div className="mono" style={{color: "var(--accent)", letterSpacing: ".1em", marginBottom: 14}}>404</div>
        <h1 className="page-h1">{window.L("الصفحة غير موجودة.", "Page not found.")}</h1>
        <p className="page-sub" style={{margin: "12px auto"}}>{window.L("الرابط الذي تبحث عنه لم نتمكن من العثور عليه.", "We couldn't find the link you're looking for.")}</p>
        <a className="btn btn-primary" href="#/" style={{marginTop: 18}}>{window.L("عودة للرئيسية", "Back to home")} <span className="mono">{window.ARR()}</span></a>
      </div>
    </section>
  );
}

// ============ SURVEY (hidden — reachable only via #/survey) ============
function SurveyPage() {
  const [form, setForm] = usePS({ name: "", email: "", phone: "", products: [] });
  const [errors, setErrors] = usePS({});
  const [sent, setSent] = usePS(false);
  const [sending, setSending] = usePS(false);
  const [sendError, setSendError] = usePS(false);
  const update = (k) => (e) => {
    setForm({ ...form, [k]: e.target.value });
    if (errors[k]) setErrors((er) => { const n = { ...er }; delete n[k]; return n; });
  };
  const toggleProduct = (id) => {
    setForm((f) => ({
      ...f,
      products: f.products.includes(id) ? f.products.filter((x) => x !== id) : [...f.products, id],
    }));
    setErrors((er) => { const n = { ...er }; delete n.products; return n; });
  };
  const validate = () => {
    const e = {};
    const req = window.L("هذا الحقل مطلوب", "This field is required");
    const name = form.name.trim();
    if (!name) e.name = req;
    else if (!(/^[\u0600-\u06FF\s]+$/.test(name) || /^[A-Za-z\s]+$/.test(name)) || name.length < 2)
      e.name = window.L("الاسم يجب أن يحتوي حروفاً فقط (عربي أو إنجليزي، دون خلط)", "Name must contain letters only (Arabic or English, not mixed)");
    if (!form.email.trim()) e.email = req;
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) e.email = window.L("بريد إلكتروني غير صالح", "Invalid email address");
    const phone = form.phone.replace(/[\s()-]/g, "");
    if (!phone) e.phone = req;
    else if (!/^(\+9665\d{8}|9665\d{8}|05\d{8})$/.test(phone)) e.phone = window.L("رقم غير صالح. ابدأ بـ 05 (10 أرقام) أو +9665 / 9665 (12 رقماً)", "Invalid number. Start with 05 (10 digits) or +9665 / 9665 (12 digits)");
    if (form.products.length === 0) e.products = window.L("يرجى اختيار منتج واحد على الأقل", "Please choose at least one product");
    return e;
  };
  const onSubmit = async (ev) => {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length !== 0) return;
    if (sending) return;
    setSending(true);
    setSendError(false);
    const labels = { ai: "وكيل الذكاء الاصطناعي", callcenter: "مركز اتصال سحابي", whatsapp: "واتساب API" };
    const ok = await window.submitMislakForm("survey", {
      fullName: form.name,
      email: form.email,
      phone: form.phone,
      products: form.products.map((id) => labels[id] || id),
    });
    setSending(false);
    if (ok) setSent(true);
    else setSendError(true);
  };

  const PRODUCTS = [
    { id: "ai", label: window.L("وكيل الذكاء الاصطناعي", "AI Agent") },
    { id: "callcenter", label: window.L("مركز اتصال سحابي", "Cloud Call Center") },
    { id: "whatsapp", label: window.L("واتساب API", "WhatsApp API") },
  ];

  return (
    <React.Fragment>
      <PageHero
        eyebrow={window.L("استبيان", "Survey")}
        title={window.L("شاركنا اهتمامك", "Share your interest")}
        sub={window.L("أكمل النموذج وسنتواصل معك حول المنتج الذي يناسب احتياجك.", "Fill out the form and we'll reach out about the product that fits your needs.")}
      />
      <section style={{ paddingTop: 16, paddingBottom: 64 }}>
        <div className="container">
          <div className="survey-wrap">
            <div className="contact-form">
              {sent ? (
                <div className="form-success">
                  <div className="mono" style={{ fontSize: 12, color: "var(--accent)", letterSpacing: ".1em", marginBottom: 12 }}>{window.L("✓ تم الاستلام", "✓ Received")}</div>
                  <h3>{window.L("شكراً لك. سنتواصل معك قريباً.", "Thank you. We'll be in touch soon.")}</h3>
                  <p style={{ color: "var(--muted)", marginTop: 14 }}>{window.L("استلمنا إجابتك بنجاح.", "Your response has been received.")}</p>
                  <button className="btn btn-ghost" style={{ marginTop: 18 }} onClick={() => { setSent(false); setErrors({}); setForm({ name: "", email: "", phone: "", products: [] }); }}>{window.L("إرسال إجابة أخرى", "Submit another response")}</button>

                  <div className="survey-tests">
                    <div className="st-head">{window.L("جرّب اختباراتنا التفاعلية", "Try our interactive tests")}</div>
                    <div className="st-sub">{window.L("احصل على تقدير سريع لوضع شركتك خلال دقيقة.", "Get a quick read on your company in under a minute.")}</div>
                    <div className="survey-tests-grid">
                      <a className="test-btn" href="#/calculator">
                        <span className="tb-ico">{window.CalcIcon && <window.CalcIcon name="trendingDown" size={24} />}</span>
                        <span className="tb-txt">
                          <span className="tb-title">{window.L("كم تكلفك المكالمات الفائتة؟", "How much do missed calls cost you?")}</span>
                          <span className="tb-desc">{window.L("احسب الإيرادات المحتملة المعرضة للضياع.", "Estimate the revenue you may be putting at risk.")}</span>
                        </span>
                        <span className="tb-arrow mono">{window.ARR()}</span>
                      </a>
                      <a className="test-btn" href="#/ai-readiness">
                        <span className="tb-ico">{window.CalcIcon && <window.CalcIcon name="robot" size={24} />}</span>
                        <span className="tb-txt">
                          <span className="tb-title">{window.L("اختبار جاهزية خدمة عملاء شركتك للذكاء الاصطناعي", "Is your customer service ready for AI?")}</span>
                          <span className="tb-desc">{window.L("قيّم جاهزية فريقك لتبنّي الذكاء الاصطناعي.", "Assess your team's readiness to adopt AI.")}</span>
                        </span>
                        <span className="tb-arrow mono">{window.ARR()}</span>
                      </a>
                    </div>
                  </div>
                </div>
              ) : (
                <form onSubmit={onSubmit} noValidate>
                  <div className="sec-eyebrow">{window.L("نموذج الاستبيان", "Survey form")}</div>
                  <h3 style={{ marginTop: 6, marginBottom: 24 }}>{window.L("أخبرنا عنك وعن المنتج الذي يهمك.", "Tell us about you and the product you're interested in.")}</h3>
                  <div className="form-grid">
                    <label className="span-2">
                      <span>{window.L("الاسم الكامل", "Full name")}<span className="req">*</span></span>
                      <input className={errors.name ? "invalid" : ""} value={form.name} onChange={update("name")} placeholder={window.L("عبدالله السعيد", "Abdullah Al-Saeed")}/>
                      {errors.name && <span className="field-error">{errors.name}</span>}
                    </label>
                    <label>
                      <span>{window.L("البريد الإلكتروني", "Email")}<span className="req">*</span></span>
                      <input className={errors.email ? "invalid" : ""} type="email" value={form.email} onChange={update("email")} placeholder="you@company.com"/>
                      {errors.email && <span className="field-error">{errors.email}</span>}
                    </label>
                    <label>
                      <span>{window.L("رقم الجوال", "Mobile number")}<span className="req">*</span></span>
                      <input className={errors.phone ? "invalid" : ""} type="tel" dir="ltr" value={form.phone} onChange={update("phone")} placeholder="+966 5X XXX XXXX"/>
                      {errors.phone && <span className="field-error">{errors.phone}</span>}
                    </label>
                  </div>
                  <div className={"survey-q" + (errors.products ? " invalid" : "")}>
                    <span className="survey-q-label">{window.L("المنتج الذي تهتم به (يمكن اختيار أكثر من واحد)", "Product you're interested in (choose one or more)")}<span className="req">*</span></span>
                    <div className="survey-options">
                      {PRODUCTS.map((p) => {
                        const checked = form.products.includes(p.id);
                        return (
                          <label key={p.id} className={`survey-option ${checked ? "active" : ""}`}>
                            <input type="checkbox" name="products" value={p.id} checked={checked} onChange={() => toggleProduct(p.id)}/>
                            <span className="survey-option-box"></span>
                            <span>{p.label}</span>
                          </label>
                        );
                      })}
                    </div>
                    {errors.products && <span className="field-error" style={{ marginTop: 10, display: "block" }}>{errors.products}</span>}
                  </div>
                  <button type="submit" disabled={sending} className="btn btn-primary" style={{ marginTop: 22, width: "100%", justifyContent: "center", opacity: sending ? 0.6 : 1 }}>{sending ? window.L("جارٍ الإرسال…", "Sending…") : <>{window.L("إرسال", "Submit")} <span className="mono">{window.ARR()}</span></>}</button>
                  {sendError && <p style={{ fontSize: 13, color: "#d33", marginTop: 12, textAlign: "center" }}>{window.L("حدث خطأ أثناء الإرسال. حاول مرة أخرى.", "Something went wrong. Please try again.")}</p>}
                </form>
              )}
            </div>
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

Object.assign(window, {
  ServicesPage, ServiceDetailPage, HowItWorksPage,
  SectorsPage, SectorDetailPage, AIAgentsPage,
  PricingPage, ContactPage, SurveyPage, NotFound, UnifiedInfographic,
});
