/* global React, Common, I18n, HelpContent, HelpCommon */
// =============================================================
// HelpArticle. Renders one article based on the slug stamped on
// the body via data-help-slug. Layout: 3-column on desktop
// (article body in the middle, sidebar TOC on the right), single
// column on mobile. Includes breadcrumb, prev/next, contextual
// "in this category" rail.
// =============================================================
const { Eyebrow } = Common;
const { useT, useI18n } = I18n;
const { HELP_CATEGORIES, HELP_ARTICLES, HELP_ARTICLE_BY_SLUG, HELP_ARTICLES_BY_CATEGORY } = HelpContent;
const { HelpBlock, ArticleCard, useHelpSearch, slugify } = HelpCommon;
const { useEffect, useMemo, useState, useRef } = React;

const ART_COPY = {
  notFoundEyebrow: { en: "404", it: "404" },
  notFoundTitle: { en: "Article not found", it: "Articolo non trovato" },
  notFoundLead: {
    en: "We couldn't find an article for this URL. It may have moved or been renamed.",
    it: "Non abbiamo trovato un articolo per questa URL. Forse è stato spostato o rinominato.",
  },
  backToHub: { en: "Back to Help center", it: "Torna al Centro assistenza" },
  searchPlaceholder: { en: "Search help…", it: "Cerca nell'help…" },
  tocTitle: { en: "On this page", it: "In questa pagina" },
  inCategory: { en: "In this category", it: "In questa categoria" },
  prev: { en: "Previous", it: "Precedente" },
  next: { en: "Next", it: "Successivo" },
  breadcrumbHome: { en: "Help", it: "Help" },
  wasHelpful: { en: "Was this helpful?", it: "Ti è stato utile?" },
  helpfulYes: { en: "Yes", it: "Sì" },
  helpfulNo: { en: "No", it: "No" },
  helpfulThanks: { en: "Thanks for the feedback.", it: "Grazie del feedback." },
  helpfulIssue: {
    en: "Tell us what's missing on GitHub.",
    it: "Dicci cosa manca su GitHub.",
  },
  lastUpdated: { en: "Last updated", it: "Ultimo aggiornamento" },
  lastUpdatedDate: "2026-05-22",
};

function readSlugFromDom() {
  if (typeof document === "undefined") return null;
  const body = document.body;
  if (body && body.dataset && body.dataset.helpSlug) return body.dataset.helpSlug;
  // Fallback: parse the URL.
  const m = (typeof window !== "undefined" ? window.location.pathname : "/").match(
    /^\/help\/([^/]+)\/?$/
  );
  return m ? m[1] : null;
}

function ArticleBreadcrumb({ article, category }) {
  const { lang } = useI18n();
  const home = useT(ART_COPY.breadcrumbHome);
  return (
    <nav
      style={{
        display: "flex",
        alignItems: "center",
        flexWrap: "wrap",
        gap: 8,
        fontFamily: "var(--font-mono)",
        fontSize: 11,
        color: "var(--fg-faint)",
        letterSpacing: "0.08em",
        textTransform: "uppercase",
      }}
      aria-label="Breadcrumb"
    >
      <a href="/help/" style={{ color: "var(--fg-muted)", textDecoration: "none" }}>
        {home}
      </a>
      <span aria-hidden="true">›</span>
      <a
        href={`/help/#${category.id}`}
        style={{ color: "var(--fg-muted)", textDecoration: "none" }}
      >
        {category.title[lang] || category.title.en}
      </a>
      <span aria-hidden="true">›</span>
      <span style={{ color: "var(--fg)" }}>{article.title[lang] || article.title.en}</span>
    </nav>
  );
}

function ArticleHeader({ article, category }) {
  const { lang } = useI18n();
  const title = article.title[lang] || article.title.en;
  const summary = article.summary[lang] || article.summary.en;
  return (
    <header
      style={{
        display: "flex",
        flexDirection: "column",
        gap: 16,
        paddingBottom: 28,
        borderBottom: "1px solid var(--line)",
      }}
    >
      <ArticleBreadcrumb article={article} category={category} />
      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
        <span
          aria-hidden="true"
          style={{
            width: 48,
            height: 48,
            borderRadius: 12,
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            background: `${category.accent}22`,
            border: `1px solid ${category.accent}44`,
            fontSize: 24,
          }}
        >
          {article.icon || category.icon}
        </span>
        <div>
          <div
            style={{
              fontFamily: "var(--font-mono)",
              fontSize: 11,
              color: category.accent,
              letterSpacing: "0.10em",
              textTransform: "uppercase",
            }}
          >
            {category.title[lang] || category.title.en}
          </div>
        </div>
      </div>
      <h1
        className="reveal"
        style={{
          margin: 0,
          fontFamily: "var(--font-display)",
          fontSize: "clamp(32px, 5vw, 48px)",
          fontWeight: 700,
          letterSpacing: "-0.02em",
          lineHeight: 1.08,
          color: "var(--fg)",
          textWrap: "balance",
        }}
      >
        {title}
      </h1>
      <p
        className="reveal"
        style={{
          margin: 0,
          fontSize: 18,
          lineHeight: 1.55,
          color: "var(--fg-muted)",
          maxWidth: 720,
          textWrap: "pretty",
        }}
      >
        {summary}
      </p>
    </header>
  );
}

function ArticleToc({ blocks }) {
  const tocTitle = useT(ART_COPY.tocTitle);
  const headings = useMemo(
    () => (blocks || []).filter((b) => b.type === "heading"),
    [blocks]
  );
  const [activeId, setActiveId] = useState("");
  useEffect(() => {
    if (headings.length === 0) return undefined;
    const observers = headings.map((bl) => {
      const el = document.getElementById(slugify(bl.text));
      if (!el) return null;
      const io = new IntersectionObserver(
        (entries) => {
          entries.forEach((e) => {
            if (e.isIntersecting) setActiveId(slugify(bl.text));
          });
        },
        { rootMargin: "-25% 0px -65% 0px", threshold: 0 }
      );
      io.observe(el);
      return io;
    });
    return () => observers.forEach((io) => io && io.disconnect());
  }, [headings]);

  if (headings.length === 0) return null;

  return (
    <aside
      className="help-article-toc"
      style={{
        position: "sticky",
        top: 96,
        alignSelf: "start",
        padding: 20,
        borderLeft: "1px solid var(--line)",
        fontFamily: "var(--font-sans)",
        fontSize: 13,
        maxHeight: "calc(100vh - 120px)",
        overflowY: "auto",
      }}
    >
      <div
        style={{
          fontFamily: "var(--font-mono)",
          fontSize: 10,
          color: "var(--fg-faint)",
          letterSpacing: "0.10em",
          textTransform: "uppercase",
          marginBottom: 14,
        }}
      >
        {tocTitle}
      </div>
      <ol style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 4 }}>
        {headings.map((bl, i) => {
          const id = slugify(bl.text);
          const isActive = activeId === id;
          return (
            <li key={id}>
              <a
                href={`#${id}`}
                style={{
                  display: "flex",
                  alignItems: "baseline",
                  gap: 8,
                  padding: "4px 0",
                  color: isActive ? "var(--fg)" : "var(--fg-muted)",
                  textDecoration: "none",
                  borderLeft: `2px solid ${isActive ? "var(--fg)" : "transparent"}`,
                  paddingLeft: 10,
                  marginLeft: -12,
                  transition: "color 180ms, border-color 180ms",
                }}
              >
                <span
                  style={{
                    fontFamily: "var(--font-mono)",
                    fontSize: 10,
                    color: "var(--fg-faint)",
                    minWidth: 16,
                  }}
                >
                  {String(i + 1).padStart(2, "0")}
                </span>
                <span style={{ textWrap: "pretty" }}>{bl.text}</span>
              </a>
            </li>
          );
        })}
      </ol>
    </aside>
  );
}

function PrevNext({ prev, next }) {
  const { lang } = useI18n();
  const prevLabel = useT(ART_COPY.prev);
  const nextLabel = useT(ART_COPY.next);
  if (!prev && !next) return null;
  return (
    <nav
      className="help-prev-next"
      style={{
        marginTop: 56,
        paddingTop: 28,
        borderTop: "1px solid var(--line)",
        display: "grid",
        gridTemplateColumns: "1fr 1fr",
        gap: 14,
      }}
    >
      {prev ? (
        <a
          href={`/help/${prev.slug}/`}
          style={{
            display: "flex",
            flexDirection: "column",
            gap: 6,
            padding: 18,
            background: "linear-gradient(180deg, var(--bg-elev), transparent)",
            border: "1px solid var(--line)",
            borderRadius: 14,
            textDecoration: "none",
            color: "var(--fg)",
            transition: "border-color 180ms",
          }}
          onMouseEnter={(e) => (e.currentTarget.style.borderColor = "var(--line-strong)")}
          onMouseLeave={(e) => (e.currentTarget.style.borderColor = "var(--line)")}
        >
          <span
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 6,
              fontFamily: "var(--font-mono)",
              fontSize: 11,
              color: "var(--fg-faint)",
              letterSpacing: "0.08em",
              textTransform: "uppercase",
            }}
          >
            ← {prevLabel}
          </span>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 600 }}>
            {prev.title[lang] || prev.title.en}
          </span>
        </a>
      ) : <span />}
      {next ? (
        <a
          href={`/help/${next.slug}/`}
          style={{
            display: "flex",
            flexDirection: "column",
            gap: 6,
            padding: 18,
            background: "linear-gradient(180deg, var(--bg-elev), transparent)",
            border: "1px solid var(--line)",
            borderRadius: 14,
            textDecoration: "none",
            color: "var(--fg)",
            textAlign: "right",
            transition: "border-color 180ms",
          }}
          onMouseEnter={(e) => (e.currentTarget.style.borderColor = "var(--line-strong)")}
          onMouseLeave={(e) => (e.currentTarget.style.borderColor = "var(--line)")}
        >
          <span
            style={{
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "flex-end",
              gap: 6,
              fontFamily: "var(--font-mono)",
              fontSize: 11,
              color: "var(--fg-faint)",
              letterSpacing: "0.08em",
              textTransform: "uppercase",
            }}
          >
            {nextLabel} →
          </span>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 600 }}>
            {next.title[lang] || next.title.en}
          </span>
        </a>
      ) : <span />}
    </nav>
  );
}

function InCategoryRail({ article, category }) {
  const title = useT(ART_COPY.inCategory);
  const siblings = (HELP_ARTICLES_BY_CATEGORY[category.id] || []).filter(
    (a) => a.slug !== article.slug
  );
  if (siblings.length === 0) return null;
  return (
    <section
      style={{
        marginTop: 56,
        paddingTop: 28,
        borderTop: "1px solid var(--line)",
      }}
    >
      <h2
        style={{
          margin: "0 0 16px",
          fontFamily: "var(--font-display)",
          fontSize: 18,
          fontWeight: 600,
          letterSpacing: "-0.01em",
          color: "var(--fg)",
        }}
      >
        {title}
      </h2>
      <div
        className="help-article-grid"
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fill, minmax(240px, 1fr))",
          gap: 12,
        }}
      >
        {siblings.map((a) => (
          <ArticleCard key={a.slug} article={a} />
        ))}
      </div>
    </section>
  );
}

function HelpfulPrompt() {
  const title = useT(ART_COPY.wasHelpful);
  const yes = useT(ART_COPY.helpfulYes);
  const no = useT(ART_COPY.helpfulNo);
  const thanks = useT(ART_COPY.helpfulThanks);
  const issue = useT(ART_COPY.helpfulIssue);
  const [picked, setPicked] = useState(null);
  return (
    <div
      style={{
        marginTop: 40,
        padding: "18px 20px",
        background: "var(--bg-elev)",
        border: "1px solid var(--line)",
        borderRadius: 14,
        display: "flex",
        flexWrap: "wrap",
        alignItems: "center",
        gap: 14,
      }}
    >
      <span style={{ fontSize: 14, color: "var(--fg)" }}>{title}</span>
      {picked ? (
        <span style={{ fontSize: 13, color: "var(--fg-muted)" }}>
          {thanks}
          {picked === "no" && (
            <>
              {" "}
              <a
                href="https://github.com/KonradDallaOrg/dimmy/issues/new?labels=docs&template=docs.md"
                target="_blank"
                rel="noopener"
                style={{ color: "var(--fg)", borderBottom: "1px solid var(--line-strong)", textDecoration: "none" }}
              >
                {issue}
              </a>
            </>
          )}
        </span>
      ) : (
        <span style={{ display: "inline-flex", gap: 8 }}>
          {["yes", "no"].map((k) => (
            <button
              key={k}
              onClick={() => setPicked(k)}
              style={{
                padding: "6px 14px",
                borderRadius: 8,
                border: "1px solid var(--line-strong)",
                background: "transparent",
                color: "var(--fg)",
                fontFamily: "var(--font-sans)",
                fontSize: 13,
                cursor: "pointer",
                transition: "background 180ms",
              }}
              onMouseEnter={(e) => (e.currentTarget.style.background = "var(--bg-deep)")}
              onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
            >
              {k === "yes" ? `👍 ${yes}` : `👎 ${no}`}
            </button>
          ))}
        </span>
      )}
    </div>
  );
}

function ArticleSearchInHeader() {
  const placeholder = useT(ART_COPY.searchPlaceholder);
  const [q, setQ] = useState("");
  const search = useHelpSearch();
  const results = q ? search(q).slice(0, 6) : [];
  const containerRef = useRef(null);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onDocClick = (e) => {
      if (!containerRef.current) return;
      if (!containerRef.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener("mousedown", onDocClick);
    return () => document.removeEventListener("mousedown", onDocClick);
  }, []);
  return (
    <div ref={containerRef} style={{ position: "relative" }}>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 10,
          padding: "8px 12px",
          background: "var(--bg-deep)",
          border: "1px solid var(--line)",
          borderRadius: 10,
        }}
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--fg-faint)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="11" cy="11" r="7" />
          <path d="M21 21l-4.35-4.35" />
        </svg>
        <input
          type="search"
          value={q}
          onChange={(e) => {
            setQ(e.target.value);
            setOpen(true);
          }}
          onFocus={() => setOpen(true)}
          placeholder={placeholder}
          style={{
            background: "transparent",
            border: 0,
            outline: "none",
            color: "var(--fg)",
            fontSize: 13,
            fontFamily: "var(--font-sans)",
            width: 220,
          }}
        />
      </div>
      {open && q && (
        <div
          style={{
            position: "absolute",
            top: "calc(100% + 6px)",
            right: 0,
            width: 360,
            background: "var(--bg-deep)",
            border: "1px solid var(--line-strong)",
            borderRadius: 12,
            boxShadow: "0 16px 40px rgba(0,0,0,0.40)",
            zIndex: 40,
            overflow: "hidden",
          }}
        >
          {results.length === 0 ? (
            <div style={{ padding: "12px 14px", color: "var(--fg-muted)", fontSize: 13 }}>
              No matches. Try the <a href="/help/" style={{ color: "var(--fg)" }}>Help center</a>.
            </div>
          ) : (
            <ul style={{ listStyle: "none", padding: 6, margin: 0, display: "flex", flexDirection: "column", gap: 2 }}>
              {results.map((r) => (
                <li key={r.article.slug}>
                  <a
                    href={`/help/${r.article.slug}/`}
                    style={{
                      display: "flex",
                      flexDirection: "column",
                      gap: 2,
                      padding: "10px 12px",
                      borderRadius: 8,
                      textDecoration: "none",
                      color: "var(--fg)",
                    }}
                    onMouseEnter={(e) => (e.currentTarget.style.background = "var(--bg-elev)")}
                    onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
                  >
                    <span style={{ fontSize: 14, fontWeight: 600 }}>{r.title}</span>
                    <span style={{ fontSize: 12, color: "var(--fg-muted)" }}>{r.catTitle}</span>
                  </a>
                </li>
              ))}
            </ul>
          )}
        </div>
      )}
    </div>
  );
}

function HelpArticleNotFound() {
  const eb = useT(ART_COPY.notFoundEyebrow);
  const title = useT(ART_COPY.notFoundTitle);
  const lead = useT(ART_COPY.notFoundLead);
  const back = useT(ART_COPY.backToHub);
  return (
    <main style={{ padding: "120px 32px", textAlign: "center" }}>
      <div className="container-narrow">
        <Eyebrow color="#F87171">{eb}</Eyebrow>
        <h1
          style={{
            marginTop: 16,
            fontFamily: "var(--font-display)",
            fontSize: "clamp(40px, 7vw, 80px)",
            fontWeight: 700,
            letterSpacing: "-0.03em",
            color: "var(--fg)",
          }}
        >
          {title}
        </h1>
        <p
          style={{
            marginTop: 18,
            fontSize: 18,
            color: "var(--fg-muted)",
            maxWidth: 560,
            marginInline: "auto",
          }}
        >
          {lead}
        </p>
        <a
          href="/help/"
          style={{
            marginTop: 28,
            display: "inline-flex",
            alignItems: "center",
            gap: 8,
            padding: "10px 16px",
            borderRadius: 10,
            border: "1px solid var(--line-strong)",
            color: "var(--fg)",
            textDecoration: "none",
            fontSize: 14,
          }}
        >
          ← {back}
        </a>
      </div>
    </main>
  );
}

function HelpArticle() {
  const { lang } = useI18n();
  const slug = useMemo(readSlugFromDom, []);
  const article = slug ? HELP_ARTICLE_BY_SLUG[slug] : null;
  const category = article ? HELP_CATEGORIES.find((c) => c.id === article.category) : null;

  // Update document title once article resolves.
  useEffect(() => {
    if (article) {
      const t = article.title[lang] || article.title.en;
      document.title = `${t}. Dimmy Help.`;
    }
  }, [article, lang]);

  if (!article || !category) {
    return <HelpArticleNotFound />;
  }

  const blocks = article.blocks[lang] || article.blocks.en;

  const idx = HELP_ARTICLES.findIndex((a) => a.slug === article.slug);
  const prev = idx > 0 ? HELP_ARTICLES[idx - 1] : null;
  const next = idx < HELP_ARTICLES.length - 1 ? HELP_ARTICLES[idx + 1] : null;

  return (
    <main style={{ background: "var(--bg)", paddingBottom: 80 }}>
      {/* Sub-header bar: search input next to the breadcrumb */}
      <div
        className="help-article-subheader"
        style={{
          borderBottom: "1px solid var(--line)",
          padding: "14px 32px",
          background: "var(--bg)",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 12,
        }}
      >
        <a
          href="/help/"
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 8,
            color: "var(--fg-muted)",
            textDecoration: "none",
            fontFamily: "var(--font-mono)",
            fontSize: 12,
            letterSpacing: "0.06em",
          }}
        >
          ← {useT(ART_COPY.backToHub)}
        </a>
        <ArticleSearchInHeader />
      </div>

      <div
        className="container help-article-shell"
        style={{
          display: "grid",
          gridTemplateColumns: "minmax(0, 1fr) 280px",
          gap: 56,
          padding: "48px 32px 0",
        }}
      >
        <article style={{ minWidth: 0 }}>
          <ArticleHeader article={article} category={category} />
          <div style={{ marginTop: 28 }}>
            {blocks.map((b, i) => (
              <HelpBlock key={i} block={b} />
            ))}
          </div>
          <HelpfulPrompt />
          <PrevNext prev={prev} next={next} />
          <InCategoryRail article={article} category={category} />
          <div
            style={{
              marginTop: 40,
              fontFamily: "var(--font-mono)",
              fontSize: 11,
              color: "var(--fg-faint)",
              letterSpacing: "0.06em",
            }}
          >
            {useT(ART_COPY.lastUpdated)}: {ART_COPY.lastUpdatedDate}
          </div>
        </article>
        <ArticleToc blocks={blocks} />
      </div>

      <style>{`
        @media (max-width: 960px) {
          .help-article-shell { grid-template-columns: 1fr !important; gap: 24px !important; }
          .help-article-toc { display: none !important; }
        }
        @media (max-width: 760px) {
          .help-article-subheader { padding: 12px 20px !important; }
          .help-article-shell { padding: 32px 20px 0 !important; }
          .help-prev-next { grid-template-columns: 1fr !important; }
        }
        @media (max-width: 600px) {
          .help-article-subheader > div[style*="position: relative"] input { width: 140px !important; }
        }
      `}</style>
    </main>
  );
}

window.HelpArticle = HelpArticle;
