// SPDX-License-Identifier: LicenseRef-Commercial
<script lang="ts">
  import {
    proGitContext,
    proGitInject,
    proBranchCheck,
    proSymbolsScan,
    proSymbolsSearch,
    type GitContext,
    type PolicyDecision,
    type CodeSymbol,
  } from './pro-bridge';

  interface Props {
    projectPath: string;
  }

  let { projectPath }: Props = $props();

  let loading = $state(true);
  let error = $state<string | null>(null);

  let gitCtx = $state<GitContext | null>(null);
  let gitInjected = $state<string | null>(null);
  let injecting = $state(false);
  let policy = $state<PolicyDecision | null>(null);
  let scanResult = $state<{ filesScanned: number; symbolsFound: number; durationMs: number } | null>(null);
  let scanning = $state(false);
  let symbolQuery = $state('');
  let symbols = $state<CodeSymbol[]>([]);
  let searchingSymbols = $state(false);

  const KIND_COLORS: Record<string, string> = {
    function: 'var(--ctp-blue)', class: 'var(--ctp-mauve)', interface: 'var(--ctp-teal)',
    type: 'var(--ctp-green)', const: 'var(--ctp-peach)', variable: 'var(--ctp-yellow)',
    enum: 'var(--ctp-pink)', method: 'var(--ctp-sapphire)', struct: 'var(--ctp-flamingo)',
  };

  function errMsg(e: unknown): string { return e instanceof Error ? e.message : String(e); }

  async function loadAll() {
    loading = true; error = null;
    try {
      const [g, p] = await Promise.all([proGitContext(projectPath), proBranchCheck(projectPath)]);
      gitCtx = g; policy = p;
    } catch (e) { error = errMsg(e); }
    finally { loading = false; }
  }

  $effect(() => { void projectPath; loadAll(); });

  async function injectGit() {
    injecting = true;
    try { gitInjected = await proGitInject(projectPath, 4000); }
    catch (e) { error = errMsg(e); }
    finally { injecting = false; }
  }

  async function scanSymbols() {
    scanning = true;
    try { scanResult = await proSymbolsScan(projectPath); }
    catch (e) { error = errMsg(e); }
    finally { scanning = false; }
  }

  async function searchSymbols() {
    if (!symbolQuery.trim() || symbolQuery.trim().length < 2) { symbols = []; return; }
    searchingSymbols = true;
    try { symbols = await proSymbolsSearch(projectPath, symbolQuery.trim()); }
    catch (e) { error = errMsg(e); }
    finally { searchingSymbols = false; }
  }

  function shortHash(h: string): string { return h.slice(0, 7); }
  function shortPath(p: string): string {
    const parts = p.split('/');
    return parts.length > 3 ? '.../' + parts.slice(-2).join('/') : p;
  }
</script>

<div class="ci-root">
  {#if loading}
    <div class="state-msg">Loading code intelligence...</div>
  {:else if error}
    <div class="state-msg error">{error}</div>
  {:else}
    <!-- Git Context -->
    <div class="section">
      <div class="section-title">Git Context</div>
      {#if gitCtx}
        <div class="git-header">
          <span class="branch-badge">{gitCtx.branch}</span>
          {#if gitCtx.hasUnstaged}<span class="unstaged-badge">unstaged changes</span>{/if}
          <button class="btn" onclick={injectGit} disabled={injecting}>
            {injecting ? 'Injecting...' : 'Inject'}
          </button>
        </div>

        {#if gitCtx.lastCommits.length > 0}
          <div class="commit-list">
            {#each gitCtx.lastCommits.slice(0, 5) as c}
              <div class="commit-row"><span class="commit-hash">{shortHash(c.hash)}</span><span class="commit-msg">{c.message}</span></div>
            {/each}
          </div>
        {/if}
        {#if gitCtx.modifiedFiles.length > 0}
          <div class="modified-files">
            <span class="file-count">{gitCtx.modifiedFiles.length} modified</span>
            {#each gitCtx.modifiedFiles.slice(0, 8) as f}<span class="file-path">{shortPath(f)}</span>{/each}
            {#if gitCtx.modifiedFiles.length > 8}<span class="file-more">+{gitCtx.modifiedFiles.length - 8} more</span>{/if}
          </div>
        {/if}

        {#if gitInjected}
          <pre class="inject-preview">{gitInjected}</pre>
        {/if}
      {/if}
    </div>

    <!-- Branch Policy -->
    <div class="section">
      <div class="section-title">Branch Policy</div>
      {#if policy}
        <div class="policy-box" class:allowed={policy.allowed} class:blocked={!policy.allowed}>
          <span class="policy-status">{policy.allowed ? 'Allowed' : 'Blocked'}</span>
          <span class="policy-branch">{policy.branch}</span>
          {#if policy.matchedPolicy}
            <span class="policy-match">Policy: {policy.matchedPolicy}</span>
          {/if}
          <span class="policy-reason">{policy.reason}</span>
        </div>
      {/if}
    </div>

    <!-- Symbol Graph -->
    <div class="section">
      <div class="section-title">Symbol Graph</div>
      <div class="symbol-toolbar">
        <button class="btn secondary" onclick={scanSymbols} disabled={scanning}>
          {scanning ? 'Scanning...' : 'Scan Project'}
        </button>
        {#if scanResult}
          <span class="scan-stats">
            {scanResult.filesScanned} files, {scanResult.symbolsFound} symbols ({scanResult.durationMs}ms)
          </span>
        {/if}
      </div>

      <div class="search-row">
        <input class="search-input" type="text" bind:value={symbolQuery} placeholder="Search symbols..." aria-label="Symbol search query" onkeydown={(e: KeyboardEvent) => e.key === 'Enter' && searchSymbols()} />
        <button class="btn" onclick={searchSymbols} disabled={searchingSymbols} aria-label="Find symbols">{searchingSymbols ? '...' : 'Find'}</button>
      </div>
      {#if symbols.length > 0}
        <div class="symbol-list">
          {#each symbols as sym}
            <div class="symbol-row">
              <span class="kind-badge" style:background={KIND_COLORS[sym.kind] ?? 'var(--ctp-overlay0)'}>{sym.kind}</span>
              <span class="symbol-name">{sym.name}</span>
              <span class="symbol-loc">{shortPath(sym.filePath)}:{sym.lineNumber}</span>
            </div>
          {/each}
        </div>
      {/if}
    </div>
  {/if}
</div>

<style>
  .ci-root {
    padding: 0.75rem; display: flex; flex-direction: column; gap: 0.75rem;
    color: var(--ctp-text); font-family: var(--ui-font-family, system-ui, sans-serif);
    font-size: var(--ui-font-size, 0.8125rem); overflow-y: auto; height: 100%;
  }
  .state-msg { padding: 1.5rem; text-align: center; color: var(--ctp-subtext0); }
  .state-msg.error { color: var(--ctp-red); }
  .section { display: flex; flex-direction: column; gap: 0.375rem; }
  .section-title { font-size: 0.75rem; color: var(--ctp-subtext1); text-transform: uppercase; letter-spacing: 0.04em; }
  .git-header, .symbol-toolbar { display: flex; align-items: center; gap: 0.375rem; flex-wrap: wrap; }
  .branch-badge {
    padding: 0.125rem 0.5rem; border-radius: 0.25rem; background: var(--ctp-mauve);
    color: var(--ctp-base); font-family: monospace; font-size: 0.75rem; font-weight: 600;
  }
  .unstaged-badge {
    padding: 0.0625rem 0.375rem; border-radius: 0.1875rem; background: var(--ctp-yellow);
    color: var(--ctp-base); font-size: 0.625rem; font-weight: 600; text-transform: uppercase;
  }
  .btn {
    padding: 0.3125rem 0.75rem; border-radius: 0.25rem; border: 1px solid var(--ctp-surface1);
    background: var(--ctp-blue); color: var(--ctp-base); cursor: pointer; font-size: 0.75rem;
    font-weight: 500; margin-left: auto;
  }
  .btn:hover { opacity: 0.9; }
  .btn:disabled { opacity: 0.5; cursor: not-allowed; }
  .btn.secondary { background: var(--ctp-surface0); color: var(--ctp-subtext0); margin-left: 0; }
  .btn.secondary:hover { background: var(--ctp-surface1); color: var(--ctp-text); }
  .commit-list, .symbol-list {
    display: flex; flex-direction: column; gap: 0.125rem; padding: 0.375rem;
    background: var(--ctp-surface0); border-radius: 0.375rem; border: 1px solid var(--ctp-surface1);
  }
  .symbol-list { max-height: 15rem; overflow-y: auto; }
  .commit-row { display: flex; gap: 0.375rem; align-items: baseline; font-size: 0.75rem; }
  .commit-hash { font-family: monospace; color: var(--ctp-peach); font-size: 0.6875rem; flex-shrink: 0; }
  .commit-msg { color: var(--ctp-subtext1); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .modified-files { display: flex; flex-wrap: wrap; gap: 0.25rem; align-items: center; font-size: 0.6875rem; }
  .file-count { color: var(--ctp-yellow); font-weight: 600; margin-right: 0.25rem; }
  .file-path {
    padding: 0.0625rem 0.3125rem; border-radius: 0.1875rem; background: var(--ctp-surface0);
    color: var(--ctp-subtext0); font-family: monospace; font-size: 0.625rem;
  }
  .file-more { color: var(--ctp-overlay0); }
  .inject-preview {
    font-family: monospace; font-size: 0.6875rem; color: var(--ctp-subtext0);
    background: var(--ctp-surface0); border-radius: 0.375rem; border: 1px solid var(--ctp-teal);
    padding: 0.375rem; white-space: pre-wrap; word-break: break-word; max-height: 8rem; overflow-y: auto; margin: 0;
  }
  .policy-box {
    display: flex; flex-wrap: wrap; gap: 0.375rem; align-items: center;
    padding: 0.5rem 0.625rem; border-radius: 0.375rem; border: 1px solid var(--ctp-surface1); font-size: 0.75rem;
  }
  .policy-box.allowed { background: color-mix(in srgb, var(--ctp-green) 8%, var(--ctp-surface0)); border-color: var(--ctp-green); }
  .policy-box.blocked { background: color-mix(in srgb, var(--ctp-red) 8%, var(--ctp-surface0)); border-color: var(--ctp-red); }
  .policy-status { font-weight: 700; }
  .policy-box.allowed .policy-status { color: var(--ctp-green); }
  .policy-box.blocked .policy-status { color: var(--ctp-red); }
  .policy-branch { font-family: monospace; color: var(--ctp-mauve); }
  .policy-match, .policy-reason, .scan-stats { color: var(--ctp-overlay0); font-size: 0.6875rem; }
  .policy-reason { flex-basis: 100%; color: var(--ctp-subtext0); }
  .search-row { display: flex; gap: 0.375rem; }
  .search-input {
    flex: 1; padding: 0.3125rem 0.5rem; border-radius: 0.25rem;
    border: 1px solid var(--ctp-surface1); background: var(--ctp-surface0); color: var(--ctp-text); font-size: 0.75rem;
  }
  .search-input:focus { outline: none; border-color: var(--ctp-blue); }
  .symbol-row {
    display: flex; gap: 0.375rem; align-items: center; font-size: 0.75rem;
    padding: 0.1875rem 0.25rem; border-radius: 0.1875rem;
  }
  .symbol-row:hover { background: var(--ctp-surface1); }
  .kind-badge {
    padding: 0.0625rem 0.3125rem; border-radius: 0.1875rem; font-size: 0.5625rem;
    font-weight: 600; color: var(--ctp-base); text-transform: uppercase; letter-spacing: 0.03em; flex-shrink: 0;
  }
  .symbol-name { font-family: monospace; color: var(--ctp-text); font-weight: 500; }
  .symbol-loc { font-family: monospace; font-size: 0.625rem; color: var(--ctp-overlay0); margin-left: auto; flex-shrink: 0; }
</style>
