const DS = window.AutoMonitorDesignSystem_a17e1e;
const { Button, Badge, Icon, TextInput, FeatureCard } = DS;
const { useState, useEffect, useRef } = React;
const SITE = window.AM_SITE;

/* Renders [placeholder] values in mono so it's obvious what still needs real data. */
function Val({ children }) {
  const s = String(children || "");
  return /^\[.*\]$/.test(s) ? <span className="mn-placeholder-val">{s}</span> : <span>{s}</span>;
}

const AM_PAGE_KEY = (location.pathname.split("/").pop() || "index").replace(/\.html?$/, "");
let amSlotSeq = 0;
function slotId(label) {
  amSlotSeq += 1;
  return AM_PAGE_KEY + "-slot-" + amSlotSeq + "-" + String(label || "").toLowerCase().replace(/[^a-zа-я0-9]+/gi, "-").slice(0, 24);
}

/* Renders a real photo when one is supplied; otherwise keeps the fillable slot. */
function ImagePh({ label, ratio = "16x9", tone, style, className = "", src, w, h, eager = false }) {
  const idRef = React.useRef(null);
  if (!idRef.current) idRef.current = slotId(label);
  return (
      <div className={`mn-ph mn-ph-${ratio} ${className}`} data-tone={tone} style={style}>
        {src
          ? <img src={src} alt={label} width={w} height={h} loading={eager ? "eager" : "lazy"} decoding={eager ? "sync" : "async"} />
          : <image-slot id={idRef.current} shape="rect" placeholder={label} aria-label={label}></image-slot>}
      </div>
  );
}

function Meta({ items }) {
  return (
    <div className="mn-meta">
      {items.filter(Boolean).map((it, i) => (
        <React.Fragment key={i}>
          {i > 0 ? <span aria-hidden="true">·</span> : null}
          <span>{it}</span>
        </React.Fragment>
      ))}
    </div>
  );
}

function AffiliateCTA({ label = "Виж актуална цена", product, variant = "primary", fullWidth = false, retailer }) {
  const shop = retailer || (product && /Ozone/.test(product.affiliateUrl) ? "Ozone.bg" : "eMAG");
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6, alignItems: "flex-start", width: fullWidth ? "100%" : "auto" }}>
      <Button
        variant={variant}
        href="#"
        rel="sponsored nofollow"
        fullWidth={fullWidth}
        aria-label={`${label} - ${product ? product.name : "продукта"} в ${shop} (партньорски линк)`}
        iconRight={<Icon name="arrow-up-right" size={16} />}
      >
        {label}
      </Button>
      <span className="mn-aff-note">Партньорски линк · {shop}</span>
    </div>
  );
}

function Disclosure({ compact = false }) {
  return (
    <p className="mn-disclosure" style={{ margin: 0 }}>
      <strong style={{ fontWeight: 500, color: "var(--color-ink-muted)" }}>Партньорски връзки: </strong>
      {compact ? "Част от линковете тук са партньорски. Ако купиш през тях, можем да получим комисиона без допълнителен разход за теб." : SITE.disclosure}
    </p>
  );
}

function Breadcrumbs({ trail }) {
  return (
    <nav aria-label="Навигация по нива" style={{ marginBottom: "var(--space-md)" }}>
      <ol style={{ listStyle: "none", display: "flex", flexWrap: "wrap", gap: 8, margin: 0, padding: 0, fontSize: "var(--text-caption-size)", color: "var(--color-ink-subtle)" }}>
        {trail.map((t, i) => (
          <li key={i} style={{ display: "flex", gap: 8, alignItems: "center" }}>
            {t.href ? <a href={t.href} style={{ color: "var(--color-ink-subtle)" }}>{t.label}</a> : <span aria-current="page">{t.label}</span>}
            {i < trail.length - 1 ? <span aria-hidden="true">/</span> : null}
          </li>
        ))}
      </ol>
    </nav>
  );
}

function SearchPanel({ onClose }) {
  const [q, setQ] = useState("");
  const inputRef = useRef(null);
  useEffect(() => { inputRef.current && inputRef.current.focus(); }, []);
  useEffect(() => {
    const h = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);
  const hits = window.AM_ARTICLES.filter((a) => {
    if (!q.trim()) return false;
    const hay = (a.title + " " + a.excerpt + " " + a.category + " " + a.keywords.join(" ")).toLowerCase();
    return hay.includes(q.trim().toLowerCase());
  });
  return (
    <React.Fragment>
      <div className="mn-scrim" onClick={onClose} />
      <div className="mn-search-panel" role="dialog" aria-label="Търсене в AutoMonitor">
        <div className="mn-wrap" style={{ display: "flex", flexDirection: "column", gap: "var(--space-md)" }}>
          <div style={{ display: "flex", gap: "var(--space-sm)", alignItems: "center" }}>
            <div className="mn-field" style={{ flex: 1 }}>
              <label className="mn-eyebrow" htmlFor="mn-search">Търси в AutoMonitor…</label>
              <input id="mn-search" ref={inputRef} type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder="напр. видеорегистратор за нощно шофиране" />
            </div>
            <button className="mn-iconbtn" onClick={onClose} aria-label="Затвори търсенето" style={{ alignSelf: "flex-end", height: 44 }}><Icon name="x" size={20} /></button>
          </div>
          {q.trim() ? (
            hits.length ? (
              <div style={{ display: "grid", gap: 8 }}>
                {hits.map((a) => (
                  <a key={a.slug} className="mn-search-result" href={a.slug}>
                    <span className="mn-eyebrow" style={{ color: "var(--color-ink-subtle)" }}>{a.category}</span>
                    <span style={{ fontWeight: 500 }}>{a.title}</span>
                  </a>
                ))}
              </div>
            ) : (
              <p className="mn-muted" style={{ margin: 0, fontSize: "var(--text-body-sm-size)" }}>Няма резултати за „{q}“. Пробвай „видеорегистратор“, „монтаж“ или „сравнение“.</p>
            )
          ) : (
            <div className="mn-row">
              <span className="mn-aff-note">Популярни търсения:</span>
              {["видеорегистратор", "монтаж", "нощно шофиране", "сравнение"].map((s) => (
                <button key={s} className="mn-chip" onClick={() => setQ(s)}>{s}</button>
              ))}
            </div>
          )}
        </div>
      </div>
    </React.Fragment>
  );
}

function Header({ active, showCta = true }) {
  const [scrolled, setScrolled] = useState(false);
  const [menu, setMenu] = useState(false);
  const [search, setSearch] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    const h = (e) => { if (e.key === "Escape") setMenu(false); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, []);
  return (
    <React.Fragment>
      <header className="mn-header" data-scrolled={String(scrolled)}>
        <div className="mn-wrap mn-header-inner">
          <a className="mn-brand mn-brand-nav" href="index.html"><span className="mn-brand-mark" aria-hidden="true" />AutoMonitor</a>
          <nav className="mn-nav" aria-label="Основна навигация">
            {SITE.nav.map((l) => (
              <a key={l.href} href={l.href} aria-current={l.label === active ? "page" : undefined}>{l.label}</a>
            ))}
          </nav>
          <div className="mn-header-actions">
            <button className="mn-iconbtn" onClick={() => setSearch(true)} aria-label="Търси в сайта"><Icon name="search" size={18} /></button>
            {showCta ? (
              <span className="mn-header-cta">
                <Button variant="secondary" href="blog-top-7-videoregistratori.html">Виж препоръчаните видеорегистратори</Button>
              </span>
            ) : null}
            <button className="mn-iconbtn mn-burger" onClick={() => setMenu(true)} aria-label="Отвори менюто" aria-expanded={menu}><Icon name="menu" size={20} /></button>
          </div>
        </div>
      </header>
      {menu ? (
        <React.Fragment>
          <div className="mn-scrim" onClick={() => setMenu(false)} />
          <div className="mn-drawer" role="dialog" aria-label="Меню">
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <span className="mn-brand">AutoMonitor</span>
              <button className="mn-iconbtn" onClick={() => setMenu(false)} aria-label="Затвори менюто"><Icon name="x" size={20} /></button>
            </div>
            <nav aria-label="Мобилна навигация">
              {SITE.nav.map((l) => <a key={l.href} href={l.href} aria-current={l.label === active ? "page" : undefined}>{l.label}</a>)}
            </nav>
            <Button variant="primary" href="blog-top-7-videoregistratori.html" fullWidth>Виж препоръчаните видеорегистратори</Button>
            <p className="mn-aff-note" style={{ marginTop: "auto" }}>{SITE.promise}<br />{SITE.city}</p>
          </div>
        </React.Fragment>
      ) : null}
      {search ? <SearchPanel onClose={() => setSearch(false)} /> : null}
    </React.Fragment>
  );
}

function Newsletter({ tone = "card" }) {
  const [email, setEmail] = useState("");
  const [sent, setSent] = useState(false);
  return (
    <section className={tone === "tinted" ? "mn-tinted" : "mn-card mn-card-hair"} aria-labelledby="nl-title" style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr)", gap: "var(--space-md)" }}>
      <div>
        <h2 id="nl-title" className="am-card-title" style={{ margin: 0 }}>Едно писмо, когато има какво да се каже</h2>
        <p className="mn-muted" style={{ margin: "var(--space-xxs) 0 0", maxWidth: "60ch" }}>Нови ръководства и обновени класации. Без реклами и без седмичен спам.</p>
      </div>
      {sent ? (
        <p style={{ margin: 0, fontSize: "var(--text-body-sm-size)" }}>Благодарим - записахме {email}. Ще получиш писмо само когато публикуваме нещо ново.</p>
      ) : (
        <form style={{ display: "flex", gap: "var(--space-sm)", flexWrap: "wrap", alignItems: "flex-end" }} onSubmit={(e) => { e.preventDefault(); if (email) setSent(true); }}>
          <div className="mn-field" style={{ flex: "1 1 260px" }}>
            <label htmlFor="nl-email">Имейл</label>
            <input id="nl-email" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="ime@example.bg" />
          </div>
          <Button variant="primary" onClick={() => {}}>Абонирай се</Button>
        </form>
      )}
      <p className="mn-aff-note" style={{ margin: 0 }}>Отписваш се с един клик. Не споделяме имейли с трети страни.</p>
    </section>
  );
}

function AdSlot({ label = "Рекламирай тук - продължи да четеш надолу" }) {
  return (
    <aside className="mn-ad" aria-label="Рекламна позиция">
      <div className="mn-ad-inner"><span>{label}</span></div>
    </aside>
  );
}

function Footer() {
  return (
    <footer className="mn-footer">
      <div className="mn-wrap">
        <div className="mn-footer-grid">
          <div className="mn-footer-col" style={{ gap: "var(--space-sm)" }}>
            <span className="mn-brand mn-brand-nav"><span className="mn-brand-mark" aria-hidden="true" />AutoMonitor</span>
            <p className="mn-subtle" style={{ margin: 0, fontSize: "var(--text-caption-size)", lineHeight: 1.6, maxWidth: "32ch" }}>
              Независим български сайт за автомобилна техника и аксесоари. Превеждаме спецификациите на разбираем език и сравняваме продуктите според реалната им употреба.
            </p>
            <span className="mn-subtle" style={{ fontSize: "var(--text-caption-size)" }}>{SITE.city}</span>
          </div>
          {SITE.footer.map((col) => (
            <div className="mn-footer-col" key={col.title}>
              <span>{col.title}</span>
              {col.links.map((l) => <a key={l.label} href={l.href}>{l.label}</a>)}
            </div>
          ))}
        </div>
        <div className="mn-footer-bottom">
          <span className="mn-brand-nav" style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>© 2026 <span className="mn-brand-mark" aria-hidden="true" />AutoMonitor. Всички права запазени.</span>
          <span>{SITE.promise}</span>
        </div>
      </div>
    </footer>
  );
}

function ArticleCard({ article, size = "md" }) {
  const im = article.images || {};
  return (
    <article className="mn-acard">
      <a href={article.slug} aria-label={article.title}>
        <ImagePh ratio={size === "lg" ? "3x2" : "16x9"} label={article.heroAlt} src={size === "lg" ? im.wide32 : im.card} w={size === "lg" ? 1400 : 1200} h={size === "lg" ? 933 : 675} />
      </a>
      <div className="mn-acard-body">
        <span className="mn-eyebrow">{article.category}</span>
        <h3><a href={article.slug}>{article.title}</a></h3>
        <p>{article.excerpt}</p>
        <Meta items={[article.readingTime + " четене", "Публикувано: " + article.publishedAt]} />
      </div>
    </article>
  );
}

function FeaturedArticle({ article }) {
  return (
    <article className="mn-featured">
      <a href={article.slug} aria-label={article.title} style={{ minWidth: 0, overflow: "hidden", display: "block" }}><ImagePh ratio="4x3" label={article.heroAlt} src={(article.images || {}).featured} w={1400} h={1050} eager /></a>
      <div className="mn-featured-body">
        <div className="mn-row">
          <Badge tone="inverse">Основно ръководство</Badge>
          <span className="mn-eyebrow">{article.category}</span>
        </div>
        <h2 className="am-display-md" style={{ margin: 0, textWrap: "pretty" }}>
          <a href={article.slug}>Най-добрите видеорегистратори за 2026 година</a>
        </h2>
        <p className="mn-muted" style={{ margin: 0, fontSize: "var(--text-body-lg-size)" }}>{article.excerpt}</p>
        <Meta items={[article.readingTime + " четене", "Публикувано: " + article.publishedAt, SITE.author.name]} />
        <div className="mn-row" style={{ marginTop: "var(--space-xs)" }}>
          <Button variant="primary" href={article.slug} iconRight={<Icon name="arrow-right" size={16} />}>Прочети ръководството</Button>
        </div>
      </div>
    </article>
  );
}

function ProductRecCard({ product, award, showRank }) {
  return (
    <div className="mn-card mn-card-hair" style={{ display: "flex", flexDirection: "column", gap: "var(--space-sm)" }}>
      <div className="mn-row">
        {showRank ? <span className="mn-rank">{showRank}</span> : null}
        <Badge tone="neutral">{award || product.award}</Badge>
      </div>
      <ImagePh ratio="4x3" label={product.imageAlt} src={product.image} className={product.image ? "mn-ph-product" : ""} w={800} h={800} />
      <div>
        <h3 className="am-card-title" style={{ margin: 0 }}>{product.name}</h3>
        <p className="mn-muted" style={{ margin: "var(--space-xxs) 0 0", fontSize: "var(--text-body-sm-size)" }}>{product.benefit}</p>
      </div>
      <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "flex", flexDirection: "column", gap: 6 }}>
        {product.pros.slice(0, 3).map((p) => (
          <li key={p} style={{ display: "flex", gap: 8, fontSize: "var(--text-body-sm-size)", color: "var(--color-ink-muted)", alignItems: "flex-start" }}>
            <span aria-hidden="true" style={{ color: "var(--color-ink)", fontWeight: 700, lineHeight: 1.4, flex: "0 0 auto" }}>•</span>{p}
          </li>
        ))}
      </ul>
      <div style={{ marginTop: "auto", paddingTop: "var(--space-sm)" }}>
        <span className="mn-aff-note" style={{ display: "block", marginBottom: 8 }}>Подходящ за: {product.bestFor}</span>
        <AffiliateCTA product={product} retailer={product.retailer} fullWidth />
      </div>
    </div>
  );
}

function SectionHead({ eyebrow, title, body, link, id }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: "var(--space-xl)", alignItems: "flex-end", flexWrap: "wrap", marginBottom: "var(--space-xl)" }}>
      <div style={{ maxWidth: "58ch" }}>
        {eyebrow ? <div className="mn-eyebrow" style={{ marginBottom: "var(--space-xs)" }}>{eyebrow}</div> : null}
        <h2 id={id} className="am-display-md" style={{ margin: 0, textWrap: "pretty" }}>{title}</h2>
        {body ? <p className="mn-muted" style={{ margin: "var(--space-sm) 0 0", fontSize: "var(--text-body-lg-size)" }}>{body}</p> : null}
      </div>
      {link ? <a href={link.href} style={{ fontSize: "var(--text-body-sm-size)", display: "inline-flex", gap: 6, alignItems: "center" }}>{link.label}<Icon name="arrow-right" size={16} /></a> : null}
    </div>
  );
}

Object.assign(window, { DS, Button, Badge, Icon, TextInput, FeatureCard, SITE, Val, ImagePh, Meta, AffiliateCTA, Disclosure, Breadcrumbs, Header, Footer, Newsletter, AdSlot, ArticleCard, FeaturedArticle, ProductRecCard, SectionHead, SearchPanel });

/* Brand display: the orange mark always precedes the wordmark, wherever it appears in copy. */
(function brandify() {
  const SKIP = /^(script|style|textarea|input|code|pre|title)$/i;
  const run = () => {
    const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
      acceptNode(n) {
        if (!n.nodeValue || n.nodeValue.indexOf("AutoMonitor") < 0) return NodeFilter.FILTER_REJECT;
        const p = n.parentElement;
        if (!p || SKIP.test(p.tagName) || p.closest(".mn-brand-nav,.mn-brandname")) return NodeFilter.FILTER_REJECT;
        return NodeFilter.FILTER_ACCEPT;
      }
    });
    const hits = [];
    while (walker.nextNode()) hits.push(walker.currentNode);
    hits.forEach((node) => {
      const frag = document.createDocumentFragment();
      node.nodeValue.split("AutoMonitor").forEach((part, i) => {
        if (i) {
          const wrap = document.createElement("span");
          wrap.className = "mn-brandname";
          const mark = document.createElement("i");
          mark.className = "mn-bmark";
          mark.setAttribute("aria-hidden", "true");
          wrap.appendChild(mark);
          wrap.appendChild(document.createTextNode("AutoMonitor"));
          frag.appendChild(wrap);
        }
        if (part) frag.appendChild(document.createTextNode(part));
      });
      node.parentNode && node.parentNode.replaceChild(frag, node);
    });
  };
  let queued = false;
  const schedule = () => { if (queued) return; queued = true; requestAnimationFrame(() => { queued = false; run(); }); };
  schedule();
  new MutationObserver(schedule).observe(document.body, { childList: true, subtree: true });
})();
