/* global React, Icon, Badge, PageHeader, apiGet, relativeTime, JSZip, marked, DOMPurify */
const { useState: useSkillsState, useEffect: useSkillsEffect, useMemo: useSkillsMemo } = React;

// === Skills library ==========================================================
// A read-only window onto the club skills repo on GitHub (Agent Skills format: SKILL.md +
// optional text files). The repo is the source of truth. Skills are added and edited by
// agents through the MCP server (upsert_skill, lib/mcp-skills.js) or on GitHub directly;
// each edit is a commit, and this page shows who created a skill and who edited it since.
// Backed by /api/skills*. See tasks/skills-github-storage.md.
//
// Routes (all deep-linkable, so a browser agent can open any view by URL):
//   #/skills                list + search (cards)
//   #/skills/<name>         detail: files (markdown formatted), about, history
//   #/skills/<name>/r/<sha> detail at an older revision (a commit SHA)

const SKILL_MAIN_FILE = 'SKILL.md';

function goToSkills(sub) {
  window.location.hash = sub ? `#/skills/${sub}` : '#/skills';
}

function parseSkillsRoute(routeParam) {
  if (!routeParam) return { view: 'list' };
  const parts = routeParam.split('/');
  const name = parts[0];
  if (parts[1] === 'r' && /^[0-9a-f]{7,40}$/i.test(parts[2] || '')) return { view: 'detail', name, revision: parts[2] };
  return { view: 'detail', name };
}

// Zip the package inside a <name>/ folder, so unzipping into ~/.claude/skills installs it.
async function downloadSkillZip(name, files) {
  if (typeof JSZip === 'undefined') throw new Error('The zip writer did not load. Check your connection and reload.');
  const zip = new JSZip();
  for (const [path, content] of Object.entries(files)) zip.file(`${name}/${path}`, content);
  const blob = await zip.generateAsync({ type: 'blob' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `${name}.zip`;
  document.body.appendChild(link);
  link.click();
  link.remove();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

function skillVia(entry) {
  if (!entry) return '';
  if (entry.via !== 'mcp') return 'on GitHub';
  const client = entry.clientName || 'an MCP client';
  return entry.agentLabel ? `via ${client} (${entry.agentLabel})` : `via ${client}`;
}

const shortSha = (sha) => (sha ? sha.slice(0, 7) : '');

// SKILL.md first, then the rest alphabetically: the entry point leads in every file list.
function sortSkillPaths(paths) {
  return paths.slice().sort((a, b) => (a === SKILL_MAIN_FILE ? -1 : b === SKILL_MAIN_FILE ? 1 : a.localeCompare(b)));
}

function skillDate(iso) {
  return iso ? new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }) : '';
}

function GitHubLink({ href, children, className = 'btn btn-ghost' }) {
  if (!href) return null;
  return (
    <a className={className} href={href} target="_blank" rel="noopener noreferrer">
      <Icon name="github" size={14}/> {children}
    </a>
  );
}

// === Page ====================================================================
function SkillsLibrary({ routeParam = null }) {
  const route = parseSkillsRoute(routeParam);
  if (route.view === 'detail') {
    return <SkillDetailPage key={`${route.name}:${route.revision || ''}`} name={route.name} revision={route.revision}/>;
  }
  return <SkillListPage/>;
}

// === Markdown ================================================================
// .md files render formatted. The text comes from the repo (members, agents, GitHub
// pushes), so marked's HTML always goes through DOMPurify before it is injected. Images are
// dropped: relative ones can't load from a private repo.
const SKILL_MARKDOWN_SANITIZE = { FORBID_TAGS: ['img', 'style', 'form', 'button', 'textarea', 'select'], FORBID_ATTR: ['style'] };

const isMarkdownPath = (path) => /\.(md|markdown)$/i.test(path);
const canRenderMarkdown = () => typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined';

// The formatted view drops the frontmatter: name and description are already the page header.
function stripFrontmatter(markdown) {
  const match = String(markdown).match(/^﻿?---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/);
  return match ? markdown.slice(match[0].length) : markdown;
}

function renderSkillMarkdown(markdown) {
  return DOMPurify.sanitize(marked.parse(stripFrontmatter(markdown), { gfm: true }), SKILL_MARKDOWN_SANITIZE);
}

// === List ====================================================================
function SkillListPage() {
  const [skills, setSkills] = useSkillsState([]);
  const [repoUrl, setRepoUrl] = useSkillsState(null);
  const [status, setStatus] = useSkillsState('loading');
  const [error, setError] = useSkillsState('');
  const [query, setQuery] = useSkillsState('');
  const [showArchived, setShowArchived] = useSkillsState(false);

  useSkillsEffect(() => {
    let cancelled = false;
    const params = new URLSearchParams();
    if (query.trim()) params.set('q', query.trim());
    if (showArchived) params.set('archived', '1');
    // Debounced so typing does not fire a request per keystroke.
    const timer = setTimeout(() => {
      apiGet(`/api/skills${params.toString() ? `?${params}` : ''}`)
        .then((data) => {
          if (cancelled) return;
          setSkills(data.skills || []);
          setRepoUrl(data.repoUrl || null);
          setStatus('ready');
        })
        .catch((err) => { if (!cancelled) { setError(err.message || 'Could not load skills.'); setStatus('error'); } });
    }, query ? 200 : 0);
    return () => { cancelled = true; clearTimeout(timer); };
  }, [query, showArchived]);

  return (
    <div className="skills-page">
      <PageHeader eyebrow="Library" title="Skills"
        sub="Reusable procedures for AI agents, kept in the club skills repo on GitHub. Agents connected to the CGAI MCP server can read them and save new ones."
        actions={<GitHubLink href={repoUrl}>View repo on GitHub</GitHubLink>}/>

      <div className="skills-toolbar">
        <label className="skills-search">
          <span className="sr-only">Search skills</span>
          <Icon name="search" size={14}/>
          <input className="input" type="search" placeholder="Search by name or description"
            aria-label="Search skills" value={query} onChange={(event) => setQuery(event.target.value)}/>
        </label>
        <label className="skills-check">
          <input type="checkbox" checked={showArchived} onChange={(event) => setShowArchived(event.target.checked)}/>
          Show archived
        </label>
        {status === 'ready' && (
          <span className="muted skills-count">{skills.length} skill{skills.length === 1 ? '' : 's'}</span>
        )}
      </div>

      {status === 'error' && <div className="form-error" role="alert">{error}</div>}
      {status === 'loading' && <div className="card muted" role="status">Loading skills…</div>}
      {status === 'ready' && skills.length === 0 && (
        <div className="card skills-empty" role="status">
          {query
            ? `No skills match "${query}".`
            : 'No skills yet. Ask an agent connected to the CGAI MCP server to save one, or add a folder under skills/ in the repo.'}
        </div>
      )}
      {status === 'ready' && skills.length > 0 && (
        <ul className="skills-grid">
          {skills.map((skill) => (
            <li key={skill.name}>
              <a className="card skills-card" href={`#/skills/${skill.name}`}>
                <span className="skills-card-head">
                  <span className="skills-name mono">{skill.name}</span>
                  {skill.archived && <Badge tone="cream">Archived</Badge>}
                  {skill.problem && <Badge tone="coral">Needs fixing</Badge>}
                </span>
                <span className="skills-card-desc">{skill.description || skill.problem}</span>
                <span className="skills-card-meta">
                  <span>By {skill.createdBy?.name || '—'}</span>
                  <span>
                    Edited {relativeTime(skill.updatedAt)}
                    {skill.updatedVia === 'mcp' ? ` via ${skill.updatedClientName || 'agent'}` : ' on GitHub'}
                  </span>
                  <span>{skill.revisionCount} revision{skill.revisionCount === 1 ? '' : 's'}</span>
                </span>
              </a>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

// === Detail ==================================================================
function SkillDetailPage({ name, revision }) {
  const [skill, setSkill] = useSkillsState(null);
  const [status, setStatus] = useSkillsState('loading');
  const [error, setError] = useSkillsState('');
  const [flash, setFlash] = useSkillsState('');
  const [busy, setBusy] = useSkillsState(false);

  useSkillsEffect(() => {
    let cancelled = false;
    setStatus('loading');
    apiGet(`/api/skills/${encodeURIComponent(name)}${revision ? `?revision=${encodeURIComponent(revision)}` : ''}`)
      .then((data) => { if (!cancelled) { setSkill(data.skill); setStatus('ready'); } })
      .catch((err) => { if (!cancelled) { setError(err.message || 'Could not load this skill.'); setStatus('error'); } });
    return () => { cancelled = true; };
  }, [name, revision]);

  async function run(work, done) {
    setBusy(true); setError('');
    try {
      await work();
      if (done) {
        setFlash(done);
        setTimeout(() => setFlash(''), 3200);
      }
    } catch (err) {
      setError(err.message || 'Something went wrong.');
    } finally { setBusy(false); }
  }

  if (status === 'loading' && !skill) return <div className="card muted" role="status">Loading skill…</div>;
  if (status === 'error' && !skill) {
    return (
      <div className="skills-page">
        <button type="button" className="btn btn-ghost btn-sm" onClick={() => goToSkills()}>
          <Icon name="chevron-left" size={14}/> All skills
        </button>
        <div className="form-error" role="alert" style={{ marginTop: 16 }}>{error}</div>
      </div>
    );
  }

  const isOld = skill.revision !== skill.currentRevision;
  const latest = skill.history[0];
  const revisionLink = (sha) => (sha === skill.currentRevision ? `#/skills/${skill.name}` : `#/skills/${skill.name}/r/${sha}`);
  const selectedEntry = skill.history.find((entry) => entry.revision === skill.revision);

  const copyMain = () => run(async () => {
    await navigator.clipboard.writeText(skill.files[SKILL_MAIN_FILE] || '');
  }, `Copied ${SKILL_MAIN_FILE}`);

  return (
    <div className="skills-page skills-detail">
      <button type="button" className="btn btn-ghost btn-sm" onClick={() => goToSkills()}>
        <Icon name="chevron-left" size={14}/> All skills
      </button>
      <div>
        <PageHeader eyebrow={isOld ? `Skill · older revision ${shortSha(skill.revision)}` : 'Skill'}
          title={<span className="mono skills-title">{skill.name}</span>}
          sub={skill.description}/>
        <div className="skills-actions">
          <GitHubLink href={isOld ? selectedEntry?.githubUrl : skill.githubUrl}>View on GitHub</GitHubLink>
          <button type="button" className="btn btn-ghost" disabled={busy}
            onClick={() => run(() => downloadSkillZip(skill.name, skill.files))}>
            <Icon name="download" size={14}/> Download .zip
          </button>
          <button type="button" className="btn btn-ghost" disabled={busy || !skill.files[SKILL_MAIN_FILE]} onClick={copyMain}>
            <Icon name="clipboard" size={14}/> Copy {SKILL_MAIN_FILE}
          </button>
          <span role="status" aria-live="polite" className="skills-flash">{flash}</span>
        </div>
      </div>

      {error && <div className="form-error" role="alert">{error}</div>}

      {skill.problem && (
        <div className="card skills-banner" role="alert">
          This skill needs fixing before agents can rely on it: {skill.problem}
        </div>
      )}
      {skill.archived && (
        <div className="card skills-banner">
          Archived{skill.archivedBy ? ` by ${skill.archivedBy.name}` : ''}{skill.archivedAt ? ` on ${skillDate(skill.archivedAt)}` : ''}.
          {' '}It is hidden from search and kept under <span className="mono">archived/</span> in the repo. Its author or an admin can restore it with an agent (<span className="mono">restore_skill</span>).
        </div>
      )}
      {isOld && (
        <div className="card skills-banner">
          You're viewing revision <span className="mono">{shortSha(skill.revision)}</span>. The current revision is <span className="mono">{shortSha(skill.currentRevision)}</span>.
          <div className="row skills-banner-actions">
            <button type="button" className="btn btn-ghost btn-sm" onClick={() => goToSkills(skill.name)}>View current</button>
          </div>
        </div>
      )}

      {/* Two columns on wide screens. Under 1000px the aside dissolves into the grid so About
          comes first and History follows the files. */}
      <div className="skills-detail-grid">
        <SkillFiles key={skill.revision} skill={skill}/>
        <aside className="skills-aside">
          <section className="card skills-about" aria-label="About this skill">
            <div className="card-eyebrow">About</div>
            <dl>
              <div>
                <dt>Revision</dt>
                <dd>
                  <span className="mono">{shortSha(skill.revision)}</span>
                  <span className="muted"> · {isOld ? 'older revision' : 'current'}</span>
                </dd>
              </div>
              <div>
                <dt>Created by</dt>
                <dd><strong>{skill.createdBy?.name || '—'}</strong> <span className="muted">· {skillDate(skill.createdAt)}</span></dd>
              </div>
              <div>
                <dt>Last edited by</dt>
                <dd>
                  <strong>{skill.lastEditedBy?.name || '—'}</strong>
                  <span className="muted"> · {relativeTime(skill.lastEditedAt)} · {skillVia(latest)}</span>
                </dd>
              </div>
              <div>
                <dt>Contributors</dt>
                <dd className="skills-contributors">
                  {skill.contributors.map((person) => (
                    <span key={person.email} className="chip">
                      {person.name} <span className="chip-count">{person.revisions}</span>
                    </span>
                  ))}
                </dd>
              </div>
            </dl>
          </section>

          <section className="card skills-history" aria-label="History">
            <div className="card-eyebrow">
              History · {skill.revisionCount} revision{skill.revisionCount === 1 ? '' : 's'}
            </div>
            <ol>
              {skill.history.map((entry) => {
                const [subject, ...body] = (entry.changeSummary || '').split('\n');
                return (
                  <li key={entry.revision} className={entry.revision === skill.revision ? 'is-shown' : ''}>
                    <a href={revisionLink(entry.revision)} title={entry.changeSummary || undefined}>
                      <span className="mono skills-sha">{shortSha(entry.revision)}</span>
                      <span className="skills-history-subject">{subject || 'No summary'}</span>
                    </a>
                    {body.join(' ').trim() && <div className="skills-history-body">{body.join(' ').trim()}</div>}
                    <div className="muted skills-small">
                      {entry.author?.name} · {relativeTime(entry.createdAt)} · {skillVia(entry)}
                    </div>
                  </li>
                );
              })}
            </ol>
          </section>

          <section className="card skills-agent-hint">
            <div className="card-eyebrow">Use it with an agent</div>
            <p>
              Agents connected to the CGAI MCP server find this skill with <code>search_skills</code> and read it
              with <code>get_skill("{skill.name}")</code>. To change it, ask the agent to save an edit
              (<code>upsert_skill</code>); it lands in the repo as a commit under your name.
            </p>
            <p>To install it in Claude Code, unzip the download into <code>~/.claude/skills/</code>.</p>
          </section>
        </aside>
      </div>
    </div>
  );
}

// The package's files as tabs. Markdown shows formatted by default, with the stored text
// one click away; everything else shows as code.
function SkillFiles({ skill }) {
  const paths = sortSkillPaths(Object.keys(skill.files));
  const [activePath, setActivePath] = useSkillsState(SKILL_MAIN_FILE);
  const [showSource, setShowSource] = useSkillsState(false);
  const shownPath = paths.includes(activePath) ? activePath : paths[0];
  const formatted = Boolean(shownPath) && isMarkdownPath(shownPath) && !showSource && canRenderMarkdown();
  const html = useSkillsMemo(
    () => (formatted ? renderSkillMarkdown(skill.files[shownPath]) : ''),
    [formatted, skill.files, shownPath],
  );

  // One handler for every link in the rendered markdown. The app routes on the hash, so a
  // bare #anchor would leave the page; a relative link is a file in this package (open its
  // tab) or elsewhere in the repo (open it on GitHub).
  function followMarkdownLink(event) {
    const link = event.target.closest('a[href]');
    if (!link) return;
    const href = link.getAttribute('href');
    event.preventDefault();
    if (href.startsWith('#')) return;
    if (/^[a-z][a-z0-9+.-]*:/i.test(href)) {
      window.open(href, '_blank', 'noopener,noreferrer');
      return;
    }
    const path = href.replace(/^\.\//, '').split(/[?#]/)[0];
    if (paths.includes(path)) setActivePath(path);
    else if (skill.githubUrl) window.open(`${skill.githubUrl}/${path}`, '_blank', 'noopener,noreferrer');
  }

  return (
    <section className="card skills-files" aria-label="Files">
      <div className="skills-files-bar">
        <div className="skills-file-tabs" role="tablist" aria-label="Skill files">
          {paths.map((path) => (
            <button key={path} type="button" role="tab" aria-selected={path === shownPath}
              className={`skills-file-tab mono ${path === shownPath ? 'active' : ''}`} onClick={() => setActivePath(path)}>
              {path}
            </button>
          ))}
        </div>
        {shownPath && isMarkdownPath(shownPath) && canRenderMarkdown() && (
          <div className="view-toggle skills-view-toggle" role="group" aria-label="Show as">
            <button type="button" className={!showSource ? 'active' : ''} aria-pressed={!showSource}
              onClick={() => setShowSource(false)}>Formatted</button>
            <button type="button" className={showSource ? 'active' : ''} aria-pressed={showSource}
              onClick={() => setShowSource(true)}>Source</button>
          </div>
        )}
      </div>
      {!shownPath && <div className="skills-code muted">No text files in this revision.</div>}
      {shownPath && formatted && (
        <div className="skills-md" role="tabpanel" aria-label={shownPath}
          onClick={followMarkdownLink} dangerouslySetInnerHTML={{ __html: html }}/>
      )}
      {shownPath && !formatted && (
        <pre className="skills-code" role="tabpanel" aria-label={shownPath} tabIndex={0}>{skill.files[shownPath]}</pre>
      )}
      {skill.binaryFiles?.length > 0 && (
        <div className="muted skills-binary-note">
          Also in the repo (binary, view on GitHub): <span className="mono">{skill.binaryFiles.join(', ')}</span>
        </div>
      )}
    </section>
  );
}

window.SkillsLibrary = SkillsLibrary;
