/* global React, Common, I18n, HelpContent, HelpCommon */
// =============================================================
// HelpHub. The /help/ landing page. Hero with a prominent search
// input, then a grid of category cards, then an article grid per
// category. Search results replace the grid in real time.
// =============================================================
const { Eyebrow } = Common;
const { useT, useI18n } = I18n;
const { HELP_CATEGORIES, HELP_ARTICLES_BY_CATEGORY } = HelpContent;
const { ArticleCard, useHelpSearch } = HelpCommon;
const { useEffect, useRef, useState } = React;

const HUB_COPY = {
  eyebrow: { en: "help center", it: "centro assistenza" },
  title: {
    en: ["How can we", "help you?"],
    it: ["Come possiamo", "aiutarti?"],
  },
  lead: {
    en: "Everything you need to set up Dimmy, dictate your first sentence, switch styles, and troubleshoot. Search below or browse by category.",
    it: "Tutto quello che ti serve per configurare Dimmy, dettare la prima frase, cambiare stile e risolvere problemi. Cerca qui sotto o sfoglia per categoria.",
  },
  searchPlaceholder: {
    en: "Search articles, e.g. hotkey, microphone, API key…",
    it: "Cerca articoli, es. scorciatoia, microfono, API key…",
  },
  searchHint: {
    en: ["Press", "to focus", "Esc", "to clear"],
    it: ["Premi", "per il focus", "Esc", "per pulire"],
  },
  noResults: {
    en: "No articles matched. Try a different word or browse the categories.",
    it: "Nessun articolo trovato. Prova un'altra parola o sfoglia le categorie.",
  },
  resultsTitle: {
    en: "Search results",
    it: "Risultati ricerca",
  },
  categoriesTitle: {
    en: "Browse by category",
    it: "Sfoglia per categoria",
  },
  needMore: {
    en: "Still stuck?",
    it: "Ancora bloccato?",
  },
  needMoreLead: {
    en: "Open an issue on GitHub or write to us. Real human, fast reply.",
    it: "Apri una issue su GitHub o scrivici. Persona vera, risposta rapida.",
  },
  needMoreCtas: {
    en: [
      { label: "Open an issue", href: "https://github.com/KonradDallaOrg/dimmy/issues" },
      { label: "Email hi@dimmy.app", href: "mailto:hi@dimmy.app" },
    ],
    it: [
      { label: "Apri una issue", href: "https://github.com/KonradDallaOrg/dimmy/issues" },
      { label: "Scrivi a hi@dimmy.app", href: "mailto:hi@dimmy.app" },
    ],
  },
};

function HelpSearchBox({ value, onChange, autoFocus }) {
  const inputRef = useRef(null);
  const placeholder = useT(HUB_COPY.searchPlaceholder);
  const hint = useT(HUB_COPY.searchHint);
  const isMac =
    typeof navigator !== "undefined" && /Mac/.test(navigator.platform || navigator.userAgent || "");

  useEffect(() => {
    if (autoFocus && inputRef.current) inputRef.current.focus();
  }, [autoFocus]);

  // Global / key focuses the input. Esc clears.
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "/" && document.activeElement !== inputRef.current) {
        const tag = document.activeElement && document.activeElement.tagName;
        if (tag === "INPUT" || tag === "TEXTAREA") return;
        e.preventDefault();
        inputRef.current && inputRef.current.focus();
      }
      if (e.key === "Escape" && document.activeElement === inputRef.current) {
        onChange("");
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onChange]);

  return (
    <div
      style={{
        position: "relative",
        display: "flex",
        alignItems: "center",
        background: "var(--bg-deep)",
        border: "1px solid var(--line-strong)",
        borderRadius: 14,
        padding: "14px 18px",
        gap: 12,
        transition: "border-color 200ms, box-shadow 200ms",
        boxShadow: "0 12px 30px rgba(0,0,0,0.25)",
      }}
      onFocus={(e) => {
        e.currentTarget.style.borderColor = "rgba(56,189,248,0.50)";
      }}
      onBlur={(e) => {
        e.currentTarget.style.borderColor = "var(--line-strong)";
      }}
    >
      <svg
        width="20"
        height="20"
        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
        ref={inputRef}
        type="search"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        aria-label="Search help articles"
        style={{
          flex: 1,
          background: "transparent",
          border: 0,
          outline: "none",
          color: "var(--fg)",
          fontFamily: "var(--font-sans)",
          fontSize: 16,
          letterSpacing: "-0.01em",
        }}
      />
      <span
        style={{
          display: "inline-flex",
          alignItems: "center",
          gap: 6,
          fontFamily: "var(--font-mono)",
          fontSize: 11,
          color: "var(--fg-faint)",
        }}
        className="help-search-hint"
      >
        <span>{hint[0]}</span>
        <kbd
          style={{
            padding: "2px 6px",
            borderRadius: 4,
            border: "1px solid var(--line-strong)",
            background: "var(--bg-elev)",
            color: "var(--fg)",
            fontFamily: "var(--font-mono)",
            fontSize: 11,
          }}
        >
          /
        </kbd>
        <span>{hint[1]}</span>
      </span>
    </div>
  );
}

function CategoryHeading({ category }) {
  const { lang } = useI18n();
  const title = category.title[lang] || category.title.en;
  const desc = category.desc[lang] || category.desc.en;
  return (
    <header
      id={category.id}
      className="reveal"
      style={{
        display: "flex",
        flexDirection: "column",
        gap: 8,
        marginBottom: 18,
        scrollMarginTop: 96,
      }}
    >
      <div
        style={{
          display: "inline-flex",
          alignItems: "center",
          gap: 10,
          fontFamily: "var(--font-mono)",
          fontSize: 11,
          color: category.accent,
          letterSpacing: "0.12em",
          textTransform: "uppercase",
        }}
      >
        <span style={{ fontSize: 16 }}>{category.icon}</span>
        <span>{title}</span>
      </div>
      <p
        style={{
          margin: 0,
          fontSize: 15,
          lineHeight: 1.55,
          color: "var(--fg-muted)",
          maxWidth: 640,
          textWrap: "pretty",
        }}
      >
        {desc}
      </p>
    </header>
  );
}

function CategoryGrid() {
  const { lang } = useI18n();
  const title = useT(HUB_COPY.categoriesTitle);
  return (
    <section
      style={{
        marginTop: 56,
        paddingTop: 32,
        borderTop: "1px solid var(--line)",
      }}
    >
      <h2
        className="reveal"
        style={{
          margin: "0 0 22px",
          fontFamily: "var(--font-display)",
          fontSize: "clamp(22px, 3vw, 28px)",
          fontWeight: 600,
          letterSpacing: "-0.01em",
          color: "var(--fg)",
        }}
      >
        {title}
      </h2>
      <div
        className="help-cat-grid"
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))",
          gap: 14,
        }}
      >
        {HELP_CATEGORIES.map((c) => {
          const articles = HELP_ARTICLES_BY_CATEGORY[c.id] || [];
          return (
            <a
              key={c.id}
              href={`#${c.id}`}
              className="reveal"
              style={{
                display: "flex",
                flexDirection: "column",
                gap: 10,
                padding: "20px 18px",
                background: "linear-gradient(180deg, var(--bg-elev), transparent)",
                border: "1px solid var(--line)",
                borderRadius: 14,
                textDecoration: "none",
                color: "var(--fg)",
                position: "relative",
                overflow: "hidden",
                transition: "border-color 180ms, transform 180ms",
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.borderColor = "var(--line-strong)";
                e.currentTarget.style.transform = "translateY(-1px)";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.borderColor = "var(--line)";
                e.currentTarget.style.transform = "translateY(0)";
              }}
            >
              <span
                style={{
                  position: "absolute",
                  top: -30,
                  right: -30,
                  width: 110,
                  height: 110,
                  borderRadius: 99,
                  background: c.accent,
                  filter: "blur(60px)",
                  opacity: 0.16,
                  pointerEvents: "none",
                }}
              />
              <span style={{ fontSize: 26 }}>{c.icon}</span>
              <span
                style={{
                  fontFamily: "var(--font-display)",
                  fontSize: 16,
                  fontWeight: 600,
                  letterSpacing: "-0.01em",
                  color: "var(--fg)",
                }}
              >
                {c.title[lang] || c.title.en}
              </span>
              <span style={{ fontSize: 13, color: "var(--fg-muted)", lineHeight: 1.5 }}>
                {c.desc[lang] || c.desc.en}
              </span>
              <span
                style={{
                  marginTop: "auto",
                  fontFamily: "var(--font-mono)",
                  fontSize: 11,
                  color: "var(--fg-faint)",
                  letterSpacing: "0.06em",
                }}
              >
                {articles.length} {articles.length === 1 ? "article" : "articles"}
              </span>
            </a>
          );
        })}
      </div>
    </section>
  );
}

function CategorySections() {
  return (
    <div style={{ marginTop: 64 }}>
      {HELP_CATEGORIES.map((c) => {
        const articles = HELP_ARTICLES_BY_CATEGORY[c.id] || [];
        if (articles.length === 0) return null;
        return (
          <section
            key={c.id}
            style={{
              paddingTop: 48,
              marginTop: 32,
              borderTop: "1px solid var(--line)",
            }}
          >
            <CategoryHeading category={c} />
            <div
              className="help-article-grid"
              style={{
                display: "grid",
                gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))",
                gap: 14,
              }}
            >
              {articles.map((a) => (
                <ArticleCard key={a.slug} article={a} />
              ))}
            </div>
          </section>
        );
      })}
    </div>
  );
}

function SearchResults({ query, results }) {
  const title = useT(HUB_COPY.resultsTitle);
  const noResults = useT(HUB_COPY.noResults);
  return (
    <section
      style={{
        marginTop: 36,
        paddingTop: 28,
        borderTop: "1px solid var(--line)",
      }}
    >
      <div
        style={{
          display: "flex",
          alignItems: "baseline",
          gap: 12,
          marginBottom: 18,
        }}
      >
        <h2
          style={{
            margin: 0,
            fontFamily: "var(--font-display)",
            fontSize: 22,
            fontWeight: 600,
            letterSpacing: "-0.01em",
            color: "var(--fg)",
          }}
        >
          {title}
        </h2>
        <span
          style={{
            fontFamily: "var(--font-mono)",
            fontSize: 12,
            color: "var(--fg-faint)",
          }}
        >
          {results.length} · "{query}"
        </span>
      </div>
      {results.length === 0 ? (
        <p
          style={{
            margin: 0,
            padding: "20px 18px",
            background: "var(--bg-elev)",
            border: "1px dashed var(--line)",
            borderRadius: 12,
            color: "var(--fg-muted)",
            fontSize: 15,
            lineHeight: 1.55,
          }}
        >
          {noResults}
        </p>
      ) : (
        <div
          className="help-article-grid"
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))",
            gap: 14,
          }}
        >
          {results.map((r) => (
            <ArticleCard key={r.article.slug} article={r.article} />
          ))}
        </div>
      )}
    </section>
  );
}

function StillStuck() {
  const title = useT(HUB_COPY.needMore);
  const lead = useT(HUB_COPY.needMoreLead);
  const ctas = useT(HUB_COPY.needMoreCtas);
  return (
    <section
      className="reveal"
      style={{
        marginTop: 80,
        padding: "32px 28px",
        borderRadius: 16,
        border: "1px solid var(--line)",
        background:
          "radial-gradient(circle at 0% 0%, rgba(56,189,248,0.10), transparent 60%), var(--bg-deep)",
        display: "flex",
        flexDirection: "column",
        gap: 12,
        alignItems: "flex-start",
      }}
    >
      <h2
        style={{
          margin: 0,
          fontFamily: "var(--font-display)",
          fontSize: 26,
          fontWeight: 700,
          letterSpacing: "-0.02em",
          color: "var(--fg)",
        }}
      >
        {title}
      </h2>
      <p
        style={{
          margin: 0,
          fontSize: 15,
          lineHeight: 1.55,
          color: "var(--fg-muted)",
          maxWidth: 520,
        }}
      >
        {lead}
      </p>
      <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 6 }}>
        {ctas.map((c) => (
          <a
            key={c.href}
            href={c.href}
            target={c.href.startsWith("http") ? "_blank" : undefined}
            rel="noopener"
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 8,
              padding: "10px 14px",
              borderRadius: 10,
              border: "1px solid var(--line-strong)",
              color: "var(--fg)",
              textDecoration: "none",
              fontSize: 13,
              fontFamily: "var(--font-sans)",
            }}
          >
            {c.label}
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M5 12h14M13 5l7 7-7 7" />
            </svg>
          </a>
        ))}
      </div>
    </section>
  );
}

function HelpHub() {
  const [a, b] = useT(HUB_COPY.title);
  const lead = useT(HUB_COPY.lead);
  const [query, setQuery] = useState("");
  const search = useHelpSearch();
  const results = query ? search(query) : null;

  return (
    <main
      style={{
        position: "relative",
        background: "var(--bg)",
      }}
    >
      <section
        style={{
          position: "relative",
          padding: "84px 32px 36px",
          textAlign: "left",
          borderBottom: "1px solid var(--line)",
        }}
      >
        <div
          aria-hidden="true"
          className="bg-grid"
          style={{
            position: "absolute",
            inset: 0,
            opacity: 0.35,
            maskImage:
              "radial-gradient(ellipse 80% 70% at 50% 30%, black, transparent 75%)",
            WebkitMaskImage:
              "radial-gradient(ellipse 80% 70% at 50% 30%, black, transparent 75%)",
            pointerEvents: "none",
          }}
        />
        <div
          aria-hidden="true"
          style={{
            position: "absolute",
            top: -120,
            right: -80,
            width: 460,
            height: 460,
            borderRadius: 99,
            background:
              "radial-gradient(circle, rgba(56,189,248,0.20), transparent 70%)",
            filter: "blur(80px)",
            pointerEvents: "none",
          }}
        />
        <div className="container-narrow" style={{ position: "relative" }}>
          <Eyebrow color="#38BDF8">{useT(HUB_COPY.eyebrow)}</Eyebrow>
          <div style={{ height: 16 }} />
          <h1
            className="reveal"
            style={{
              fontFamily: "var(--font-display)",
              fontSize: "clamp(40px, 7vw, 80px)",
              fontWeight: 700,
              letterSpacing: "-0.03em",
              lineHeight: 1.02,
              margin: 0,
              color: "var(--fg)",
              textWrap: "balance",
            }}
          >
            {a}
            <br />
            <span className="grad-text">{b}</span>
          </h1>
          <p
            className="reveal"
            style={{
              marginTop: 22,
              fontSize: 19,
              lineHeight: 1.55,
              color: "var(--fg-muted)",
              maxWidth: 640,
              textWrap: "pretty",
            }}
          >
            {lead}
          </p>
          <div style={{ marginTop: 32 }}>
            <HelpSearchBox value={query} onChange={setQuery} autoFocus={false} />
          </div>
        </div>
      </section>

      <div className="container-narrow" style={{ paddingTop: 24, paddingBottom: 96 }}>
        {results ? (
          <SearchResults query={query} results={results} />
        ) : (
          <>
            <CategoryGrid />
            <CategorySections />
          </>
        )}
        <StillStuck />
      </div>

      <style>{`
        @media (max-width: 760px) {
          .help-cat-grid { grid-template-columns: 1fr 1fr !important; }
          .help-article-grid { grid-template-columns: 1fr !important; }
          .help-search-hint { display: none !important; }
        }
        @media (max-width: 480px) {
          .help-cat-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </main>
  );
}

window.HelpHub = HelpHub;
