/* Galadari Advocates — interactive home prototype */
const { useState, useEffect, useMemo, useRef } = React;

const LOCALES = window.LOCALES;
const PRACTICES = window.PRACTICES;
const INDUSTRIES = window.INDUSTRIES;
const PEOPLE = window.PEOPLE;
const OFFICES = window.OFFICES;
const AWARDS = window.AWARDS;
const INSIGHTS = window.INSIGHTS;

// ---------- Topbar (lang switcher) ----------
function Topbar({ lang, setLang, t }) {
  return (
    <div className="topbar">
      <div className="wrap topbar-inner">
        <div>
          {lang === "ar"
            ? "خدمة العملاء العاجلة · +٩٧١ ٥٥ ٩٤٤ ٤٠٠٠ · clientservice@galadarilaw.com"
            : "Urgent client service · +971 55 944 4000 · clientservice@galadarilaw.com"}
        </div>
        <div className="topbar-langs">
          {["en", "ar", "ru", "zh"].map((l) => (
            <button
              key={l}
              className={lang === l ? "active" : ""}
              onClick={() => setLang(l)}
              aria-label={`Switch to ${l}`}
            >
              {l === "en" ? "EN" : l === "ar" ? "ع" : l === "ru" ? "RU" : "中"}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ---------- Nav ----------
function Nav({ t, lang, onConsult, activeSection }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const sections = ["practice", "industries", "people", "insights", "about", "contact"];

  return (
    <nav className={"nav" + (scrolled ? " scrolled" : "")}>
      <div className="wrap nav-inner">
        <a className="brand" href="#top">
          <div className="brand-mark">G</div>
          <div>
            <div className="brand-name">{lang === "ar" ? "كلداري" : "Galadari"}</div>
            <div className="brand-sub">{lang === "ar" ? "محامون ومستشارون قانونيون" : "Advocates & Legal Consultants"}</div>
          </div>
        </a>
        <div className="nav-links">
          {t.nav.map((label, i) => {
            const sec = sections[i];
            return (
              <button
                key={i}
                className={"nav-link" + (activeSection === sec ? " active" : "")}
                onClick={() => {
                  const el = document.getElementById(sec);
                  if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
                }}
              >
                {label}
              </button>
            );
          })}
          <button className="btn" onClick={onConsult}>
            {t.cta}
            <span className="btn-arrow">{lang === "ar" ? "←" : "→"}</span>
          </button>
        </div>
      </div>
    </nav>
  );
}

// ---------- Hero ----------
function Hero({ t, lang, onConsult }) {
  const metaItems = lang === "ar"
    ? ["دبي", "مركز دبي المالي", "أبوظبي"]
    : ["Dubai", "DIFC", "Abu Dhabi"];
  return (
    <section className="hero" id="top">
      <div className="wrap">
        <div className="hero-inner">
          <div className="hero-kicker">
            <span className="hero-kicker-line"></span>
            <span className="eyebrow">{lang === "ar" ? "شركة محاماة إماراتية" : "An Emirati law firm"}</span>
            <span className="hero-kicker-line"></span>
          </div>
          <div className="hero-est">{lang === "ar" ? "تأسست عام ١٩٨٣" : "Est. 1983"}</div>
          <h1>
            {t.proposition.map((line, i) => (
              <span className="ln" key={i}>
                {i === 1 ? <span className="em">{line}</span> : line}
              </span>
            ))}
          </h1>
          <div className="hero-rule"></div>
          <p className="hero-body">{t.heroBody}</p>
          <div className="cta-row">
            <button className="btn" onClick={onConsult}>
              {t.cta}
              <span className="btn-arrow">{lang === "ar" ? "←" : "→"}</span>
            </button>
            <a className="btn btn-ghost" href="#people"
              onClick={(e) => { e.preventDefault(); document.getElementById("people").scrollIntoView({ behavior: "smooth" }); }}
            >
              {lang === "ar" ? "تصفح المحامين" : "Meet our lawyers"}
            </a>
          </div>
          <div className="hero-meta">
            {metaItems.map((item, i) => (
              <React.Fragment key={item}>
                <span>{item}</span>
                {i < metaItems.length - 1 && <span className="dot">◆</span>}
              </React.Fragment>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Trust strip ----------
function TrustStrip({ lang }) {
  const items = lang === "ar"
    ? [
        { num: "١٩٨٣", em: false, lbl: "تأسست منذ" },
        { num: "٤٠+", em: true, lbl: "أربعة عقود" },
        { num: "٥٠+", em: false, lbl: "محامون" },
        { num: "١٨", em: false, lbl: "لغة" },
        { num: "٣", em: false, lbl: "مكاتب في الإمارات" },
        { num: "٢", em: true, lbl: "تصنيفات تشامبرز ٢٠٢٦" },
      ]
    : [
        { num: "1983", em: false, lbl: "Established" },
        { num: "40+", em: true, lbl: "Years of practice" },
        { num: "50+", em: false, lbl: "Lawyers" },
        { num: "18", em: false, lbl: "Languages" },
        { num: "3", em: false, lbl: "UAE offices" },
        { num: "11", em: true, lbl: "Legal 500 EMEA 2026 ranked areas" },
      ];
  return (
    <div className="trust">
      <div className="wrap trust-grid">
        {items.map((it, i) => (
          <div key={i}>
            <div className="trust-num">{it.em ? <em>{it.num}</em> : it.num}</div>
            <div className="trust-lbl">{it.lbl}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---------- Practice grid ----------
function PracticeSection({ t, lang, activePractice, setActivePractice }) {
  const rows = [];
  for (let i = 0; i < PRACTICES.length; i += 3) rows.push(PRACTICES.slice(i, i + 3));

  return (
    <section className="section section-anchor" id="practice">
      <div className="wrap">
        <div className="section-head">
          <div>
            <span className="eyebrow">{lang === "ar" ? "خمسة عشر مجالاً" : "Fifteen practices · 01–15"}</span>
            <h2>{t.sectionPractice}</h2>
          </div>
          <p className="section-head-kick">
            {lang === "ar"
              ? "ممارسة قائمة على التقاضي مع عمق إقليمي عبر النزاعات، الشركات، الخدمات المصرفية، العقارات، والامتثال."
              : "A litigation-led full-service practice. Anchored by Dispute Resolution — supported by deep regional bench strength across corporate, finance, real estate, and regulatory."}
          </p>
        </div>

        <div className="practice-grid">
          {rows.map((row, ri) => {
            const rowHasActive = row.some(p => p.slug === activePractice);
            return (
              <React.Fragment key={ri}>
                <div className="practice-grid-row">
                  {row.map((p) => {
                    const isActive = p.slug === activePractice;
                    return (
                      <button
                        key={p.slug}
                        className={"practice-card" + (p.anchor ? " anchor" : "") + (isActive ? " is-active" : "")}
                        onClick={() => setActivePractice(isActive ? null : p.slug)}
                      >
                        {p.anchor && <span className="pchip">{lang === "ar" ? "الممارسة المرساة" : "Anchor practice"}</span>}
                        <div className="pn">{p.n}</div>
                        <div className="pt">{lang === "ar" ? p.titleAr : p.title}</div>
                        <p className="pscope">{p.scope}</p>
                        <span className="pmore">
                          {isActive ? (lang === "ar" ? "إغلاق" : "Close") : (lang === "ar" ? "اقرأ المزيد" : "Read more")}
                          {!isActive && <span style={{ fontFamily: "Instrument Serif", fontSize: "14px" }}>{lang === "ar" ? "←" : "→"}</span>}
                        </span>
                      </button>
                    );
                  })}
                </div>
                {rowHasActive && (
                  <PracticeDrill
                    practice={PRACTICES.find(p => p.slug === activePractice)}
                    lang={lang}
                    onClose={() => setActivePractice(null)}
                    onEnquiry={() => {
                      window.dispatchEvent(new CustomEvent("open-consult", { detail: { practice: activePractice } }));
                    }}
                  />
                )}
              </React.Fragment>
            );
          })}
        </div>
      </div>
    </section>
  );
}

function PracticeDrill({ practice, lang, onClose, onEnquiry }) {
  const relatedPeople = PEOPLE.filter(p => p.practices.includes(practice.slug)).slice(0, 4);
  return (
    <div className="drill-wrap">
      <div className="drill">
        <button className="drill-close" onClick={onClose} aria-label="Close">×</button>
        <div>
          <div className="eyebrow">{practice.n} · {lang === "ar" ? "النطاق" : "Scope"}</div>
          <h3>{lang === "ar" ? practice.titleAr : practice.title}</h3>
          <p>{practice.scope}</p>
          {practice.ranking && (
            <div className="drill-rank">{practice.ranking}</div>
          )}
          <div style={{ marginTop: 22 }}>
            <button className="btn" onClick={onEnquiry}>
              {lang === "ar" ? `استشارة في ${practice.titleAr}` : `Enquire about ${practice.title}`}
              <span className="btn-arrow">{lang === "ar" ? "←" : "→"}</span>
            </button>
          </div>
        </div>
        <div>
          <div className="eyebrow">{lang === "ar" ? "أمثلة على القضايا" : "Typical matters"}</div>
          <ul className="drill-list">
            {practice.matters.map((m, i) => (
              <li key={i}>
                <span className="mn">{String(i + 1).padStart(2, "0")}</span>
                <span>{m}</span>
              </li>
            ))}
          </ul>
          {relatedPeople.length > 0 && (
            <div style={{ marginTop: 22 }}>
              <div className="eyebrow">{lang === "ar" ? "محامو هذا المجال" : "Lawyers in this practice"}</div>
              <div style={{ display: "flex", gap: 12, marginTop: 12, flexWrap: "wrap" }}>
                {relatedPeople.map(person => (
                  <div key={person.slug} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <div style={{ width: 36, height: 36, borderRadius: "50%", overflow: "hidden", border: "1px solid var(--line)" }}>
                      <img src={person.photo} alt={person.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                    </div>
                    <span style={{ fontSize: 13 }}>{lang === "ar" && person.nameAr ? person.nameAr : person.name}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ---------- Industries ----------
function IndustriesSection({ t, lang }) {
  const sectorsAr = {
    "Consumer & Retail": "التجزئة والمستهلك",
    "Education": "التعليم",
    "Energy": "الطاقة",
    "Healthcare": "الرعاية الصحية",
    "Insurance": "التأمين",
    "Leisure & Hospitality": "الترفيه والضيافة",
    "Manufacturing & Industrial": "التصنيع والصناعة",
    "Maritime & Transport": "البحرية والنقل",
    "Public Sector": "القطاع العام",
    "Technology, Media & Telecommunications": "التكنولوجيا والإعلام والاتصالات",
  };
  return (
    <section className="section section-tight section-anchor" id="industries" style={{ background: "var(--paper-warm)" }}>
      <div className="wrap">
        <div className="section-head">
          <div>
            <span className="eyebrow">{lang === "ar" ? "أحد عشر قطاعاً" : "Eleven sectors · 01–11"}</span>
            <h2>{lang === "ar" ? "القطاعات" : "Industries"}</h2>
          </div>
          <p className="section-head-kick">
            {lang === "ar"
              ? "قطاعات الاقتصاد الإماراتي التي نخدمها — البحرية والتأمين تقدمان كقدرات داخل ممارسة حل النزاعات."
              : "The UAE economy we serve. Maritime/Shipping and Insurance live here as sector capabilities (delivered through Dispute Resolution and related practices) — not separate practice pages."}
          </p>
        </div>
        <div className="industries">
          {INDUSTRIES.map((ind, i) => (
            <div className="industry-chip" key={ind}>
              <span className="imn">{String(i + 1).padStart(2, "0")}</span>
              <span>{lang === "ar" ? sectorsAr[ind] : ind}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- People ----------
function PeopleSection({ t, lang, setPersonModal }) {
  const [officeFilter, setOfficeFilter] = useState("all");
  const [practiceFilter, setPracticeFilter] = useState("all");

  const filtered = useMemo(() => {
    return PEOPLE.filter(p =>
      (officeFilter === "all" || p.office === officeFilter) &&
      (practiceFilter === "all" || p.practices.includes(practiceFilter))
    );
  }, [officeFilter, practiceFilter]);

  const offices = ["all", ...new Set(PEOPLE.map(p => p.office))];
  const topPractices = ["all", "dispute-resolution", "corporate", "banking-and-finance", "employment", "family-divorce"];

  return (
    <section className="section section-anchor" id="people">
      <div className="wrap">
        <div className="section-head">
          <div>
            <span className="eyebrow">{lang === "ar" ? "المحامون" : "Verified portraits · 15 / 50+"}</span>
            <h2>{t.sectionPeople}</h2>
          </div>
          <p className="section-head-kick">
            {lang === "ar"
              ? "محامون إماراتيون ودوليون. الأسماء والصور موثقة فقط — الباقي بانتظار تأكيد العميل."
              : "Emirati and international lawyers. Names and photographs shown are verified from research; titles and credentials remain marked \"to confirm\" until the client signs off."}
          </p>
        </div>

        <div className="people-filters">
          <div className="filter-group">
            <span className="filter-label">{lang === "ar" ? "المكتب" : "Office"}</span>
            {offices.map(o => (
              <button
                key={o}
                className={"filter" + (officeFilter === o ? " active" : "")}
                onClick={() => setOfficeFilter(o)}
              >
                {o === "all" ? (lang === "ar" ? "الكل" : "All") : o}
              </button>
            ))}
          </div>
          <div className="filter-group">
            <span className="filter-label">{lang === "ar" ? "المجال" : "Practice"}</span>
            {topPractices.map(slug => {
              const label = slug === "all"
                ? (lang === "ar" ? "الكل" : "All")
                : (PRACTICES.find(p => p.slug === slug) || {}).title;
              return (
                <button
                  key={slug}
                  className={"filter" + (practiceFilter === slug ? " active" : "")}
                  onClick={() => setPracticeFilter(slug)}
                >
                  {label}
                </button>
              );
            })}
          </div>
        </div>

        <div className="people-grid">
          {filtered.length === 0 ? (
            <div className="no-people">
              {lang === "ar" ? "لا يوجد محامون يطابقون هذه الفلاتر." : "No lawyers match these filters."}
            </div>
          ) : (
            filtered.map(person => (
              <button key={person.slug} className="person-card" onClick={() => setPersonModal(person)}>
                <div className="person-photo">
                  {person.featured && (
                    <span className="ribbon">{lang === "ar" ? "بارز" : "Featured"}</span>
                  )}
                  <img src={person.photo} alt={person.name} loading="lazy" />
                </div>
                <h3 className="person-name">{lang === "ar" && person.nameAr ? person.nameAr : person.name}</h3>
                <div className="person-title">{person.title}</div>
                <div className="person-meta">
                  <span>{person.office}</span>
                  <span className="dot">·</span>
                  <span>{person.languages.length} {lang === "ar" ? "لغات" : "langs"}</span>
                </div>
              </button>
            ))
          )}
        </div>
      </div>
    </section>
  );
}

// ---------- Awards ----------
function AwardsSection({ t, lang }) {
  return (
    <section className="section ink section-anchor" id="about">
      <div className="wrap">
        <div className="section-head">
          <div>
            <span className="eyebrow">{lang === "ar" ? "تصنيفات مستقلة" : "Independent rankings · attributed"}</span>
            <h2>{t.sectionAwards}</h2>
          </div>
          <p className="section-head-kick">
            {lang === "ar"
              ? "كل تصنيف موثق بالجهة والإصدار والسنة والفئة. لا توجد تقييمات نجوم ذاتية الإسناد."
              : "Every recognition cites body, edition, year and tier. No self-asserted star ratings."}
          </p>
        </div>
        <div className="awards-list">
          {AWARDS.map((a, i) => (
            <div className={"award" + (a.primary ? " primary" : "")} key={i}>
              <div>
                <div className="award-body">{a.body}</div>
                <div className="award-edition">{a.edition}</div>
              </div>
              <div className="award-note">{a.note}</div>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 32, fontSize: 12, color: "var(--brass-soft)", fontStyle: "italic", maxWidth: 760, lineHeight: 1.6 }}>
          {lang === "ar"
            ? "ملاحظة: الموقع الحالي يعرض تقييماً ذاتي الإسناد ٤٫٢ / ٣ في بيانات منظمة — هذا الإصدار يُحذف بالكامل وفقاً للمعايير القانونية."
            : "Note: The live site self-asserts an AggregateRating of 4.2/3 with anonymous testimonials in its JSON-LD. This redesign removes both — no star rating until a real, attributable one exists."}
        </div>
      </div>
    </section>
  );
}

// ---------- Insights ----------
function InsightsSection({ t, lang }) {
  return (
    <section className="section section-tight section-anchor" id="insights" style={{ background: "var(--paper-warm)" }}>
      <div className="wrap">
        <div className="section-head">
          <div>
            <span className="eyebrow">{lang === "ar" ? "المنشورات والأخبار والفعاليات" : "Publications · News · Events · Podcasts"}</span>
            <h2>{t.sectionInsights}</h2>
          </div>
          <p className="section-head-kick">
            {lang === "ar"
              ? "محتوى يصدر بانتظام من محامي الشركة — يعكس الممارسة الفعلية، لا التسويق."
              : "Regular thought leadership from our lawyers — practice-rooted, attribution-clean, no marketing fluff."}
          </p>
        </div>
        <div className="insights-list">
          {INSIGHTS.map((it, i) => (
            <div className="insight" key={i}>
              <div className="insight-kind">{it.kind}</div>
              <div className="insight-date">{it.date}</div>
              <div className="insight-title">{it.title}</div>
              <div className="insight-area">{(PRACTICES.find(p => p.slug === it.practice) || {}).title}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Offices ----------
function OfficesSection({ t, lang, onConsult }) {
  return (
    <section className="section section-anchor" id="contact">
      <div className="wrap">
        <div className="section-head">
          <div>
            <span className="eyebrow">{lang === "ar" ? "ثلاثة مكاتب" : "Three offices · never merged"}</span>
            <h2>{t.sectionOffices}</h2>
          </div>
          <p className="section-head-kick">
            {lang === "ar"
              ? "المقر الرئيسي في بر دبي، ومكاتب في مركز دبي المالي العالمي وأبوظبي. عناوين الشوارع الكاملة لمكتبي DIFC وأبوظبي قيد التأكيد."
              : "Headquartered in Bur Dubai, with practice offices in DIFC and Abu Dhabi. Full street addresses for DIFC and Abu Dhabi are pending client sign-off — flagged inline rather than guessed."}
          </p>
        </div>
        <div className="offices-grid">
          {OFFICES.map(o => (
            <div key={o.id} className={"office" + (o.primary ? " primary" : "")}>
              {o.primary && <span className="office-flag">{lang === "ar" ? "المقر" : "HQ"}</span>}
              <h3 className="office-label">{lang === "ar" ? o.labelAr : o.label}</h3>
              <div className="office-area">{o.area}</div>
              <p className="office-addr">{o.address}</p>
              <div className="office-row">
                <span className="office-row-lbl">{lang === "ar" ? "هاتف" : "Phone"}</span>
                <a href={o.phoneHref}>{o.phone}</a>
              </div>
              <div className="office-row">
                <span className="office-row-lbl">{lang === "ar" ? "بريد إلكتروني" : "Email"}</span>
                <a href={`mailto:${o.email}`}>{o.email}</a>
              </div>
              <div className="office-row">
                <span className="office-row-lbl">{lang === "ar" ? "صندوق بريد" : "PO Box"}</span>
                <span>{o.poBox}</span>
              </div>
              <div className="office-confirm">{o.addressNote}</div>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 56, textAlign: "center" }}>
          <button className="btn" onClick={onConsult} style={{ padding: "16px 32px", fontSize: 14 }}>
            {t.cta}
            <span className="btn-arrow">{lang === "ar" ? "←" : "→"}</span>
          </button>
          <div style={{ marginTop: 14, fontSize: 12, color: "var(--muted)", fontStyle: "italic" }}>
            {lang === "ar"
              ? "ساعات العمل: الإثنين – الجمعة، ٠٩:٠٠ – ١٨:٠٠ (بتوقيت الخليج). نؤكد الجمعة مع العميل."
              : "Hours: Mon–Fri 09:00–18:00 (GST). UAE working-week confirmation pending."}
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Consultation modal ----------
function ConsultModal({ open, onClose, t, lang, presetPractice }) {
  const [form, setForm] = useState({
    name: "", email: "", phone: "", practice: "", office: "Dubai HQ", message: "",
  });
  const [errs, setErrs] = useState({});
  const [sent, setSent] = useState(false);

  useEffect(() => {
    if (presetPractice) {
      setForm(f => ({ ...f, practice: presetPractice }));
    }
  }, [presetPractice]);

  useEffect(() => {
    if (open) { setSent(false); setErrs({}); }
  }, [open]);

  if (!open) return null;

  const submit = (e) => {
    e.preventDefault();
    const next = {};
    if (!form.name.trim()) next.name = lang === "ar" ? "الاسم مطلوب" : "Name is required";
    if (!form.email.trim()) next.email = lang === "ar" ? "البريد الإلكتروني مطلوب" : "Email is required";
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) next.email = lang === "ar" ? "صيغة البريد الإلكتروني غير صحيحة" : "Enter a valid email";
    if (!form.practice) next.practice = lang === "ar" ? "اختر مجال الممارسة" : "Choose a practice area";
    if (!form.message.trim()) next.message = lang === "ar" ? "وصف الاستفسار مطلوب" : "Please describe your matter";
    setErrs(next);
    if (Object.keys(next).length === 0) {
      setSent(true);
    }
  };

  const labels = lang === "ar"
    ? { name: "الاسم", email: "البريد", phone: "الهاتف", practice: "مجال الممارسة", office: "المكتب المفضل", message: "نبذة عن القضية", submit: "إرسال الاستفسار", choose: "اختر…", note: "هذا الاستفسار سري. لا توجد علاقة محامٍ/موكل حتى التحقق من تضارب المصالح." }
    : { name: "Full name", email: "Email", phone: "Phone (optional)", practice: "Practice area", office: "Preferred office", message: "Brief description of your matter", submit: "Send enquiry", choose: "Choose…", note: "This enquiry is confidential. No attorney–client relationship is created until our conflict-check is cleared and you receive a written engagement." };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <span className="eyebrow">{lang === "ar" ? "خطوة واحدة" : "One step · low pressure"}</span>
            <h3>{t.sectionConsult}</h3>
          </div>
          <button className="x" onClick={onClose} aria-label="Close">×</button>
        </div>
        <div className="modal-body">
          {sent ? (
            <div className="success">
              <div className="success-mark">✓</div>
              <h4>{lang === "ar" ? "تم استلام طلبك" : "Enquiry received"}</h4>
              <p style={{ color: "var(--ink-soft)", fontSize: 14, maxWidth: 380, margin: "0 auto" }}>
                {lang === "ar"
                  ? "سيتواصل معك أحد محامينا خلال يوم عمل واحد. للحالات العاجلة: ‎+٩٧١ ٥٥ ٩٤٤ ٤٠٠٠"
                  : "A lawyer in the relevant practice will reply within one UAE business day. For urgent matters call +971 55 944 4000."}
              </p>
              <div style={{ marginTop: 28 }}>
                <button className="btn btn-ghost" onClick={onClose}>{lang === "ar" ? "إغلاق" : "Close"}</button>
              </div>
            </div>
          ) : (
            <form onSubmit={submit} noValidate>
              <div className="field-row">
                <div className="field">
                  <label>{labels.name}</label>
                  <input
                    className={errs.name ? "err" : ""}
                    value={form.name}
                    onChange={e => setForm({ ...form, name: e.target.value })}
                  />
                  {errs.name && <div className="field-err">{errs.name}</div>}
                </div>
                <div className="field">
                  <label>{labels.email}</label>
                  <input
                    type="email"
                    className={errs.email ? "err" : ""}
                    value={form.email}
                    onChange={e => setForm({ ...form, email: e.target.value })}
                  />
                  {errs.email && <div className="field-err">{errs.email}</div>}
                </div>
              </div>
              <div className="field-row">
                <div className="field">
                  <label>{labels.phone}</label>
                  <input type="tel" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} />
                </div>
                <div className="field">
                  <label>{labels.office}</label>
                  <select value={form.office} onChange={e => setForm({ ...form, office: e.target.value })}>
                    {OFFICES.map(o => <option key={o.id} value={o.label}>{o.label}</option>)}
                  </select>
                </div>
              </div>
              <div className="field">
                <label>{labels.practice}</label>
                <select
                  className={errs.practice ? "err" : ""}
                  value={form.practice}
                  onChange={e => setForm({ ...form, practice: e.target.value })}
                >
                  <option value="">{labels.choose}</option>
                  {PRACTICES.map(p => <option key={p.slug} value={p.slug}>{p.title}</option>)}
                </select>
                {errs.practice && <div className="field-err">{errs.practice}</div>}
              </div>
              <div className="field">
                <label>{labels.message}</label>
                <textarea
                  className={errs.message ? "err" : ""}
                  value={form.message}
                  onChange={e => setForm({ ...form, message: e.target.value })}
                />
                {errs.message && <div className="field-err">{errs.message}</div>}
              </div>
              <div className="modal-foot">
                <div className="note">{labels.note}</div>
                <button className="btn" type="submit">
                  {labels.submit}
                  <span className="btn-arrow">{lang === "ar" ? "←" : "→"}</span>
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

// ---------- Person modal ----------
function PersonModal({ person, lang, onClose, onEnquiry }) {
  if (!person) return null;
  const practices = person.practices.map(s => (PRACTICES.find(p => p.slug === s) || {}).title).filter(Boolean);
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{ maxWidth: 860 }} onClick={e => e.stopPropagation()}>
        <div className="modal-head" style={{ padding: "20px 24px" }}>
          <div style={{ flex: 1 }}>
            <span className="eyebrow">{lang === "ar" ? "بطاقة المحامي" : "Lawyer profile"}</span>
          </div>
          <button className="x" onClick={onClose} aria-label="Close">×</button>
        </div>
        <div className="pmodal-grid">
          <div className="pmodal-photo">
            <img src={person.photo} alt={person.name} />
          </div>
          <div className="pmodal-body">
            <h3>{person.name}</h3>
            {person.nameAr && <div className="ar">{person.nameAr}</div>}
            <div className="ptitle">{person.title} · {person.office}</div>

            <div className="pmodal-section">
              <h4>{lang === "ar" ? "المؤهلات" : "Qualifications"}</h4>
              <p>{person.qualifications}</p>
            </div>

            <div className="pmodal-section">
              <h4>{lang === "ar" ? "اللغات" : "Languages"}</h4>
              <p>{person.languages.join(" · ")}</p>
            </div>

            <div className="pmodal-section">
              <h4>{lang === "ar" ? "مجالات الممارسة" : "Practice areas"}</h4>
              <p>{practices.join(" · ")}</p>
            </div>

            {person.recognitions && (
              <div className="pmodal-section">
                <h4>{lang === "ar" ? "تصنيفات وتقدير" : "Recognition (attributed)"}</h4>
                <ul>
                  {person.recognitions.map((r, i) => <li key={i}>{r}</li>)}
                </ul>
              </div>
            )}

            <div className="pmodal-section" style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
              <button className="btn" onClick={() => onEnquiry(person)}>
                {lang === "ar" ? `استشارة مع ${person.name}` : `Enquire with ${person.name.split(" ")[0]}`}
                <span className="btn-arrow">{lang === "ar" ? "←" : "→"}</span>
              </button>
              <button className="btn btn-ghost" onClick={onClose}>{lang === "ar" ? "العودة" : "Back to directory"}</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- Footer ----------
function Footer({ lang }) {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-cols">
          <div>
            <div className="footer-brand-block">
              {lang === "ar"
                ? "حلول عملية. نتائج قابلة للقياس. مشورة موثوقة."
                : <>Practical solutions.<br/>Measurable results.<br/>Trusted advice.</>}
            </div>
            <p style={{ fontSize: 13, color: "rgba(246,241,231,0.7)", lineHeight: 1.6, maxWidth: 360 }}>
              {lang === "ar"
                ? "شركة محاماة إماراتية تأسست عام ١٩٨٣. جزء من مجموعة زياد كلداري — مستقلة عن مجموعة كلداري للإخوان."
                : "An Emirati law firm established 1983. Part of the Ziad Galadari Group — separate and distinct from Galadari Brothers Co. LLC, the UAE conglomerate."}
            </p>
          </div>
          <div>
            <h5>{lang === "ar" ? "الممارسات" : "Practices"}</h5>
            <ul>
              {PRACTICES.slice(0, 6).map(p => <li key={p.slug}><a href={`#practice`}>{p.title}</a></li>)}
              <li><a href="#practice">{lang === "ar" ? "كل المجالات الخمسة عشر" : "All 15 practices →"}</a></li>
            </ul>
          </div>
          <div>
            <h5>{lang === "ar" ? "الشركة" : "The firm"}</h5>
            <ul>
              <li><a href="#people">{lang === "ar" ? "المحامون" : "People"}</a></li>
              <li><a href="#about">{lang === "ar" ? "التصنيفات" : "Recognition"}</a></li>
              <li><a href="#insights">{lang === "ar" ? "الرؤى" : "Insights"}</a></li>
              <li><a href="#contact">{lang === "ar" ? "اتصل بنا" : "Offices"}</a></li>
              <li><a href="#">{lang === "ar" ? "الوظائف القانونية" : "Legal careers"}</a></li>
            </ul>
          </div>
          <div>
            <h5>{lang === "ar" ? "اتصل" : "Connect"}</h5>
            <ul>
              <li><a href="tel:+97143778100">+971 4 377 8100</a></li>
              <li><a href="mailto:info@galadarilaw.com">info@galadarilaw.com</a></li>
              <li><a href="https://www.linkedin.com/company/galadari-&-associates/" target="_blank" rel="noopener">LinkedIn</a></li>
              <li><a href="https://www.instagram.com/galadarilaw/" target="_blank" rel="noopener">Instagram</a></li>
              <li><a href="https://x.com/GaladariLaw" target="_blank" rel="noopener">X</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-fine">
          <div>© 2026 Galadari Advocates & Legal Consultants · {lang === "ar" ? "جميع الحقوق محفوظة" : "All rights reserved"}</div>
          <div className="legal">
            {lang === "ar"
              ? "لا تشكل المعلومات الواردة في هذا الموقع مشورة قانونية. ينطبق التحقق من تضارب المصالح."
              : "Information on this site is general only and not legal advice. Conflict-check rules apply."}
          </div>
        </div>
      </div>
    </footer>
  );
}

// ---------- App root ----------
function App() {
  const [lang, setLang] = useState("en");
  const [activePractice, setActivePractice] = useState(null);
  const [consultOpen, setConsultOpen] = useState(false);
  const [presetPractice, setPresetPractice] = useState("");
  const [personModal, setPersonModal] = useState(null);
  const [activeSection, setActiveSection] = useState(null);

  const t = LOCALES[lang] || LOCALES.en;

  useEffect(() => {
    document.body.setAttribute("dir", t.dir);
    document.documentElement.setAttribute("lang", lang);
  }, [lang, t.dir]);

  // Active-section spy
  useEffect(() => {
    const ids = ["practice", "industries", "people", "insights", "about", "contact"];
    const els = ids.map(id => document.getElementById(id)).filter(Boolean);
    const observer = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) setActiveSection(e.target.id);
      });
    }, { rootMargin: "-30% 0px -55% 0px" });
    els.forEach(el => observer.observe(el));
    return () => observer.disconnect();
  }, []);

  // Listen for "enquire about practice X"
  useEffect(() => {
    const handler = (e) => {
      setPresetPractice(e.detail?.practice || "");
      setConsultOpen(true);
    };
    window.addEventListener("open-consult", handler);
    return () => window.removeEventListener("open-consult", handler);
  }, []);

  const openConsult = () => { setPresetPractice(""); setConsultOpen(true); };

  return (
    <React.Fragment>
      <Topbar lang={lang} setLang={setLang} t={t} />
      <Nav t={t} lang={lang} onConsult={openConsult} activeSection={activeSection} />
      <Hero t={t} lang={lang} onConsult={openConsult} />
      <TrustStrip lang={lang} />
      <PracticeSection
        t={t} lang={lang}
        activePractice={activePractice}
        setActivePractice={setActivePractice}
      />
      <IndustriesSection t={t} lang={lang} />
      <PeopleSection t={t} lang={lang} setPersonModal={setPersonModal} />
      <AwardsSection t={t} lang={lang} />
      <InsightsSection t={t} lang={lang} />
      <OfficesSection t={t} lang={lang} onConsult={openConsult} />
      <Footer lang={lang} />

      <ConsultModal
        open={consultOpen}
        onClose={() => setConsultOpen(false)}
        t={t}
        lang={lang}
        presetPractice={presetPractice}
      />
      <PersonModal
        person={personModal}
        lang={lang}
        onClose={() => setPersonModal(null)}
        onEnquiry={(person) => {
          setPersonModal(null);
          setPresetPractice(person.practices[0] || "");
          setConsultOpen(true);
        }}
      />

      <GaladariTweaks lang={lang} setLang={setLang} />
    </React.Fragment>
  );
}

// ---------- Tweaks ----------
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "paper",
  "accent": "brass",
  "density": "regular",
  "displayFont": "instrument-serif",
  "showAnchorChip": true
}/*EDITMODE-END*/;

function GaladariTweaks({ lang, setLang }) {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply theme to body
  useEffect(() => {
    document.body.classList.remove("theme-paper", "theme-ivory", "theme-ink", "theme-bone");
    document.body.classList.add("theme-" + tweaks.palette);
    document.body.classList.toggle("no-accent", tweaks.accent === "none");
    document.body.classList.remove("density-airy", "density-tight");
    if (tweaks.density === "airy") document.body.classList.add("density-airy");
    if (tweaks.density === "tight") document.body.classList.add("density-tight");

    // Display font swap
    const map = {
      "instrument-serif": "'Instrument Serif', serif",
      "newsreader": "'Newsreader', serif",
      "playfair": "'Playfair Display', serif",
    };
    const fam = map[tweaks.displayFont] || map["instrument-serif"];
    let style = document.getElementById("__tweak-font");
    if (!style) {
      style = document.createElement("style");
      style.id = "__tweak-font";
      document.head.appendChild(style);
    }
    style.textContent = `
      .serif, .hero h1, .section-head h2, .practice-card .pt, .drill h3, .person-name,
      .pmodal-body h3, .office-label, .modal-head h3, .footer-brand-block,
      .award-body, .insight-title, .brand-mark, .brand-name, .industry-chip,
      .trust-num, .success h4 {
        font-family: ${fam};
      }
      body[dir="rtl"] .serif, body[dir="rtl"] .hero h1,
      body[dir="rtl"] .section-head h2, body[dir="rtl"] .practice-card .pt,
      body[dir="rtl"] .drill h3, body[dir="rtl"] .person-name,
      body[dir="rtl"] .pmodal-body h3, body[dir="rtl"] .office-label,
      body[dir="rtl"] .modal-head h3, body[dir="rtl"] .insight-title,
      body[dir="rtl"] .industry-chip, body[dir="rtl"] .trust-num,
      body[dir="rtl"] .award-body {
        font-family: 'Amiri', serif;
      }
    `;
  }, [tweaks.palette, tweaks.accent, tweaks.density, tweaks.displayFont]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Palette">
        <TweakRadio
          value={tweaks.palette}
          options={[
            { value: "paper", label: "Parchment" },
            { value: "ivory", label: "Ivory" },
          ]}
          onChange={v => setTweak("palette", v)}
        />
        <TweakSelect
          label="More themes"
          value={tweaks.palette}
          options={[
            { value: "paper", label: "Parchment (warm cream)" },
            { value: "ivory", label: "Ivory (cool cream)" },
            { value: "bone", label: "Bone (deeper)" },
            { value: "ink", label: "Inked (dark mode)" },
          ]}
          onChange={v => setTweak("palette", v)}
        />
      </TweakSection>
      <TweakSection title="Accent">
        <TweakRadio
          value={tweaks.accent}
          options={[
            { value: "brass", label: "Brass" },
            { value: "none", label: "Stricter" },
          ]}
          onChange={v => setTweak("accent", v)}
        />
      </TweakSection>
      <TweakSection title="Display type">
        <TweakSelect
          value={tweaks.displayFont}
          options={[
            { value: "instrument-serif", label: "Instrument Serif (default)" },
            { value: "newsreader", label: "Newsreader" },
            { value: "playfair", label: "Playfair Display" },
          ]}
          onChange={v => setTweak("displayFont", v)}
        />
      </TweakSection>
      <TweakSection title="Density">
        <TweakRadio
          value={tweaks.density}
          options={[
            { value: "tight", label: "Tight" },
            { value: "regular", label: "Reg" },
            { value: "airy", label: "Airy" },
          ]}
          onChange={v => setTweak("density", v)}
        />
      </TweakSection>
      <TweakSection title="Language preview">
        <TweakRadio
          value={lang}
          options={[
            { value: "en", label: "EN" },
            { value: "ar", label: "AR" },
          ]}
          onChange={v => setLang(v)}
        />
        <div style={{ fontSize: 11, color: "#6B6685", marginTop: 6, fontStyle: "italic" }}>
          RTL with real Arabic copy — the headline value-add per the brief.
        </div>
      </TweakSection>
    </TweaksPanel>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
