// Shared components: nav, footer, brand mark, seal SVG, common bits

const { useState, useEffect, useRef } = React;

// Reveal-on-scroll
function Reveal({ children, delay = 0, ...rest }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setTimeout(() => setSeen(true), delay);
            io.disconnect();
          }
        });
      },
      { threshold: 0.1, rootMargin: "0px 0px -60px 0px" }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, [delay]);
  return (
    <div ref={ref} className={"reveal " + (seen ? "in" : "")} {...rest}>
      {children}
    </div>
  );
}

function BrandMark({ size = 44, className = "" }) {
  return (
    <span className={"brand-mark " + className} style={{ width: size, height: size }}>
      <span className="brand-mark-text" style={{ fontSize: size * 0.42 }}>
        NM
      </span>
    </span>
  );
}

function Brand({ onClick }) {
  return (
    <a className="brand" href="#" onClick={(e) => { e.preventDefault(); onClick && onClick(); }}>
      <BrandMark />
      <span className="brand-name">
        <strong>Nasser Malalla</strong>
        <span>Advocates &amp; Legal Consultants</span>
      </span>
    </a>
  );
}

function Seal() {
  return (
    <svg viewBox="0 0 220 220" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <defs>
        <path id="circ" d="M 110 110 m -88 0 a 88 88 0 1 1 176 0 a 88 88 0 1 1 -176 0" />
      </defs>
      <circle cx="110" cy="110" r="105" fill="none" stroke="currentColor" strokeWidth="1" opacity="0.6" />
      <circle cx="110" cy="110" r="74" fill="none" stroke="currentColor" strokeWidth="0.6" opacity="0.5" />
      <text fontFamily="JetBrains Mono, monospace" fontSize="11" letterSpacing="3" fill="currentColor">
        <textPath href="#circ" startOffset="0">
          NM LAW · ESTABLISHED 2000 · BUSINESS BAY · DUBAI ·
        </textPath>
      </text>
      <g fill="none" stroke="currentColor" strokeWidth="1.2">
        <path d="M85 95 L110 70 L135 95" />
        <line x1="80" y1="100" x2="140" y2="100" />
        <line x1="86" y1="140" x2="134" y2="140" />
        <line x1="92" y1="100" x2="92" y2="138" />
        <line x1="128" y1="100" x2="128" y2="138" />
        <line x1="110" y1="100" x2="110" y2="138" />
      </g>
    </svg>
  );
}

// TOPBAR
function TopBar({ t }) {
  return (
    <div className="topbar">
      <div className="container topbar-row">
        <div className="topbar-meta">
          <span className="dot"></span>
          <span className="desktop-only">{CONTACT.address.split(",").slice(0, 2).join(",")}</span>
        </div>
        <div className="topbar-meta">
          <span className="desktop-only">{t.topbar.hours}</span>
          <a href={CONTACT.phone_link}>{CONTACT.phone}</a>
          <a href={"mailto:" + CONTACT.emails[0]} className="desktop-only">
            {CONTACT.emails[0]}
          </a>
        </div>
      </div>
    </div>
  );
}

// HEADER
function Header({ route, navigate, lang, setLang, t }) {
  const [open, setOpen] = useState(false);
  const langs = [
    { id: "en", label: "EN" },
    { id: "ar", label: "AR" },
    { id: "ru", label: "RU" },
  ];
  const links = [
    { id: "home", label: t.nav.home },
    { id: "practice", label: t.nav.practice },
    { id: "firm", label: t.nav.firm },
    { id: "insights", label: t.nav.insights },
    { id: "contact", label: t.nav.contact },
  ];
  const onNav = (id) => {
    setOpen(false);
    navigate(id);
  };
  return (
    <React.Fragment>
      <TopBar t={t} />
      <header className="site">
        <div className="container nav-row">
          <Brand onClick={() => onNav("home")} />
          <nav className="main">
            {links.map((l) => (
              <a
                key={l.id}
                href="#"
                onClick={(e) => { e.preventDefault(); onNav(l.id); }}
                className={route.page === l.id ? "active" : ""}
              >
                {l.label}
              </a>
            ))}
          </nav>
          <div className="nav-cta">
            <div className="lang-switch force-ltr" role="tablist" aria-label="Language">
              {langs.map((l) => (
                <button
                  key={l.id}
                  onClick={() => setLang(l.id)}
                  className={lang === l.id ? "on" : ""}
                  aria-label={"Switch to " + l.label}
                >
                  {l.label}
                </button>
              ))}
            </div>
            <button className="btn btn-primary" onClick={() => navigate("contact")}>
              {t.cta.consult}
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M5 12h14M13 5l7 7-7 7" />
              </svg>
            </button>
            <button className="mobile-burger" onClick={() => setOpen(true)} aria-label="Open menu">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
                <line x1="3" y1="7" x2="21" y2="7" />
                <line x1="3" y1="12" x2="21" y2="12" />
                <line x1="3" y1="17" x2="21" y2="17" />
              </svg>
            </button>
          </div>
        </div>
      </header>
      <div className={"mobile-menu " + (open ? "open" : "")}>
        <div className="top">
          <Brand onClick={() => onNav("home")} />
          <button className="mobile-burger" onClick={() => setOpen(false)} aria-label="Close menu">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
              <line x1="5" y1="5" x2="19" y2="19" />
              <line x1="19" y1="5" x2="5" y2="19" />
            </svg>
          </button>
        </div>
        <nav>
          {links.map((l) => (
            <a key={l.id} href="#" onClick={(e) => { e.preventDefault(); onNav(l.id); }}>
              {l.label}
            </a>
          ))}
        </nav>
        <div style={{ marginTop: 32 }}>
          <button className="btn btn-primary" style={{ width: "100%", justifyContent: "center" }} onClick={() => onNav("contact")}>
            {t.cta.consult}
          </button>
        </div>
      </div>
    </React.Fragment>
  );
}

// FOOTER
function Footer({ t, navigate, setLang, lang }) {
  return (
    <footer className="site">
      <div className="container">
        <div className="footer-grid">
          <div>
            <a className="brand" href="#" onClick={(e) => { e.preventDefault(); navigate("home"); }}>
              <BrandMark className="f-brand-mark" />
              <span className="brand-name" style={{ color: "var(--paper)" }}>
                <strong style={{ color: "var(--paper)" }}>Nasser Malalla</strong>
                <span style={{ color: "var(--bronze)" }}>Advocates &amp; Legal Consultants</span>
              </span>
            </a>
            <p className="footer-claim">
              An established UAE law firm in Business Bay, Dubai. Litigation and advisory across the
              full breadth of UAE law — local and international clients welcome.
            </p>
          </div>

          <div>
            <h4>Practice</h4>
            <ul>
              {PRACTICE_AREAS.slice(0, 7).map((p) => (
                <li key={p.slug}>
                  <a
                    href="#"
                    onClick={(e) => { e.preventDefault(); navigate({ page: "practice-detail", slug: p.slug }); }}
                  >
                    {p.name}
                  </a>
                </li>
              ))}
            </ul>
          </div>

          <div>
            <h4>&nbsp;</h4>
            <ul>
              {PRACTICE_AREAS.slice(7).map((p) => (
                <li key={p.slug}>
                  <a
                    href="#"
                    onClick={(e) => { e.preventDefault(); navigate({ page: "practice-detail", slug: p.slug }); }}
                  >
                    {p.name}
                  </a>
                </li>
              ))}
              <li>
                <a href="#" onClick={(e) => { e.preventDefault(); navigate("insights"); }}>
                  Insights
                </a>
              </li>
              <li>
                <a href="#" onClick={(e) => { e.preventDefault(); navigate("firm"); }}>
                  The Firm
                </a>
              </li>
            </ul>
          </div>

          <div>
            <h4>Contact</h4>
            <ul>
              <li style={{ color: "color-mix(in oklab, var(--paper) 78%, transparent)" }}>
                {CONTACT.address}
              </li>
              <li>
                <a href={CONTACT.phone_link}>{CONTACT.phone}</a>
              </li>
              <li>
                <a href={CONTACT.mobile_link}>{CONTACT.mobile} (mobile)</a>
              </li>
              <li>
                <a href={"mailto:" + CONTACT.emails[0]}>{CONTACT.emails[0]}</a>
              </li>
              <li>
                <a href={"mailto:" + CONTACT.emails[1]}>{CONTACT.emails[1]}</a>
              </li>
            </ul>
          </div>
        </div>

        <div className="footer-base">
          <div>
            © 2026 Nasser Malalla Advocates &amp; Legal Consultants
            <span className="sep">·</span>
            Licensed by the Government of Dubai
          </div>
          <div className="force-ltr" style={{ display: "flex", gap: 16 }}>
            <a href="#" onClick={(e) => e.preventDefault()}>Privacy</a>
            <a href="#" onClick={(e) => e.preventDefault()}>Terms</a>
            <a href="#" onClick={(e) => e.preventDefault()}>Legal notice</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// CONSULTATION FORM — used both on Contact page and inline
function ConsultationForm({ defaultArea = "", t, compact = false }) {
  const [data, setData] = useState({
    name: "",
    email: "",
    phone: "",
    area: defaultArea,
    message: "",
  });
  const [errors, setErrors] = useState({});
  const [sent, setSent] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const update = (k) => (e) => {
    setData({ ...data, [k]: e.target.value });
    if (errors[k]) setErrors({ ...errors, [k]: null });
  };

  const validate = () => {
    const e = {};
    if (!data.name.trim()) e.name = "Required";
    if (!data.email.trim()) e.email = "Required";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) e.email = "Invalid email";
    if (!data.message.trim()) e.message = "Tell us briefly what the matter concerns";
    return e;
  };

  const submit = (e) => {
    e.preventDefault();
    const v = validate();
    setErrors(v);
    if (Object.keys(v).length) return;
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      setSent(true);
    }, 900);
  };

  if (sent) {
    return (
      <div className="success">
        <div className="check">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
            <path d="M5 13l4 4L19 7" />
          </svg>
        </div>
        <h3>Your request is <em>received.</em></h3>
        <p>A member of the firm will reply to <strong>{data.email}</strong> within two working days. For urgent matters, please call {CONTACT.phone}.</p>
        <button
          className="btn btn-ghost"
          style={{ marginTop: 24 }}
          onClick={() => { setSent(false); setData({ name: "", email: "", phone: "", area: defaultArea, message: "" }); }}
        >
          Submit another request
        </button>
      </div>
    );
  }

  return (
    <form className="form-block" onSubmit={submit} noValidate>
      <div className="form-row">
        <div className="field">
          <label htmlFor="cf-name">Full name</label>
          <input
            id="cf-name"
            type="text"
            value={data.name}
            onChange={update("name")}
            className={errors.name ? "err" : ""}
            placeholder="As it appears on your identification"
          />
          {errors.name && <div className="err-msg">{errors.name}</div>}
        </div>
        <div className="field">
          <label htmlFor="cf-email">Email</label>
          <input
            id="cf-email"
            type="email"
            value={data.email}
            onChange={update("email")}
            className={errors.email ? "err" : ""}
            placeholder="you@company.com"
          />
          {errors.email && <div className="err-msg">{errors.email}</div>}
        </div>
      </div>
      <div className="form-row">
        <div className="field">
          <label htmlFor="cf-phone">Phone (optional)</label>
          <input
            id="cf-phone"
            type="tel"
            value={data.phone}
            onChange={update("phone")}
            placeholder="+971 …"
          />
        </div>
        <div className="field">
          <label htmlFor="cf-area">Practice area</label>
          <select id="cf-area" value={data.area} onChange={update("area")}>
            <option value="">Select an area</option>
            {PRACTICE_AREAS.map((p) => (
              <option key={p.slug} value={p.slug}>{p.name}</option>
            ))}
            <option value="other">Other / not sure</option>
          </select>
        </div>
      </div>
      <div className="field">
        <label htmlFor="cf-msg">Briefly describe the matter</label>
        <textarea
          id="cf-msg"
          value={data.message}
          onChange={update("message")}
          className={errors.message ? "err" : ""}
          rows={compact ? 3 : 4}
          placeholder="A short summary is fine — counterparty, key dates, what you are looking to achieve."
        ></textarea>
        {errors.message && <div className="err-msg">{errors.message}</div>}
      </div>
      <div className="form-submit">
        <button type="submit" className="btn btn-primary" disabled={submitting}>
          {submitting ? "Sending…" : t.cta.consult}
          {!submitting && (
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M5 12h14M13 5l7 7-7 7" />
            </svg>
          )}
        </button>
        <div className="note">Confidential · Reply within 2 working days</div>
      </div>
    </form>
  );
}

Object.assign(window, { Reveal, Brand, BrandMark, Seal, Header, Footer, ConsultationForm });
