/* Language context + hash router + header + footer + flag SVGs. */

const LangCtx = React.createContext({ lang: "ka", setLang: () => {} });

const LangProvider = ({ children }) => {
  const [lang, setLangRaw] = React.useState(() => localStorage.getItem("mr.lang") || "ka");
  React.useEffect(() => {
    localStorage.setItem("mr.lang", lang);
    document.documentElement.setAttribute("lang", lang);
  }, [lang]);
  const setLang = (l) => setLangRaw(l);
  return <LangCtx.Provider value={{ lang, setLang }}>{children}</LangCtx.Provider>;
};
const useT = () => React.useContext(LangCtx);

/* ── Hash router ─────────────────────────────────────────── */
const RouteCtx = React.createContext({ path: "/", go: () => {} });
const RouterProvider = ({ children }) => {
  const get = () => (window.location.hash.replace(/^#/, "") || "/");
  const [path, setPath] = React.useState(get());
  React.useEffect(() => {
    const onHash = () => { setPath(get()); window.scrollTo(0, 0); };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  const go = (p) => { window.location.hash = p; };
  return <RouteCtx.Provider value={{ path, go }}>{children}</RouteCtx.Provider>;
};
const useRoute = () => React.useContext(RouteCtx);

const RLink = ({ to, className, style, children, onClick }) => {
  const { go } = useRoute();
  return (
    <a href={"#" + to}
       className={className}
       style={style}
       onClick={(e) => { e.preventDefault(); go(to); onClick && onClick(); }}>
      {children}
    </a>
  );
};

/* ── Flag SVGs ───────────────────────────────────────────── */
const FlagGE = (props) => (
  <svg viewBox="0 0 30 20" width={props.w || 18} height={props.h || 12} aria-label="Flag of Georgia"
       style={{ display: "inline-block", border: "1px solid var(--color-rule)", borderRadius: 1, verticalAlign: -1, ...props.style }}>
    <rect width="30" height="20" fill="#FFFFFF"/>
    <rect x="0" y="8" width="30" height="4" fill="#7B1E1E"/>
    <rect x="13" y="0" width="4" height="20" fill="#7B1E1E"/>
    <g fill="#7B1E1E">
      <rect x="5" y="3" width="3" height="1"/><rect x="6" y="2" width="1" height="3"/>
      <rect x="22" y="3" width="3" height="1"/><rect x="23" y="2" width="1" height="3"/>
      <rect x="5" y="16" width="3" height="1"/><rect x="6" y="15" width="1" height="3"/>
      <rect x="22" y="16" width="3" height="1"/><rect x="23" y="15" width="1" height="3"/>
    </g>
  </svg>
);
const FlagGB = (props) => (
  <svg viewBox="0 0 30 20" width={props.w || 18} height={props.h || 12} aria-label="Flag of the United Kingdom"
       style={{ display: "inline-block", border: "1px solid var(--color-rule)", borderRadius: 1, verticalAlign: -1, ...props.style }}>
    <rect width="30" height="20" fill="#012169"/>
    <path d="M0 0 L30 20 M30 0 L0 20" stroke="#FFFFFF" strokeWidth="3"/>
    <path d="M0 0 L30 20 M30 0 L0 20" stroke="#C8102E" strokeWidth="1.5"/>
    <path d="M15 0 V20 M0 10 H30" stroke="#FFFFFF" strokeWidth="5"/>
    <path d="M15 0 V20 M0 10 H30" stroke="#C8102E" strokeWidth="3"/>
  </svg>
);

/* ── Hover dropdown for nav (Products) ──────────────────── */
const NAV_EASE = "cubic-bezier(0.22,0.61,0.36,1)";

const NavDropdown = ({ active, label, children }) => {
  const [open, setOpen] = React.useState(false);
  const closeTimer = React.useRef(null);
  const openNow  = () => { clearTimeout(closeTimer.current); setOpen(true); };
  const closeSoon = () => { closeTimer.current = setTimeout(() => setOpen(false), 180); };
  const closeNow = () => { clearTimeout(closeTimer.current); setOpen(false); };
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => { window.removeEventListener("keydown", onKey); clearTimeout(closeTimer.current); };
  }, []);
  return (
    <div style={{ position: "relative" }} onMouseEnter={openNow} onMouseLeave={closeSoon}>
      <button
        type="button"
        onFocus={openNow}
        onClick={() => setOpen(o => !o)}
        aria-haspopup="menu"
        aria-expanded={open}
        style={{
          background: "transparent", border: 0, padding: 0, cursor: "pointer",
          fontFamily: "inherit", fontSize: 14,
          color: active ? "var(--color-ink)" : "var(--color-ink-2)",
          paddingBottom: 2,
          borderBottom: active ? "1px solid var(--color-ink)" : "1px solid transparent",
          transition: `border-color 200ms ${NAV_EASE}, color 200ms ${NAV_EASE}`,
          display: "inline-flex", alignItems: "center",
        }}
      >
        {label}
        <span aria-hidden style={{
          marginLeft: 6, fontSize: 9, opacity: 0.6,
          transform: open ? "rotate(180deg)" : "rotate(0deg)",
          transition: `transform 200ms ${NAV_EASE}`,
        }}>▾</span>
      </button>
      <div
        role="menu"
        onClick={closeNow}
        style={{
          position: "absolute", top: "calc(100% + 14px)", left: -18, zIndex: 30,
          opacity: open ? 1 : 0,
          transform: open ? "translateY(0)" : "translateY(-6px)",
          pointerEvents: open ? "auto" : "none",
          transition: `opacity 200ms ${NAV_EASE}, transform 200ms ${NAV_EASE}`,
        }}
      >
        {children}
      </div>
    </div>
  );
};

const SectorRow = ({ item, lang }) => {
  const [hov, setHov] = React.useState(false);
  return (
    <RLink
      to={item.href}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        display: "flex", alignItems: "center", gap: 14,
        padding: "10px 12px", margin: "2px 0",
        border: 0, borderRadius: 10,
        color: "var(--color-ink)", textDecoration: "none",
        background: hov ? "rgba(27,22,18,0.045)" : "transparent",
        transition: `background 180ms ${NAV_EASE}`,
      }}
    >
      <span style={{
        width: 30, height: 30, borderRadius: 8,
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        fontSize: 11, fontWeight: 600, letterSpacing: "0.04em",
        color: hov ? "var(--color-ink)" : "var(--color-ink-2)",
        background: hov ? "rgba(27,22,18,0.06)" : "rgba(27,22,18,0.035)",
        transition: `background 180ms ${NAV_EASE}, color 180ms ${NAV_EASE}`,
      }}>{item.num}</span>
      <span style={{ flex: 1, fontSize: 14, fontWeight: 500, lineHeight: 1.3,
                     letterSpacing: "-0.005em" }}>{item[lang]}</span>
      <span aria-hidden style={{
        fontSize: 14, color: hov ? "var(--color-ink-2)" : "var(--color-ink-4)",
        transform: hov ? "translateX(4px)" : "translateX(0)",
        transition: `transform 200ms ${NAV_EASE}, color 200ms ${NAV_EASE}`,
      }}>→</span>
    </RLink>
  );
};

const ProductsMenu = ({ lang }) => {
  const p = window.MR.products;
  const f = p.featured;
  const [ctaHov, setCtaHov] = React.useState(false);
  return (
    <div style={{
      width: 380,
      background: "rgba(255,255,255,0.92)",
      backdropFilter: "blur(16px) saturate(140%)",
      WebkitBackdropFilter: "blur(16px) saturate(140%)",
      border: "1px solid rgba(27,22,18,0.08)",
      borderRadius: 16,
      boxShadow: "0 4px 12px rgba(27,22,18,0.04), 0 24px 48px -8px rgba(27,22,18,0.12)",
      overflow: "hidden",
    }}>
      <RLink to={f.href}
        onMouseEnter={() => setCtaHov(true)}
        onMouseLeave={() => setCtaHov(false)}
        style={{
          display: "block", padding: "22px 22px 20px",
          border: 0, color: "var(--color-ink)", textDecoration: "none",
        }}>
        <div style={{
          display: "inline-flex", alignItems: "center", gap: 8,
          fontSize: 11, fontWeight: 600, letterSpacing: "0.04em",
          textTransform: "uppercase",
          color: "var(--color-accent)",
          padding: "4px 10px 4px 8px",
          background: "rgba(123,30,30,0.08)",
          borderRadius: 100,
          marginBottom: 14,
        }}>
          <span style={{
            width: 6, height: 6, borderRadius: "50%",
            background: "var(--color-accent)",
            boxShadow: "0 0 0 3px rgba(123,30,30,0.15)",
          }} />
          {f.eyebrow[lang]}
        </div>
        <div style={{
          fontSize: 24, fontWeight: 600, lineHeight: 1.15,
          letterSpacing: "-0.02em", marginBottom: 6,
        }}>
          {f.name}
        </div>
        <div style={{
          fontSize: 14, lineHeight: 1.5, color: "var(--color-ink-2)",
          marginBottom: 14,
        }}>
          {f.tagline[lang]}
        </div>
        <div style={{
          display: "inline-flex", alignItems: "center", gap: 6,
          fontSize: 13, fontWeight: 500,
          color: "var(--color-ink)",
        }}>
          {f.cta[lang].replace(" →", "")}
          <span aria-hidden style={{
            transform: ctaHov ? "translateX(4px)" : "translateX(0)",
            transition: `transform 200ms ${NAV_EASE}`,
          }}>→</span>
        </div>
      </RLink>
      <div style={{ borderTop: "1px solid rgba(27,22,18,0.06)", padding: "12px" }}>
        <div style={{
          padding: "4px 12px 8px",
          fontSize: 10, fontWeight: 600, letterSpacing: "0.06em",
          color: "var(--color-ink-3)", textTransform: "uppercase",
        }}>
          {p.sectorsLabel[lang]}
        </div>
        {p.sectors.map(s => <SectorRow key={s.href} item={s} lang={lang} />)}
      </div>
    </div>
  );
};

/* ── Mobile menu (hamburger → dropdown with nav + lang) ── */
const MobileMenu = () => {
  const { lang, setLang } = useT();
  const { path } = useRoute();
  const [open, setOpen] = React.useState(false);
  const close = () => setOpen(false);
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);
  return (
    <div className="mr-mobile-menu">
      <button
        className="mr-mobile-menu__trigger"
        type="button"
        onClick={() => setOpen(o => !o)}
        aria-haspopup="menu"
        aria-expanded={open}
        aria-label="Menu"
      >
        <span className={`mr-mobile-menu__icon${open ? " is-open" : ""}`}>
          <span/><span/><span/>
        </span>
      </button>
      <div className={`mr-mobile-menu__panel${open ? " is-open" : ""}`} role="menu">
        <div className="mr-mobile-menu__items" onClick={close}>
          {window.MR.routes.slice(1).map(r => {
            const active = path === r.path || (r.path !== "/" && path.startsWith(r.path));
            return (
              <RLink key={r.path} to={r.path}
                     className={`mr-mobile-menu__item${active ? " is-active" : ""}`}>
                {r[lang]}
              </RLink>
            );
          })}
        </div>
        <div className="mr-mobile-menu__lang">
          <button
            type="button"
            className={`mr-mobile-menu__lang-btn${lang === "ka" ? " is-active" : ""}`}
            onClick={() => { setLang("ka"); }}
          ><FlagGE/> KA</button>
          <button
            type="button"
            className={`mr-mobile-menu__lang-btn${lang === "en" ? " is-active" : ""}`}
            onClick={() => { setLang("en"); }}
          ><FlagGB/> EN</button>
        </div>
      </div>
    </div>
  );
};

/* ── Header ──────────────────────────────────────────────── */
const Header = () => {
  const { lang, setLang } = useT();
  const { path } = useRoute();
  const opp = (l) => (l === "ka" ? "var(--color-ink-3)" : "var(--color-ink)");
  return (
    <header style={{ position: "sticky", top: 0, zIndex: 20, background: "var(--color-bg)", borderBottom: "1px solid var(--color-rule)" }}>
      <div style={{ maxWidth: 1440, margin: "0 auto", padding: "16px 32px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 32 }}>
        <RLink to="/" style={{ display: "inline-flex", alignItems: "center", border: 0 }} aria-label={window.MR.brand.name}>
          <img src="../brand/logo-lockup.png" alt={window.MR.brand.name} style={{ height: 120, display: "block" }} />
        </RLink>
        <nav style={{ display: "flex", gap: 28, alignItems: "center" }}>
          {window.MR.routes.slice(1).map(r => {
            const active = path === r.path || (r.path !== "/" && path.startsWith(r.path));
            if (r.path === "/technology") {
              return (
                <NavDropdown key={r.path} active={active} label={r[lang]}>
                  <ProductsMenu lang={lang} />
                </NavDropdown>
              );
            }
            return (
              <RLink key={r.path} to={r.path}
                     style={{ fontSize: 14, color: active ? "var(--color-ink)" : "var(--color-ink-2)",
                              border: 0, paddingBottom: 2,
                              borderBottom: active ? "1px solid var(--color-ink)" : "1px solid transparent",
                              transition: "border-color 200ms cubic-bezier(0.22,0.61,0.36,1)" }}>
                {r[lang]}
              </RLink>
            );
          })}
        </nav>
        <div className="mr-lang-desktop" style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 13, letterSpacing: "0.04em" }}>
          <button className="mr-lang-btn" onClick={() => setLang("ka")} style={{ background: "transparent", border: 0, padding: 0, cursor: "pointer", color: lang==="ka" ? "var(--color-ink)" : "var(--color-ink-3)", display: "inline-flex", alignItems: "center", gap: 6 }}><FlagGE/> KA</button>
          <span style={{ color: "var(--color-ink-4)" }}>|</span>
          <button className="mr-lang-btn" onClick={() => setLang("en")} style={{ background: "transparent", border: 0, padding: 0, cursor: "pointer", color: lang==="en" ? "var(--color-ink)" : "var(--color-ink-3)", display: "inline-flex", alignItems: "center", gap: 6 }}><FlagGB/> EN</button>
        </div>
        <MobileMenu />
      </div>
    </header>
  );
};

/* ── Footer ──────────────────────────────────────────────── */
const Footer = () => {
  const { lang } = useT();
  const f = window.MR.footer;
  return (
    <footer style={{ borderTop: "1px solid var(--color-ink)", padding: "96px 0 32px", marginTop: 96 }}>
      <div style={{ maxWidth: 1440, margin: "0 auto", padding: "0 32px", display: "grid", gridTemplateColumns: "1.5fr 1fr 1.2fr", gap: 32 }}>
        <div style={{ position: "relative" }}>
          <img src="../brand/logo-lockup.png" alt={window.MR.brand.name} style={{ height: 72, display: "block", position: "absolute", bottom: "calc(100% + 12px)", left: 0 }} />
          <div style={{ fontSize: 13, color: "var(--color-ink-3)" }}>{window.MR.brand.tag[lang]}</div>
          <div style={{ fontSize: 14, marginTop: 24, lineHeight: 1.7, color: "var(--color-ink-2)" }}>
            <div>{f.contact.addr}</div>
            <div><a href={"mailto:" + f.contact.email}>{f.contact.email}</a></div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 13 }}>{f.contact.phone}</div>
          </div>
        </div>
        <div>
          <span className="eyebrow" style={{ display: "block", marginBottom: 14 }}>{lang === "ka" ? "ნავიგაცია" : "Navigate"}</span>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
            {window.MR.routes.slice(1).map(r => (
              <li key={r.path}><RLink to={r.path} style={{ fontSize: 14, color: "var(--color-ink)", border: 0 }}>{r[lang]}</RLink></li>
            ))}
          </ul>
        </div>
        <div style={{ textAlign: "right" }}>
          <span className="eyebrow" style={{ display: "block", marginBottom: 14 }}>{lang === "ka" ? "წარმოშობა" : "Provenance"}</span>
          <div style={{ fontSize: 14, color: "var(--color-ink)" }}>{f.sign.ka}</div>
          <div style={{ fontSize: 14, color: "var(--color-ink-2)", marginTop: 4, display: "inline-flex", alignItems: "center", gap: 8 }}>
            {f.sign.en} <FlagGE/>
          </div>
        </div>
      </div>
      <div style={{ maxWidth: 1440, margin: "48px auto 0", padding: "0 32px", borderTop: "1px solid var(--color-rule)", paddingTop: 20, fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--color-ink-3)" }}>
        {f.legal}
      </div>
    </footer>
  );
};

Object.assign(window, { LangProvider, RouterProvider, useT, useRoute, RLink, FlagGE, FlagGB, Header, Footer });
