// app.jsx — Afridi & Angell elevation prototype
// Main shell: nav, footer, home page, tweaks panel, and route dispatcher.
// Page modules live in pages.jsx.

const { useState, useEffect, useMemo, useRef, useCallback } = React;
const { PRACTICES, SECTORS, PEOPLE, OFFICES, ARTICLES, QUOTES, AR } = window.AA_DATA;

// ─────────────────────────── TWEAKS DEFAULTS ───────────────────────────
const AA_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#9C7A3C",
  "displaySerif": "Source Serif 4",
  "showRibbon": true,
  "heroVariant": "editorial"
}/*EDITMODE-END*/;

// ─────────────────────────── LOGO (redrawn SVG) ───────────────────────────
// Per brief §8: the source logo is a 298×98 raster JPEG. Rebuild as clean SVG.
// Original-design wordmark: serif "Afridi & Angell" with hairline rule and
// year mark below. No copying of any third-party UI; this is original mark-making.
function Logo({ height = 30, dark = false }) {
  const inkColor = dark ? "#F6F4EF" : "#13233B";
  const accentColor = "var(--accent)";
  return (
    <svg viewBox="0 0 220 56" height={height} style={{ display: "block" }} aria-label="Afridi & Angell">
      {/* Monogram block */}
      <g>
        <rect x="0" y="4" width="44" height="44" fill={inkColor} />
        <text x="22" y="34" textAnchor="middle"
          style={{ font: '500 24px "Source Serif 4", Georgia, serif', fill: dark ? "#0E1726" : "#F6F4EF", letterSpacing: "-0.02em" }}>
          A&amp;A
        </text>
        <rect x="0" y="48" width="44" height="2" fill={accentColor} />
      </g>
      {/* Wordmark */}
      <g transform="translate(56, 0)">
        <text x="0" y="28"
          style={{ font: '400 22px "Source Serif 4", Georgia, serif', fill: inkColor, letterSpacing: "0.005em" }}>
          Afridi <tspan style={{ fill: accentColor }}>&amp;</tspan> Angell
        </text>
        <text x="0" y="46"
          style={{ font: '500 8.5px "Inter", sans-serif', fill: dark ? "#C9D0DC" : "#5A6473", letterSpacing: "0.22em" }}>
          LEGAL CONSULTANTS · EST. 1975
        </text>
      </g>
    </svg>
  );
}

// ─────────────────────────── ROUTING ───────────────────────────
// Hash-based router so the prototype works file://. Sets a body data attribute
// for screen-label context, too.
function useRoute() {
  const [route, setRoute] = useState(() => parseHash(location.hash));
  useEffect(() => {
    const h = () => setRoute(parseHash(location.hash));
    window.addEventListener("hashchange", h);
    return () => window.removeEventListener("hashchange", h);
  }, []);
  useEffect(() => {
    document.body.setAttribute("data-screen-label", route.label || "00 Home");
    window.scrollTo({ top: 0, behavior: "instant" });
  }, [route]);
  return route;
}
function parseHash(h) {
  const path = (h || "#/").replace(/^#/, "");
  const parts = path.split("/").filter(Boolean);
  if (parts.length === 0) return { name: "home", label: "01 Home" };
  if (parts[0] === "expertise" && parts[1]) return { name: "practice", slug: parts[1], label: "04 Practice — " + parts[1] };
  if (parts[0] === "expertise") return { name: "expertise", label: "03 Expertise" };
  if (parts[0] === "people" && parts[1]) return { name: "lawyer", slug: parts[1], label: "06 Lawyer — " + parts[1] };
  if (parts[0] === "people") return { name: "people", label: "05 People" };
  if (parts[0] === "insights") return { name: "insights", label: "07 Insights" };
  if (parts[0] === "offices" && parts[1]) return { name: "office", slug: parts[1], label: "09 Office — " + parts[1] };
  if (parts[0] === "offices") return { name: "offices", label: "08 Offices" };
  if (parts[0] === "about") return { name: "about", label: "10 About" };
  if (parts[0] === "contact") return { name: "contact", label: "11 Contact" };
  return { name: "home", label: "01 Home" };
}
const go = (path) => { location.hash = "#/" + path.replace(/^\//, ""); };

// ─────────────────────────── NAV ───────────────────────────
function Nav({ route, lang, setLang, dir }) {
  const items = [
    { key: "expertise",  en: "Expertise",  ar: AR.navExpertise },
    { key: "people",     en: "People",     ar: AR.navPeople },
    { key: "insights",   en: "Insights",   ar: AR.navInsights },
    { key: "offices",    en: "Offices",    ar: AR.navOffices },
    { key: "about",      en: "About",      ar: AR.navAbout }
  ];
  return (
    <nav className="nav">
      <div className="nav-inner">
        <div className="nav-logo" onClick={() => go("/")}>
          <Logo height={32} />
        </div>
        <div className="nav-links">
          {items.map(it => (
            <a key={it.key}
              className={"nav-link" + (route.name === it.key || route.name === "practice" && it.key === "expertise" || route.name === "lawyer" && it.key === "people" || route.name === "office" && it.key === "offices" ? " active" : "")}
              onClick={() => go("/" + it.key)}>
              {lang === "ar" ? it.ar : it.en}
            </a>
          ))}
        </div>
        <div className="nav-right">
          <div className="lang-switch" role="group" aria-label="Language">
            <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
            <button className={lang === "ar" ? "on" : ""} onClick={() => setLang("ar")}>عربي</button>
          </div>
          <a className="btn btn-primary" onClick={() => go("/contact")}>
            {lang === "ar" ? AR.ctaConsult : "Request a consultation"}
            <span className="arr">{dir === "rtl" ? "←" : "→"}</span>
          </a>
        </div>
      </div>
    </nav>
  );
}

// ─────────────────────────── FOOTER ───────────────────────────
function Footer({ lang }) {
  const ar = lang === "ar";
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <Logo height={32} dark={true} />
            <p style={{ marginTop: 22, fontSize: 13, lineHeight: 1.6, color: "rgba(255,255,255,0.7)", maxWidth: 36 + "ch" }}>
              {ar
                ? "تأسس عام ١٩٧٥. مرخّص في دبي وأبوظبي والشارقة ومركز دبي المالي العالمي، مع مكتب دولي في تورنتو، كندا."
                : "Established 1975. Licensed in Dubai, Abu Dhabi, Sharjah and the DIFC, with an international office in Toronto, Canada."}
            </p>
            <p style={{ marginTop: 22, fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--accent)" }}>
              {ar ? "عضو" : "Member"} · Lex Mundi (UAE) · World Services Group
            </p>
          </div>
          <div>
            <h5>Expertise</h5>
            <ul>
              {PRACTICES.filter(p => p.flagship).map(p => (
                <li key={p.slug}><a onClick={() => go("/expertise/" + p.slug)}>{p.name}</a></li>
              ))}
              <li><a onClick={() => go("/expertise")}>All 27 practice areas</a></li>
              <li><a onClick={() => go("/expertise")}>Industry sectors</a></li>
            </ul>
          </div>
          <div>
            <h5>{ar ? AR.navPeople : "People"}</h5>
            <ul>
              <li><a onClick={() => go("/people")}>Partners & lawyers</a></li>
              <li><a onClick={() => go("/people/bashir-ahmed")}>Bashir Ahmed</a></li>
              <li><a onClick={() => go("/people/haider-k-afridi")}>Haider K Afridi</a></li>
              <li><a onClick={() => go("/about")}>About the firm</a></li>
            </ul>
          </div>
          <div>
            <h5>Offices</h5>
            <ul>
              {OFFICES.map(o => (
                <li key={o.slug}><a onClick={() => go("/offices/" + o.slug)}>{o.city}</a></li>
              ))}
            </ul>
          </div>
          <div>
            <h5>Contact</h5>
            <ul>
              <li><a href="tel:+97143303900">+971 4 330 3900</a></li>
              <li><a href="mailto:dubai@afridi-angell.com">dubai@afridi-angell.com</a></li>
              <li><a href="https://www.linkedin.com/company/afridi-angell" target="_blank" rel="noreferrer">LinkedIn</a></li>
              <li><a onClick={() => go("/insights")}>Subscribe to inBrief</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bot">
          <div>© 1975–2026 Afridi &amp; Angell Legal Consultants. All rights reserved.</div>
          <div style={{ display: "flex", gap: 18 }}>
            <a>Privacy</a><a>Cookies</a><a>Disclaimer</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ─────────────────────────── HOME ───────────────────────────
function HomePage({ lang, dir }) {
  const ar = lang === "ar";
  return (
    <main data-screen-label="01 Home">
      {/* HERO */}
      <section className="hero">
        <div className="wrap hero-grid">
          <div>
            <div className="hero-meta">
              <span>{ar ? AR.est : "Established 1975"}</span>
              <span className="dot" />
              <span>Dubai · Abu Dhabi · Sharjah · DIFC · Toronto</span>
            </div>
            <h1 className="h-display">
              {ar
                ? AR.heroH1
                : <>Advising clients in the <em style={{ fontStyle: "italic", color: "var(--accent-deep)" }}>Middle East</em> and beyond for 50 years.</>}
            </h1>
            <p className="lede">
              {ar
                ? AR.heroLede
                : "A full-service UAE law firm in its fifth decade — pragmatic local-law advice combined with international quality. Exclusive UAE member firm of Lex Mundi."}
            </p>
            <div className="hero-actions">
              <a className="btn btn-primary" onClick={() => go("/contact")}>
                {ar ? AR.ctaConsult : "Request a consultation"} <span className="arr">{dir === "rtl" ? "←" : "→"}</span>
              </a>
              <a className="btn btn-outline" onClick={() => go("/expertise")}>
                {ar ? "تصفّح مجالات الممارسة" : "Explore our 27 practice areas"}
              </a>
            </div>
          </div>
          <div className="hero-rhs">
            <div className="hero-stat">
              <div className="num tnum">50<span style={{ color: "var(--accent)" }}>·</span></div>
              <div className="lab">{ar ? "خمسون عامًا من الممارسة" : "Years of practice in the UAE"}</div>
            </div>
            <div className="hero-stat">
              <div className="num tnum">4 <span style={{ fontSize: 28, color: "var(--muted)" }}>offices</span></div>
              <div className="lab">Dubai · Abu Dhabi · Sharjah · Toronto</div>
            </div>
            <div className="hero-stat">
              <div className="num tnum">100+ <span style={{ fontSize: 22, color: "var(--muted)" }}>countries</span></div>
              <div className="lab">Reach via Lex Mundi <span className="flag" style={{ marginLeft: 8 }}>attributed</span></div>
            </div>
          </div>
        </div>
      </section>

      {/* TRUST STRIP — verifiable claims only, no star rating */}
      <section className="trust">
        <div className="wrap trust-row">
          <span><strong>Est. 1975</strong></span>
          <span className="sep">/</span>
          <span>Licensed in <strong>Dubai · Abu Dhabi · Sharjah · DIFC</strong></span>
          <span className="sep">/</span>
          <span>Exclusive UAE member · <strong>Lex Mundi</strong></span>
          <span className="sep">/</span>
          <span>Ranked by <strong>Chambers Global</strong> &amp; <strong>The Legal 500 EMEA</strong></span>
        </div>
      </section>

      {/* PRACTICE GRID */}
      <section className="section">
        <div className="wrap">
          <div className="sec-hd">
            <div>
              <div className="h-eyebrow">{ar ? "مجالات الممارسة" : "01 / Practice areas"}</div>
              <h2 className="h-display" style={{ marginTop: 18 }}>
                {ar ? "خبرة قانونية متكاملة في الإمارات." : "Twenty-seven practice areas, two flagship strengths."}
              </h2>
            </div>
            <p className="sub">
              {ar
                ? "نقدّم خدمات قانونية شاملة عبر الإمارات الثلاث الكبرى ومركز دبي المالي العالمي."
                : "Full-service across the three largest Emirates and the DIFC. Ranked in dispute resolution and banking & finance by Chambers Global and The Legal 500 EMEA."}
            </p>
          </div>
          <div className="practice-grid">
            {PRACTICES.map((p, i) => (
              <a key={p.slug} className={"practice-cell" + (p.flagship ? " flagship" : "")} onClick={() => go("/expertise/" + p.slug)}>
                <div className="num tnum">{String(i + 1).padStart(2, "0")}</div>
                <div className="nm">{p.name}</div>
                <div className="arr">→</div>
              </a>
            ))}
          </div>
          <div style={{ marginTop: 24, display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 16 }}>
            <p style={{ fontSize: 13, color: "var(--muted)" }}>
              <span style={{ color: "var(--accent)" }}>★</span>&nbsp;Ranked by Chambers Global &amp; The Legal 500 EMEA. Tier &amp; edition to confirm before publication.
            </p>
            <a className="btn btn-ghost" onClick={() => go("/expertise")}>{ar ? "كل المجالات والقطاعات" : "All practice areas & industry sectors"} <span className="arr">→</span></a>
          </div>
        </div>
      </section>

      <hr className="rule" />

      {/* PULLQUOTE — attributed editorial, never a numeric score */}
      <section className="section" style={{ background: "var(--paper-warm)" }}>
        <div className="wrap" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 60, alignItems: "center" }}>
          <div>
            <div className="h-eyebrow" style={{ marginBottom: 30 }}>02 / Independent recognition</div>
            <blockquote className="pullquote">
              "The firm is unique in that it can provide international quality services and advice on local law issues."
              <span className="att">— The Legal 500 EMEA <span className="flag" style={{ marginLeft: 10 }}>edition to confirm</span></span>
            </blockquote>
            <p style={{ marginTop: 28, fontSize: 13, color: "var(--muted)", maxWidth: 56 + "ch" }}>
              Quotes are independent editorial assessments from legal directories — they are not client testimonials, and the firm does not publish any aggregate star rating.
            </p>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <div style={{ border: "1px solid var(--line-strong)", padding: "22px 26px", background: "var(--paper)" }}>
              <div className="h-eyebrow">Lex Mundi</div>
              <p style={{ fontFamily: "var(--serif)", fontSize: 17, marginTop: 8 }}>Exclusive UAE member firm — access to <strong>21,000+ lawyers in 100+ countries</strong>.</p>
              <p style={{ fontSize: 11, color: "var(--muted)", marginTop: 8, letterSpacing: "0.06em" }}>Figures attributed to Lex Mundi · Badge rights to confirm</p>
            </div>
            <div style={{ border: "1px solid var(--line-strong)", padding: "22px 26px", background: "var(--paper)" }}>
              <div className="h-eyebrow">World Services Group</div>
              <p style={{ fontFamily: "var(--serif)", fontSize: 17, marginTop: 8 }}>Member of the global multidisciplinary network.</p>
            </div>
          </div>
        </div>
      </section>

      {/* PEOPLE TEASER */}
      <section className="section">
        <div className="wrap">
          <div className="sec-hd">
            <div>
              <div className="h-eyebrow">03 / Partners &amp; senior lawyers</div>
              <h2 className="h-display" style={{ marginTop: 18 }}>{ar ? "نخبة من الشركاء والمستشارين." : "The people behind every matter."}</h2>
            </div>
            <a className="btn btn-ghost" onClick={() => go("/people")}>View all {PEOPLE.length} <span className="arr">→</span></a>
          </div>
          <div className="people-grid">
            {PEOPLE.filter(p => p.rank <= 8).slice(0, 8).map(p => (
              <LawyerCard key={p.id} p={p} />
            ))}
          </div>
        </div>
      </section>

      <hr className="rule" />

      {/* INBRIEF TEASER */}
      <section className="section" style={{ background: "var(--paper-warm)" }}>
        <div className="wrap">
          <div className="sec-hd">
            <div>
              <div className="h-eyebrow">04 / inBrief</div>
              <h2 className="h-display" style={{ marginTop: 18 }}>{ar ? "أحدث النشرات القانونية." : "Recent legal updates."}</h2>
              <p className="sub" style={{ marginTop: 8 }}>The firm's branded publications series.</p>
            </div>
            <a className="btn btn-ghost" onClick={() => go("/insights")}>All publications <span className="arr">→</span></a>
          </div>
          <div>
            {ARTICLES.map(a => (
              <a key={a.slug} className="brief-row" onClick={() => go("/insights")}>
                <div className="dt">{a.date}</div>
                <div className="tt">{a.title}</div>
                <div className="pa">{a.areaLabel}</div>
                <div className="arr">→</div>
              </a>
            ))}
          </div>
        </div>
      </section>

      {/* OFFICES STRIP */}
      <section className="section">
        <div className="wrap">
          <div className="sec-hd">
            <div>
              <div className="h-eyebrow">05 / Offices</div>
              <h2 className="h-display" style={{ marginTop: 18 }}>{ar ? "أربعة مكاتب، ثلاث إمارات، وعاصمة كندية." : "Four offices, three Emirates, one Canadian city."}</h2>
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 24 }}>
            {OFFICES.map(o => (
              <a key={o.slug} onClick={() => go("/offices/" + o.slug)} style={{ cursor: "pointer", background: "var(--paper)", border: "1px solid var(--line)", padding: 0, transition: "all .18s ease" }}>
                <div style={{ aspectRatio: "4/3", background: "var(--paper-warmer)", overflow: "hidden" }}>
                  <img src={o.image} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                </div>
                <div style={{ padding: "20px 22px" }}>
                  <div className="h-eyebrow" style={{ color: "var(--accent-deep)" }}>{o.country}</div>
                  <h3 style={{ marginTop: 6, fontSize: 24 }}>{o.city}</h3>
                  <p style={{ fontSize: 13, color: "var(--muted)", marginTop: 10, lineHeight: 1.5 }}>{o.address[0]}<br />{o.address[1]}</p>
                  <p style={{ marginTop: 14, fontFamily: "var(--mono)", fontSize: 12, color: "var(--ink)" }}>{o.phone}</p>
                </div>
              </a>
            ))}
          </div>
          <p style={{ marginTop: 24, fontSize: 12, color: "var(--muted)" }}>
            Office hours and map coordinates are not currently published — to be confirmed by the firm before launch.
          </p>
        </div>
      </section>

      {/* SUBSCRIBE */}
      <section style={{ paddingBottom: 80 }}>
        <div className="wrap">
          <div className="subscribe">
            <div>
              <div className="h-eyebrow on-dark">Subscribe</div>
              <h3 className="h-display" style={{ marginTop: 12 }}>{ar ? "اشترك في نشرة inBrief." : "Receive inBrief in your inbox."}</h3>
              <p className="sub">{ar ? "تحليلات قانونية موجزة حول التطورات في الإمارات والمنطقة." : "Concise legal updates on UAE and regional developments — by practice area."}</p>
            </div>
            <form onSubmit={e => { e.preventDefault(); alert("Demo — wire to Formspree / Netlify Forms + CRM webhook."); }}>
              <input type="email" required placeholder={ar ? "بريدك الإلكتروني" : "you@firm.com"} />
              <button type="submit" className="btn btn-on-dark">{ar ? "اشتراك" : "Subscribe"}</button>
            </form>
          </div>
        </div>
      </section>
    </main>
  );
}

// ─────────────────────────── REUSED ─────────────────────────────
function LawyerCard({ p }) {
  return (
    <a className="lawyer-card" onClick={() => go("/people/" + p.id)}>
      <div className="pic">
        <img src={p.portrait} alt={p.name} loading="lazy" />
      </div>
      <div className="nm">{p.name}</div>
      <div className="ro">{p.role}</div>
    </a>
  );
}

// ─────────────────────────── APP ROOT ───────────────────────────
function App() {
  const [t, setTweak] = useTweaks(AA_TWEAK_DEFAULTS);
  const [lang, setLang] = useState(() => localStorage.getItem("aa-lang") || "en");
  const route = useRoute();
  const dir = lang === "ar" ? "rtl" : "ltr";

  useEffect(() => {
    document.documentElement.lang = lang;
    document.documentElement.dir = dir;
    localStorage.setItem("aa-lang", lang);
  }, [lang, dir]);

  // Tweak: live accent color
  useEffect(() => {
    document.documentElement.style.setProperty("--accent", t.accent);
  }, [t.accent]);

  useEffect(() => {
    document.documentElement.style.setProperty("--serif", `"${t.displaySerif}", Georgia, serif`);
  }, [t.displaySerif]);

  let page;
  if (route.name === "home") page = <HomePage lang={lang} dir={dir} />;
  else if (route.name === "expertise") page = <ExpertisePage lang={lang} />;
  else if (route.name === "practice") page = <PracticePage slug={route.slug} lang={lang} />;
  else if (route.name === "people") page = <PeoplePage lang={lang} />;
  else if (route.name === "lawyer") page = <LawyerPage slug={route.slug} lang={lang} />;
  else if (route.name === "insights") page = <InsightsPage lang={lang} />;
  else if (route.name === "offices") page = <OfficesPage lang={lang} />;
  else if (route.name === "office") page = <OfficePage slug={route.slug} lang={lang} />;
  else if (route.name === "about") page = <AboutPage lang={lang} />;
  else if (route.name === "contact") page = <ContactPage lang={lang} />;

  return (
    <React.Fragment>
      <Nav route={route} lang={lang} setLang={setLang} dir={dir} />
      {page}
      <Footer lang={lang} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Accent" />
        <TweakColor label="Accent color" value={t.accent}
          options={["#9C7A3C", "#1C3A4B", "#7E2628", "#13233B"]}
          onChange={(v) => setTweak("accent", v)} />
        <TweakSection label="Display type" />
        <TweakRadio label="Serif" value={t.displaySerif}
          options={["Source Serif 4", "Lora", "Cormorant Garamond"]}
          onChange={(v) => setTweak("displaySerif", v)} />
        <TweakSection label="Layout" />
        <TweakToggle label="Show year ribbon" value={t.showRibbon}
          onChange={(v) => setTweak("showRibbon", v)} />
      </TweaksPanel>
    </React.Fragment>
  );
}

// Expose to global scope; mount happens at end of pages.jsx (after all pages are loaded).
Object.assign(window, { App, HomePage, LawyerCard, Logo, Nav, Footer, go });
