/* global React */
const { useState: useSB, useEffect: useEB, useRef: useRB } = React;

/* ============ RESULTS ============ */
function ResultChart() {
  return (
    <svg viewBox="0 0 320 90" className="chart-line" preserveAspectRatio="none">
      <defs>
        <linearGradient id="gradLine" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="oklch(58% 0.19 255)" stopOpacity="0.35" />
          <stop offset="100%" stopColor="oklch(58% 0.19 255)" stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d="M0 70 L40 60 L80 65 L120 50 L160 55 L200 35 L240 30 L280 22 L320 10 L320 90 L0 90 Z" fill="url(#gradLine)" />
      <path d="M0 70 L40 60 L80 65 L120 50 L160 55 L200 35 L240 30 L280 22 L320 10" stroke="oklch(58% 0.19 255)" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      {[[0,70],[40,60],[80,65],[120,50],[160,55],[200,35],[240,30],[280,22],[320,10]].map(([x,y], i) => (
        <circle key={i} cx={x} cy={y} r="3" fill="white" stroke="oklch(58% 0.19 255)" strokeWidth="2" />
      ))}
    </svg>
  );
}

function ResultDonut() {
  const r = 36, c = 2 * Math.PI * r;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 24 }}>
      <svg width="100" height="100" viewBox="0 0 100 100">
        <circle cx="50" cy="50" r={r} stroke="rgba(255,255,255,0.1)" strokeWidth="10" fill="none" />
        <circle cx="50" cy="50" r={r} stroke="oklch(78% 0.13 225)" strokeWidth="10" fill="none"
          strokeDasharray={c} strokeDashoffset={c * 0.35} strokeLinecap="round"
          transform="rotate(-90 50 50)" />
      </svg>
      <div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 36, fontWeight: 500, letterSpacing: "-0.03em", color: "white" }}>
          <Counter to={65} suffix="%" />
        </div>
        <div style={{ fontSize: 13, color: "color-mix(in oklch, white 70%, transparent)" }}>Lead time reduced</div>
      </div>
    </div>
  );
}

function Results() {
  return (
    <section className="section" id="results">
      <div className="container">
        <div className="section-head reveal">
          <span className="eyebrow"><span className="dot" />Results</span>
          <h2>Measurable outcomes — not slide decks.</h2>
        </div>
        <div className="results-grid reveal-stagger">
          <div className="result-card span-7">
            <div className="result-label">Manufacturing · SAP S/4HANA</div>
            <div className="result-headline">
              <Counter to={35} suffix="%" /> <span className="accent">reduction</span><br />in operational cost
            </div>
            <p className="result-desc">
              Consolidated 4 legacy ERPs into a single SAP S/4HANA tenant across 12 plants —
              eliminating duplicate data entry and cutting month-end close from 9 days to 2.
            </p>
            <div className="result-viz"><ResultChart /></div>
          </div>
          <div className="result-card span-5 dark">
            <div className="result-label">Retail · Multi-location ERP</div>
            <div className="result-headline" style={{ color: "white" }}>
              <Counter to={30} /> days<br />to cloud, end-to-end
            </div>
            <p className="result-desc">
              Migrated 47-location retail chain from on-prem to AWS with zero customer-facing downtime
              and full POS continuity through cutover weekend.
            </p>
            <div className="result-viz"><ResultDonut /></div>
          </div>
          <div className="result-card span-4">
            <div className="result-label">Logistics</div>
            <div className="result-headline" style={{ fontSize: 36 }}>
              +<Counter to={50} suffix="%" />
            </div>
            <p className="result-desc">Business efficiency uplift after warehouse + CRM automation rollout.</p>
          </div>
          <div className="result-card span-4">
            <div className="result-label">Finance</div>
            <div className="result-headline" style={{ fontSize: 36 }}>
              <Counter to={4} suffix="hr" />
            </div>
            <p className="result-desc">SLA response time on Tier-1 incidents, down from 24-hour previous baseline.</p>
          </div>
          <div className="result-card span-4">
            <div className="result-label">Healthcare</div>
            <div className="result-headline" style={{ fontSize: 36 }}>
              <Counter to={99} suffix=".98%" />
            </div>
            <p className="result-desc">System uptime across 18 months on the new managed cloud infrastructure.</p>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ TESTIMONIALS ============ */
function Testimonials() {
  const items = [
    { q: "JSA's team didn't just migrate our SAP — they re-engineered how our finance team works. Month-end close is now a Tuesday afternoon.", n: "Ahmed Al-Maktoum", r: "CFO · Al-Falah Industries", a: "AM", res: "−65% close time" },
    { q: "We moved 47 retail locations to AWS in 30 days. Zero customer-facing downtime. I still don't quite believe it happened.", n: "Layla Al-Saeed", r: "CTO · Gulf Retail Group", a: "LS", res: "30-day cutover" },
    { q: "The level of ownership is genuinely unusual. They flag risks before we even know to ask. Best IT partner we've had in 15 years.", n: "Daniel Okafor", r: "COO · Emirates Logistics", a: "DO", res: "Ongoing · 2yr" },
    { q: "Their managed support team feels like part of our company. 24/7 response is real, not a marketing line.", n: "Hessa Al-Rashid", r: "VP IT · Falcon Healthcare", a: "HR", res: "99.98% uptime" },
    { q: "We were three weeks from a board ultimatum on our CRM mess. JSA fixed it in five. Saved my year.", n: "Markus Lindqvist", r: "Director · Al-Bahar Group", a: "ML", res: "−5wk to launch" },
    { q: "Pragmatic, senior, on-time. Their playbook for Microsoft 365 adoption alone was worth the engagement.", n: "Fatima Al-Hassan", r: "Head of Ops · Knowledge Group KSA", a: "FA", res: "94% adoption" },
  ];
  const stars = Array.from({ length: 5 }, (_, i) => <Icon key={i} name="star" size={14} stroke={0} />);
  const all = [...items, ...items];
  return (
    <section className="section">
      <div className="container">
        <div className="section-head center reveal">
          <span className="eyebrow"><span className="dot" />What clients say</span>
          <h2>Five-star results, written by the people we ship for.</h2>
        </div>
      </div>
      <div className="testimonial-wrap">
        <div className="testimonial-track">
          {all.map((t, i) => (
            <div key={i} className="testimonial">
              <div className="testimonial-stars">
                {stars.map((s, j) => <svg key={j} width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3 7 7 1-5 5 1 7-6-3-6 3 1-7-5-5 7-1 3-7z" /></svg>)}
              </div>
              <p className="testimonial-quote">"{t.q}"</p>
              <div className="testimonial-foot">
                <div className="testimonial-avatar">{t.a}</div>
                <div>
                  <div className="testimonial-name">{t.n}</div>
                  <div className="testimonial-role">{t.r}</div>
                </div>
                <div className="testimonial-result">{t.res}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============ LEAD FORM ============ */
function LeadForm() {
  const [sent, setSent] = useSB(false);
  const [loading, setLoading] = useSB(false);
  const [error, setError] = useSB(null);
  const [form, setForm] = useSB({ name: "", company: "", email: "", phone: "", service: "SAP Implementation", message: "" });
  const onSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/submit.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (res.ok && data.success) {
        setSent(true);
      } else {
        setError(data.error || 'Submission failed. Please try again or email us directly.');
      }
    } catch (err) {
      setError('Network error. Please try again or email hello@jsaitsolutions.com');
    } finally {
      setLoading(false);
    }
  };
  const bullets = [
    "Free 45-minute infrastructure assessment",
    "Custom ROI projection within 5 business days",
    "Senior consultant — not a sales rep",
    "Zero obligation. NDA available on request.",
  ];
  return (
    <section className="section" id="consult" style={{ background: "var(--bg-2)", borderTop: "1px solid var(--line)" }}>
      <div className="container">
        <div className="lead-section">
          <div className="lead-side reveal">
            <span className="eyebrow"><span className="dot" />Free assessment</span>
            <h2 style={{ marginTop: 20 }}>Get a free IT &amp; infrastructure assessment.</h2>
            <p className="lead">
              Tell us where you are. We'll tell you what's worth fixing, in plain language,
              with numbers attached.
            </p>
            <ul className="lead-bullets">
              {bullets.map((b, i) => (
                <li key={i}><Icon name="check" size={18} />{b}</li>
              ))}
            </ul>
            <div className="lead-contacts">
              <div className="lead-contact">
                <div className="ic"><Icon name="phone" size={18} /></div>
                <div>
                  <strong>+971 4 123 4567</strong>
                  <span>SUN–THU · 9AM – 6PM GST</span>
                </div>
              </div>
              <div className="lead-contact">
                <div className="ic"><Icon name="mail" size={18} /></div>
                <div>
                  <strong>hello@jsaitsolutions.com</strong>
                  <span>Reply within 4 working hours</span>
                </div>
              </div>
            </div>
          </div>

          <form className="lead-form reveal" onSubmit={onSubmit}>
            {sent ? (
              <div className="success-state">
                <div className="check"><Icon name="check" size={28} /></div>
                <h3>Request received.</h3>
                <p style={{ color: "var(--ink-3)", maxWidth: 36 + "ch", margin: "0 auto" }}>
                  A senior consultant will reach out within 24 hours to schedule your free assessment.
                </p>
              </div>
            ) : (
              <>
                <h3 style={{ marginBottom: 6, fontSize: 22 }}>Book your free consultation</h3>
                <p style={{ color: "var(--ink-3)", fontSize: 14, marginTop: 0, marginBottom: 24 }}>
                  Takes 30 seconds. No spam.
                </p>
                <div className="form-row">
                  <div className="field">
                    <label>Full name</label>
                    <input required value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="Your name" />
                  </div>
                  <div className="field">
                    <label>Company</label>
                    <input required value={form.company} onChange={e => setForm({ ...form, company: e.target.value })} placeholder="Company Pvt. Ltd." />
                  </div>
                </div>
                <div className="form-row">
                  <div className="field">
                    <label>Work email</label>
                    <input required type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} placeholder="you@company.com" />
                  </div>
                  <div className="field">
                    <label>Phone</label>
                    <input required value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} placeholder="+971 ..." />
                  </div>
                </div>
                <div className="field">
                  <label>Service interested in</label>
                  <select value={form.service} onChange={e => setForm({ ...form, service: e.target.value })}>
                    {["SAP Implementation", "ERP & CRM Solutions", "Cloud Migration", "Managed IT Support", "Digital Transformation", "Cybersecurity", "Microsoft 365", "IT Infrastructure", "Not sure — please advise"].map((s, i) => (
                      <option key={i}>{s}</option>
                    ))}
                  </select>
                </div>
                <div className="field">
                  <label>Tell us a bit about your project</label>
                  <textarea value={form.message} onChange={e => setForm({ ...form, message: e.target.value })} placeholder="What are you trying to solve? Current stack? Timeline?" />
                </div>
                {error && (
                  <p style={{ color: "var(--red, #dc2626)", fontSize: 13, margin: "0 0 12px" }}>{error}</p>
                )}
                <div className="form-foot">
                  <span className="form-trust">
                    <Icon name="lock" size={14} />
                    Secured · Reply within 24h
                  </span>
                  <button type="submit" className="btn btn-blue" disabled={loading}>
                    {loading ? "Sending…" : <>Get free consultation <Icon name="arrow" size={14} className="arr" /></>}
                  </button>
                </div>
              </>
            )}
          </form>
        </div>
      </div>
    </section>
  );
}

/* ============ FAQ ============ */
function FAQ() {
  const [open, setOpen] = useSB(0);
  const items = [
    { q: "Which countries do you operate in?", a: "We deliver across the GCC — UAE, Saudi Arabia, Qatar, Bahrain, Kuwait, and Oman — with offices in Dubai, Abu Dhabi, Riyadh, and Doha. Our consultants are on-site or in-region for every engagement." },
    { q: "What ERP solutions do you provide?", a: "We implement SAP S/4HANA, SAP Business One, Microsoft Dynamics 365, Oracle NetSuite, and a curated set of vertical ERPs for manufacturing and retail. We also build composable ERP layers on top of best-in-class point solutions when a monolith doesn't fit." },
    { q: "Do you provide SAP implementation?", a: "Yes — we are a certified SAP partner with end-to-end S/4HANA capability: greenfield, brownfield, and selective data transition. Our consultants average 12+ years of SAP delivery experience across manufacturing, retail, and services in the Middle East." },
    { q: "Can you migrate our business to the cloud?", a: "We migrate workloads to AWS, Azure, and Google Cloud — with regional data residency (UAE, KSA) where compliance demands it. Most mid-market cutovers complete in 30–90 days with zero customer-facing downtime." },
    { q: "Are you compliant with regional regulations?", a: "Yes — we deliver to NESA (UAE), SAMA Cyber Security Framework (KSA), ISR (Dubai), ISO 27001, SOC 2 Type II, and HIPAA. We're a registered IT services provider in the UAE and KSA." },
    { q: "How long does implementation take?", a: "Cloud migrations: 30–90 days. ERP rollouts: 4–9 months depending on scope. Managed IT and Microsoft 365 transitions: 2–6 weeks. We share a detailed timeline as part of the free assessment." },
    { q: "Do you provide ongoing IT support?", a: "Yes — 24/7 SLA-backed managed services covering helpdesk, infrastructure monitoring, cybersecurity, and ERP application support. Dedicated account manager and Arabic + English support included from day one." },
    { q: "Which industries do you serve?", a: "Manufacturing, retail, healthcare, logistics, finance, education, real estate, and e-commerce across the GCC. We're industry-agnostic on tech, but vertical-deep on processes." },
  ];
  return (
    <section className="section" id="faq">
      <div className="container">
        <div className="section-head center reveal">
          <span className="eyebrow"><span className="dot" />Frequently asked</span>
          <h2>Answers to questions sales teams usually duck.</h2>
        </div>
        <div className="faq-list reveal">
          {items.map((it, i) => (
            <div key={i} className={`faq-item ${open === i ? "open" : ""}`}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span>{it.q}</span>
                <span className="faq-icon"><Icon name="plus" size={14} /></span>
              </button>
              <div className="faq-a"><p>{it.a}</p></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============ FINAL CTA ============ */
function FinalCTA() {
  return (
    <section className="section">
      <div className="final-cta">
        <div className="final-cta-inner reveal">
          <span className="eyebrow why-eyebrow"><span className="dot" />Let's build</span>
          <h2>Ready to modernize your<br />business infrastructure?</h2>
          <p className="lead">
            Get a free consultation with our IT transformation experts.
            We'll tell you what's worth doing — and what isn't.
          </p>
          <div className="cta-row">
            <a href="#consult" className="btn btn-white btn-lg">Schedule consultation <Icon name="arrow" size={16} className="arr" /></a>
            <a href="tel:+97141234567" className="btn btn-light btn-lg"><Icon name="phone" size={16} />Contact sales</a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ FOOTER ============ */
function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <a href="#top" className="logo" style={{ color: "white" }}>
              <span className="logo-mark">JSA</span>
              <span>JSA IT Solutions</span>
            </a>
            <p className="footer-tag">
              Enterprise IT, SAP, cloud, and digital transformation services across the GCC —
              built for businesses ready to scale.
            </p>
            <div className="footer-social">
              <a href="#"><Icon name="linkedin" size={16} /></a>
              <a href="#"><Icon name="twitter" size={16} /></a>
              <a href="#"><Icon name="mail" size={16} /></a>
            </div>
            <div className="footer-trust-stmt">
              <Icon name="sparkle" size={14} />
              Enterprise IT solutions, built for growth.
            </div>
          </div>
          <div>
            <h4>Services</h4>
            <ul>
              <li><a href="#">SAP Implementation</a></li>
              <li><a href="#">ERP &amp; CRM</a></li>
              <li><a href="#">Cloud Migration</a></li>
              <li><a href="#">Managed IT</a></li>
              <li><a href="#">Cybersecurity</a></li>
            </ul>
          </div>
          <div>
            <h4>Company</h4>
            <ul>
              <li><a href="#">About</a></li>
              <li><a href="#">Industries</a></li>
              <li><a href="#">Case studies</a></li>
              <li><a href="#">Careers</a></li>
              <li><a href="#">Partners</a></li>
            </ul>
          </div>
          <div>
            <h4>Contact</h4>
            <ul>
              <li><a href="tel:+97141234567">+971 4 123 4567</a></li>
              <li><a href="mailto:hello@jsaitsolutions.com">hello@jsaitsolutions.com</a></li>
              <li><a href="#">Dubai · Abu Dhabi · Riyadh · Doha</a></li>
              <li><a href="#">Privacy policy</a></li>
              <li><a href="#">Terms</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 2026 JSA IT Solutions. All rights reserved.</div>
          <div>v2026.05 · Made for growing businesses.</div>
        </div>
      </div>
    </footer>
  );
}

/* ============ FLOATING + STICKY ============ */
function Floaters() {
  const [showBar, setShowBar] = useSB(false);
  useEB(() => {
    const onScroll = () => setShowBar(window.scrollY > 1200 && window.scrollY < document.body.scrollHeight - 1400);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <>
      <div className="fab-stack">
        <a href="https://wa.me/97141234567" className="fab whatsapp" aria-label="WhatsApp">
          <Icon name="whatsapp" size={26} stroke={0} />
        </a>
        <a href="tel:+97141234567" className="fab phone" aria-label="Call">
          <Icon name="phone" size={22} />
        </a>
      </div>
      <div className={`sticky-bar ${showBar ? "show" : ""}`}>
        <span className="sticky-bar-text"><strong>Free IT assessment</strong> · No obligation</span>
        <a href="#consult" className="btn btn-blue" style={{ padding: "10px 18px", fontSize: 14 }}>
          Book now <Icon name="arrow" size={14} />
        </a>
      </div>
    </>
  );
}

/* ============ EXIT INTENT ============ */
function ExitIntent() {
  const [show, setShow] = useSB(false);
  const fired = useRB(false);
  useEB(() => {
    const onLeave = (e) => {
      if (e.clientY < 0 && !fired.current && !sessionStorage.getItem("ei-fired")) {
        fired.current = true;
        sessionStorage.setItem("ei-fired", "1");
        setShow(true);
      }
    };
    document.addEventListener("mouseleave", onLeave);
    return () => document.removeEventListener("mouseleave", onLeave);
  }, []);
  return (
    <div className={`modal-overlay ${show ? "show" : ""}`} onClick={() => setShow(false)}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={() => setShow(false)}><Icon name="x" size={14} /></button>
        <div className="modal-eyebrow">Wait — one moment</div>
        <h3>Free IT Infrastructure Assessment</h3>
        <p>
          A senior consultant will audit your current stack and deliver a custom ROI plan —
          no obligation, no sales pressure.
        </p>
        <a href="#consult" className="btn btn-blue btn-lg" onClick={() => setShow(false)}>
          Claim free assessment <Icon name="arrow" size={14} className="arr" />
        </a>
        <p style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 16, marginBottom: 0 }}>
          Limited to new clients. Reply within 24 hours.
        </p>
      </div>
    </div>
  );
}

window.Results = Results;
window.Testimonials = Testimonials;
window.LeadForm = LeadForm;
window.FAQ = FAQ;
window.FinalCTA = FinalCTA;
window.Footer = Footer;
window.Floaters = Floaters;
window.ExitIntent = ExitIntent;
