// ALT-TAG SOLUTIONS — UAE page (Dubai-focused)

const { useState: useStateUae, useEffect: useEffectUae, useRef: useRefUae } = React;

// reuse from site.jsx via window globals if needed; otherwise define minimal local versions
// Sign up at formspree.io → create a form → paste the form ID here
const UAE_FORMSPREE_ID = "mqewrpqd";

const UAE_ACCENTS = {
  cyan:   { hex: "#00E5FF", rgb: "0,229,255",  name: "Electric Cyan" },
  violet: { hex: "#7B61FF", rgb: "123,97,255", name: "Electric Violet" },
  lime:   { hex: "#C6FF3D", rgb: "198,255,61", name: "Acid Lime" },
};

function UaeReveal({ children, delay = 0, className = "", as: Tag = "div" }) {
  const ref = useRefUae(null);
  const [shown, setShown] = useStateUae(false);
  useEffectUae(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => { if (e.isIntersecting) setShown(true); }),
      { threshold: 0.15 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <Tag
      ref={ref}
      className={`reveal ${shown ? "reveal-in" : ""} ${className}`}
      style={{ transitionDelay: `${delay}ms` }}
    >
      {children}
    </Tag>
  );
}

function UaeSectionLabel({ num, children }) {
  return (
    <div className="section-label">
      <span className="section-label-num">{num}</span>
      <span className="section-label-line" />
      <span className="section-label-text">{children}</span>
    </div>
  );
}

// ---------- HERO (UAE) ----------

function UaeHero({ accentRgb, showArabic, theme, onToggleTheme }) {
  const canvasRef = useRefUae(null);

  // Subtle grid + scanning sweep — different from US hero
  useEffectUae(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    let raf;
    let dpr = Math.min(window.devicePixelRatio || 1, 2);
    let w = 0, h = 0;
    let t = 0;

    function resize() {
      const r = canvas.getBoundingClientRect();
      w = r.width; h = r.height;
      canvas.width = w * dpr; canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    }
    resize();
    window.addEventListener("resize", resize);

    function frame() {
      ctx.clearRect(0, 0, w, h);
      const grid = 60;
      ctx.strokeStyle = `rgba(${accentRgb}, 0.05)`;
      ctx.lineWidth = 1;
      for (let x = 0; x < w; x += grid) {
        ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke();
      }
      for (let y = 0; y < h; y += grid) {
        ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(w, y); ctx.stroke();
      }
      // sweeping arc
      const cx = w * 0.7, cy = h * 0.5;
      const radius = Math.min(w, h) * 0.4;
      ctx.strokeStyle = `rgba(${accentRgb}, 0.18)`;
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.arc(cx, cy, radius, t, t + 0.6);
      ctx.stroke();
      ctx.strokeStyle = `rgba(${accentRgb}, 0.08)`;
      ctx.beginPath();
      ctx.arc(cx, cy, radius * 0.7, t * 1.3, t * 1.3 + 0.4);
      ctx.stroke();
      ctx.beginPath();
      ctx.arc(cx, cy, radius * 1.2, -t * 0.8, -t * 0.8 + 0.3);
      ctx.stroke();
      t += 0.005;
      raf = requestAnimationFrame(frame);
    }
    frame();
    return () => { cancelAnimationFrame(raf); window.removeEventListener("resize", resize); };
  }, [accentRgb]);

  return (
    <section className="uae-hero hero" data-screen-label="UAE Hero">
      <canvas ref={canvasRef} className="hero-canvas" aria-hidden="true" />

      <nav className="topnav">
        <a href="ALTTAGSOLUTIONS.html" className="logo" aria-label="ALT-TAG Solutions">
          <img src="assets/logo.png" alt="ALT-TAG Solutions" className="logo-img" />
        </a>
        <ul className="topnav-links">
          <li><a href="ALTTAGSOLUTIONS.html#services">Services</a></li>
          <li><a href="ALTTAGSOLUTIONS.html#work">Work</a></li>
          <li><a href="ALTTAGSOLUTIONS.html">USA</a></li>
          <li><a href="UAE.html" className="active">UAE</a></li>
          <li><a href="#uae-contact">Contact</a></li>
        </ul>
        <div className="topnav-right">
          <ThemeToggle theme={theme} onToggle={onToggleTheme} />
          <a href="#uae-contact" className="topnav-cta">
            <span>Start a Project</span>
            <span className="arrow">→</span>
          </a>
        </div>
      </nav>

      <div className="hero-inner uae-hero-inner">
        <div className="hero-eyebrow uae-eyebrow">
          <span className="eyebrow-dot" />
          <span>Dubai &nbsp;·&nbsp; DIFC</span>
          <span className="eyebrow-divider">/</span>
          <span>Operating across the GCC</span>
        </div>

        <div className="uae-hero-coords" aria-hidden="true">
          <div>25.2048° N</div>
          <div>55.2708° E</div>
        </div>

        <h1 className="hero-headline uae-headline">
          Built in <span className="hero-headline-accent">Dubai.</span><br />
          Engineered for the <br />
          <span className="uae-region">GCC, MENA &amp; beyond.</span>
        </h1>

        {showArabic && (
          <div className="uae-arabic" dir="rtl" lang="ar">
            مقرّنا دبي · نبني منتجات رقمية عالميّة
          </div>
        )}

        <p className="hero-sub">
          <span className="hero-sub-tag">Web &amp; eCommerce</span>
          <span className="hero-sub-sep">·</span>
          <span className="hero-sub-tag">Mobile Apps</span>
          <span className="hero-sub-sep">·</span>
          <span className="hero-sub-tag">Web3</span>
          <span className="hero-sub-sep">·</span>
          <span className="hero-sub-tag">SEO &amp; Performance Marketing</span>
        </p>

        <div className="hero-actions">
          <a href="#uae-contact" className="btn btn-primary">
            <span>Book a Dubai consultation</span>
            <span className="btn-arrow">→</span>
          </a>
          <a href="ALTTAGSOLUTIONS.html" className="btn btn-ghost">
            <span>Visit USA site</span>
          </a>
        </div>

        <div className="hero-meta uae-meta">
          <div className="hero-meta-item">
            <span className="hero-meta-label">HQ</span>
            <span className="hero-meta-value">DIFC, Dubai</span>
          </div>
          <div className="hero-meta-item">
            <span className="hero-meta-label">Time zone</span>
            <span className="hero-meta-value">GST · GMT+4</span>
          </div>
          <div className="hero-meta-item">
            <span className="hero-meta-label">Working week</span>
            <span className="hero-meta-value">Mon &mdash; Fri</span>
          </div>
          <div className="hero-meta-item">
            <span className="hero-meta-label">Languages</span>
            <span className="hero-meta-value">EN · AR</span>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- WHY DUBAI ----------

function WhyDubai() {
  const cards = [
    {
      n: "01",
      title: "Local presence, global delivery.",
      body: "Our Dubai team handles strategy, account management, and on-the-ground execution across the GCC. Engineering capacity flexes between our DIFC and US offices — 24-hour velocity, single point of contact.",
    },
    {
      n: "02",
      title: "Compliant by default.",
      body: "VAT-registered. NDA-friendly. Familiar with TDRA, DIFC, ADGM and SCA regulatory contexts. We ship products that pass legal review the first time.",
    },
    {
      n: "03",
      title: "Bilingual, RTL-first.",
      body: "Arabic and English from day one. RTL layouts, locale-aware typography, and culturally fluent copywriting — not bolted on after launch.",
    },
  ];

  return (
    <section className="uae-why" data-screen-label="Why Dubai">
      <UaeSectionLabel num="01">Why Dubai</UaeSectionLabel>
      <div className="uae-why-head">
        <h2 className="section-headline">
          A studio built for the<br />
          <span className="muted">region's pace.</span>
        </h2>
        <p className="section-lede">
          Government-grade rigor. Hospitality-grade craft. Startup-grade speed. We sit at the intersection.
        </p>
      </div>
      <div className="uae-why-grid">
        {cards.map((c, i) => (
          <UaeReveal key={c.n} delay={i * 80} className="uae-why-card">
            <div className="uae-why-num">/{c.n}</div>
            <h3 className="uae-why-title">{c.title}</h3>
            <p className="uae-why-body">{c.body}</p>
          </UaeReveal>
        ))}
      </div>
    </section>
  );
}

// ---------- SECTORS ----------

const SECTORS = [
  { name: "Real Estate & Property", brief: "Listing platforms, off-plan launches, lead routing" },
  { name: "Hospitality & F&B", brief: "Booking flows, loyalty, multi-property CMS" },
  { name: "Retail & Luxury", brief: "Shopify Plus, headless storefronts, AR try-on" },
  { name: "Finance & Fintech", brief: "Onboarding, KYC flows, dashboards" },
  { name: "Government & Enterprise", brief: "Portals, intranets, accessibility-first" },
  { name: "Web3 & Digital Assets", brief: "Wallets, marketplaces, on-chain infra" },
];

function Sectors() {
  return (
    <section className="uae-sectors" data-screen-label="Sectors">
      <UaeSectionLabel num="02">Sectors we serve</UaeSectionLabel>
      <div className="uae-sectors-list">
        {SECTORS.map((s, i) => (
          <UaeReveal key={s.name} delay={i * 40} className="sector-row">
            <div className="sector-num">{String(i + 1).padStart(2, "0")}</div>
            <div className="sector-name">{s.name}</div>
            <div className="sector-brief">{s.brief}</div>
            <div className="sector-arrow">→</div>
          </UaeReveal>
        ))}
      </div>
    </section>
  );
}

// ---------- ENGAGEMENT MODELS ----------

const MODELS = [
  {
    label: "Project",
    headline: "Fixed scope. Fixed price.",
    body: "For brands with a defined brief. We scope, build, and ship within an agreed window — typically 8 to 16 weeks.",
    points: ["Discovery sprint", "Milestone-based delivery", "30-day post-launch warranty"],
    range: "Starting AED 75,000",
  },
  {
    label: "Retainer",
    headline: "Embedded squad.",
    body: "A dedicated cross-functional team — designers, engineers, marketers — operating as an extension of your in-house function.",
    points: ["Monthly cadence", "Sprint-based delivery", "Shared roadmap"],
    range: "From AED 45,000 / month",
    featured: true,
  },
  {
    label: "Growth",
    headline: "Performance-led.",
    body: "Ongoing SEO, paid media, and CRO with monthly reporting tied to revenue, not vanity metrics.",
    points: ["Quarterly strategy", "Weekly optimization", "Live dashboards"],
    range: "From AED 25,000 / month",
  },
];

function Engagement() {
  return (
    <section className="uae-engagement" data-screen-label="Engagement">
      <UaeSectionLabel num="03">How we engage</UaeSectionLabel>
      <div className="uae-engagement-head">
        <h2 className="section-headline">
          Three models.<br />
          <span className="muted">All fully accountable.</span>
        </h2>
      </div>
      <div className="uae-engagement-grid">
        {MODELS.map((m, i) => (
          <UaeReveal key={m.label} delay={i * 80} className={`engagement-card ${m.featured ? "engagement-card-featured" : ""}`}>
            <div className="engagement-top">
              <span className="engagement-label">{m.label}</span>
              {m.featured && <span className="engagement-badge">Most popular</span>}
            </div>
            <h3 className="engagement-headline">{m.headline}</h3>
            <p className="engagement-body">{m.body}</p>
            <ul className="engagement-points">
              {m.points.map((p) => (
                <li key={p}><span className="bullet-dash">—</span><span>{p}</span></li>
              ))}
            </ul>
            <div className="engagement-foot">
              <span className="engagement-range">{m.range}</span>
              <span className="arrow">→</span>
            </div>
          </UaeReveal>
        ))}
      </div>
    </section>
  );
}

// ---------- PROCESS TIMELINE ----------

const PROCESS = [
  { week: "W 01–02", phase: "Discovery",    body: "Stakeholder interviews · technical audit · success metrics" },
  { week: "W 03–04", phase: "Strategy",     body: "Architecture · roadmap · design principles · scope sign-off" },
  { week: "W 05–10", phase: "Build",        body: "Bi-weekly sprints · staging environment · weekly demos" },
  { week: "W 11–12", phase: "QA & Launch",  body: "Cross-browser · performance · accessibility · go-live" },
  { week: "W 13+",   phase: "Grow",         body: "SEO · paid media · CRO · monthly performance reviews" },
];

function Process() {
  return (
    <section className="uae-process" data-screen-label="Process">
      <UaeSectionLabel num="04">Engagement timeline</UaeSectionLabel>
      <div className="uae-process-head">
        <h2 className="section-headline">
          Twelve weeks,<br />
          <span className="muted">end to end.</span>
        </h2>
      </div>
      <div className="uae-process-timeline">
        <div className="timeline-rail" aria-hidden="true" />
        {PROCESS.map((p, i) => (
          <UaeReveal key={p.phase} delay={i * 60} className="timeline-step">
            <div className="timeline-marker">
              <span className="timeline-dot" />
            </div>
            <div className="timeline-content">
              <div className="timeline-week">{p.week}</div>
              <div className="timeline-phase">{p.phase}</div>
              <div className="timeline-body">{p.body}</div>
            </div>
          </UaeReveal>
        ))}
      </div>
    </section>
  );
}

// ---------- CONTACT (UAE) ----------

function UaeContactForm() {
  const [form, setForm] = useStateUae({ name: "", company: "", email: "", phone: "", scope: "Web", message: "" });
  const [status, setStatus] = useStateUae("idle");
  const [errors, setErrors] = useStateUae({});

  function validate() {
    const e = {};
    if (!form.name.trim()) e.name = "Required";
    if (!form.email.trim()) e.email = "Required";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = "Invalid";
    if (!form.message.trim()) e.message = "Required";
    return e;
  }

  async function onSubmit(ev) {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length) return;
    setStatus("sending");
    try {
      const res = await fetch(`https://formspree.io/f/${UAE_FORMSPREE_ID}`, {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify(form),
      });
      if (res.ok) {
        setStatus("sent");
        setTimeout(() => { setStatus("idle"); setForm({ name: "", company: "", email: "", phone: "", scope: "Web", message: "" }); }, 3500);
      } else {
        setStatus("error");
        setTimeout(() => setStatus("idle"), 3000);
      }
    } catch {
      setStatus("error");
      setTimeout(() => setStatus("idle"), 3000);
    }
  }

  function inputField(key, label, type = "text") {
    return (
      <div className={`field ${errors[key] ? "field-error" : ""} ${form[key] ? "field-filled" : ""}`}>
        <label htmlFor={`uae-${key}`}>{label}</label>
        <input
          id={`uae-${key}`}
          type={type}
          value={form[key]}
          onChange={(e) => setForm({ ...form, [key]: e.target.value })}
        />
        {errors[key] && <span className="field-err">{errors[key]}</span>}
      </div>
    );
  }

  return (
    <form className="contact-form uae-form" onSubmit={onSubmit}>
      <div className="form-row">
        {inputField("name", "Name")}
        {inputField("company", "Company")}
      </div>
      <div className="form-row">
        {inputField("email", "Email", "email")}
        {inputField("phone", "Phone (optional)", "tel")}
      </div>
      <div className="field field-filled">
        <label htmlFor="uae-scope">Scope</label>
        <select
          id="uae-scope"
          value={form.scope}
          onChange={(e) => setForm({ ...form, scope: e.target.value })}
          className="uae-select"
        >
          <option>Web &amp; eCommerce</option>
          <option>Custom Web Application</option>
          <option>Mobile App</option>
          <option>SEO &amp; Performance Marketing</option>
          <option>Web3</option>
          <option>Not sure yet</option>
        </select>
      </div>
      <div className={`field ${errors.message ? "field-error" : ""} ${form.message ? "field-filled" : ""}`}>
        <label htmlFor="uae-message">Project brief</label>
        <textarea
          id="uae-message"
          rows={4}
          value={form.message}
          onChange={(e) => setForm({ ...form, message: e.target.value })}
        />
        {errors.message && <span className="field-err">{errors.message}</span>}
      </div>
      <button
        type="submit"
        className={`btn btn-primary contact-submit ${status}`}
        disabled={status === "sending" || status === "sent"}
      >
        {status === "idle" && (<><span>Send brief</span><span className="btn-arrow">→</span></>)}
        {status === "sending" && (<><span>Sending</span><span className="btn-spin" /></>)}
        {status === "sent" && (<><span>Message received</span><span className="btn-check">✓</span></>)}
        {status === "error" && <span>Failed — please try again</span>}
      </button>
    </form>
  );
}

function UaeContact() {
  return (
    <section id="uae-contact" className="contact uae-contact" data-screen-label="Contact">
      <UaeSectionLabel num="05">Visit us in Dubai</UaeSectionLabel>
      <div className="contact-grid">
        <div className="contact-left">
          <h2 className="contact-headline">
            Let's meet<br />
            in <span className="accent-text">DIFC.</span>
          </h2>
          <p className="contact-lede">
            Coffee at our office, a video call, or anywhere in between. We respond within 4 working hours.
          </p>

          <div className="uae-office-card">
            <div className="office-flag">UAE Headquarters</div>
            <div className="uae-office-addr">
              <div>FDCW1471 Compass Building</div>
              <div>Al Shohada Road, AL Hamra Industrial Zone-FZ</div>
              <div>Ras Al Khaimah, UAE</div>
            </div>
            <div className="uae-office-contact">
              <a href="mailto:dubai@alttagsolutions.com">dubai@alttagsolutions.com</a>
              <a href="tel:+97145550182">+971 4 555 0182</a>
              <a href="https://wa.me/971501234567" className="uae-whatsapp">
                <span className="wa-dot" /> WhatsApp · +971 50 123 4567
              </a>
            </div>
            <div className="uae-office-hours">
              <div className="hours-row"><span>Mon — Thu</span><span>09:00 — 18:00 GST</span></div>
              <div className="hours-row"><span>Fri</span><span>09:00 — 13:00 GST</span></div>
              <div className="hours-row"><span>Sat — Sun</span><span className="muted">Closed</span></div>
            </div>
          </div>
        </div>
        <div className="contact-right">
          <UaeContactForm />
        </div>
      </div>
    </section>
  );
}

// ---------- FOOTER (reuse style) ----------

function UaeFooter() {
  return (
    <footer className="footer" data-screen-label="Footer">
      <div className="footer-inner">
        <div className="footer-logo">
          <img src="assets/logo.png" alt="ALT-TAG Solutions" className="footer-logo-img" />
        </div>
        <ul className="footer-nav">
          <li><a href="ALTTAGSOLUTIONS.html#services">Services</a></li>
          <li><a href="ALTTAGSOLUTIONS.html#work">Work</a></li>
          <li><a href="ALTTAGSOLUTIONS.html">USA</a></li>
          <li><a href="UAE.html">UAE</a></li>
          <li><a href="#uae-contact">Contact</a></li>
        </ul>
        <div className="footer-meta">
          <span>© 2026 ALT-TAG SOLUTIONS</span>
          <span className="footer-dot">·</span>
          <span>DIFC, Dubai</span>
        </div>
      </div>
      <div className="footer-bigtype" aria-hidden="true">DUBAI · DIFC</div>
    </footer>
  );
}

// ---------- APP ----------

function UaeBgTexture({ kind }) {
  if (kind === "dots") return <div className="bg-texture bg-dots" aria-hidden="true" />;
  if (kind === "grid") return <div className="bg-texture bg-grid" aria-hidden="true" />;
  if (kind === "noise") return <div className="bg-texture bg-noise" aria-hidden="true" />;
  return null;
}

function UaeApp() {
  const [theme, setTheme] = useTheme();
  const accent = UAE_ACCENTS.cyan;

  useSmoothScrollLinks();
  useActiveNav(['uae-contact']);

  useEffectUae(() => {
    const root = document.documentElement;
    root.style.setProperty("--accent", accent.hex);
    root.style.setProperty("--accent-rgb", accent.rgb);
  }, []);

  return (
    <div className="site texture-dots">
      <ScrollProgress />
      <UaeBgTexture kind="dots" />
      <UaeHero accentRgb={accent.rgb} showArabic={true} theme={theme} onToggleTheme={() => setTheme(theme === "dark" ? "light" : "dark")} />
      <WhyDubai />
      <Sectors />
      <Engagement />
      <Process />
      <UaeContact />
      <UaeFooter />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<UaeApp />);
