/* ============================================================
   page-help.jsx — Help / API tab
   ============================================================ */

const _T = (window.appT || (s => s));
const QUICK_START = [
  { emoji: '📋', label: _T('Sign in'),          slug: 'signin-format' },
  { emoji: '🌴', label: _T('Request time off'), slug: 'request-pto' },
  { emoji: '☁️', label: _T('Manage VMs'),       slug: 'vpsie-manage-vms' },
  { emoji: '🤖', label: _T('Ask the AI'),       slug: 'ask-ai' },
];

/* ─── VPSie docs collapsible card ────────────────────────── */
function VpsieDocCard({ doc }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ border: '1px solid var(--line)', borderRadius: 'var(--r-md)', marginBottom: 8, overflow: 'hidden' }}>
      <div
        onClick={() => setOpen(x => !x)}
        style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          padding: '10px 14px', cursor: 'pointer', background: 'var(--bg-elev-1)',
          transition: 'background .1s',
        }}
      >
        <div>
          <div style={{ fontWeight: 500, fontSize: 13 }}>{doc.topic}</div>
          {!open && <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 2 }}>{(doc.summary || '').slice(0, 120)}{(doc.summary || '').length > 120 ? '…' : ''}</div>}
        </div>
        <span style={{ fontSize: 16, color: 'var(--text-3)', flexShrink: 0, marginLeft: 12 }}>{open ? '▲' : '▼'}</span>
      </div>
      {open && (
        <div style={{ padding: '12px 14px', background: 'var(--bg)', borderTop: '1px solid var(--line)' }}>
          {doc.summary && <div style={{ fontSize: 13, color: 'var(--text-2)', marginBottom: 12 }}>{doc.summary}</div>}
          {(doc.steps || []).length > 0 && (
            <ol style={{ paddingLeft: 18, margin: 0, display: 'flex', flexDirection: 'column', gap: 6 }}>
              {doc.steps.map((step, i) => (
                <li key={i} style={{ fontSize: 12.5, lineHeight: 1.55, color: 'var(--text)' }}>{step}</li>
              ))}
            </ol>
          )}
          {doc.source_url && (
            <div style={{ marginTop: 12 }}>
              <a href={doc.source_url} target="_blank" rel="noopener noreferrer"
                 className="btn btn-ghost" style={{ display: 'inline-flex', gap: 6, fontSize: 12 }}>
                {(window.appT||(s=>s))("External source")}
              </a>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

/* ─── VPSie docs section ─────────────────────────────────── */
function VpsieDocsSection() {
  const toast = useToast();
  const [docs, setDocs] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [searchQ, setSearchQ] = React.useState('');

  const load = React.useCallback(async (notify) => {
    setLoading(true);
    try {
      const r = await fetch('/api/vpsie-docs', { credentials: 'include' });
      if (!r.ok) throw new Error(`${r.status}`);
      const data = await r.json();
      setDocs(Array.isArray(data) ? data : []);
      if (notify) toast.push({ msg: (window.appT||(s=>s))('VPSie docs refreshed'), kind: 'ok', icon: '✓' });
    } catch (e) {
      toast.push({ msg: `${(window.appT||(s=>s))('VPSie docs error')}: ${e.message}`, kind: 'err', icon: '!' });
    } finally {
      setLoading(false);
    }
  }, [toast]);

  React.useEffect(() => { load(false); }, []);

  const filtered = React.useMemo(() => {
    if (!searchQ.trim()) return docs;
    const q = searchQ.toLowerCase();
    return docs.filter(d =>
      (d.topic || '').toLowerCase().includes(q) ||
      (d.summary || '').toLowerCase().includes(q)
    );
  }, [docs, searchQ]);

  return (
    <div className="card" style={{ marginTop: 24 }}>
      <SectionHeader
        title={(window.appT||(s=>s))("VPSie Documentation")}
          tip={(window.appT||(s=>s))("Searchable knowledge base scraped from the VPSie docs site. Re-scraped weekly by the _job_refresh_vpsie_docs cron.")}
        sub={(window.appT||(s=>s))("Scraped from apidocs.vpsie.com and vpsie.com/knowledge-base — refreshed weekly")}
        right={<Refresh onClick={() => load(true)} loading={loading} />}
      />
      <SearchInput
        value={searchQ}
        onChange={setSearchQ}
        placeholder={(window.appT||(s=>s))("Filter VPSie topics...")}
        style={{ marginBottom: 12 }}
      />
      {loading && docs.length === 0 && (
        <div><Skel h={48} /><Skel h={48} style={{ marginTop: 8 }} /></div>
      )}
      {!loading && filtered.length === 0 && (
        <Empty icon="·" title={(window.appT||(s=>s))("No VPSie topics")} subtitle={searchQ ? (window.appT||(s=>s))('Try a different search.') : (window.appT||(s=>s))('Docs will be fetched on first load.')} />
      )}
      {filtered.map((doc, i) => (
        <VpsieDocCard key={doc.slug || i} doc={doc} />
      ))}
    </div>
  );
}

function HelpPage() {
  const toast = useToast();

  const [categories, setCategories] = React.useState([]);
  const [articles, setArticles]     = React.useState([]);
  const [activeCategory, setActiveCat] = React.useState(null);
  const [openArticle, setOpenArticle]  = React.useState(null); // full article object
  const [searchQ, setSearchQ]          = React.useState('');
  const [loading, setLoading]          = React.useState(false);
  const [artLoading, setArtLoading]    = React.useState(false);

  /* Load categories on mount */
  React.useEffect(() => {
    fetch('/api/help/categories', { credentials: 'include' })
      .then(r => r.ok ? r.json() : [])
      .then(setCategories)
      .catch(() => {});
  }, []);

  /* Load articles whenever category or search changes */
  const loadArticles = React.useCallback(async (cat, q, notify) => {
    setLoading(true);
    try {
      const p = new URLSearchParams();
      if (cat) p.set('category', cat);
      if (q)   p.set('q', q);
      const r = await fetch(`/api/help/articles?${p}`, { credentials: 'include' });
      if (!r.ok) throw new Error(`${r.status}`);
      const data = await r.json();
      setArticles(Array.isArray(data) ? data : []);
      if (notify) toast.push({ msg: (window.appT||(s=>s))('Refreshed'), kind: 'ok', icon: '✓' });
    } catch (e) {
      toast.push({ msg: `${(window.appT||(s=>s))('Help error')}: ${e.message}`, kind: 'err', icon: '!' });
    } finally {
      setLoading(false);
    }
  }, [toast]);

  /* Debounced search */
  const debRef = React.useRef(null);
  React.useEffect(() => {
    clearTimeout(debRef.current);
    debRef.current = setTimeout(() => loadArticles(activeCategory, searchQ, false), 320);
    return () => clearTimeout(debRef.current);
  }, [activeCategory, searchQ]);

  /* Open article by slug */
  const openSlug = React.useCallback(async (slug) => {
    setArtLoading(true);
    try {
      const r = await fetch(`/api/help/articles/${slug}`, { credentials: 'include' });
      if (r.status === 404) {
        toast.push({ msg: (window.appT||(s=>s))('Article not yet documented'), kind: 'warn', icon: '·' });
        return;
      }
      if (!r.ok) throw new Error(`${r.status}`);
      setOpenArticle(await r.json());
    } catch (e) {
      toast.push({ msg: `${(window.appT||(s=>s))('Could not load article')}: ${e.message}`, kind: 'err', icon: '!' });
    } finally {
      setArtLoading(false);
    }
  }, [toast]);

  const catLabel = categories.find(c => c.slug === activeCategory)?.title || (window.appT||(s=>s))('All categories');

  return (
    <div className="page">
      <PageHeader
        title={(window.appT||(s=>s))("Help / API")}
        meta={(window.appT||(s=>s))("Guides, quick-start cards, and API reference")}
        right={<Refresh onClick={() => loadArticles(activeCategory, searchQ, true)} loading={loading} />}
      />

      {/* Search bar */}
      <SearchInput
        value={searchQ}
        onChange={v => { setSearchQ(v); setOpenArticle(null); }}
        placeholder={(window.appT||(s=>s))("Search articles, topics, API endpoints...")}
        style={{ marginBottom: 20, maxWidth: '100%' }}
      />

      {/* Quick-start tiles */}
      {!openArticle && !searchQ && !activeCategory && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))', gap: 12, marginBottom: 24 }}>
          {QUICK_START.map(({ emoji, label, slug }) => (
            <button
              key={slug}
              className="btn btn-ghost"
              style={{
                flexDirection: 'column', gap: 10, padding: '18px 14px',
                height: 'auto', textAlign: 'center', fontSize: 13,
                border: '1px solid var(--line)', borderRadius: 'var(--r-md)',
                background: 'var(--bg-elev-1)',
              }}
              onClick={() => openSlug(slug)}
              disabled={artLoading}
            >
              <span style={{ fontSize: 26 }}>{emoji}</span>
              <span>{label}</span>
            </button>
          ))}
        </div>
      )}

      {/* Two-column layout */}
      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 16, alignItems: 'start' }}>

        {/* Left: category list */}
        <div className="card" style={{ position: 'sticky', top: 16 }}>
          <SectionHeader title={(window.appT||(s=>s))("Categories")}
          tip={(window.appT||(s=>s))("Help articles grouped by topic. Click a category to filter.")} />
          <div
            onClick={() => { setActiveCat(null); setOpenArticle(null); }}
            style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              padding: '6px 4px', cursor: 'pointer', borderRadius: 'var(--r-xs)',
              background: activeCategory === null ? 'var(--bg-elev-2)' : 'transparent',
              fontSize: 12.5, marginBottom: 4,
            }}
          >
            <span>{(window.appT||(s=>s))("All")}</span>
            <Badge kind="mute">{articles.length || categories.reduce((a, c) => a + (c.article_count || 0), 0)}</Badge>
          </div>
          {categories.map(cat => (
            <div
              key={cat.slug}
              onClick={() => { setActiveCat(cat.slug); setOpenArticle(null); }}
              style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                padding: '6px 4px', cursor: 'pointer', borderRadius: 'var(--r-xs)',
                background: activeCategory === cat.slug ? 'var(--bg-elev-2)' : 'transparent',
                fontSize: 12.5,
              }}
            >
              <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>
                {cat.title}
              </span>
              <Badge kind="mute">{cat.article_count || 0}</Badge>
            </div>
          ))}
        </div>

        {/* Right: article list or article detail */}
        <div>
          {openArticle ? (
            /* Article detail */
            <div className="card">
              {/* Breadcrumb */}
              <div style={{ fontSize: 11.5, color: 'var(--text-3)', marginBottom: 12, display: 'flex', gap: 6, alignItems: 'center' }}>
                <span
                  style={{ cursor: 'pointer', color: 'var(--brand)' }}
                  onClick={() => setOpenArticle(null)}
                >
                  {categories.find(c => c.slug === openArticle.category)?.title || (window.appT||(s=>s))('Help')}
                </span>
                <span>›</span>
                <span>{openArticle.title}</span>
              </div>

              <h3 style={{ fontSize: 17, fontWeight: 600, marginBottom: 6 }}>{openArticle.title}</h3>
              <div style={{ fontSize: 13, color: 'var(--text-2)', marginBottom: 18 }}>{openArticle.summary}</div>

              {/* Steps */}
              {(openArticle.steps || []).length > 0 && (
                <ol style={{ paddingLeft: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {openArticle.steps.map((step, i) => (
                    <li key={i} style={{ fontSize: 13, lineHeight: 1.6, color: 'var(--text)' }}>
                      <span style={{ fontFamily: 'var(--font-mono)', whiteSpace: 'pre-wrap', fontSize: 12.5 }}>{step}</span>
                    </li>
                  ))}
                </ol>
              )}

              {/* Markdown fallback (for file-based docs) */}
              {openArticle.markdown && !openArticle.steps?.length && (
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, whiteSpace: 'pre-wrap', color: 'var(--text-2)', background: 'var(--bg-elev-2)', borderRadius: 'var(--r-sm)', padding: '12px 16px', maxHeight: 420, overflowY: 'auto' }}>
                  {openArticle.markdown.slice(0, 4000)}{openArticle.markdown.length > 4000 ? '\n…(truncated)' : ''}
                </div>
              )}

              {/* External link */}
              {openArticle.external_url && (
                <div style={{ marginTop: 20 }}>
                  <a
                    href={/^https?:\/\//i.test(openArticle.external_url || '') ? openArticle.external_url : '#'}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="btn btn-ghost"
                    style={{ display: 'inline-flex', gap: 6 }}
                  >
                    <Icon name="arrowR" size={13} /> {(window.appT||(s=>s))("External docs")}
                  </a>
                </div>
              )}

              <div style={{ marginTop: 20, paddingTop: 14, borderTop: '1px solid var(--line)' }}>
                <button className="btn btn-ghost" onClick={() => setOpenArticle(null)}>
                  <Icon name="arrowL" size={13} /> {(window.appT||(s=>s))("Back to list")}
                </button>
              </div>
            </div>
          ) : (
            /* Article list */
            <div className="card">
              <SectionHeader
                title={searchQ ? `${(window.appT||(s=>s))("Results for")} "${searchQ}"` : catLabel}
                sub={`${articles.length} ${articles.length !== 1 ? (window.appT||(s=>s))('articles') : (window.appT||(s=>s))('article')}`}
              />

              {loading && articles.length === 0 && (
                <div><Skel h={52} /><Skel h={52} style={{ marginTop: 8 }} /><Skel h={52} style={{ marginTop: 8 }} /></div>
              )}
              {!loading && articles.length === 0 && (
                <Empty icon="·" title={(window.appT||(s=>s))("No articles")} subtitle={searchQ ? (window.appT||(s=>s))('Try a different search.') : (window.appT||(s=>s))('Select a category or search above.')} />
              )}

              {articles.map(art => (
                <div
                  key={art.slug}
                  onClick={() => openSlug(art.slug)}
                  style={{
                    padding: '10px 8px', cursor: 'pointer', borderRadius: 'var(--r-sm)',
                    transition: 'background .12s',
                    borderTop: '1px solid var(--line)',
                  }}
                  className="hover-row"
                >
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
                    <div>
                      <div style={{ fontWeight: 500, fontSize: 13, marginBottom: 2 }}>{art.title}</div>
                      <div style={{ fontSize: 12, color: 'var(--text-2)' }}>{art.summary}</div>
                    </div>
                    <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexShrink: 0 }}>
                      {art.external_url && <Badge kind="info">ext</Badge>}
                      <Badge kind="mute">{(categories.find(c => c.slug === art.category)?.title || art.category)}</Badge>
                      <Icon name="arrowR" size={13} />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* VPSie documentation — DB-cached scrape of external docs */}
      {!openArticle && <VpsieDocsSection />}
    </div>
  );
}

window.HelpPage = HelpPage;
