/* Sections: agents, automation flow, run drawer, api, install, faq, footer */
const { useState: useState2, useEffect: useEffect2, useRef: useRef2 } = React;


/* ---------- Run drawer (live agent stream mock) ---------- */

const RUN_LINES = [
  { t: "cmd", s: "$ claude --skill .agents/programmer/SKILL.md" },
  { t: "dim", s: "→ trigger: ticketInColumn(InProgress) on #51" },
  { t: "dim", s: "→ memory: .agents/programmer/memory.md (1.2kb)" },
  { t: "",    s: "Reading ticket #51 — Stream claude CLI output…" },
  { t: "",    s: "Locating SSE endpoint in KittyClaw.Web/Endpoints…" },
  { t: "ok",  s: "✓ Found AgentRunsController.cs:84" },
  { t: "",    s: "Patching response stream → drawer hub…" },
  { t: "ok",  s: "✓ 3 files modified, 0 tests broken" },
  { t: "dim", s: "→ commitAgentMemory: writing memory.md" },
  { t: "ok",  s: "✓ git commit \"programmer ran on #51\"" },
  { t: "",    s: "Moving #51 → Review" },
];

function RunDrawer() {
  const [count, setCount] = useState2(1);
  useEffect2(() => {
    const i = setInterval(() => {
      setCount((c) => (c >= RUN_LINES.length ? 1 : c + 1));
    }, 900);
    return () => clearInterval(i);
  }, []);
  return (
    <div className="run-drawer">
      <div className="run-head">
        <div className="left">
          <span className="pulse"></span>
          <span>programmer · run.42f8e1</span>
        </div>
        <div style={{ color: "var(--ink-dim)" }}>streaming</div>
      </div>
      <div className="run-body">
        {RUN_LINES.slice(0, count).map((l, i) => (
          <span key={i} className={`line ${l.t}`}>{l.s}</span>
        ))}
        {count < RUN_LINES.length && <span className="cursor"></span>}
      </div>
    </div>
  );
}

/* ---------- Agents ---------- */

const AGENTS = [
  { handle: "programmer",   glyph: "01", title: "Programmer",   desc: "Reads tickets, writes code, runs tests, opens PRs." },
  { handle: "groomer",      glyph: "02", title: "Groomer",      desc: "Splits epics into sub-tickets, sets labels and priority." },
  { handle: "producer",     glyph: "03", title: "Producer",     desc: "Sequences work across columns, unblocks stalls." },
  { handle: "qa-tester",    glyph: "04", title: "QA Tester",    desc: "Reviews diffs, writes test plans, files bugs." },
  { handle: "committer",    glyph: "05", title: "Committer",    desc: "Auto-commits memory.md and groups changes by ticket." },
  { handle: "code-janitor", glyph: "06", title: "Code Janitor", desc: "Refactors, deletes dead code, keeps the repo tidy." },
  { handle: "evaluator",    glyph: "07", title: "Evaluator",    desc: "Grades agent outputs against rubrics, escalates regressions." },
];

const AGENT_ICON = (
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
    <circle cx="12" cy="12" r="3"/>
    <path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/>
  </svg>
);

function Agents() {
  return (
    <section id="agents" className="section">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow"><span className="dot"></span>The roster</span>
          <h2 className="h2">A member becomes an agent.</h2>
          <p className="lead">
            There's no second-class citizen — humans and agents share the same membership model.
            Wire a <span className="mono">SKILL.md</span> + an automation to a handle, and that
            member starts taking shifts.
          </p>
        </div>

        <div className="agent-grid">
          {AGENTS.map((a) => (
            <div key={a.handle} className="agent-card">
              <span className="glyph">{a.glyph}</span>
              <div className="icon">{AGENT_ICON}</div>
              <h4>{a.title}</h4>
              <p>{a.desc}</p>
              <span className="handle">@{a.handle}</span>
            </div>
          ))}
          <div className="agent-card" style={{ display: "flex", flexDirection: "column", justifyContent: "center" }}>
            <h4 style={{ color: "var(--ink-mute)" }}>+ define your own</h4>
            <p>Drop a SKILL.md and memory.md into <span className="mono">.agents/&lt;your-name&gt;/</span> and KittyClaw picks it up on next init.</p>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Automation flow ---------- */

const TRIGGERS = ["interval", "ticketInColumn", "statusChange", "ticketCommentAdded", "gitCommit", "boardIdle"];
const CONDITIONS = ["priority", "labels", "assignedTo", "hasParent", "ticketAge", "fieldLength"];
const ACTIONS = ["runAgent", "moveTicketStatus", "setLabels", "assignTicket", "addComment", "commitAgentMemory"];

const Arrow = () => (
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
    <path d="M5 12h14M13 6l6 6-6 6"/>
  </svg>
);

function Automations() {
  return (
    <section id="automations" className="section">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow"><span className="dot"></span>The engine</span>
          <h2 className="h2">When this, check that, run them.</h2>
          <p className="lead">
            A background AutomationEngine watches the board and dispatches agents.
            Compose triggers, conditions, and actions into rules — version them in <span className="mono">automations.json</span>.
          </p>
        </div>

        <div className="automation">
          <div className="auto-flow">
            <div className="auto-col">
              <h5>Triggers</h5>
              <ul className="auto-list">{TRIGGERS.map((t) => <li key={t}>{t}</li>)}</ul>
            </div>
            <div className="arrow"><Arrow/></div>
            <div className="auto-col">
              <h5>Conditions</h5>
              <ul className="auto-list">{CONDITIONS.map((t) => <li key={t}>{t}</li>)}</ul>
            </div>
            <div className="arrow"><Arrow/></div>
            <div className="auto-col">
              <h5>Actions</h5>
              <ul className="auto-list">{ACTIONS.map((t) => <li key={t}>{t}</li>)}</ul>
            </div>
          </div>

          <div style={{ marginTop: 28, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}
               className="auto-bottom">
            <div className="code-block">
              <div className="code-head">
                <span style={{ color: "var(--ink)" }}>automations.json</span>
                <span>rule 03</span>
              </div>
              <div className="code-body">{`{
  `}<span className="tk-key">"trigger"</span>{`: { `}<span className="tk-key">"type"</span>{`: `}<span className="tk-str">"ticketInColumn"</span>{`,
              `}<span className="tk-key">"column"</span>{`: `}<span className="tk-str">"InProgress"</span>{` },
  `}<span className="tk-key">"conditions"</span>{`: [
    { `}<span className="tk-key">"type"</span>{`: `}<span className="tk-str">"priority"</span>{`,
      `}<span className="tk-key">"in"</span>{`: [`}<span className="tk-str">"Required"</span>{`, `}<span className="tk-str">"Critical"</span>{`] }
  ],
  `}<span className="tk-key">"actions"</span>{`: [
    { `}<span className="tk-key">"type"</span>{`: `}<span className="tk-str">"runAgent"</span>{`,
      `}<span className="tk-key">"agent"</span>{`: `}<span className="tk-str">{'"{assignee}"'}</span>{` },
    { `}<span className="tk-key">"type"</span>{`: `}<span className="tk-str">"commitAgentMemory"</span>{` }
  ]
}`}</div>
            </div>
            <RunDrawer/>
          </div>
        </div>
      </div>
      <style dangerouslySetInnerHTML={{ __html: `
        @media (max-width: 880px) {
          .auto-bottom { grid-template-columns: 1fr !important; }
        }
      `}}/>
    </section>
  );
}

/* ---------- API section ---------- */

const API_POINTS = [
  { num: "01", title: "Self-describing", body: "Live OpenAPI at /openapi/v1.json. Auto-generated Markdown docs at /api/docs — always in sync with the running server." },
  { num: "02", title: "Members are members", body: "No special prefix — humans and agents share one membership model. A member becomes an agent the moment a SKILL.md and an automation are wired up to its handle." },
  { num: "03", title: "Discover the board", body: "Columns, members, labels — fetch them first, then create or move tickets. The schema is the contract." },
  { num: "04", title: "Mentions & references", body: "@handle pings members, #id cross-links tickets. /api/projects/{slug}/mentions/{handle} returns your inbox." },
];

function ApiSection() {
  const [tab, setTab] = useState2("create");

  const tabs = {
    create: `<span class="tk-method">POST</span> /api/projects/kittyclaw/tickets

{
  <span class="tk-key">"title"</span>: <span class="tk-str">"Wire automation engine"</span>,
  <span class="tk-key">"status"</span>: <span class="tk-str">"InProgress"</span>,
  <span class="tk-key">"priority"</span>: <span class="tk-str">"Critical"</span>,
  <span class="tk-key">"labels"</span>: [<span class="tk-str">"arch"</span>],
  <span class="tk-key">"assignedTo"</span>: <span class="tk-str">"programmer"</span>,
  <span class="tk-key">"createdBy"</span>: <span class="tk-str">"groomer"</span>
}`,
    move: `<span class="tk-method">PUT</span> /api/projects/kittyclaw/tickets/<span class="tk-num">51</span>/status

{
  <span class="tk-key">"status"</span>: <span class="tk-str">"Review"</span>,
  <span class="tk-key">"updatedBy"</span>: <span class="tk-str">"programmer"</span>
}

<span class="tk-com">// 200 OK — column.onEnter triggers fire</span>`,
    comment: `<span class="tk-method">POST</span> /api/projects/kittyclaw/tickets/<span class="tk-num">51</span>/comments

{
  <span class="tk-key">"body"</span>: <span class="tk-str">"Patched. cc @owner, depends on #47"</span>,
  <span class="tk-key">"author"</span>: <span class="tk-str">"programmer"</span>
}`,
    mentions: `<span class="tk-method">GET</span> /api/projects/kittyclaw/mentions/programmer

[
  { <span class="tk-key">"ticketId"</span>: <span class="tk-num">51</span>,
    <span class="tk-key">"by"</span>: <span class="tk-str">"owner"</span>,
    <span class="tk-key">"context"</span>: <span class="tk-str">"@programmer can you take #51?"</span> },
  { <span class="tk-key">"ticketId"</span>: <span class="tk-num">47</span>,
    <span class="tk-key">"by"</span>: <span class="tk-str">"groomer"</span>,
    <span class="tk-key">"context"</span>: <span class="tk-str">"split out #47 — assigned @programmer"</span> }
]`
  };

  return (
    <section id="api" className="section">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow"><span className="dot"></span>The API</span>
          <h2 className="h2">An API agents can drive.</h2>
          <p className="lead">
            Every UI action is a REST call. Point an LLM at the docs and it can plan, file, comment,
            and move tickets — same surface as a human teammate.
          </p>
        </div>

        <div className="api-grid">
          <div className="api-points">
            {API_POINTS.map((p) => (
              <div key={p.num} className="api-point">
                <div className="num">{p.num}</div>
                <div>
                  <h4>{p.title}</h4>
                  <p>{p.body}</p>
                </div>
              </div>
            ))}
          </div>

          <div className="code-block">
            <div className="code-head">
              <div className="tabs">
                {[["create","create"],["move","move"],["comment","comment"],["mentions","mentions"]].map(([k,l]) => (
                  <span key={k} className={`tab ${tab===k?"active":""}`} onClick={()=>setTab(k)}>{l}</span>
                ))}
              </div>
              <span>http</span>
            </div>
            <div className="code-body" dangerouslySetInnerHTML={{ __html: tabs[tab] }}/>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Install ---------- */

function Install() {
  return (
    <section id="install" className="section">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow"><span className="dot"></span>Get it running</span>
          <h2 className="h2">Three steps. Local-first.</h2>
          <p className="lead">
            Self-hosted .NET 10 + Blazor Server. SQLite per project, files on disk, your repo stays yours.
          </p>
        </div>

        <div className="steps">
          <div className="step">
            <span className="step-num">STEP 01</span>
            <h4>Install the prereqs</h4>
            <p>.NET 10 SDK, the Claude Code CLI, and git on your PATH.</p>
            <div className="cmd"><span className="prompt">$</span><span>brew install dotnet@10 git</span></div>
          </div>
          <div className="step">
            <span className="step-num">STEP 02</span>
            <h4>Clone &amp; run</h4>
            <p>Hot-reload dev server at <span className="mono">localhost:5230</span>.</p>
            <div className="cmd"><span className="prompt">$</span><span>./run.sh</span></div>
          </div>
          <div className="step">
            <span className="step-num">STEP 03</span>
            <h4>Create a project</h4>
            <p>Point it at a workspace folder. KittyClaw scaffolds <span className="mono">.agents/</span> and <span className="mono">git init</span>s if needed.</p>
            <div className="cmd"><span className="prompt">→</span><span style={{color:"var(--accent)"}}>open localhost:5230</span></div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Features grid ---------- */

const FEATURES = [
  { t: "Drag-and-drop", d: "Real kanban with dependable drag, column reorder, custom colors." },
  { t: "Sub-tickets", d: "Parent/child relationships with rolled-up progress and detach support." },
  { t: "Live run drawer", d: "SSE-streamed Claude Code output with steer + stop controls." },
  { t: "Image upload", d: "Drop screenshots into descriptions and comments." },
  { t: "Search syntax", d: "#42, @owner, label:bug, priority:critical, by:owner, >date." },
  { t: "Per-project DB", d: "One SQLite file per project in %APPDATA%. Easy to back up." },
];

const FEAT_ICONS = ["⌘","⊞","∿","◫","⌕","⎔"];

function Features() {
  return (
    <section className="section section-tight">
      <div className="container">
        <div className="feature-row">
          {FEATURES.map((f, i) => (
            <div key={f.t} className="feature">
              <span className="ico mono" style={{ fontSize: 22 }}>{FEAT_ICONS[i]}</span>
              <h4>{f.t}</h4>
              <p>{f.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- FAQ ---------- */

const FAQS = [
  { q: "Do I need the Claude Code CLI?", a: "Only for agent runs. The board, tickets, automations editor, and API all work without it. The onboarding popup detects whether claude is on your PATH and tells you what's missing." },
  { q: "Where does my data live?", a: "Locally. The registry, per-project SQLite databases, uploads, and run snapshots all sit in %APPDATA%/KittyClaw/. Per-project agent state (memory.md, channel/) lives in your workspace folder." },
  { q: "Can humans and agents collaborate on the same board?", a: "That's the whole point. Members are members — there's no special prefix. A member becomes an agent the moment you wire a SKILL.md and an automation to its handle. Same mentions, same assignments, same timeline." },
  { q: "How do I add my own agent?", a: "Drop a SKILL.md and an empty memory.md into .agents/<your-name>/, then re-init the template from the Automations page. The slug becomes a member you can assign tickets to." },
  { q: "Is it self-hosted?", a: "Yes. Single Blazor Server app, runs on Windows, macOS, and Linux. No cloud, no telemetry, no accounts." },
];

function Faq() {
  const [open, setOpen] = useState2(0);
  return (
    <section id="faq" className="section">
      <div className="container" style={{ maxWidth: 820 }}>
        <div className="section-head" style={{ marginBottom: 32 }}>
          <span className="eyebrow"><span className="dot"></span>FAQ</span>
          <h2 className="h2">Things people ask.</h2>
        </div>
        <div className="faq">
          {FAQS.map((f, i) => (
            <div key={i} className={`faq-item ${open===i?"open":""}`} onClick={() => setOpen(open===i?-1:i)}>
              <div className="faq-q">
                <span>{f.q}</span>
                <span className="toggle">+</span>
              </div>
              <div className="faq-a">{f.a}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- CTA + Footer ---------- */

function CtaStrip() {
  return (
    <section className="section section-tight">
      <div className="container">
        <div className="cta-strip">
          <span className="eyebrow" style={{marginBottom:16}}><span className="dot"></span>MIT licensed · self-hosted</span>
          <h2 className="h2">Hand the board to your agents.</h2>
          <p className="lead" style={{margin:"0 auto 28px"}}>
            Open source, local-first, and built for the way LLMs actually want to work.
          </p>
          <div style={{ display:"flex", gap:12, justifyContent:"center", flexWrap:"wrap" }}>
            <a className="btn btn-primary" href="https://github.com/Ekioo/KittyClaw">
              <GithubIcon/> Star on GitHub
            </a>
            <a className="btn btn-ghost" href="#install">Read the quickstart</a>
          </div>
        </div>
      </div>
    </section>
  );
}

function GithubIcon() {
  return (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor">
      <path d="M12 .3a12 12 0 0 0-3.8 23.4c.6.1.8-.3.8-.6v-2.2c-3.3.7-4-1.6-4-1.6-.6-1.4-1.4-1.8-1.4-1.8-1.1-.7.1-.7.1-.7 1.2.1 1.9 1.3 1.9 1.3 1.1 1.9 2.9 1.4 3.6 1 .1-.8.4-1.4.8-1.7-2.7-.3-5.5-1.3-5.5-6 0-1.3.5-2.4 1.2-3.2-.1-.3-.5-1.5.1-3.2 0 0 1-.3 3.3 1.2a11.5 11.5 0 0 1 6 0c2.3-1.5 3.3-1.2 3.3-1.2.7 1.7.2 2.9.1 3.2.8.8 1.2 1.9 1.2 3.2 0 4.7-2.8 5.7-5.5 6 .4.4.8 1.1.8 2.2v3.2c0 .3.2.7.8.6A12 12 0 0 0 12 .3"/>
    </svg>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div className="foot-col">
            <div className="brand" style={{ marginBottom: 14 }}>
              <span className="brand-mark"><PawMark/></span>
              <span>KittyClaw</span>
            </div>
            <p style={{ fontSize: 13, color: "var(--ink-mute)", margin:0, maxWidth: 280, lineHeight: 1.55 }}>
              A kanban that orchestrates agents. Open source, local-first, MIT licensed.
            </p>
          </div>
          <div className="foot-col">
            <h6>Project</h6>
            <a href="#agents">Agents</a>
            <a href="#automations">Automations</a>
            <a href="#api">API</a>
            <a href="#install">Quickstart</a>
          </div>
          <div className="foot-col">
            <h6>Resources</h6>
            <a href="https://github.com/Ekioo/KittyClaw">GitHub</a>
            <a href="https://github.com/Ekioo/KittyClaw/blob/main/README.md">README</a>
            <a href="https://github.com/Ekioo/KittyClaw/blob/main/LICENSE">License</a>
            <a href="https://docs.claude.com/en/docs/claude-code/overview">Claude Code</a>
          </div>
          <div className="foot-col">
            <h6>Contact</h6>
            <a href="https://ekioo.com">ekioo.com</a>
            <a href="https://x.com/DamienHOFFSCHIR">@DamienHOFFSCHIR</a>
          </div>
        </div>
        <div className="foot-bottom">
          <span>© 2026 Ekioo · MIT</span>
          <span>built local, runs local</span>
        </div>
      </div>
    </footer>
  );
}

/* ---------- Paw mark logo ---------- */

function PawMark({ size = 28 }) {
  return (
    <img src="assets/picto.png" alt="" width={size} height={size} style={{ objectFit: "contain" }}/>
  );
}

Object.assign(window, {
  Agents, Automations, ApiSection, Install, Features, Faq, CtaStrip, Footer, PawMark, GithubIcon
});
