/* global document, window, fetch */
(function () {
  const EN_PREFIX = "/en";

  function isEnglishPath(pathname) {
    return /^\/en(?:\/|$)/.test(pathname || window.location.pathname);
  }

  function lang() {
    return isEnglishPath(window.location.pathname) ? "en" : "ja";
  }

  function withLangPath(path, targetLang = lang()) {
    if (!path || /^(https?:|mailto:|tel:)/.test(path)) return path;
    if (path.startsWith("#")) return path;
    if (path.startsWith("/word-ai-agent/en/")) return targetLang === "ja" ? "/word-ai-agent/" : path;
    if (path.startsWith("/word-ai-agent/")) return targetLang === "en" ? "/word-ai-agent/en/" : path;
    if (targetLang === "en") {
      if (path === "/") return "/en/";
      return path.startsWith(EN_PREFIX + "/") ? path : EN_PREFIX + path;
    }
    return path.replace(/^\/en(?=\/|$)/, "") || "/";
  }

  function alternatePath(targetLang) {
    const path = window.location.pathname || "/";
    const search = window.location.search || "";
    const hash = window.location.hash || "";
    if (path.startsWith("/word-ai-agent/en/")) return targetLang === "ja" ? "/word-ai-agent/" + search + hash : path + search + hash;
    if (path.startsWith("/word-ai-agent/")) return targetLang === "en" ? "/word-ai-agent/en/" + search + hash : path + search + hash;
    return withLangPath(path, targetLang) + search + hash;
  }

  const TEXT = {
    "お問い合わせ": "Contact",
    "サービス": "Services",
    "強み": "Strengths",
    "対応分野": "Practice Areas",
    "弁護士": "Attorneys",
    "メンバー": "Members",
    "コラム": "Insights",
    "採用": "Careers",
    "ご相談・お問い合わせ": "Contact Us",
    "サービスを見る": "View Services",
    "サービスの詳細 →": "View Details →",
    "外部リンクを開く": "Open external link",
    "続きを読む": "Read More",
    "閉じる": "Close",
    "コラム・お知らせ": "Insights & News",
    "記事を読み込み中、または posts/index.json が見つかりません。": "Loading articles, or posts/index.json could not be found.",
    "法務アウトソーシング": "Legal Outsourcing",
    "M&A支援": "M&A Support",
    "スタートアップ法務": "Startup Legal",
    "契約書レビュー・ドラフト": "Contract Review and Drafting",
    "労務・コンプライアンス相談": "Labor and Compliance Advice",
    "知的財産・利用規約の整備": "IP and Terms of Use",
    "社内規程・ガバナンス支援": "Internal Rules and Governance",
    "リーガルデューデリジェンス": "Legal Due Diligence",
    "SPA・株主間契約の作成・交渉": "SPA and Shareholders Agreement Drafting",
    "表明保証・補償条項の設計": "Representations, Warranties and Indemnities",
    "クロージング・PMI対応": "Closing and PMI Support",
    "創業・資本政策・株主間契約": "Incorporation, Capital Policy and Shareholders Agreements",
    "シード・シリーズAの資金調達対応": "Seed and Series A Financing",
    "投資契約・優先株式・J-KISS対応": "Investment Agreements, Preferred Shares and J-KISS",
    "ストックオプション設計・登記": "Stock Option Design and Registration",
    "クライアント様": "Client",
    "担当弁護士": "Attorney",
    "新規取引先からNDAが届きました。レビューお願いできますか。": "We received an NDA from a new counterparty. Could you review it?",
    "承知しました。本日中にコメント付きでお戻しいたします。": "Understood. We will return it with comments today.",
    "資料開示・スコープ確定": "Document disclosure and scope confirmed",
    "リーガルDD・論点整理": "Legal DD and issue mapping",
    "SPAドラフト・交渉": "SPA drafting and negotiation",
    "クロージング対応": "Closing support",
    "創業・資本政策": "Incorporation and capital policy",
    "シリーズA／SO設計": "Series A and stock option design",
    "シリーズB以降": "Series B and beyond",
    "IPO準備": "IPO preparation",
    "完了": "Done",
    "進行中": "In progress",
    "整備": "Set up",
    "プライム上場企業 A社": "Prime-listed company A",
    "契約レビューの工数を、最大10分の1に": "Contract review workload reduced by up to 90%",
    "固定料金による明確なコスト設定は、コストの把握という観点からも非常に安心感があります。": "The fixed-fee structure gives us strong cost visibility and peace of mind.",
    "工数削減": "Workload reduction",
    "固定": "Fixed fee",
    "料金体系": "Pricing",
    "投資決定から実行までが、格段にスピードアップ": "Faster execution from investment decision to closing",
    "法的リスクを定額・素早く把握でき、投資決定から実行までのスピードが格段に上がりました。": "We can understand legal risks quickly at a fixed fee, which significantly accelerates investment execution.",
    "定額": "Fixed fee",
    "契約4点セット": "Four core documents",
    "即時": "Fast",
    "納品": "Delivery",
    "顧問契約数": "Retainer clients",
    "標準納期": "Standard turnaround",
    "有料プラン継続率": "Paid plan retention",
    "対応スピード比": "Speed ratio",
    "1営業日": "1 business day",
    "プライム上場企業からスタートアップまで、100社以上の取引実績。": "Experience with more than 100 companies, from prime-listed enterprises to startups.",
    "ご依頼から原則1営業日以内に納品。ビジネスのスピードを止めません。": "As a rule, we deliver within one business day and do not slow down business speed.",
    "サービス品質と価格設定への高い満足度を、数字が証明しています。": "The numbers reflect strong satisfaction with service quality and pricing.",
    "従来の法律事務所と比較して、2〜10倍の速さで案件対応が可能です。": "We can respond two to ten times faster than traditional law firms.",
    "プロフィールを見る": "View Profile",
    "採用情報を見る": "View Careers",
    "カジュアル面談へ": "Casual Interview",
    "初回ご相談": "Initial Consultation",
    "は、": "is",
    "無料です": "Free",
    "お問い合わせフォームへ": "Go to Contact Form",
    "ご相談の流れ": "Consultation Flow",
    "お問い合わせフォームよりご連絡": "Send us the contact form",
    "30分の無料オンラインミーティング": "30-minute free online meeting",
    "最適なプランをご提案": "We propose the right plan",
    "即日から対応可能": "Support can start the same day",
    "お問い合わせフォーム": "Contact Form",
    "下記フォームよりお気軽にご連絡ください。": "Please contact us using the form below.",
    "通常2営業日以内にご返信いたします。": "We usually reply within two business days.",
    "会社名": "Company",
    "お名前": "Name",
    "メールアドレス": "Email",
    "お電話番号": "Phone",
    "ご相談内容": "Topic",
    "お問い合わせ詳細": "Message",
    "必須": "Required",
    "選択してください": "Please select",
    "その他": "Other",
    "スタッフ": "Staff",
    "エンジニア": "Engineers",
    "契約書レビュー・作成について": "About Contract Drafting and Review",
    "紛争・トラブル対応について": "About Litigation and Dispute Resolution",
    "AI法務サービスについて": "About AI Legal Services",
    "東京都中央区日本橋兜町22-6": "22-6 Nihonbashi Kabutocho, Chuo-ku, Tokyo",
    "東京セントラルプレイス5階": "Tokyo Central Place 5F",
    "5営業日": "5 business days",
    "nda_review.docx · 添付済み ✓": "nda_review.docx · attached ✓",
    "送信中...": "Sending...",
    "送信する": "Submit",
    "お問い合わせありがとうございます。内容を確認の上、追ってご連絡いたします。": "Thank you for your inquiry. We will review it and contact you shortly.",
    "所属弁護士": "Attorneys",
    "所属弁護士とエンジニア": "Attorneys and engineers",
    "導入事例": "Client Stories",
    "実績": "Results",
    "プライバシーポリシー": "Privacy Policy",
    "に同意します": "I agree to the privacy policy",
    "よくあるご質問": "FAQ",
    "法務アウトソーシングは可能ですか？": "Do you provide legal outsourcing?",
    "初回ご相談は有料ですか？": "Is the initial consultation paid?",
    "顧問契約の最低期間はありますか？": "Is there a minimum contract period?",
    "料金体系を教えてください": "What is your pricing structure?",
    "英文契約にも対応していますか？": "Do you handle English contracts?",
    "導入までどのくらいかかりますか？": "How long does onboarding take?",
    "法務特化の": "Legal-specialized",
    "サービス詳細を見る": "View Details",
    "※掲載は一部のクライアント。順不同。": "Selected clients shown. Logos are listed in no particular order.",
  };

  let servicesPromise;
  let lawyersPromise;

  function loadServices() {
    if (!servicesPromise) {
      servicesPromise = fetch("/services/index.en.json").then((r) => r.json());
    }
    return servicesPromise;
  }

  function loadLawyers() {
    if (!lawyersPromise) {
      lawyersPromise = fetch("/lawyers/index.en.json").then((r) => r.json());
    }
    return lawyersPromise;
  }

  const SPECIAL_HTML = {
    ".hero__solo-headline": '<span class="hero__line"><span>AI Native Law Firm</span></span><span class="hero__line"><span>for Modern Enterprises</span></span>',
    ".about__title": '<span class="heading-line">Lawyers × AI Agents</span><span class="heading-line">delivering a new form of legal service</span>',
    ".about__lede": "LegalAgent is an <em>AI Native Law Firm</em> specialized in corporate legal work.<br>Attorneys with deep expertise and diverse professional backgrounds work with our proprietary AI Agents.<br>We provide an entirely new legal service, with speed, quality and fixed-fee pricing that traditional law firms could not provide, while committing to the growth of our clients' businesses.",
    ".services__title": '<span class="heading-line">A law firm for the</span><span class="heading-line">generative AI era,</span><span class="heading-line">combining expertise</span><span class="heading-line">with speed</span>',
    ".clients__title": 'Trusted by leading companies,<br>from prime-listed enterprises to startups',
    ".challenges__title": '<span class="heading-line">Four deep-rooted problems</span><span class="heading-line">facing companies</span><span class="heading-line">and law firms</span>',
    ".strengths__title": 'Three reasons companies choose <em>LegalAgent</em>',
    ".practice__title": 'We cover the full range of <em>corporate legal</em> work',
    ".results__title": '<em>LegalAgent</em> by the numbers',
    ".lawyers__title": 'Attorneys and engineers with<br><em>specialized expertise</em>',
    ".ai-agent-promo__title": '<span>Legal-Specialized</span><em>Word AI Agent</em>',
    ".careers__title": 'Build the law firm<br>for the generative AI era<br><em>with us</em>',
    ".footer__cta-title": '<em>Initial Consultation</em><br>is Free',
  };

  const BLOCK_TEXT = {
    ".services__lede": "Specialized attorneys work deeply with your business and support legal operations in a way that is close to an internal legal team. We provide legal outsourcing, M&A support and startup fundraising support on an integrated basis.",
    ".challenges__lede": "Corporate legal teams face persistent shortages, cost pressure, conservative responses and gaps in business speed. LegalAgent addresses these issues through expertise, speed and business understanding.",
    ".practice__lede": "From daily contract review to M&A, IPO, funds, litigation, data, FinTech, healthcare and crisis management, LegalAgent supports the full range of corporate legal matters.",
    ".column__lede": "We regularly share practical insights on corporate legal work, legal updates, media coverage and events from LegalAgent.",
    ".careers__lede": "LegalAgent is hiring attorneys, staff members and engineers who will build the foundation of an AI Native Law Firm. If you are interested, we would be happy to start with a casual conversation.",
    ".footer__cta-lede": "We will learn about your business and legal function, then propose the most suitable support plan. Within the initial consultation, we can also provide legal answers where appropriate. Please feel free to contact us for an online meeting.",
    ".ai-agent-promo__lede": "In addition to our law firm services, LegalAgent provides a Word-based AI Agent for contract review and legal document drafting. It works inside Word files, revises content and adds comments based on your instructions. Put an excellent associate inside your Word file. Legal Agent makes contract drafting and review work ten times more efficient.",
  };

  function translateText(raw) {
    const trimmed = raw.trim();
    if (!trimmed) return raw;
    if (TEXT[trimmed]) return raw.replace(trimmed, TEXT[trimmed]);
    const more = trimmed.match(/^もっと見る（あと\s*(\d+)\s*件）$/);
    if (more) return `Show more (${more[1]} more)`;
    if (trimmed.endsWith("について")) {
      const base = trimmed.replace(/について$/, "");
      if (TEXT[base]) return `About ${TEXT[base]}`;
    }
    return raw;
  }

  function walkText(node) {
    if (!node || ["SCRIPT", "STYLE", "NOSCRIPT"].includes(node.nodeName)) return;
    if (node.nodeType === 3) {
      const next = translateText(node.nodeValue);
      if (next !== node.nodeValue) node.nodeValue = next;
      return;
    }
    Array.from(node.childNodes || []).forEach(walkText);
  }

  function localizeLinks(root) {
    (root || document).querySelectorAll("a[href]").forEach((a) => {
      if (a.classList && a.classList.contains("nav__lang")) return;
      if (a.closest && a.closest(".lp-nav__lang")) return;
      const href = a.getAttribute("href");
      if (!href || href.startsWith("#") || /^(https?:|mailto:|tel:)/.test(href)) return;
      const next = withLangPath(href, "en");
      if (next !== href) a.setAttribute("href", next);
    });
    (root || document).querySelectorAll("img[src]").forEach((img) => {
      const src = img.getAttribute("src");
      if (src && src.startsWith("assets/")) img.setAttribute("src", "/" + src);
    });
  }

  function translateAttributes(root) {
    (root || document).querySelectorAll("[placeholder]").forEach((el) => {
      const value = el.getAttribute("placeholder");
      const map = {
        "株式会社LegalAgent": "LegalAgent Inc.",
        "山田 太郎": "Taro Yamada",
        "example@company.co.jp": "example@company.com",
        "03-0000-0000": "+81-3-0000-0000",
        "ご相談内容を具体的にお書きください。": "Please describe your inquiry.",
      };
      if (map[value]) el.setAttribute("placeholder", map[value]);
    });
    (root || document).querySelectorAll("[alt]").forEach((el) => {
      const value = el.getAttribute("alt");
      const map = {
        "コンクルー": "Concluder",
        "顧問バンク": "Komon Bank",
        "法務特化のWord AI Agent — Word文書上で動作するLegal Agentのスクリーンショット": "Legal-specialized Word AI Agent screenshot running inside Microsoft Word",
      };
      if (map[value]) el.setAttribute("alt", map[value]);
    });
    (root || document).querySelectorAll("[aria-label]").forEach((el) => {
      const value = el.getAttribute("aria-label");
      if (!value) return;
      if (value === "募集職種") el.setAttribute("aria-label", "Open roles");
      if (value === "関連キーワード") el.setAttribute("aria-label", "Related keywords");
      if (value.includes("プロフィールを見る")) el.setAttribute("aria-label", value.replace("のプロフィールを見る", " profile"));
      if (value.includes("のサービス詳細を見る")) el.setAttribute("aria-label", value.replace("のサービス詳細を見る", " service details"));
    });
  }

  function applySpecialBlocks() {
    Object.entries(SPECIAL_HTML).forEach(([selector, html]) => {
      document.querySelectorAll(selector).forEach((el) => {
        if (el.dataset.enApplied) return;
        el.innerHTML = html;
        el.dataset.enApplied = "true";
      });
    });
    Object.entries(BLOCK_TEXT).forEach(([selector, text]) => {
      document.querySelectorAll(selector).forEach((el) => {
        if (el.dataset.enApplied) return;
        el.textContent = text;
        el.dataset.enApplied = "true";
      });
    });
  }

  function hydrateStaticSections() {
    const about = [
      {
        title: "What is an AI Native Law Firm?",
        body: "Unlike firms that introduce AI merely as an auxiliary tool, LegalAgent assumes AI as part of the operating model and embeds it into workflow, quality control and knowledge sharing. Our goal is not to replace lawyers with AI, but to enable AI-equipped lawyers to provide deeper, faster and more strategic advice.",
      },
      {
        title: "What is legal outsourcing (AI-BPO)?",
        body: "LegalAgent provides legal work as a business process outsourcing service and uses AI to improve efficiency, consistency and cost optimization. From routine contract review to strategic M&A and fundraising support, we deliver an experience close to an internal legal team from outside the company.",
      },
      {
        title: "Service features",
        html: "<li><strong>Expertise</strong>Top-tier knowledge and practical experience</li><li><strong>Speed</strong>Two to ten times faster than traditional firms</li><li><strong>Business understanding</strong>Close to in-house operations through Slack and Teams</li><li><strong>Transparency</strong>Fixed-fee and clear pricing</li>",
      },
    ];
    document.querySelectorAll(".about__pillar").forEach((card, i) => {
      if (card.dataset.enHydrated) return;
      const data = about[i];
      if (!data) return;
      const title = card.querySelector("h3");
      if (title) title.textContent = data.title;
      const p = card.querySelector("p");
      if (p && data.body) p.textContent = data.body;
      const ul = card.querySelector("ul");
      if (ul && data.html) ul.innerHTML = data.html;
      card.dataset.enHydrated = "true";
    });

    const serviceCards = [
      {
        desc: "As legal outsourcing, attorneys stationed in Slack and Teams work close to your internal legal team. We do not merely respond passively; we identify legal risks early and support business decision-making.",
        note: "attached",
      },
      {
        desc: "We remove the problem of deals slowing down because of legal work. From document disclosure, we complete initial risk analysis in two to five business days and accelerate legal due diligence, SPA negotiations and issue management.",
      },
      {
        desc: "We support startup legal work from seed stage to pre-IPO. Centered on fundraising support, we build legal foundations that do not slow growth, including formation, investment agreements, stock option design and IPO preparation.",
      },
    ];
    document.querySelectorAll(".services__card").forEach((card, i) => {
      if (card.dataset.enHydrated) return;
      const data = serviceCards[i];
      if (!data) return;
      const desc = card.querySelector(".services__card-desc");
      if (desc) desc.textContent = data.desc;
      card.dataset.enHydrated = "true";
    });
    document.querySelectorAll(".services__figure-line--us em").forEach((el) => {
      el.textContent = "nda_review.docx · attached ✓";
    });

    const challenges = [
      ["Overloaded legal teams", "Legal teams are under pressure because of staffing shortages and growing workloads. Recruiting strong legal talent can cost several million yen in referral fees alone."],
      ["Passive and conservative responses", "Traditional law firms are often passive and conservative, creating a gap with business speed. Important decisions can stall while teams wait for legal review."],
      ["Opaque hourly billing", "Traditional firms often rely on hourly billing, making costs difficult to predict and causing teams to hesitate before asking for advice."],
      ["Shallow business understanding", "Outside lawyers often answer without fully understanding the client’s business or internal rules, making it difficult to provide practical recommendations."],
    ];
    document.querySelectorAll(".challenges__item").forEach((item, i) => {
      if (item.dataset.enHydrated) return;
      const data = challenges[i];
      if (!data) return;
      const h = item.querySelector("h3");
      const p = item.querySelector("p");
      if (h) h.textContent = data[0];
      if (p) p.textContent = data[1];
      item.dataset.enHydrated = "true";
    });

    const strengths = [
      {
        jp: "Expertise",
        head: "Top-tier knowledge and practical legal experience",
        points: [
          ["Handled only by highly specialized attorneys", "Only attorneys with top-tier knowledge and practical experience handle matters. We support M&A, IPO and complex corporate legal work with reliable expertise from the first response."],
          ["Diverse professional backgrounds", "Our team includes founders, in-house counsel, former business development professionals and Japan Patent Office secondees, bringing strong problem-solving capability from diverse backgrounds."],
          ["Knowledge sharing and accumulation", "LegalAgent’s strength also lies in its internal knowledge sharing and information accumulation system."],
        ],
      },
      {
        jp: "Speed",
        head: "Two to five times faster than traditional law firms",
        points: [
          ["Same-day to next-business-day delivery as standard", "We respond on the day of consultation and generally deliver by the next business day, without stopping business speed."],
          ["Understanding of decision-making processes", "Through experience supporting many companies and businesses, we support fast decision-making."],
          ["M&A risk analysis in two to five business days", "From document disclosure, we complete initial risk analysis in two to five business days so legal work does not stall the deal."],
        ],
      },
      {
        jp: "Business Sense",
        head: "Deep business understanding and support close to an internal legal team",
        points: [
          ["Embedded in Slack and Teams", "From request to delivery, work is completed through Slack and Teams, as if we were part of your internal legal team."],
          ["Understanding internal rules and operations", "We understand internal review standards and operational flows, then provide the most efficient support for each organization."],
          ["Fixed-fee and transparent pricing", "Both monthly retainers and spot matters are generally fixed fee, giving clients cost predictability and confidence."],
        ],
      },
    ];
    document.querySelectorAll(".strength-block").forEach((block, i) => {
      if (block.dataset.enHydrated) return;
      const data = strengths[i];
      if (!data) return;
      const jp = block.querySelector(".strength-block__jp");
      const head = block.querySelector(".strength-block__head");
      if (jp) jp.textContent = data.jp;
      if (head) head.textContent = data.head;
      if (i === 1) {
        const from = block.querySelector(".strength-block__stat-from");
        const to = block.querySelector(".strength-block__stat-to");
        const label = block.querySelector(".strength-block__stat em");
        if (from) from.textContent = "5 business days";
        if (to) to.textContent = "1 business day";
        if (label) label.textContent = "Standard turnaround";
      }
      block.querySelectorAll(".strength-point").forEach((point, k) => {
        const p = data.points[k];
        if (!p) return;
        const h = point.querySelector("h4");
        const body = point.querySelector("p");
        if (h) h.textContent = p[0];
        if (body) body.textContent = p[1];
      });
      block.dataset.enHydrated = "true";
    });

    const cases = [
      {
        kind: "Prime-listed company A",
        title: "Contract review workload reduced by up to 90%",
        body: "The legal department previously needed to review entire contracts of 10 to 30 pages, creating a heavy workload. After introducing LegalAgent, the company moved to an operation that efficiently checks only important points based on its review standards, reducing contract review workload to one-fifth to one-tenth.",
      },
      {
        kind: "Boost Capital",
        title: "Significantly faster execution from investment decision to closing",
        body: "For complex startup investment documents such as investment agreements, shareholders agreements, distribution agreements and articles of incorporation, LegalAgent provides high-quality deliverables quickly at a fixed fee. Speed is essential in startup investment.",
      },
    ];
    document.querySelectorAll(".case-card").forEach((card, i) => {
      if (card.dataset.enHydrated) return;
      const data = cases[i];
      if (!data) return;
      const kind = card.querySelector(".case-card__kind");
      const title = card.querySelector(".case-card__title");
      const body = card.querySelector(".case-card__body");
      if (kind) kind.textContent = data.kind;
      if (title) title.textContent = data.title;
      if (body) body.textContent = data.body;
      card.dataset.enHydrated = "true";
    });

    const faqAnswers = [
      "Yes. LegalAgent provides AI-assisted legal outsourcing as a core service. We can support contract review, legal strategy and broader corporate legal work as a substitute for or extension of your legal department.",
      "The initial 30-minute online consultation is free. We will learn about your business and legal function, then propose the most suitable support plan.",
      "There is no minimum contract period, and monthly plans can be cancelled. Unused monthly fees may be carried forward for three months.",
      "We offer monthly retainer plans and fixed-fee spot matters. M&A support is quoted individually depending on the target company and scope.",
      "Yes. We support English contract review, drafting and translation. Fees for English matters may differ from Japanese matters, so we will provide a separate quote.",
      "We can start as early as the same day after the initial consultation. Please contact us for details.",
    ];
    document.querySelectorAll(".faq__a p").forEach((p, i) => {
      if (p.dataset.enHydrated) return;
      if (faqAnswers[i]) p.textContent = faqAnswers[i];
      p.dataset.enHydrated = "true";
    });

    document.querySelectorAll(".results__item").forEach((item) => {
      const num = item.querySelector(".results__num");
      if (num && num.dataset.countSuffix === "営業日") {
        num.dataset.countSuffix = " business day";
        num.dataset.countFrom = "1";
        num.dataset.countTo = "1";
        num.dataset.countDuration = "1";
        num.textContent = "1 business day";
        num.classList.add("results__num--long");
      }
    });
  }

  async function hydratePracticeAndLawyers() {
    try {
      const services = await loadServices();
      const byId = Object.fromEntries(services.map((s) => [s.id, s]));
      const serviceAliases = {
        contract: "contracts",
        dispute: "dispute-resolution",
        ai: "ai-legal-consulting",
      };
      document.querySelectorAll(".practice__item").forEach((item) => {
        const href = item.getAttribute("href") || "";
        const rawId = href.split("/").filter(Boolean).pop();
        const id = serviceAliases[rawId] || rawId;
        const service = byId[id];
        if (!service) return;
        const title = item.querySelector(".practice__item-title span");
        const desc = item.querySelector(".practice__item-desc");
        if (title) title.textContent = service.shortTitle || service.title;
        if (desc) desc.textContent = service.lead;
        item.setAttribute("aria-label", `${service.shortTitle || service.title} service details`);
      });
      document.querySelectorAll("select[name='topic'] option").forEach((option) => {
        const id = serviceAliases[option.value] || option.value;
        const service = byId[id];
        if (service) option.textContent = `About ${service.shortTitle || service.title}`;
      });
    } catch (_) {}

    try {
      const lawyers = await loadLawyers();
      const byId = Object.fromEntries(lawyers.map((l) => [l.id, l]));
      document.querySelectorAll(".lawyer--link").forEach((card) => {
        const href = card.getAttribute("href") || "";
        const id = href.split("/").filter(Boolean).pop();
        const lawyer = byId[id];
        if (!lawyer) return;
        const name = card.querySelector(".lawyer__name");
        const role = card.querySelector(".lawyer__head .label");
        const image = card.querySelector(".lawyer__portrait img");
        const specs = card.querySelectorAll(".lawyer__spec span");
        const bio = card.querySelectorAll(".lawyer__bio li");
        card.setAttribute("aria-label", `${lawyer.name} profile`);
        if (image) image.setAttribute("alt", lawyer.name);
        if (name) name.textContent = lawyer.name;
        if (role) role.textContent = lawyer.role;
        specs.forEach((s, i) => {
          if (lawyer.specialty[i]) s.textContent = lawyer.specialty[i];
          else s.remove();
        });
        bio.forEach((b, i) => {
          if (lawyer.career[i]) b.textContent = lawyer.career[i].text;
          else b.remove();
        });
      });
    } catch (_) {}
  }

  function applyEnglish(root) {
    if (lang() !== "en") return;
    document.documentElement.lang = "en";
    applySpecialBlocks();
    hydrateStaticSections();
    walkText(root || document.body);
    translateAttributes(root || document);
    localizeLinks(root || document);
  }

  function init() {
    if (lang() !== "en") {
      document.documentElement.lang = "ja";
      return;
    }
    const run = () => {
      applyEnglish(document.body);
      hydratePracticeAndLawyers().then(() => applyEnglish(document.body));
    };
    run();
    [50, 250, 900, 1800, 3200].forEach((delay) => window.setTimeout(run, delay));
    document.addEventListener("click", () => window.setTimeout(run, 0), true);
  }

  window.LA_I18N = {
    lang,
    isEnglish: () => lang() === "en",
    withLangPath,
    alternatePath,
    applyEnglish,
  };

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", init);
  } else {
    init();
  }
})();
