<script>
  let { spark, showActions = true, onApprove, onReject, onLocalOnly, onDelete, onEdit, onRevert } = $props();

  let expanded = $state(false);
  let editing = $state(false);
  let editContent = $state(spark.content);
  let editDomain = $state(spark.domain || '');
  let editTags = $state(spark.tags?.join(', ') || '');

  function getCardClass() {
    if (spark.state === 'blocked') return 'blocked';
    if (spark.has_warnings) return 'warning';
    return '';
  }

  function formatDate(dateStr) {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return date.toLocaleString();
  }

  function handleApprove() {
    if (spark.state === 'blocked') {
      if (confirm('This spark has security issues. Are you sure you want to approve it?')) {
        onApprove(spark.id, { override_block: true });
      }
    } else {
      onApprove(spark.id);
    }
  }

  function startEditing() {
    editContent = spark.content;
    editDomain = spark.domain || '';
    editTags = spark.tags?.join(', ') || '';
    editing = true;
  }

  function cancelEditing() {
    editing = false;
  }

  function saveEdit() {
    const tags = editTags.split(',').map(t => t.trim()).filter(t => t);
    onEdit(spark.id, {
      content: editContent,
      domain: editDomain || null,
      tags: tags.length > 0 ? tags : null,
    });
    editing = false;
  }

  function handleRevert() {
    if (confirm('Revert this spark to pending for re-review?')) {
      onRevert(spark.id);
    }
  }
</script>

<div class="spark-card {getCardClass()}">
  <div class="spark-header">
    <div class="spark-type">
      <span>{spark.spark_type}</span>
      <span class="tag">{spark.knowledge_type}</span>
    </div>
    <div class="spark-state">
      {#if spark.state === 'blocked'}
        <span class="tag red">Blocked</span>
      {:else if spark.state === 'pending'}
        <span class="tag orange">Pending</span>
      {:else if spark.state === 'approved'}
        <span class="tag green">Approved</span>
      {:else}
        <span class="tag">{spark.state}</span>
      {/if}
    </div>
  </div>

  <div class="spark-content">
    {spark.content}
  </div>

  <div class="spark-meta">
    {#if spark.domain}
      <span>Domain: {spark.domain}</span>
    {/if}
    <span>Confidence: {(spark.confidence * 100).toFixed(0)}%</span>
    <span>{formatDate(spark.created_at)}</span>
  </div>

  {#if spark.tags && spark.tags.length > 0}
    <div class="spark-tags mt-2">
      {#each spark.tags as tag}
        <span class="tag">{tag}</span>
      {/each}
    </div>
  {/if}

  {#if spark.has_warnings || spark.warnings?.length > 0}
    <div class="scan-result">
      <button class="btn btn-ghost" onclick={() => expanded = !expanded}>
        {expanded ? 'Hide' : 'Show'} Security Findings ({spark.warnings?.length || 0})
      </button>

      {#if expanded && spark.warnings}
        <div class="findings mt-2">
          {#each spark.warnings as warning}
            <div class="finding">
              <span class="finding-severity high">Warning</span>
              <span class="finding-text">{warning}</span>
            </div>
          {/each}
        </div>
      {/if}

      {#if expanded && spark.scan_result?.findings}
        <div class="findings mt-2">
          {#each spark.scan_result.findings as finding}
            <div class="finding">
              <span class="finding-severity {finding.severity?.toLowerCase() || 'medium'}">
                {finding.severity || 'Medium'}
              </span>
              <span class="finding-text">
                <strong>{finding.rule_name}:</strong> {finding.description}
              </span>
            </div>
          {/each}
        </div>
      {/if}
    </div>
  {/if}

  {#if editing}
    <div class="edit-form">
      <div class="form-group">
        <label for="edit-content">Content</label>
        <textarea id="edit-content" bind:value={editContent} rows="4"></textarea>
      </div>
      <div class="form-group">
        <label for="edit-domain">Domain</label>
        <input id="edit-domain" type="text" bind:value={editDomain} placeholder="e.g., python, react, devops" />
      </div>
      <div class="form-group">
        <label for="edit-tags">Tags (comma-separated)</label>
        <input id="edit-tags" type="text" bind:value={editTags} placeholder="e.g., pattern, best-practice" />
      </div>
      <div class="edit-actions">
        <button class="btn btn-primary" onclick={saveEdit}>Save</button>
        <button class="btn btn-ghost" onclick={cancelEditing}>Cancel</button>
      </div>
    </div>
  {:else if showActions}
    <div class="action-buttons">
      <button class="btn btn-primary" onclick={handleApprove}>
        {spark.state === 'blocked' ? 'Override & Approve' : 'Approve'}
      </button>
      <button class="btn btn-danger" onclick={() => onReject(spark.id)}>
        Reject
      </button>
      <button class="btn btn-warning" onclick={() => onLocalOnly(spark.id)}>
        Keep Local
      </button>
      <button class="btn btn-ghost" onclick={startEditing}>
        Edit
      </button>
    </div>
  {/if}

  {#if spark.state === 'approved' && !editing}
    <div class="approved-actions mt-2">
      <button class="btn btn-ghost" onclick={startEditing}>Edit Content</button>
      <button class="btn btn-warning" onclick={handleRevert}>Revert to Pending</button>
    </div>
  {/if}

  {#if spark.decision}
    <div class="decision-info mt-2">
      <span class="label">
        {spark.decision.decision} by {spark.decision.decided_by} at {formatDate(spark.decision.decided_at)}
      </span>
      {#if spark.decision.reason}
        <p class="text-muted mt-2">{spark.decision.reason}</p>
      {/if}
    </div>
  {/if}
</div>

<style>
  .spark-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
  }

  .findings {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }

  .decision-info {
    padding-top: 0.75rem;
    border-top: 1px solid var(--border-color);
  }

  .edit-form {
    display: flex;
    flex-direction: column;
    gap: 1rem;
    padding: 1rem;
    background: var(--bg-secondary);
    margin-top: 1rem;
  }

  .form-group {
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
  }

  .form-group label {
    font-size: 0.875rem;
    font-weight: 500;
    color: var(--text-muted);
  }

  .form-group textarea,
  .form-group input {
    padding: 0.5rem;
    border: 1px solid var(--border-color);
    background: var(--bg-primary);
    color: var(--text-primary);
    font-family: inherit;
    font-size: 0.875rem;
  }

  .form-group textarea {
    resize: vertical;
    min-height: 80px;
  }

  .edit-actions {
    display: flex;
    gap: 0.5rem;
  }

  .approved-actions {
    display: flex;
    gap: 0.5rem;
    padding-top: 0.5rem;
    border-top: 1px solid var(--border-color);
  }
</style>
