// Home Page — combines all sections per the PowerPoint's الرئيسية spec
const { useState: useStateH, useEffect: useEffectH, useRef: useRefH } = React;

// Backend endpoint helper (defined here too so it never depends on script load order)
if (!window.submitMislakForm) {
  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;
    }
  };
}

function scrollToContact(e) {
  if (e) e.preventDefault();
  const el = document.getElementById("contact");
  if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 72, behavior: "smooth" });
}

function HeroFlow() {
  const ref = useRefH(null);
  const ribbons = Array.from({ length: 11 });
  // two batches of ribbons running side by side; same curve, just offset
  // four side-by-side batches; ph/ds desync them so they don't flow in lockstep
  const batches = [
    { ox: -860, oy: 180, ph: 2.3, ds: 1.1 },
    { ox: -430, oy: 90, ph: 0.9, ds: 0.4 },
    { ox: 0, oy: 0, ph: 0, ds: 0 },
    { ox: 430, oy: -90, ph: 1.6, ds: 0.7 },
  ];
  // same control points as before — only the endpoints are extended so the lines run longer
  const pathD = (i, ox, oy) => {
    const o = i * 30;
    return `M ${1040 - i * 5 + ox} ${-240 + o + oy} C ${640 - i * 4 + ox} ${260 + o + oy}, ${500 - i * 3 + ox} ${600 + o + oy}, ${60 - i * 6 + ox} ${1340 + o + oy}`;
  };
  const star = (sz) => `M0 ${-sz} L ${sz*0.26} ${-sz*0.26} L ${sz} 0 L ${sz*0.26} ${sz*0.26} L 0 ${sz} L ${-sz*0.26} ${sz*0.26} L ${-sz} 0 L ${-sz*0.26} ${-sz*0.26} Z`;
  return (
    <div className="page-flow" ref={ref} aria-hidden="true">
      <svg viewBox="0 0 1000 1100" preserveAspectRatio="xMidYMid slice">
        <defs>
          <linearGradient id="flowGrad" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0" stopColor="#2E2BE0"/>
            <stop offset="0.45" stopColor="#7A4DFF"/>
            <stop offset="0.75" stopColor="#B84DFF"/>
            <stop offset="1" stopColor="#FF7AD9"/>
          </linearGradient>
        </defs>
        {batches.map((b, bi) => (
          <g key={bi}>
            {ribbons.map((_, i) => (
              <path
                key={i}
                id={`flowpath-${bi}-${i}`}
                d={pathD(i, b.ox, b.oy)}
                className="ribbon"
                style={{
                  strokeWidth: 4 + (i % 3) * 2.6,
                  opacity: 0.6 - i * 0.025,
                  animationDuration: `${7 + i * 0.6 + b.ds}s`,
                  animationDelay: `${i * -0.8 - b.ph}s`,
                }}
              />
            ))}
          </g>
        ))}
        {batches.map((b, bi) => (
          <g className="flow-stars" key={bi}>
            {ribbons.map((_, i) => {
              const dur = 8 + (i % 5) * 1.4;
              const s = i % 4 === 0 ? 7 : i % 3 === 0 ? 5.2 : 4;
              return (
                <g key={i}>
                  <path d={star(s)} className="flow-star">
                    <animateMotion dur={`${dur}s`} begin={`${-i * 0.9 - b.ph}s`} repeatCount="indefinite" keyPoints="0;1" keyTimes="0;1" calcMode="linear">
                      <mpath href={`#flowpath-${bi}-${i}`}/>
                    </animateMotion>
                    <animate attributeName="opacity" values="0;1;1;0.7;0" dur={`${dur}s`} begin={`${-i * 0.9 - b.ph}s`} repeatCount="indefinite"/>
                  </path>
                  <path d={star(s * 0.6)} className="flow-star alt">
                    <animateMotion dur={`${dur + 2}s`} begin={`${-i * 1.5 - 3 - b.ph}s`} repeatCount="indefinite" keyPoints="0;1" keyTimes="0;1" calcMode="linear">
                      <mpath href={`#flowpath-${bi}-${i}`}/>
                    </animateMotion>
                    <animate attributeName="opacity" values="0;0.95;0.95;0" dur={`${dur + 2}s`} begin={`${-i * 1.5 - 3 - b.ph}s`} repeatCount="indefinite"/>
                  </path>
                </g>
              );
            })}
          </g>
        ))}
      </svg>
    </div>
  );
}

function HomeHero({ showDemo, heroLayout }) {
  return (
    <section className={"hero" + (heroLayout === "center" ? " center" : "")}>
      <div className="container">
        <h1>
          {window.L("نحو تواصل ", "Toward ")}<span className="accent-word">{window.L("اذكى", "smarter")}</span>{window.L(" للاعمال،", " communication for business,")}
        </h1>
        <p className="hero-sub">
          {window.L("مسلاك يطوّر نظام الاتصال لديك من خلال أتمتة سير العمل، إدارة المكالمات بذكاء، وتوجيه المتصلين بكفاءة أعلى، مع استخدام الذكاء الاصطناعي لفهم احتياجات العملاء، تقليل المهام المتكررة، وأتمتة العمليات اليومية لتوفير الوقت وتحسين كفاءة التشغيل.", "Mislak elevates your communication system through workflow automation, smart call management, and more efficient caller routing — using AI to understand customer needs, reduce repetitive tasks, and automate daily operations to save time and improve operational efficiency.")}
        </p>
        <div className="hero-cta">
          <a className="btn btn-primary" href="#contact" onClick={scrollToContact}>{window.L("احجز عرضك التجريبي المجاني", "Book your free demo")}<span className="mono">{window.ARR()}</span></a>
        </div>
        {showDemo && <DemoCard/>}
      </div>
    </section>
  );
}

function DemoNavItem({ label, active, refCb }) {
  return (
    <div ref={refCb} className={`demo-sb-item ${active ? "active" : ""}`}>
      <span className="ring"></span>
      <span>{label}</span>
    </div>
  );
}

// --- small building blocks shared by demo screens ---
function DSHead({ title, sub, action }) {
  return (
    <div className="ds-head">
      <div>
        <div className="ds-title">{title}</div>
        <div className="ds-sub">{sub}</div>
      </div>
      {action}
    </div>
  );
}
function DSAvatar({ t, dark }) {
  return <span className={`ds-avatar ${dark ? "dark" : ""}`}>{t}</span>;
}
function DSTag({ children }) { return <span className="ds-tag mono">{children}</span>; }

function DemoScreen({ idx }) {
  const L = window.L;

  // 0 — Insights & Analysis
  if (idx === 0) {
    const metrics = [
      {l: L("متوسط التقييم", "AVG RATING"), v: "4.7", u: "/5", d: "+0.1"},
      {l: L("نسبة الحل", "RESOLUTION"), v: "90", u: "%", d: "+2%"},
      {l: L("مكالمات مُعالَجة", "CALLS HANDLED"), v: "552", u: "", d: "+48"},
    ];
    return (
      <div className="demo-screen">
        <DSHead title={L("الرؤى والتحليلات", "Insights & Analysis")} sub={L("كيف يؤدي فريقك ووكلاء الذكاء الاصطناعي عبر الوقت.", "How your team and AI agents are performing over time.")} />
        <div className="ds-label">{L("قائمة الانتظار المباشرة", "LIVE QUEUE")}</div>
        <div className="ds-grid-2">
          <div className="ds-card ds-queue">
            <div className="ds-label">{L("مركز الاتصال", "CALL CENTER")}</div>
            <div className="ds-bignum">3 <span>{L("مكالمات في الانتظار", "calls waiting")}</span></div>
            <div className="ds-rowline"><span>{L("أطول انتظار", "Longest wait")}</span><span className="mono">2m 14s</span></div>
          </div>
          <div className="ds-card ds-queue">
            <div className="ds-label">{L("المحادثات", "CHATS")}</div>
            <div className="ds-bignum">5 <span>{L("محادثات لم تُستلم", "chats unpicked")}</span></div>
            <div className="ds-rowline"><span>{L("أقدم محادثة", "Oldest chat")}</span><span className="mono">6m 02s</span></div>
          </div>
        </div>
        <div className="ds-label">{L("الأداء", "PERFORMANCE")}</div>
        <div className="ds-grid-3">
          {metrics.map((m, i) => (
            <div key={i} className="ds-card ds-metric">
              <div className="ds-metric-top"><span className="ds-label">{m.l}</span><span className="ds-delta mono">{m.d}</span></div>
              <div className="ds-metric-v">{m.v}<small>{m.u}</small></div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // 1 — Agents
  if (idx === 1) {
    const agents = [
      {i: "FA", n: L("فهد العتيبي", "Fahd Al-Otaibi"), ch: L("مكالمات", "CALLS"), on: true, r: 4.6, m: "14"},
      {i: "SA", n: L("سارة القحطاني", "Sara Al-Qahtani"), ch: L("مكالمات", "CALLS"), on: true, r: 4.9, m: "18"},
      {i: "ON", n: L("عمر ناصر", "Omar Nasser"), ch: L("مكالمات", "CALLS"), on: false, r: 4.4, m: "0"},
      {i: "LH", n: L("لينا حداد", "Lina Haddad"), ch: L("محادثات", "CHATS"), on: true, r: 4.8, m: "32"},
    ];
    return (
      <div className="demo-screen">
        <DSHead title={L("الوكلاء", "Agents")} sub={L("عرض مباشر لمن ينتظر وأداء فريقك الآن.", "Live view of who's waiting and how your team is performing right now.")} />
        <div className="ds-card">
          <div className="ds-card-head">
            <span className="ds-card-title">{L("الوكلاء", "Agents")} <em>6</em></span>
            <span className="ds-legend"><b className="on">●</b> {L("4 نشطون", "4 active")} <b>○</b> {L("2 غير نشط", "2 inactive")}</span>
          </div>
          <table className="ds-table">
            <thead><tr>
              <th>{L("الوكيل", "AGENT")}</th><th>{L("الحالة", "STATUS")}</th><th>{L("التقييم", "RATING")}</th><th className="num">{L("/ساعة", "CALLS / HR")}</th>
            </tr></thead>
            <tbody>
              {agents.map((a, i) => (
                <tr key={i}>
                  <td><div className="ds-agent"><DSAvatar t={a.i} dark={a.on} /><div><div className="ds-agent-n">{a.n}</div><div className="ds-agent-ch mono">{a.ch}</div></div></div></td>
                  <td><span className={`ds-status ${a.on ? "on" : ""}`}>● {a.on ? L("نشط", "Active") : L("غير نشط", "Inactive")}</span></td>
                  <td><div className="ds-rating"><b>{a.r}</b><span className="ds-ratebar"><i style={{width: `${(a.r/5)*100}%`}}></i></span></div></td>
                  <td className="num mono">{a.m}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  // 2 — Automations
  if (idx === 2) {
    return (
      <div className="demo-screen">
        <DSHead
          title={L("الأتمتة", "Automations")}
          sub={L("اضبط كيف تُعالَج المحادثات والمكالمات قبل تدخّل موظف — وكلاء ذكاء، قوائم IVR، والبريد الصوتي.", "Set up how chats and calls are handled before a person steps in — AI agents, IVR menus, and voicemail.")}
          action={<span className="ds-btn">+ {L("أتمتة جديدة", "New automation")}</span>}
        />
        <div className="ds-grid-2">
          <div className="ds-card ds-auto">
            <div className="ds-auto-head"><span className="ds-ico">✦</span><div className="ds-auto-titles"><div className="ds-auto-t">{L("مساعد الموقع", "Website assistant")} <DSTag>CHAT</DSTag></div><div className="ds-auto-s">{L("3 قيود", "3 limitations")}</div></div></div>
            <ul className="ds-auto-list">
              <li>{L("مشاركة الأسعار الداخلية", "Share internal pricing")}</li>
              <li>{L("الوعد باسترداد أو خصومات", "Promise refunds or discounts")}</li>
              <li>{L("جمع أرقام البطاقات في المحادثة", "Collect card numbers in chat")}</li>
            </ul>
            <span className="ds-btn ghost">{L("تعديل", "Edit")}</span>
          </div>
          <div className="ds-card ds-auto">
            <div className="ds-auto-head"><span className="ds-ico">✦</span><div className="ds-auto-titles"><div className="ds-auto-t">{L("الذكاء الأمامي", "Front-line AI")} <DSTag>CALL</DSTag></div><div className="ds-auto-s">{L("قاعدتا تصعيد", "2 escalation rules")}</div></div></div>
            <ul className="ds-auto-list">
              <li>{L("إذا طلب المتصل موظفاً ← فريق الدعم", "If caller requests a human → Support team")}</li>
              <li>{L("إذا انزعج المتصل ← فريق الدعم", "If caller is frustrated → Support team")}</li>
            </ul>
            <span className="ds-btn ghost">{L("تعديل", "Edit")}</span>
          </div>
        </div>
      </div>
    );
  }

  // 3 — Conversations
  if (idx === 3) {
    const rows = [
      {n: L("ريما الحربي", "Reema Al-Harbi"), a: L("سارة القحطاني", "Sara Al-Qahtani"), o: L("مُسترَد", "Refunded"), w: "20/06/2026 · 11:24", c: "CSAT 2/5", dot: true},
      {n: L("يوسف خليل", "Yousef Khalil"), a: L("فهد العتيبي", "Fahad Al-Otaibi"), o: L("مُصعَّد", "Escalated"), w: "20/06/2026 · 10:02", c: L("بلا تقييم", "No CSAT"), dot: true},
      {n: L("هناء منصور", "Hana Mansour"), a: L("سارة القحطاني", "Sara Al-Qahtani"), o: L("مُحلّ", "Resolved"), w: "19/06/2026 · 16:48", c: "CSAT 5/5"},
      {n: L("طارق سعد", "Tariq Saad"), a: L("عمر ناصر", "Omar Nasser"), o: L("مُحلّ", "Resolved"), w: "19/06/2026 · 14:12", c: "CSAT 4/5"},
    ];
    return (
      <div className="demo-screen">
        <DSHead
          title={L("المحادثات", "Conversations")}
          sub={L("كل مكالمة ومحادثة — افتح أيّها لقراءة النص الكامل والتفاصيل.", "Every call and chat — open one to read the full transcript and details.")}
          action={<span className="ds-seg"><b className="on">{L("مكالمات", "Calls")}</b><b>{L("محادثات", "Chats")}</b></span>}
        />
        <div className="ds-filters">
          <span className="ds-field"><em>{L("الوكيل", "AGENT")}</em>{L("كل الوكلاء", "All agents")} ▾</span>
          <span className="ds-field"><em>{L("النتيجة", "OUTCOME")}</em>{L("كل النتائج", "All outcomes")} ▾</span>
          <span className="ds-field mono"><em>{L("من", "FROM")}</em>DD/MM/YYYY</span>
          <span className="ds-field mono"><em>{L("إلى", "TO")}</em>DD/MM/YYYY</span>
        </div>
        <div className="ds-card">
          <div className="ds-card-head"><span className="ds-card-title">{L("كل المكالمات", "All calls")}</span><span className="ds-muted">{L("عرض 5 من 5", "Showing 5 of 5")}</span></div>
          <table className="ds-table">
            <thead><tr><th>{L("العميل · الوكيل", "CUSTOMER · AGENT")}</th><th>{L("النتيجة", "OUTCOME")}</th><th>{L("متى", "WHEN")}</th><th>{L("الرضا", "CSAT")}</th></tr></thead>
            <tbody>
              {rows.map((r, i) => (
                <tr key={i}>
                  <td><div className="ds-conv-n">{r.n} {r.dot && <b className="ds-redflag">●</b>}</div><div className="ds-agent-ch">{L("مع", "with")} {r.a}</div></td>
                  <td className="ds-muted">{r.o}</td>
                  <td className="mono ds-muted ds-when">{r.w}</td>
                  <td className="ds-muted">{r.c}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  // 4 — Call Flow
  if (idx === 4) {
    return (
      <div className="demo-screen">
        <DSHead
          title={L("مسار المكالمات", "Call Flow")}
          sub={L("اسحب العناصر من اللوحة بالأسفل. اضغط على مساحة فارغة واسحب للتحريك.", "Drag nodes from the palette below. Click empty space and drag to pan.")}
          action={<span className="ds-btn-group"><b>{L("توسيط", "Recenter")}</b><b>{L("إعادة", "Reset")}</b><b className="solid">{L("حفظ المسار", "Save flow")}</b></span>}
        />
        <div className="ds-canvas">
          <div className="ds-node">
            <div className="ds-node-head"><span className="ds-tag mono">TEL</span><b>{L("مكالمة واردة", "Incoming")}</b></div>
            <div className="mono ds-node-num">9200 12345</div>
            <div className="ds-node-sub">{L("الخط الرئيسي", "Main line")}</div>
          </div>
          <span className="ds-connector"></span>
          <div className="ds-node">
            <div className="ds-node-head"><span className="ds-tag mono">AI</span><b>{L("الذكاء الأمامي", "Front-line AI")}</b></div>
            <div className="ds-node-sub">{L("يرد ويوجّه المتصل", "Answers & routes the caller")}</div>
          </div>
          <span className="ds-connector"></span>
          <div className="ds-node">
            <div className="ds-node-head"><span className="ds-tag mono">TEAM</span><b>{L("فريق المبيعات", "Sales team")}</b></div>
            <div className="ds-node-sub">{L("3 وكلاء متاحون", "3 agents available")}</div>
          </div>
        </div>
        <div className="ds-palette">
          <span className="ds-palette-label mono">{L("اسحب", "DRAG IN")}</span>
          <span className="ds-chip"><b className="mono">AI</b>{L("الذكاء الأمامي", "Front-line AI")}</span>
          <span className="ds-chip"><b className="mono">IVR</b>{L("القائمة الرئيسية", "Main phone menu")}</span>
          <span className="ds-chip"><b className="mono">VM</b>{L("خارج الدوام", "After-hours")}</span>
        </div>
      </div>
    );
  }

  // 5 — Chat Flow
  return (
    <div className="demo-screen">
      <DSHead
        title={L("مسار الدردشة", "Chat Flow")}
        sub={L("كل محادثة تبدأ مع وكيل الذكاء. وعندما لا يستطيع حلّها — أو يحتاج العميل لشخص — تُحوَّل مباشرة لموظف.", "Every chat opens with your AI agent. When it can't resolve it — or the customer needs a person — the chat is handed straight to a real agent.")}
        action={<span className="ds-btn">{L("حفظ المسار", "Save flow")}</span>}
      />
      <div className="ds-card">
        <div className="ds-auto-head"><span className="ds-ico">✦</span><div className="ds-auto-titles"><div className="ds-auto-t">{L("وكيل الذكاء يجيب أولاً", "AI agent answers first")} <DSTag>CHAT AI</DSTag></div><div className="ds-auto-s">{L("أول من يتحدث معه كل عميل.", "The first thing every customer talks to.")}</div></div></div>
        <div className="ds-field-label">{L("أي وكيل ذكاء", "WHICH AI AGENT")}</div>
        <div className="ds-select">{L("مساعد الموقع", "Website assistant")} ▾</div>
        <div className="ds-opens"><span className="ds-label">{L("يبدأ بـ", "OPENS WITH")}</span>"{L("مرحباً! أنا مساعد مسلاك. اسألني أي شيء عن طلبك.", "Hi! I'm the Mislak assistant. Ask me anything about your order.")}"</div>
        <div className="ds-rollout">
          <div className="ds-rollout-top"><div><div className="ds-rollout-t">{L("الطرح للعملاء", "Rollout to customers")}</div><div className="ds-auto-s">{L("نسبة المحادثات الجديدة التي تبدأ بالذكاء.", "Share of new chats that start with the AI.")}</div></div><div className="ds-rollout-pct">10%</div></div>
          <div className="ds-slider"><span style={{width: "10%"}}></span><i style={{insetInlineStart: "10%"}}></i></div>
        </div>
      </div>
    </div>
  );
}

function DemoCard() {
  const L = window.L;
  const navItems = [
    L("الرؤى والتحليلات", "Insights & Analysis"),
    L("الوكلاء", "Agents"),
    L("الأتمتة", "Automations"),
    L("المحادثات", "Conversations"),
    L("مسار المكالمات", "Call Flow"),
    L("مسار الدردشة", "Chat Flow"),
    L("الإعدادات", "Settings"),
  ];
  const tour = [0, 1, 2, 3, 4, 5];
  const [ti, setTi] = useStateH(0);
  const active = tour[ti];
  const itemRefs = useRefH([]);
  const [cursorY, setCursorY] = useStateH(120);
  const [clicking, setClicking] = useStateH(false);
  const cardRef = useRefH(null);
  const frameRef = useRefH(null);
  const scaleRef = useRefH(null);

  useEffectH(() => {
    const id = setInterval(() => setTi((t) => (t + 1) % tour.length), 2200);
    return () => clearInterval(id);
  }, []);

  // Squeeze the full dashboard down to fit narrow viewports (phones/tablets)
  // instead of collapsing it into a broken single column.
  useEffectH(() => {
    const card = cardRef.current, frame = frameRef.current, scaler = scaleRef.current;
    if (!card || !frame || !scaler) return;
    const DESIGN = 900; // design width of the dashboard frame
    const apply = () => {
      const cs = getComputedStyle(card);
      const padX = parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight);
      const inner = card.clientWidth - padX;
      if (inner > 0 && inner < DESIGN) {
        const s = inner / DESIGN;
        frame.style.width = DESIGN + "px";
        scaler.style.transform = `scale(${s})`;
        scaler.style.height = (frame.offsetHeight * s) + "px";
      } else {
        frame.style.width = "";
        scaler.style.transform = "";
        scaler.style.height = "";
      }
    };
    apply();
    const ro = new ResizeObserver(apply);
    ro.observe(card);
    window.addEventListener("resize", apply);
    return () => { ro.disconnect(); window.removeEventListener("resize", apply); };
  }, []);

  useEffectH(() => {
    const el = itemRefs.current[active];
    if (el) setCursorY(el.offsetTop + el.offsetHeight / 2);
    setClicking(true);
    const t = setTimeout(() => setClicking(false), 420);
    return () => clearTimeout(t);
  }, [active]);

  return (
    <div className="demo-card" ref={cardRef}>
      <div className="demo-scale" ref={scaleRef}>
      <div className="demo-frame" ref={frameRef}>
        <div className="demo-sidebar">
          <div className="demo-brand">
            <span className="demo-brand-logo"><img src="assets/mislak-mark.png" alt="Mislak"/></span>
            <div>
              <div className="demo-brand-name">Mislak</div>
              <div className="demo-brand-role mono">{L("مدير", "Manager")}</div>
            </div>
          </div>
          <div className="demo-nav-label mono">{L("التنقل", "NAVIGATION")}</div>
          <div className="demo-nav">
            {navItems.map((n, k) => (
              <DemoNavItem key={k} label={n} active={k === active} refCb={(el) => (itemRefs.current[k] = el)} />
            ))}
          </div>
          <div className="demo-sb-foot">
            <div className="demo-team">
              <span className="demo-team-logo">S</span>
              <div>
                <div className="demo-team-name">{L("فريق الدعم", "Support team")}</div>
                <div className="demo-team-num mono">+966 11 234 5678</div>
              </div>
            </div>
            <div className="demo-signout">{L("تسجيل الخروج", "Sign out")}</div>
          </div>
          <span className={`demo-cursor ${clicking ? "click" : ""}`} style={{top: cursorY}}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M5 2l14 9-6.5 1.3L16 19l-2.5 1.2-3.4-6.7L5 18V2z"/></svg>
          </span>
        </div>
        <div className="demo-main">
          <DemoScreen key={active} idx={active} />
        </div>
      </div>
      </div>
    </div>
  );
}

function HomeFeatures() {
  return (
    <section id="features">
      <div className="container">
        <div className="sec-head">
          <div className="sec-head-l">
            <div className="sec-eyebrow">{window.L("الخدمات", "Services")}</div>
            <h2>{window.L(<>إدارة جميع اتصالاتك<br/>من منصة واحدة.</>, <>Manage all your communications<br/>from a single platform.</>)}</h2>
          </div>
          <p className="sec-sub">{window.L("نظام سحابي متكامل يجمع المكالمات الصوتية، محادثات الواتساب، وأتمتة خدمة العملاء في واجهة موحدة، ليمنحك سيطرة كاملة من أي مكان.", "An integrated cloud platform that brings voice calls, WhatsApp conversations, and customer-service automation into one unified interface — giving you full control from anywhere.")}</p>
        </div>
        <div className="feat-grid">
          {window.getData().features.map((f) => (
            <div key={f.num} className={`feat ${f.dark ? "dark wide" : ""}`}>
              <h3>{f.title}</h3>
              <p>{f.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function HomeWhy() {
  return (
    <section id="why">
      <div className="container">
        <div className="why-grid">
          {window.getData().why.map((w) => (
            <div key={w.num} className="why-card">
              <div className="why-num">{w.num}</div>
              <div>
                <h3>{w.title}</h3>
                <p>{w.desc}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function HomeSectors() {
  const SECTORS = [
    { id: "ecom", label: window.L("التجزئة والتجارة الإلكترونية", "Retail & E-Commerce"), desc: window.L("إدارة استفسارات الطلبات والشحن والاستبدال والعروض وخدمة ما بعد البيع، وتوجيهها للفريق المناسب — تواصل أسرع وأوضح وطلبات أقل ضياعاً.", "Manage inquiries around orders, shipping, returns, offers, and after-sales — routed to the right team for faster, clearer communication and fewer lost orders.") },
    { id: "health", label: window.L("الصحة والرعاية", "Health & Care"), desc: window.L("تنظيم تواصل المرضى لحجز المواعيد وتعديلها والاستفسار والمتابعة، مع توجيه المكالمات للقسم المناسب وتقليل الضغط على الاستقبال.", "Organize patient communication for booking, rescheduling, inquiries, and follow-ups — routing calls to the right department and easing reception load.") },
    { id: "realestate", label: window.L("العقار والمقاولات", "Real Estate & Contracting"), desc: window.L("استقبال الاستفسارات وتوزيع المكالمات وتوثيق المحادثات ومتابعة العملاء المحتملين بوضوح من أول تواصل حتى الإغلاق.", "Receive inquiries, distribute calls, document conversations, and follow up with prospects clearly — from first contact to closing.") },
    { id: "edu", label: window.L("التعليم والتدريب", "Education & Training"), desc: window.L("تنظيم التواصل مع الطلاب وأولياء الأمور والمتدربين حول التسجيل والجداول والرسوم والبرامج، مع توجيه كل رسالة للقسم المناسب.", "Organize communication with students, parents, and trainees around enrollment, schedules, fees, and programs — routing every message to the right department.") },
    { id: "hospitality", label: window.L("الضيافة والمطاعم", "Hospitality & Restaurants"), desc: window.L("إدارة الحجوزات والاستفسارات والطلبات والشكاوى بطريقة منظمة، مع رد أسرع وتأخير أقل وتجربة أفضل قبل الزيارة وأثناءها وبعدها.", "Manage reservations, inquiries, orders, and complaints in an organized way — faster responses, fewer delays, and a better experience before, during, and after the visit.") },
    { id: "professional", label: window.L("الخدمات المهنية والتشغيلية", "Professional & Operational"), desc: window.L("تنظيم طلبات العملاء والمتابعات اليومية لشركات الصيانة والنظافة وإدارة المرافق والاستشارات عبر رقم موحد ولوحة تحكم واضحة.", "Organize customer requests and daily follow-ups for maintenance, cleaning, facilities, and consulting firms — through a unified number and a clear dashboard.") },
  ];
  return (
    <section id="sectors">
      <div className="container">
        <div className="sec-head">
          <div className="sec-head-l">
            <div className="sec-eyebrow">{window.L("القطاعات", "Sectors")}</div>
            <h2>{window.L(<>نظام اتصال مرن<br/>يتكيف مع مختلف القطاعات.</>, <>A flexible communication system<br/>that adapts to every sector.</>)}</h2>
          </div>
          <p className="sec-sub">{window.L("لكل قطاع طريقته في استقبال العملاء وإدارة الاستفسارات ومتابعة الطلبات. مسلاك يمنح كل قطاع نظام تواصل مرن ينظّم المكالمات والرسائل ويوجّه العملاء للفريق المناسب.", "Every sector has its own way of receiving customers and managing inquiries. Mislak gives each one a flexible communication system that organizes calls and messages and routes customers to the right team.")}</p>
        </div>
        <div className="home-sector-grid">
          {SECTORS.map((s) => (
            <div key={s.id} className={`home-sector-card ${s.id === "ecom" ? "dark" : ""}`}>
              <h3>{s.label}</h3>
              <p>{s.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function HomeAgents() {
  return (
    <section id="agents">
      <div className="container">
        <div className="sec-head">
          <div className="sec-head-l">
            <div className="sec-eyebrow">{window.L("وكلاء الذكاء الاصطناعي", "AI Agents")}</div>
            <h2>{window.L(<>وكيل ذكي يعمل على مدار الساعة،<br/>يفهم العملاء ويحلل التفاعلات.</>, <>A smart agent that works around the clock,<br/>understanding customers and analyzing interactions.</>)}</h2>
            <p className="sec-sub" style={{marginTop: 18, maxWidth: 560}}>{window.L("مسلاك يطوّر أنظمة الاتصال التقليدية بإضافة الذكاء الاصطناعي، حيث يحلل الوكلاء الأذكياء اتصالات العملاء، يستخرجون المعلومات المهمة، ويساعدون في أتمتة العمليات اليومية.", "Mislak enhances traditional communication systems with AI, where smart agents analyze customer communications, extract key information, and help automate daily operations.")}</p>
          </div>
        </div>
        <div className="ai-grid">
          {window.getDetails().aiCapabilities.map((c, i) => (
            <div key={c.num} className={`ai-card ${i === 0 ? "wide dark" : ""}`}>
              <div className="ai-tag mono">{c.tag}</div>
              <h3>{c.title}</h3>
              <p>{c.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function HomeJourney() {
  return (
    <section id="how">
      <div className="container">
        <div className="sec-head">
          <div className="sec-head-l">
            <div className="sec-eyebrow">{window.L("كيف يعمل مسلاك", "How Mislak Works")}</div>
            <h2>{window.L(<>رحلة عميلك مع مسلاك،<br/>ذكاء في كل خطوة.</>, <>Your customer's journey with Mislak,<br/>intelligence at every step.</>)}</h2>
          </div>
          <p className="sec-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.")}</p>
        </div>
        <div className="journey-track">
          {window.getData().journey.map((s, i) => (
            <div key={s.n} className={`j-step ${i === 0 ? "active" : ""}`}>
              <div className="j-bub">{s.n}</div>
              <h4>{s.title}</h4>
              <p>{s.desc}</p>
            </div>
          ))}
        </div>
        <div style={{marginTop: 40, textAlign: "center"}}>
          <a className="btn btn-ghost" href="#/how">{window.L("اكتشف الرحلة كاملة", "Discover the full journey")} <span className="mono">{window.ARR()}</span></a>
        </div>
      </div>
    </section>
  );
}

function HomeStats() {
  return (
    <section>
      <div className="container">
        <div className="stats-band">
          <div className="sec-eyebrow" style={{color: "var(--accent)"}}>{window.L("أرقام تتحدث عن ثقتنا", "Numbers that speak to the trust in us")}</div>
          <h2>{window.L(<>مسلاك،<br/>القوة التي تثق بها كبرى الشركات.</>, <>Mislak,<br/>the power that major companies trust.</>)}</h2>
          <p className="sec-sub" style={{marginTop: 14}}>{window.L("كل رقم هنا يمثّل عميلاً نجح في مضاعفة إنتاجيته، وفريقاً تحرّر من المهام الروتينية.", "Every number here represents a customer who doubled their productivity, and a team freed from routine tasks.")}</p>
          <div className="stats-row">
            {window.getData().stats.map((s) => (
              <div key={s.l} className="stat">
                <div className="v">
                  <span className="mono">{s.v}</span>
                  <span className="accent mono">{s.suf}</span>
                </div>
                <div className="l">{s.l}</div>
              </div>
            ))}
          </div>
          <div className="logos">
            <div className="logos-label">{window.L("يثقون بمسلاك", "Trusted by")}</div>
            <div className="logos-row">
              {window.getData().logos.map((l) => (
                <div key={l} className="logo-cell mono">{l}</div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function HomeIntegrations() {
  return (
    <section>
      <div className="container">
        <div className="sec-head">
          <div className="sec-head-l">
            <div className="sec-eyebrow">{window.L("التكامل", "Integration")}</div>
            <h2>{window.L(<>تكامل سلس مع الأدوات<br/>التي تستخدمها اليوم.</>, <>Seamless integration with the tools<br/>you already use today.</>)}</h2>
          </div>
          <p className="sec-sub">{window.L("لا داعي لتشتيت فريقك بين البرامج. مسلاك يربط اتصالاتك بقلب أنظمتك الإدارية لتبقى بيانات عملائك محدّثة لحظة بلحظة.", "No need to scatter your team across apps. Mislak connects your communications to the heart of your management systems, keeping your customer data updated moment by moment.")}</p>
        </div>
        <div className="integ-board">
          <div className="integ-ring r1"></div>
          <div className="integ-ring r2"></div>
          <div className="integ-center">{window.L("مسلاك", "Mislak")}</div>
          {window.getData().integrations.map((i) => (
            <div key={i.code} className="integ-pill" style={{right: `${i.x}%`, top: `${i.y}%`, transform: "translate(50%, -50%)"}}>
              <span className="sq">{i.code}</span>
              <span>{i.name}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function HomePricingTeaser() {
  return (
    <section>
      <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>
              <a className={`btn btn-${p.ctaStyle}`} href="#/pricing">{window.L("شاهد التفاصيل", "View details")}</a>
            </div>
          ))}
        </div>
        <div style={{marginTop: 28, textAlign: "center"}}>
          <a className="btn btn-ghost" href="#/pricing">{window.L("قارن الباقات بالتفصيل", "Compare plans in detail")} <span className="mono">{window.ARR()}</span></a>
        </div>
      </div>
    </section>
  );
}

function HomeFinalCTA() {
  return (
    <section>
      <div className="container">
        <div className="final-cta">
          <h2>{window.L(<>جاهز لتجربة مسلاك؟</>, <>Ready to try Mislak?</>)}</h2>
          <p>{window.L("تعرّف على طريقة جديدة لإدارة اتصالات شركتك. احجز عرضاً تجريبياً وسنساعدك في اكتشاف الأدوات المناسبة لاحتياجاتك.", "Discover a new way to manage your company's communications. Book a demo and we'll help you discover the right tools for your needs.")}</p>
          <div style={{display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap"}}>
            <a className="btn btn-accent" href="#contact" onClick={scrollToContact}>{window.L("احجز عرضك التجريبي (مجانًا)", "Book your free demo")}</a>
            <a className="btn btn-ghost cta-secondary" href="#contact" onClick={scrollToContact}>{window.L("تواصل معنا", "Contact us")}</a>
          </div>
        </div>
      </div>
    </section>
  );
}

function HomeContact() {
  const [form, setForm] = useStateH({ name: "", company: "", email: "", phone: "", sector: "", msg: "" });
  const [errors, setErrors] = useStateH({});
  const [sent, setSent] = useStateH(false);
  const [sending, setSending] = useStateH(false);
  const [sendError, setSendError] = useStateH(false);
  const c = window.getDetails().contact;
  const update = (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 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.company.trim()) e.company = req;
    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.sector) e.sector = window.L("يرجى اختيار القطاع", "Please choose a sector");
    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 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 setSendError(true);
  };
  return (
    <section id="contact">
      <div className="container">
        <div className="sec-head">
          <div className="sec-head-l">
            <div className="sec-eyebrow">{window.L("تواصل معنا", "Contact Us")}</div>
            <h2>{c.title}</h2>
          </div>
          <p className="sec-sub">{c.sub}</p>
        </div>
        <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); setErrors({}); setForm({ name: "", company: "", email: "", phone: "", sector: "", msg: "" }); }}>{window.L("إرسال طلب آخر", "Send another request")}</button>
              </div>
            ) : (
              <form onSubmit={onSubmit} noValidate>
                <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 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("اسم الشركة", "Company name")}<span className="req">*</span></span>
                    <input className={errors.company ? "invalid" : ""} value={form.company} onChange={update("company")} placeholder={window.L("شركة المثال", "Example Co.")}/>
                    {errors.company && <span className="field-error">{errors.company}</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>
                  <label className="span-2">
                    <span>{window.L("القطاع", "Sector")}<span className="req">*</span></span>
                    <select className={errors.sector ? "invalid" : ""} value={form.sector} onChange={update("sector")}>
                      <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>
                    {errors.sector && <span className="field-error">{errors.sector}</span>}
                  </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>
                {sendError && <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>
  );
}

function HomePage({ showDemo, heroLayout }) {
  useEffectH(() => {
    if (window.__pendingScroll) {
      const id = window.__pendingScroll;
      window.__pendingScroll = null;
      const t = setTimeout(() => {
        const el = document.getElementById(id);
        if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 72, behavior: "smooth" });
      }, 140);
      return () => clearTimeout(t);
    }
  }, []);
  return (
    <React.Fragment>
      <HeroFlow/>
      <HomeHero showDemo={showDemo} heroLayout={heroLayout}/>
      <HomeFeatures/>
      <HomeSectors/>
      <HomeAgents/>
      <HomeFinalCTA/>
      <HomeContact/>
    </React.Fragment>
  );
}

Object.assign(window, { HomePage });
