/* global React */

const { useState, useEffect, useRef } = React;

// ---------- Utilities ----------

function getSiteBasePath() {
  const marker = "/ui_kits/website";
  const path = window.location.pathname.replace(/\/index\.html$/, "");
  const markerIndex = path.indexOf(marker);
  return markerIndex >= 0 ? path.slice(0, markerIndex + marker.length) : "";
}

const SITE_BASE_PATH = getSiteBasePath();
const CONTACT_WORKER_URL = window.CONTACT_WORKER_URL || "https://frm.kuczynski.biz/";
window.SITE_BASE_PATH = SITE_BASE_PATH;
window.CONTACT_WORKER_URL = CONTACT_WORKER_URL;

function sitePath(path) {
  if (!path || path.startsWith("#") || path.startsWith("mailto:") || path.startsWith("tel:") || /^https?:\/\//.test(path)) {
    return path;
  }
  return `${SITE_BASE_PATH}${path === "/" ? "/" : path}`;
}

function assetPath(path) {
  return `${SITE_BASE_PATH}/assets/${path}`;
}

window.sitePath = sitePath;
window.assetPath = assetPath;

const UI_COPY = {
  pl: {
    brandSub: "Kancelaria Adwokacka",
    navLabel: "Główna nawigacja",
    openMenu: "Otwórz menu",
    closeMenu: "Zamknij menu",
    ctaTalk: "Umów rozmowę",
    nav: [
      { path: "/deweloperzy", label: "Deweloperzy" },
      { path: "/portfele-wierzytelnosci", label: "Portfele wierzytelności" },
      { path: "/nieruchomosci-komercyjne", label: "Nieruchomości komercyjne" },
      { path: "/legaltech", label: "LegalTech" },
      { path: "/o-kancelarii", label: "O kancelarii" },
    ],
    heroEyebrow: "Kancelaria Adwokacka · Warszawa",
    heroTitle: "Bieżąca obsługa prawna biznesu, procesy i LegalTech.",
    heroLead: "Od 20 lat wspieram deweloperów, właścicieli nieruchomości komercyjnych oraz podmioty obsługujące portfele wierzytelności — łącząc doświadczenie procesowe z technologią, raportowaniem i bezpośrednią odpowiedzialnością adwokata.",
    heroSecondary: "Zobacz obszary obsługi",
    heroStrip: "Adwokat · Warszawa · Obsługa firm · Procesy · EPU · Nieruchomości · LegalTech",
    captionName: "adw. Marcin Kuczyński",
    captionSince: "od 2006 r.",
    servicesMore: "Zobacz obsługę",
    services: [
      {
        icon: "Building",
        eyebrow: "Filar I",
        title: "Deweloperzy i inwestycje budowlane",
        desc: "Bieżąca obsługa inwestycji — od projektu, przez umowy i relacje z wykonawcami, po spory i rękojmię.",
        items: ["umowy deweloperskie", "umowy o roboty budowlane", "relacje z wykonawcami", "rękojmia i wady inwestycji", "spory sądowe i pozasądowe"],
        path: "/deweloperzy",
      },
      {
        icon: "Layers",
        eyebrow: "Filar II",
        title: "Portfele wierzytelności i procesy masowe",
        desc: "EPU, sądy powszechne, postępowania klauzulowe i egzekucja — z integracjami i raportowaniem.",
        items: ["Elektroniczne Postępowanie Upominawcze", "sądy powszechne", "egzekucja", "integracje API", "raportowanie portfeli"],
        path: "/portfele-wierzytelnosci",
      },
      {
        icon: "Landmark",
        eyebrow: "Filar III",
        title: "Nieruchomości komercyjne i najem",
        desc: "Obsługa właścicieli, zarządców i asset managerów w sprawach najmu komercyjnego.",
        items: ["umowy najmu", "zabezpieczenia i gwarancje", "rozliczenia czynszu", "wypowiedzenia", "windykacja czynszów"],
        path: "/nieruchomosci-komercyjne",
      },
    ],
    metrics: [
      { sub: "Praktyka", num: "20+", lbl: "lat praktyki adwokackiej w Warszawie" },
      { sub: "Skala", num: "50 000+", lbl: "pozwów sądowych wniesionych w imieniu klientów" },
      { sub: "LegalTech", num: "8", lbl: "własnych aplikacji wspierających obsługę" },
      { sub: "Odpowiedzialność", num: "1", lbl: "adwokat odpowiedzialny za strategię i decyzje" },
    ],
    flowSteps: [
      { icon: "Database", label: "Dane", sub: "import, walidacja" },
      { icon: "FileText", label: "Dokumenty", sub: "przetwarzanie, AI, automatyzacja pism" },
      { icon: "Gavel", label: "Postępowanie", sub: "EPU · sąd powszechny" },
      { icon: "Activity", label: "Raporty", sub: "statusy, terminy, KPI" },
      { icon: "CheckCircle", label: "Egzekucja", sub: "klauzule, KM, rozliczenia" },
    ],
    flowEyebrow: "LegalTech kancelarii",
    flowTitle: "Technologia nie zastępuje decyzji prawnika. Wspiera przepustowość, jakość i kontrolę.",
    flowLead: "Najwięcej ryzyk powstaje nie na sali sądowej, ale wcześniej — w danych, dokumentach, terminach i komunikacji. Dlatego kancelaria rozwija własne narzędzia IT wspierające przepływ informacji, generowanie pism i raportowanie statusów spraw.",
    flowItems: ["import danych z systemów klienta", "automatyzacja dokumentów", "analiza i przetwarzanie dokumentów wspierane AI", "obsługa korespondencji", "raportowanie statusów", "EPU i postępowania egzekucyjne"],
    flowCta: "Zobacz rozwiązania LegalTech",
    models: [
      { no: "01.", title: "Stała obsługa prawna", desc: "Dla firm potrzebujących bieżącego wsparcia przy inwestycjach, umowach, najmie, ryzykach i sporach." },
      { no: "02.", title: "Projekt lub konkretna sprawa", desc: "Dla klientów potrzebujących reprezentacji w określonym sporze, negocjacji lub projekcie prawnym." },
      { no: "03.", title: "Obsługa portfela spraw", desc: "Dla podmiotów przekazujących większy wolumen spraw wymagających procesu, automatyzacji i raportowania." },
    ],
    aboutEyebrow: "O kancelarii",
    aboutTitle: "Kancelaria adwokacka dla klientów biznesowych",
    aboutLead: "Nazywam się Marcin Kuczyński. Jestem adwokatem i od 2006 r. prowadzę kancelarię w Warszawie. Wspieram firmy w sprawach, które wymagają nie tylko znajomości prawa, ale również rozumienia biznesu, procesu decyzyjnego, kosztów, ryzyka i organizacji pracy.",
    aboutCta: "Poznaj kancelarię",
    form: {
      name: "Imię i nazwisko",
      namePlaceholder: "Anna Wiśniewska",
      company: "Firma",
      companyPlaceholder: "Nazwa spółki",
      email: "E-mail",
      emailPlaceholder: "a.wisniewska@firma.pl",
      phone: "Telefon",
      topic: "Obszar sprawy",
      choose: "Wybierz obszar…",
      topics: ["Deweloperzy i inwestycje budowlane", "Portfele wierzytelności i procesy masowe", "Nieruchomości komercyjne i najem", "LegalTech / rozwiązania IT", "Inne"],
      message: "Wiadomość",
      messagePlaceholder: "Krótki opis sprawy lub modelu współpracy",
      consent: "Wyrażam zgodę na przetwarzanie podanych danych osobowych w celu odpowiedzi na zapytanie.",
      sending: "Wysyłanie wiadomości...",
      success: "Dziękuję — wiadomość została wysłana.",
      successToast: "Dziękuję — wiadomość została wysłana. Skontaktuję się w ciągu 1 dnia roboczego.",
      error: "Nie udało się wysłać wiadomości. Proszę spróbować ponownie albo napisać na info@kuczynski.eu.",
      submit: "Wyślij wiadomość",
      submitting: "Wysyłanie...",
      payloadTopic: "Obszar sprawy",
      payloadMissing: "nie wskazano",
      payloadCompany: "Firma",
      payloadPhone: "Telefon",
    },
    mobile: { label: "Szybki kontakt", call: "Zadzwoń", email: "E-mail", form: "Formularz" },
    footerDesc: "Kancelaria adwokacka dla klientów biznesowych. Bieżąca obsługa prawna, procesy i LegalTech.",
    footerServices: "Obszary obsługi",
    footerFirm: "Kancelaria",
    footerData: "Dane",
    footerAbout: "O kancelarii",
    footerContact: "Kontakt",
    footerCopyright: "2026 Kancelaria Adwokacka Marcin Kuczyński",
    langLabel: "English",
  },
  en: {
    brandSub: "Law Firm · Warsaw",
    navLabel: "Main navigation",
    openMenu: "Open menu",
    closeMenu: "Close menu",
    ctaTalk: "Schedule a call",
    nav: [
      { path: "/en/developers", label: "Developers" },
      { path: "/en/debt-portfolios", label: "Debt portfolios" },
      { path: "/en/commercial-real-estate", label: "Commercial real estate" },
      { path: "/en/legaltech", label: "LegalTech" },
      { path: "/en/about", label: "About" },
    ],
    heroEyebrow: "Law Firm · Warsaw",
    heroTitle: "Business legal support, litigation and LegalTech.",
    heroLead: "For 20 years I have supported developers, commercial real estate owners and companies managing debt portfolios in Poland — combining litigation experience with technology, reporting and direct attorney responsibility.",
    heroSecondary: "View practice areas",
    heroStrip: "Attorney-at-law · Warsaw · Business legal support · Litigation · EPU · Real estate · LegalTech",
    captionName: "Marcin Kuczyński, attorney-at-law",
    captionSince: "since 2006",
    servicesMore: "View service",
    services: [
      {
        icon: "Building",
        eyebrow: "Pillar I",
        title: "Developers and construction projects",
        desc: "Ongoing legal support for investments in Poland — from project documentation and contracts to contractors, defects, warranty claims and disputes.",
        items: ["development contracts", "construction works contracts", "contractor relations", "defects and warranty claims", "court and out-of-court disputes"],
        path: "/en/developers",
      },
      {
        icon: "Layers",
        eyebrow: "Pillar II",
        title: "Debt portfolios and high-volume litigation",
        desc: "EPU proceedings, civil courts, enforcement and status reporting supported by data imports, integrations and document automation.",
        items: ["Electronic Writ-of-Payment Proceedings", "civil court proceedings", "enforcement", "API integrations", "portfolio reporting"],
        path: "/en/debt-portfolios",
      },
      {
        icon: "Landmark",
        eyebrow: "Pillar III",
        title: "Commercial real estate and leases",
        desc: "Legal support for owners, property managers and asset managers in commercial lease matters in Poland.",
        items: ["lease agreements", "security instruments", "rent and service charge settlements", "terminations", "rent arrears recovery"],
        path: "/en/commercial-real-estate",
      },
    ],
    metrics: [
      { sub: "Practice", num: "20+", lbl: "years of attorney practice in Warsaw" },
      { sub: "Scale", num: "50,000+", lbl: "court claims filed on behalf of clients" },
      { sub: "LegalTech", num: "8", lbl: "in-house applications supporting legal work" },
      { sub: "Responsibility", num: "1", lbl: "attorney responsible for strategy and key decisions" },
    ],
    flowSteps: [
      { icon: "Database", label: "Data", sub: "import, validation" },
      { icon: "FileText", label: "Documents", sub: "processing, AI, document automation" },
      { icon: "Gavel", label: "Proceedings", sub: "EPU · civil courts" },
      { icon: "Activity", label: "Reports", sub: "statuses, deadlines, KPIs" },
      { icon: "CheckCircle", label: "Enforcement", sub: "enforcement titles, bailiffs, settlements" },
    ],
    flowEyebrow: "Law firm LegalTech",
    flowTitle: "Technology does not replace legal judgement. It supports throughput, quality and control.",
    flowLead: "Many risks arise before a court hearing: in data, documents, deadlines, statuses and communication. The law firm develops in-house tools for information flow, document generation and case status reporting.",
    flowItems: ["data imports from client systems", "document automation", "AI-supported document analysis and processing", "correspondence handling", "status reporting", "EPU and enforcement workflows"],
    flowCta: "View LegalTech operations",
    models: [
      { no: "01.", title: "Ongoing legal support", desc: "For companies that need day-to-day support with investments, contracts, leases, risks and disputes." },
      { no: "02.", title: "Project or specific matter", desc: "For clients seeking representation in a defined dispute, negotiation or legal project." },
      { no: "03.", title: "Portfolio handling", desc: "For organizations transferring larger volumes of matters requiring legal process, automation and reporting." },
    ],
    aboutEyebrow: "About the firm",
    aboutTitle: "A Warsaw law firm for business clients",
    aboutLead: "My name is Marcin Kuczyński. I am an attorney-at-law and have run my law firm in Warsaw since 2006. I support businesses in matters that require not only legal knowledge, but also an understanding of business decisions, costs, risk and operational workflow.",
    aboutCta: "About the firm",
    form: {
      name: "Full name",
      namePlaceholder: "Anna Wisniewska",
      company: "Company",
      companyPlaceholder: "Company name",
      email: "E-mail",
      emailPlaceholder: "a.wisniewska@company.com",
      phone: "Phone",
      topic: "Matter area",
      choose: "Select an area...",
      topics: ["Developers and construction projects", "Debt portfolios and high-volume litigation", "Commercial real estate and leases", "LegalTech / IT-enabled workflows", "Other"],
      message: "Message",
      messagePlaceholder: "Brief description of the matter or cooperation model",
      consent: "I consent to the processing of the provided personal data for the purpose of responding to this inquiry.",
      sending: "Sending message...",
      success: "Thank you - your message has been sent.",
      successToast: "Thank you - your message has been sent. I will reply within one business day.",
      error: "The message could not be sent. Please try again or write to info@kuczynski.eu.",
      submit: "Send message",
      submitting: "Sending...",
      payloadTopic: "Matter area",
      payloadMissing: "not specified",
      payloadCompany: "Company",
      payloadPhone: "Phone",
    },
    mobile: { label: "Quick contact", call: "Call", email: "E-mail", form: "Form" },
    footerDesc: "Warsaw law firm for business clients. Business legal support, litigation and LegalTech-enabled operations.",
    footerServices: "Practice areas",
    footerFirm: "Law firm",
    footerData: "Details",
    footerAbout: "About",
    footerContact: "Contact",
    footerCopyright: "2026 Kuczyński Law Firm · Marcin Kuczyński",
    langLabel: "Polski",
  },
};

function ui(locale) {
  return UI_COPY[locale] || UI_COPY.pl;
}

function Container({ children, narrow }) {
  return (
    <div className="container" style={narrow ? { maxWidth: 880 } : undefined}>
      {children}
    </div>
  );
}

function Section({ tone = "paper", children, id }) {
  return (
    <section className={`uk-section uk-section--${tone}`} id={id}>
      <Container>{children}</Container>
    </section>
  );
}

function Eyebrow({ children, onDark }) {
  return (
    <span className={`uk-eyebrow ${onDark ? "uk-eyebrow--on-dark" : ""}`}>
      {children}
    </span>
  );
}

function SectionHead({ eyebrow, title, lead, onDark }) {
  return (
    <div className="uk-section__head">
      {eyebrow ? <Eyebrow onDark={onDark}>{eyebrow}</Eyebrow> : null}
      <h2 className="uk-section__title">{title}</h2>
      {lead ? <p className="uk-section__lead">{lead}</p> : null}
    </div>
  );
}

// ---------- Buttons ----------

function Button({ kind = "primary", children, href, onClick, asLink, type = "button", disabled }) {
  const cls = `uk-btn uk-btn--${kind}`;
  if (asLink || href) {
    return (
      <a className={cls} href={href || "#"} onClick={onClick}>
        {children}
      </a>
    );
  }
  return (
    <button className={cls} onClick={onClick} type={type} disabled={disabled}>
      {children}
    </button>
  );
}

// ---------- Lucide-style icons (inline copies) ----------

const Icon = {
  ArrowRight: (p) => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
  ),
  Menu: (p) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M4 6h16"/><path d="M4 12h16"/><path d="M4 18h16"/></svg>
  ),
  X: (p) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
  ),
  Building: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z"/><path d="M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2"/><path d="M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"/><path d="M10 6h4"/><path d="M10 10h4"/><path d="M10 14h4"/></svg>
  ),
  Layers: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z"/><path d="m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65"/><path d="m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65"/></svg>
  ),
  Landmark: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><line x1="3" x2="21" y1="22" y2="22"/><line x1="6" x2="6" y1="18" y2="11"/><line x1="10" x2="10" y1="18" y2="11"/><line x1="14" x2="14" y1="18" y2="11"/><line x1="18" x2="18" y1="18" y2="11"/><polygon points="12 2 20 7 4 7"/></svg>
  ),
  Cpu: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="4" y="4" width="16" height="16" rx="2"/><rect x="9" y="9" width="6" height="6"/><path d="M15 2v2"/><path d="M15 20v2"/><path d="M2 15h2"/><path d="M2 9h2"/><path d="M20 15h2"/><path d="M20 9h2"/><path d="M9 2v2"/><path d="M9 20v2"/></svg>
  ),
  Database: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14a9 3 0 0 0 18 0V5"/><path d="M3 12a9 3 0 0 0 18 0"/></svg>
  ),
  FileText: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><line x1="16" x2="8" y1="13" y2="13"/><line x1="16" x2="8" y1="17" y2="17"/><line x1="10" x2="8" y1="9" y2="9"/></svg>
  ),
  Gavel: (p) => (
    /* used only as PROCESS icon, not "justice" — represents court step */
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="11" width="18" height="3"/><rect x="6" y="14" width="12" height="7" rx="0.5"/><path d="M8 11V5h8v6"/></svg>
  ),
  Activity: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
  ),
  CheckCircle: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
  ),
  Phone: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92Z"/></svg>
  ),
  Mail: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>
  ),
  MapPin: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 10c0 7-8 12-8 12s-8-5-8-12a8 8 0 0 1 16 0Z"/><circle cx="12" cy="10" r="3"/></svg>
  ),
  Linkedin: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-4 0v7h-4v-7a6 6 0 0 1 6-6z"/><rect width="4" height="12" x="2" y="9"/><circle cx="4" cy="4" r="2"/></svg>
  ),
};

// ---------- Header ----------

function Header({ route, routeKey = "home", locale = "pl" }) {
  const copy = ui(locale);
  const alternateLocale = locale === "en" ? "pl" : "en";
  const alternate = window.alternatePath ? window.alternatePath(routeKey, alternateLocale) : (locale === "en" ? "/" : "/en");
  const [isMenuOpen, setIsMenuOpen] = useState(false);

  useEffect(() => {
    setIsMenuOpen(false);
  }, [route]);

  return (
    <header className="uk-header">
      <Container>
        <div className="uk-header__inner">
          <a href={sitePath(locale === "en" ? "/en" : "/")} className="uk-header__brand">
            <img src={assetPath("logo.svg")} alt="" className="uk-header__mark" />
            <span className="uk-header__wordmark">
              <span className="uk-header__name">KUCZYŃSKI</span>
              <span className="uk-header__sub">{copy.brandSub}</span>
            </span>
          </a>
          <nav className={`uk-header__nav ${isMenuOpen ? "is-open" : ""}`} aria-label={copy.navLabel}>
            {copy.nav.map((n) => (
              <a key={n.path} href={sitePath(n.path)} className={route === n.path ? "is-active" : ""}>
                {n.label}
              </a>
            ))}
          </nav>
          <a className="uk-lang" href={sitePath(alternate)} hrefLang={alternateLocale}>{copy.langLabel}</a>
          <Button kind="primary" href={sitePath(locale === "en" ? "/en/contact" : "/kontakt")}>
            {copy.ctaTalk} <Icon.ArrowRight />
          </Button>
          <button
            className="uk-header__menu"
            type="button"
            aria-label={isMenuOpen ? copy.closeMenu : copy.openMenu}
            aria-expanded={isMenuOpen}
            onClick={() => setIsMenuOpen(!isMenuOpen)}
          >
            {isMenuOpen ? <Icon.X /> : <Icon.Menu />}
          </button>
        </div>
      </Container>
    </header>
  );
}

// ---------- Hero ----------

function Hero({ locale = "pl" }) {
  const copy = ui(locale);
  return (
    <section className="uk-hero tech-bg">
      <Container>
        <div className="uk-hero__grid">
          <div>
            <Eyebrow onDark>{copy.heroEyebrow}</Eyebrow>
            <h1 className="uk-hero__display">
              {copy.heroTitle}
            </h1>
            <p className="uk-hero__lead">
              {copy.heroLead}
            </p>
            <div className="uk-hero__cta">
              <Button kind="primary" href={sitePath(locale === "en" ? "/en/contact" : "/kontakt")}>
                {copy.ctaTalk} <Icon.ArrowRight />
              </Button>
              <Button kind="outline-light" href="#paths">
                {copy.heroSecondary}
              </Button>
            </div>
            <div className="uk-hero__strip">
              <div>{copy.heroStrip}</div>
            </div>
          </div>
          <div className="uk-hero__visual">
            <img src={assetPath("portrait-marcin.jpg")} alt="adw. Marcin Kuczyński" />
            <div className="uk-hero__caption">
              <span>{copy.captionName}</span>
              <span>{copy.captionSince}</span>
            </div>
          </div>
        </div>
      </Container>
    </section>
  );
}

// ---------- Service cards ----------

function ServiceCard({ eyebrow, title, desc, items, href, icon, more }) {
  const IconCmp = icon;
  return (
    <a className="uk-svc" href={href}>
      {IconCmp ? <IconCmp className="uk-svc__icon" /> : null}
      <Eyebrow>{eyebrow}</Eyebrow>
      <h3 className="uk-svc__title">{title}</h3>
      <p className="uk-svc__desc">{desc}</p>
      <ul className="uk-svc__list">
        {items.map((i) => <li key={i}>{i}</li>)}
      </ul>
      <span className="uk-svc__more">{more} <span className="arr">→</span></span>
    </a>
  );
}

function ServiceGrid({ locale = "pl" }) {
  const copy = ui(locale);
  return (
    <div id="paths" className="uk-services">
      {copy.services.map((service) => (
        <ServiceCard
          key={service.title}
          icon={Icon[service.icon]}
          eyebrow={service.eyebrow}
          title={service.title}
          desc={service.desc}
          items={service.items}
          href={sitePath(service.path)}
          more={copy.servicesMore}
        />
      ))}
    </div>
  );
}

// ---------- Metric strip ----------

function MetricStrip({ locale = "pl" }) {
  const items = ui(locale).metrics;
  return (
    <div className="uk-metrics">
      {items.map((m) => (
        <div className="uk-metric" key={m.sub}>
          <div className="uk-metric__sub">{m.sub}</div>
          <div className="uk-metric__num">{m.num}</div>
          <div className="uk-metric__lbl">{m.lbl}</div>
        </div>
      ))}
    </div>
  );
}

// ---------- LegalTech flow ----------

function LegalTechFlow({ locale = "pl" }) {
  const copy = ui(locale);
  const steps = copy.flowSteps;
  return (
    <div className="uk-flow">
      <div className="uk-flow__steps">
        <div className="uk-flow__line"></div>
        <div className="uk-flow__items">
          {steps.map((s) => {
            const IconCmp = Icon[s.icon];
            return (
              <div className="uk-flow__item" key={s.label}>
                <div className="uk-flow__node"><IconCmp /></div>
                <div className="uk-flow__step">{s.label}</div>
                <div className="uk-flow__sub">{s.sub}</div>
              </div>
            );
          })}
        </div>
      </div>
      <div>
        <Eyebrow onDark>{copy.flowEyebrow}</Eyebrow>
        <h2 className="uk-section__title" style={{ color: "var(--text-on-dark)" }}>
          {copy.flowTitle}
        </h2>
        <p style={{ color: "var(--text-on-dark-muted)", fontSize: 16, lineHeight: 1.65 }}>
          {copy.flowLead}
        </p>
        <ul className="uk-flow__list">
          {copy.flowItems.map((item) => <li key={item}>{item}</li>)}
        </ul>
        <div style={{ marginTop: 28 }}>
          <Button kind="primary" href={sitePath(locale === "en" ? "/en/legaltech" : "/legaltech")}>
            {copy.flowCta} <Icon.ArrowRight />
          </Button>
        </div>
      </div>
    </div>
  );
}

// ---------- Cooperation models ----------

function ModelsGrid({ locale = "pl" }) {
  const models = ui(locale).models;
  return (
    <div className="uk-models">
      {models.map((m) => (
        <div className="uk-model" key={m.no}>
          <div className="uk-model__no">{m.no}</div>
          <h3 className="uk-model__title">{m.title}</h3>
          <p className="uk-model__desc">{m.desc}</p>
        </div>
      ))}
    </div>
  );
}

// ---------- About teaser ----------

function AboutTeaser({ locale = "pl" }) {
  const copy = ui(locale);
  return (
    <div className="uk-about">
      <div className="uk-about__photo">
        <img src={assetPath("portrait-marcin.jpg")} alt="adw. Marcin Kuczyński" />
      </div>
      <div>
        <Eyebrow>{copy.aboutEyebrow}</Eyebrow>
        <h2 className="uk-section__title">{copy.aboutTitle}</h2>
        <p style={{ fontSize: 18, lineHeight: 1.65, color: "var(--text-700)" }}>
          {copy.aboutLead}
        </p>
        <div className="uk-about__sig">— adw. Marcin Kuczyński</div>
        <div style={{ marginTop: 28 }}>
          <Button kind="outline-dark" href={sitePath(locale === "en" ? "/en/about" : "/o-kancelarii")}>{copy.aboutCta}</Button>
        </div>
      </div>
    </div>
  );
}

// ---------- Contact form ----------

function ContactForm({ onSubmitted, locale = "pl" }) {
  const copy = ui(locale).form;
  const [status, setStatus] = useState({ type: "idle", message: "" });

  async function handleSubmit(e) {
    e.preventDefault();
    const form = e.currentTarget;
    const formData = new FormData(form);
    const name = String(formData.get("name") || "").trim();
    const company = String(formData.get("company") || "").trim();
    const email = String(formData.get("email") || "").trim();
    const phone = String(formData.get("phone") || "").trim();
    const topic = String(formData.get("topic") || "").trim();
    const rawMessage = String(formData.get("message") || "").trim();

    const message = [
      `${copy.payloadTopic}: ${topic || copy.payloadMissing}`,
      company ? `${copy.payloadCompany}: ${company}` : null,
      phone ? `${copy.payloadPhone}: ${phone}` : null,
      "",
      rawMessage,
    ].filter((line) => line !== null).join("\n");

    setStatus({ type: "sending", message: copy.sending });

    try {
      const response = await fetch(CONTACT_WORKER_URL, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name,
          email,
          message,
          company,
          phone,
          topic,
          source: window.location.href,
        }),
      });

      if (!response.ok) {
        throw new Error(`Worker returned ${response.status}`);
      }

      form.reset();
      setStatus({ type: "success", message: copy.success });
      onSubmitted && onSubmitted(copy.successToast);
    } catch (error) {
      setStatus({
        type: "error",
        message: copy.error,
      });
    }
  }

  const isSending = status.type === "sending";

  return (
    <form className="uk-form" onSubmit={handleSubmit}>
      <div className="uk-form__field">
        <label className="uk-form__label">{copy.name}</label>
        <input className="uk-form__input" name="name" type="text" placeholder={copy.namePlaceholder} required disabled={isSending} />
      </div>
      <div className="uk-form__field">
        <label className="uk-form__label">{copy.company}</label>
        <input className="uk-form__input" name="company" type="text" placeholder={copy.companyPlaceholder} disabled={isSending} />
      </div>
      <div className="uk-form__field">
        <label className="uk-form__label">{copy.email}</label>
        <input className="uk-form__input" name="email" type="email" placeholder={copy.emailPlaceholder} required disabled={isSending} />
      </div>
      <div className="uk-form__field">
        <label className="uk-form__label">{copy.phone}</label>
        <input className="uk-form__input" name="phone" type="tel" placeholder="+48" disabled={isSending} />
      </div>
      <div className="uk-form__field uk-form__field--full">
        <label className="uk-form__label">{copy.topic}</label>
        <select className="uk-form__select" name="topic" defaultValue="" required disabled={isSending}>
          <option value="" disabled>{copy.choose}</option>
          {copy.topics.map((topic) => <option key={topic}>{topic}</option>)}
        </select>
      </div>
      <div className="uk-form__field uk-form__field--full">
        <label className="uk-form__label">{copy.message}</label>
        <textarea className="uk-form__textarea" name="message" placeholder={copy.messagePlaceholder} required disabled={isSending} />
      </div>
      <label className="uk-form__rodo">
        <input className="uk-form__check" name="consent" type="checkbox" required disabled={isSending} />
        <span>{copy.consent}</span>
      </label>
      {status.message ? (
        <div className={`uk-form__status uk-form__status--${status.type}`} role="status" aria-live="polite">
          {status.message}
        </div>
      ) : null}
      <div className="uk-form__submit">
        <Button kind="primary" type="submit" disabled={isSending}>
          {isSending ? copy.submitting : copy.submit} <Icon.ArrowRight />
        </Button>
      </div>
    </form>
  );
}

// ---------- Mobile CTA ----------

function MobileCta({ locale = "pl" }) {
  const copy = ui(locale).mobile;
  return (
    <nav className="uk-mobile-cta" aria-label={copy.label}>
      <a href="tel:+48222472097">
        <Icon.Phone />
        <span>{copy.call}</span>
      </a>
      <a href="mailto:info@kuczynski.eu">
        <Icon.Mail />
        <span>{copy.email}</span>
      </a>
      <a href={sitePath(locale === "en" ? "/en/contact" : "/kontakt")}>
        <Icon.ArrowRight />
        <span>{copy.form}</span>
      </a>
    </nav>
  );
}

// ---------- Accordion ----------

function Accordion({ items }) {
  const [open, setOpen] = useState(0);
  return (
    <div className="uk-acc">
      {items.map((it, i) => (
        <div className="uk-acc__item" key={i}>
          <button className="uk-acc__btn" onClick={() => setOpen(open === i ? -1 : i)}>
            {it.q}
            <span className="uk-acc__plus">{open === i ? "–" : "+"}</span>
          </button>
          {open === i ? <div className="uk-acc__body">{it.a}</div> : null}
        </div>
      ))}
    </div>
  );
}

// ---------- Footer ----------

function Footer({ locale = "pl" }) {
  const copy = ui(locale);
  return (
    <footer className="uk-footer">
      <Container>
        <div className="uk-footer__grid">
          <div className="uk-footer__col">
            <a href={sitePath(locale === "en" ? "/en" : "/")} className="uk-header__brand" style={{ marginBottom: 18 }}>
              <img src={assetPath("logo.svg")} alt="" className="uk-header__mark" />
              <span className="uk-header__wordmark">
                <span className="uk-header__name">KUCZYŃSKI</span>
                <span className="uk-header__sub">{copy.brandSub}</span>
              </span>
            </a>
            <p>{copy.footerDesc}</p>
          </div>
          <div className="uk-footer__col">
            <h4>{copy.footerServices}</h4>
            {copy.nav.slice(0, 4).map((item) => (
              <a key={item.path} href={sitePath(item.path)}>{item.label}</a>
            ))}
          </div>
          <div className="uk-footer__col">
            <h4>{copy.footerFirm}</h4>
            <a href={sitePath(locale === "en" ? "/en/about" : "/o-kancelarii")}>{copy.footerAbout}</a>
            <a href={sitePath(locale === "en" ? "/en/contact" : "/kontakt")}>{copy.footerContact}</a>
          </div>
          <div className="uk-footer__col">
            <h4>{copy.footerData}</h4>
            <p>ul. Nowy Świat 53<br/>00-042 Warszawa</p>
            <p>tel. 22 247 20 97<br/>info@kuczynski.eu</p>
          </div>
        </div>
        <div className="uk-footer__bottom">
          <span>{copy.footerCopyright}</span>
        </div>
      </Container>
    </footer>
  );
}

// Export to window
Object.assign(window, {
  Container, Section, Eyebrow, SectionHead,
  Button, Icon,
  Header, Footer, Hero,
  ServiceCard, ServiceGrid,
  MetricStrip, LegalTechFlow, ModelsGrid, AboutTeaser,
  ContactForm, MobileCta, Accordion,
  UI_COPY, ui, sitePath, assetPath, CONTACT_WORKER_URL,
});
