/* global React */
// Shared chrome (header + footer) and layout helpers for inner pages.
// Nav links route to the homepage anchors; "Вики" stays within the section.
const { Button, Input, Textarea } = window.DoslovnoByDesignSystem_88f6e6;
const DBIcon = window.DBIcon;

const DB_MAXW = "var(--container-max)";

/* --------------------------------------------------- flags (brand-neutral) */
const FLAGS = {
  PL:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="30" height="10" fill="#fff"/><rect y="10" width="30" height="10" fill="#d4213d"/></svg>`,
  DE:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="30" height="6.67" fill="#1a1a1a"/><rect y="6.67" width="30" height="6.66" fill="#d7141a"/><rect y="13.33" width="30" height="6.67" fill="#ffce00"/></svg>`,
  LT:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="30" height="6.67" fill="#fdb913"/><rect y="6.67" width="30" height="6.66" fill="#006a44"/><rect y="13.33" width="30" height="6.67" fill="#c1272d"/></svg>`,
  CZ:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="30" height="10" fill="#fff"/><rect y="10" width="30" height="10" fill="#d7141a"/><polygon points="0,0 16,10 0,20" fill="#11457e"/></svg>`,
  IT:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="10" height="20" fill="#009246"/><rect x="10" width="10" height="20" fill="#fff"/><rect x="20" width="10" height="20" fill="#ce2b37"/></svg>`,
  ES:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="30" height="20" fill="#c60b1e"/><rect y="5" width="30" height="10" fill="#ffc400"/></svg>`,
  FR:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="10" height="20" fill="#0055a4"/><rect x="10" width="10" height="20" fill="#fff"/><rect x="20" width="10" height="20" fill="#ef4135"/></svg>`,
  NL:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="30" height="6.67" fill="#ae1c28"/><rect y="6.67" width="30" height="6.66" fill="#fff"/><rect y="13.33" width="30" height="6.67" fill="#21468b"/></svg>`,
  US:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="30" height="20" fill="#fff"/><g fill="#b22234"><rect width="30" height="2.2"/><rect y="4.4" width="30" height="2.2"/><rect y="8.8" width="30" height="2.2"/><rect y="13.2" width="30" height="2.2"/><rect y="17.6" width="30" height="2.2"/></g><rect width="13" height="11" fill="#3c3b6e"/></svg>`,
  CA:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="30" height="20" fill="#fff"/><rect width="7.5" height="20" fill="#d52b1e"/><rect x="22.5" width="7.5" height="20" fill="#d52b1e"/><circle cx="15" cy="10" r="3.4" fill="#d52b1e"/></svg>`,
  GB:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="30" height="20" fill="#012169"/><path d="M0,0 30,20 M30,0 0,20" stroke="#fff" stroke-width="4"/><path d="M0,0 30,20 M30,0 0,20" stroke="#c8102e" stroke-width="2"/><path d="M15,0 V20 M0,10 H30" stroke="#fff" stroke-width="6"/><path d="M15,0 V20 M0,10 H30" stroke="#c8102e" stroke-width="3.5"/></svg>`,
  AE:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="30" height="6.67" fill="#00843d"/><rect y="6.67" width="30" height="6.66" fill="#fff"/><rect y="13.33" width="30" height="6.67" fill="#1a1a1a"/><rect width="8" height="20" fill="#cd1126"/></svg>`,
  CN:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="30" height="20" fill="#de2910"/><circle cx="6" cy="6" r="2.6" fill="#ffde00"/></svg>`,
  IR:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="30" height="6.67" fill="#239f40"/><rect y="6.67" width="30" height="6.66" fill="#fff"/><rect y="13.33" width="30" height="6.67" fill="#da0000"/></svg>`,
  TM:`<svg viewBox="0 0 30 20" preserveAspectRatio="none"><rect width="30" height="20" fill="#1eb53a"/><rect width="7" height="20" fill="#d22630"/></svg>`,
};
const CODE3 = { PL:"POL", DE:"DEU", LT:"LTU", CZ:"CZE", US:"USA", CA:"CAN", IT:"ITA", ES:"ESP", FR:"FRA", NL:"NLD", GB:"GBR", AE:"ARE", CN:"CHN", IR:"IRN", TM:"TKM" };

// Префикс для ссылок: пустая строка из корня сайта, "../" из articles/
var LINK_PREFIX = (window.location.pathname.indexOf("/articles/") !== -1) ? "../" : "";

/* Country card with the flag-as-background treatment (settled variant):
   flag fills the right at 30% opacity behind a white→translucent fade;
   on hover the flag reaches full brightness and the fade clears. */
function FlagCard({ code, name, count, href }) {
  href = href || (LINK_PREFIX + "articles.html");
  const [hover, setHover] = React.useState(false);
  return (
    <a href={href} style={{ textDecoration: "none" }}>
      <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{ position: "relative", overflow: "hidden", display: "flex", alignItems: "center", gap: 13,
          border: `1px solid ${hover ? "var(--color-border-strong)" : "var(--color-border)"}`,
          borderRadius: "var(--radius-lg)", padding: "15px 16px", background: "var(--color-canvas)",
          transition: "border-color 140ms ease" }}>
        <span aria-hidden="true" style={{ position: "absolute", top: 0, right: 0, height: "100%", aspectRatio: "3 / 2", opacity: hover ? 1 : 0.3, transition: "opacity 250ms ease" }}
          dangerouslySetInnerHTML={{ __html: FLAGS[code] || "" }} />
        <span aria-hidden="true" style={{ position: "absolute", inset: 0, pointerEvents: "none",
          background: "linear-gradient(90deg, var(--color-canvas) 34%, rgba(255,255,255,0.45) 100%)",
          opacity: hover ? 0 : 1, transition: "opacity 250ms ease" }} />
        <div style={{ position: "relative", zIndex: 1 }}>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 13, letterSpacing: "0.04em", color: "var(--color-navy-deep)", lineHeight: 1, marginBottom: 4 }}>{CODE3[code] || code}</div>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16, color: "var(--color-ink)", lineHeight: 1.1, whiteSpace: "nowrap" }}>{name}</div>
          <div style={{ fontSize: 13, color: "var(--color-mute)", fontWeight: 600, marginTop: 2, whiteSpace: "nowrap" }}>{count} статей</div>
        </div>
      </div>
    </a>
  );
}

function DBSection({ children, bg = "var(--surface-page)", id, style = {}, pad = "80px 24px" }) {
  return (
    <section id={id} style={{ background: bg, padding: pad, ...style }}>
      <div style={{ maxWidth: DB_MAXW, margin: "0 auto" }}>{children}</div>
    </section>
  );
}

function DBEyebrow({ children, onDark = false }) {
  return (
    <div style={{
      fontSize: 13, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase",
      color: onDark ? "var(--color-primary)" : "#b06f12", marginBottom: 14,
    }}>{children}</div>
  );
}

const HEADER_LANGS = [["RU", "Русский"], ["BY", "Беларуская"], ["EN", "English"], ["PL", "Polski"]];
function LangSwitcher() {
  const [cur, setCur] = React.useState("RU");
  return (
    <div style={{ position: "relative", display: "inline-flex", alignItems: "center", gap: 6, border: "1px solid var(--color-border)", background: "var(--color-canvas)", borderRadius: "var(--radius-pill)", padding: "6px 26px 6px 12px" }}>
      <DBIcon name="globe" size={16} color="var(--color-navy-deep)" />
      <select aria-label="Язык сайта" value={cur} onChange={(e) => setCur(e.target.value)}
        style={{ appearance: "none", WebkitAppearance: "none", MozAppearance: "none", border: "none", outline: "none", background: "transparent", font: "inherit", fontFamily: "var(--font-body)", fontSize: 14, fontWeight: 700, color: "var(--color-navy-deep)", cursor: "pointer", padding: 0 }}>
        {HEADER_LANGS.map(([code, name]) => (<option key={code} value={code}>{name}</option>))}
      </select>
      <span style={{ position: "absolute", right: 12, pointerEvents: "none", fontSize: 10, color: "var(--color-mute)" }}>▾</span>
    </div>
  );
}

function DBHeader({ active }) {
  var p = LINK_PREFIX;
  const links = [
    ["Услуги", p + "index.html#services"],
    ["Доставка", p + "index.html#delivery"],
    ["Цены", p + "price.html", "prices"],
    ["Вики", p + "wiki.html", "wiki"],
    ["Контакты", p + "index.html#lead"],
  ];
  const [hover, setHover] = React.useState(null);
  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 30,
      background: "rgba(255,255,255,0.9)", backdropFilter: "saturate(140%) blur(10px)",
      borderBottom: "1px solid var(--color-border)",
    }}>
      <div style={{ maxWidth: DB_MAXW, margin: "0 auto", padding: "12px 24px", display: "flex", alignItems: "center", gap: 24 }}>
        <a href={LINK_PREFIX + "index.html"} style={{ textDecoration: "none", display: "flex", alignItems: "center", gap: 10 }}>
          <img src="assets/mark.svg" style={{ height: 30 }} alt="doslovno.by" />
          <span style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 22, color: "var(--color-navy-deep)", letterSpacing: "-0.02em" }}>
            doslovno<span style={{ color: "var(--color-primary)" }}>.by</span>
          </span>
        </a>
        <nav className="dby-nav-links" style={{ display: "flex", alignItems: "center", gap: 4, marginLeft: 22 }}>
          {links.map(([label, href, key]) => {
            const on = key === active;
            return (
              <a key={label} href={href}
                onMouseEnter={() => setHover(label)} onMouseLeave={() => setHover(null)}
                style={{
                  position: "relative", textDecoration: "none", fontSize: 15, fontWeight: 600,
                  padding: "8px 12px", borderRadius: "var(--radius-pill)",
                  color: on || hover === label ? "var(--color-navy-deep)" : "var(--color-body)",
                  transition: "color 120ms ease",
                }}>
                {label}
                {on && <span style={{ position: "absolute", left: 12, right: 12, bottom: 2, height: 2, background: "var(--color-primary)", borderRadius: 2 }} />}
              </a>
            );
          })}
        </nav>
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 14 }}>
          <LangSwitcher />
          <a href="tel:+375296234176" className="dby-phone" style={{ textDecoration: "none", fontWeight: 700, color: "var(--color-navy-deep)", fontSize: 15, whiteSpace: "nowrap" }}>+375 29 623-41-76</a>
          <Button variant="primary" size="sm" onClick={() => openArticleLead("")}>Рассчитать стоимость</Button>
        </div>
      </div>
    </header>
  );
}

function DBFooter() {
  var p = LINK_PREFIX;
  const col = (title, links) => (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      <div style={{ fontSize: 13, fontWeight: 700, color: "#fff", marginBottom: 2 }}>{title}</div>
      {links.map(([label, href]) => (
        <a key={label} href={href} style={{ textDecoration: "none", color: "var(--color-on-dark-mute)", fontSize: 14 }}>{label}</a>
      ))}
    </div>
  );
  return (
    <footer style={{ background: "var(--color-navy-deep)", color: "var(--color-on-dark)", padding: "56px 24px 32px" }}>
      <div style={{ maxWidth: DB_MAXW, margin: "0 auto" }}>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 48, justifyContent: "space-between" }}>
          <div style={{ maxWidth: 320 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
              <img src="assets/mark-light.svg" style={{ height: 30 }} alt="" />
              <span style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 22, color: "#fff", letterSpacing: "-0.02em" }}>
                doslovno<span style={{ color: "var(--color-primary)" }}>.by</span>
              </span>
            </div>
            <p style={{ margin: 0, fontSize: 14, lineHeight: "22px", color: "var(--color-on-dark-mute)" }}>
              Бюро нотариальных переводов в Минске. Рядом с визовым центром. Заберём и доставим документ по городу.
            </p>
          </div>
          {col("Услуги", [["Посольства", p + "index.html#services"], ["Выезд за границу", p + "index.html#services"], ["Учёба", p + "index.html#services"], ["Медицина", p + "index.html#services"]])}
          {col("Полезное", [["Вики: по странам", p + "wiki.html"], ["Цены", p + "index.html#prices"], ["Доставка по Минску", p + "index.html#delivery"]])}
          {col("Контакты", [["+375 29 623-41-76", p + "index.html#lead"], ["Оставить заявку", p + "index.html#lead"], ["Как нас найти", p + "index.html#delivery"]])}
        </div>
        <div style={{ marginTop: 44, paddingTop: 20, borderTop: "1px solid var(--color-border-dark)", display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8, fontSize: 13, color: "var(--color-on-dark-mute)" }}>
          <span>© 2026 doslovno.by · Минск</span>
          <span>Ценим ваше время</span>
        </div>
      </div>
    </footer>
  );
}

/* ---- lead modal для страниц статей (Article, Articles) ---- */
const ARTICLE_LEAD_ENDPOINT = "";

async function submitArticleLead(payload) {
  const lead = {
    id: Date.now().toString(36) + Math.random().toString(36).slice(2, 7),
    ts: new Date().toISOString(),
    page: typeof location !== "undefined" ? location.pathname : "",
    ...payload,
  };
  try {
    const k = "doslovno_leads";
    const all = JSON.parse(localStorage.getItem(k) || "[]");
    all.push(lead);
    localStorage.setItem(k, JSON.stringify(all));
  } catch (e) {}
  if (ARTICLE_LEAD_ENDPOINT) {
    await fetch(ARTICLE_LEAD_ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(lead) });
  }
  console.log("[lead]", lead);
  return lead;
}

function isPhoneOk(raw) { return (raw || "").replace(/\D/g, "").length >= 9; }

function ReqLabel({ text }) {
  return <span>{text} <span style={{ color: "var(--color-negative)" }}>*</span></span>;
}

function AgreementCheck(props) {
  return (
    <label style={{ display: "flex", gap: 10, alignItems: "flex-start", cursor: "pointer", fontSize: 13, color: props.error ? "var(--color-negative)" : "var(--color-mute)", lineHeight: 1.4, margin: 0 }}>
      <input type="checkbox" checked={props.checked} onChange={props.onChange} style={{ marginTop: 1, width: 16, height: 16, flexShrink: 0, accentColor: "#e8a02c", cursor: "pointer" }} />
      <span>Согласен на обработку персональных данных</span>
    </label>
  );
}

function ArticleLeadModal() {
  const [open, setOpen] = React.useState(false);
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [message, setMessage] = React.useState("");
  const [consent, setConsent] = React.useState(false);
  const [status, setStatus] = React.useState("idle");
  const [touched, setTouched] = React.useState(false);

  React.useEffect(() => {
    const onOpen = (e) => {
      setOpen(true);
      setMessage((e.detail && e.detail.message) || "");
      setName(""); setPhone(""); setConsent(false); setStatus("idle"); setTouched(false);
    };
    const onClose = () => setOpen(false);
    window.addEventListener("doslovno:article-lead-open", onOpen);
    window.addEventListener("doslovno:article-lead-close", onClose);
    return () => {
      window.removeEventListener("doslovno:article-lead-open", onOpen);
      window.removeEventListener("doslovno:article-lead-close", onClose);
    };
  }, []);

  React.useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const nameOk = name.trim().length > 0;
  const phoneOk = isPhoneOk(phone);

  const handleSubmit = async () => {
    setTouched(true);
    if (!nameOk || !phoneOk || !consent) return;
    setStatus("sending");
    try {
      await submitArticleLead({ kind: "article_lead", name: name.trim(), phone: "+375" + phone.replace(/\D/g, "").slice(-9), message: message.trim() });
      setStatus("sent");
    } catch (e) { setStatus("error"); }
  };

  if (!open) return null;

  return (
    <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(20,20,58,0.55)", backdropFilter: "blur(4px)", display: "flex", alignItems: "flex-start", justifyContent: "center", padding: "6vh 16px 16px", overflowY: "auto" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "100%", maxWidth: 460, position: "relative" }}>
        <button onClick={() => setOpen(false)} aria-label="Закрыть" style={{ position: "absolute", top: -42, right: 0, background: "transparent", border: "none", cursor: "pointer", color: "#fff", display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "var(--font-body)", fontSize: 15, fontWeight: 600 }}>
          Закрыть <DBIcon name="x" size={20} color="#fff" />
        </button>
        <div style={{ background: "var(--color-canvas)", border: "1px solid var(--color-border)", borderRadius: "var(--radius-xl)", padding: 24, fontFamily: "var(--font-body)" }}>
          {status === "sent" ? (
            <div style={{ textAlign: "center", padding: "32px 8px" }}>
              <div style={{ width: 56, height: 56, borderRadius: "50%", background: "var(--color-positive-pale)", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 14px" }}>
                <DBIcon name="check" size={28} color="var(--color-positive-deep)" />
              </div>
              <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 22, color: "var(--color-ink)", margin: "0 0 6px" }}>Заявка принята</h3>
              <p style={{ color: "var(--color-body)", margin: 0 }}>Перезвоним в течение 30 минут.</p>
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 22, color: "var(--color-ink)", margin: "0 0 2px" }}>Оставьте заявку</h3>
              <Input id="art-lead-name" label={<ReqLabel text="Имя" />} placeholder="Как к вам обращаться" value={name} onChange={(e) => setName(e.target.value)} error={touched && !nameOk ? "Укажите имя" : undefined} />
              <Input id="art-lead-phone" label={<ReqLabel text="Телефон" />} prefix="+375" placeholder="29 000-00-00" value={phone} onChange={(e) => setPhone(e.target.value)} error={touched && !phoneOk ? "Укажите номер телефона" : undefined} />
              <Textarea label="Что нужно перевести?" rows={2} placeholder="Например: свидетельство о рождении на польский, с заверением" value={message} onChange={(e) => setMessage(e.target.value)} />
              <AgreementCheck checked={consent} onChange={(e) => setConsent(e.target.checked)} error={touched && !consent} />
              <Button variant="primary" size="lg" fullWidth disabled={status === "sending"} onClick={handleSubmit}>{status === "sending" ? "Отправляем…" : "Отправить заявку"}</Button>
              {touched && (!nameOk || !phoneOk || !consent) ? <p style={{ fontSize: 13, color: "var(--color-negative)", textAlign: "center", margin: 0 }}>Заполните обязательные поля и отметьте согласие</p> : null}
              {status === "error" ? <p style={{ fontSize: 13, color: "var(--color-negative)", textAlign: "center", margin: 0 }}>Не удалось отправить. Позвоните нам или попробуйте ещё раз.</p> : null}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function openArticleLead(message) {
  window.dispatchEvent(new CustomEvent("doslovno:article-lead-open", { detail: { message: message || "" } }));
}

// Монтируем модал в отдельный корень — работает на любой странице, загружающей Shared.jsx
(function () {
  const el = document.createElement("div");
  document.body.appendChild(el);
  ReactDOM.createRoot(el).render(React.createElement(ArticleLeadModal));
}());

Object.assign(window, { DBSection, DBEyebrow, DBHeader, DBFooter, DB_MAXW, FlagCard, FLAGS, CODE3, openArticleLead });
