<!-- @format -->
<script lang="ts">
  import type { AiHealthDto, CoachPlanDto } from "$lib/backend/ai";
  import {
    activeConversationStore,
    sendConversationMessage,
    clearActiveConversation,
  } from "$lib/stores/conversations";

  export let health: AiHealthDto | null = null;
  export let healthChecking = false;

  export let coachBusy = false;
  export let coachError = "";
  export let coachPlan: CoachPlanDto | null = null;
  export let coachKind = "";

  $: chatBusy = $activeConversationStore.busy;
  $: chatMessages = $activeConversationStore.messages;

  let chatInput = "";

  function handleChatSubmit() {
    const prompt = chatInput.trim();
    if (!prompt) return;
    chatInput = "";
    void sendConversationMessage(prompt);
  }

  function handleChatKeydown(event: KeyboardEvent) {
    if (event.key === "Enter" && !event.shiftKey) {
      event.preventDefault();
      handleChatSubmit();
    }
  }

  const kindLabels: Record<string, string> = {
    daily: "Daily Check-In",
    daily_checkin: "Daily Check-In",
    evening: "Evening Review",
    evening_review: "Evening Review",
    weekly: "Weekly Review",
    weekly_review: "Weekly Review",
  };
</script>

<div class="coach-panel">
  <!-- Health banner -->
  <div
    class="health-banner"
    class:is-healthy={health?.healthy}
    class:is-unhealthy={health && !health.healthy}
  >
    {#if healthChecking}
      <span class="health-dot checking"></span>
      <span class="health-label">Checking AI status…</span>
    {:else if health}
      <span
        class="health-dot"
        class:healthy={health.healthy}
        class:unhealthy={!health.healthy}
      ></span>
      <span class="health-label">
        {health.provider || "AI"} — {health.healthy ? "Ready" : "Unavailable"}
      </span>
      {#if health.message}
        <span class="health-message">{health.message}</span>
      {/if}
    {:else}
      <span class="health-dot unknown"></span>
      <span class="health-label">AI status unknown</span>
    {/if}
  </div>

  <!-- Coach result -->
  {#if coachBusy}
    <div class="coach-loading">
      <div class="spinner"></div>
      <p>Running {kindLabels[coachKind] ?? "coach session"}…</p>
      <p class="loading-hint">
        This may take a moment while the model generates a response.
      </p>
    </div>
  {:else if coachError}
    <div class="coach-error">
      <span class="material-symbols-outlined error-icon">error</span>
      <p>{coachError}</p>
    </div>
  {:else if coachPlan}
    <article class="coach-plan">
      <header class="plan-header">
        <span class="plan-kind"
          >{kindLabels[coachPlan.kind] ?? coachPlan.kind}</span
        >
        <h2>{coachPlan.title}</h2>
      </header>

      {#if coachPlan.summary}
        <section class="plan-section">
          <h3>Summary</h3>
          <p>{coachPlan.summary}</p>
        </section>
      {/if}

      {#if coachPlan.questions.length > 0}
        <section class="plan-section">
          <h3>Reflection Questions</h3>
          <ol class="plan-list">
            {#each coachPlan.questions as question}
              <li>{question}</li>
            {/each}
          </ol>
        </section>
      {/if}

      {#if coachPlan.suggestedNextActions.length > 0}
        <section class="plan-section">
          <h3>Suggested Next Actions</h3>
          <ul class="plan-list">
            {#each coachPlan.suggestedNextActions as action}
              <li>{action}</li>
            {/each}
          </ul>
        </section>
      {/if}

      {#if coachPlan.suggestedTags.length > 0}
        <section class="plan-section">
          <h3>Suggested Tags</h3>
          <div class="tag-list">
            {#each coachPlan.suggestedTags as tag}
              <span class="tag">{tag}</span>
            {/each}
          </div>
        </section>
      {/if}

      {#if coachPlan.evidence.length > 0}
        <section class="plan-section">
          <h3>Evidence</h3>
          <ul class="evidence-list">
            {#each coachPlan.evidence as item}
              <li>
                <span class="evidence-text">{item.text}</span>
                {#if item.recordId}
                  <span class="evidence-ref">({item.recordId})</span>
                {/if}
              </li>
            {/each}
          </ul>
        </section>
      {/if}

      {#if coachPlan.patchProposal}
        <section class="plan-section">
          <h3>Patch Proposal</h3>
          <div class="patch-proposal">
            <span class="patch-kind">{coachPlan.patchProposal.kind}</span>
            {#if coachPlan.patchProposal.description}
              <p>{coachPlan.patchProposal.description}</p>
            {/if}
            {#if coachPlan.patchProposal.content}
              <pre class="patch-content">{coachPlan.patchProposal.content}</pre>
            {/if}
          </div>
        </section>
      {/if}
    </article>
  {:else if chatMessages.length === 0 && !chatBusy}
    <div class="coach-empty">
      <span class="material-symbols-outlined empty-icon">psychology</span>
      <p>
        Select a coaching session from the sidebar, or ask a question using the
        input below.
      </p>
    </div>
  {/if}

  <!-- Chat conversation -->
  {#if chatMessages.length > 0}
    <section class="chat-history">
      <h3>Conversation</h3>
      <div class="chat-messages">
        {#each chatMessages as msg}
          <div
            class="chat-msg"
            class:chat-user={msg.role === "user"}
            class:chat-assistant={msg.role === "assistant"}
            class:chat-error={msg.role === "error"}
          >
            <span class="chat-role"
              >{msg.role === "user"
                ? "You"
                : msg.role === "error"
                  ? "Error"
                  : "AI"}</span
            >
            <div class="chat-text">{msg.text}</div>
          </div>
        {/each}
        {#if chatBusy}
          <div class="chat-msg chat-assistant">
            <span class="chat-role">AI</span>
            <div class="chat-thinking">
              <div class="spinner-sm"></div>
              <span>Thinking…</span>
            </div>
          </div>
        {/if}
      </div>
    </section>
  {:else if chatBusy}
    <div class="chat-loading">
      <div class="spinner"></div>
      <p>Thinking…</p>
    </div>
  {/if}

  <!-- Chat input (pinned at bottom) -->
  <div class="chat-input-bar">
    <div class="chat-input-row">
      <input
        type="text"
        bind:value={chatInput}
        placeholder="Ask a question…"
        on:keydown={handleChatKeydown}
        disabled={chatBusy}
      />
      <button
        type="button"
        class="chat-send-btn"
        on:click={handleChatSubmit}
        disabled={chatBusy || !chatInput.trim()}
        aria-label="Send"
      >
        <span class="material-symbols-outlined">send</span>
      </button>
    </div>
    {#if chatMessages.length > 0}
      <button
        type="button"
        class="chat-clear-btn"
        on:click={clearActiveConversation}
      >
        Clear Chat
      </button>
    {/if}
  </div>
</div>

<style>
  .coach-panel {
    display: flex;
    flex-direction: column;
    gap: 20px;
    padding: 24px 24px 0;
    overflow: auto;
    min-height: 0;
    flex: 1;
  }

  /* ── Health banner ───────────────────────────────── */

  .health-banner {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 14px;
    border-radius: 10px;
    border: 1px solid var(--border-soft);
    background: var(--surface-1);
    font-size: 0.82rem;
  }

  .health-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    flex-shrink: 0;

    &.healthy {
      background: #4ade80;
    }

    &.unhealthy {
      background: #e06c75;
    }

    &.checking {
      background: var(--text-dim);
      animation: pulse 1s ease-in-out infinite;
    }

    &.unknown {
      background: var(--text-dim);
    }
  }

  .health-label {
    color: var(--text-primary);
    font-weight: 500;
  }

  .health-message {
    color: var(--text-dim);
    margin-left: auto;
  }

  /* ── Coach plan ──────────────────────────────────── */

  .coach-plan {
    display: flex;
    flex-direction: column;
    gap: 18px;
  }

  .plan-header {
    display: flex;
    flex-direction: column;
    gap: 4px;

    h2 {
      font-size: 1.15rem;
      font-weight: 600;
      color: var(--text-primary);
    }
  }

  .plan-kind {
    font-size: 0.72rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    color: var(--text-dim);
  }

  .plan-section {
    display: flex;
    flex-direction: column;
    gap: 8px;

    h3 {
      font-size: 0.82rem;
      font-weight: 600;
      color: var(--text-muted);
      letter-spacing: 0.01em;
    }

    p {
      font-size: 0.88rem;
      color: var(--text-primary);
      line-height: 1.55;
    }
  }

  .plan-list {
    display: flex;
    flex-direction: column;
    gap: 6px;
    padding-left: 20px;

    li {
      font-size: 0.86rem;
      color: var(--text-primary);
      line-height: 1.5;
    }
  }

  .tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
  }

  .tag {
    padding: 3px 10px;
    border-radius: 20px;
    border: 1px solid var(--border-soft);
    background: var(--surface-2);
    font-size: 0.76rem;
    color: var(--text-muted);
  }

  .evidence-list {
    display: flex;
    flex-direction: column;
    gap: 6px;
    list-style: none;

    li {
      padding: 8px 12px;
      border-radius: 8px;
      border: 1px solid var(--border-soft);
      background: var(--surface-1);
      font-size: 0.84rem;
      line-height: 1.45;
    }
  }

  .evidence-text {
    color: var(--text-primary);
  }

  .evidence-ref {
    color: var(--text-dim);
    font-size: 0.76rem;
    margin-left: 6px;
  }

  .patch-proposal {
    padding: 12px;
    border-radius: 8px;
    border: 1px solid var(--border-soft);
    background: var(--surface-1);
    display: flex;
    flex-direction: column;
    gap: 8px;

    p {
      font-size: 0.84rem;
      color: var(--text-primary);
      line-height: 1.5;
    }
  }

  .patch-kind {
    font-size: 0.72rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.04em;
    color: var(--text-dim);
  }

  .patch-content {
    font-family: "Cascadia Code", "Fira Code", monospace;
    font-size: 0.8rem;
    color: var(--text-muted);
    background: var(--surface-2);
    padding: 10px 12px;
    border-radius: 6px;
    border: 1px solid var(--border-soft);
    overflow-x: auto;
    white-space: pre-wrap;
    word-break: break-word;
  }

  /* ── Chat conversation ────────────────────────────── */

  .chat-history {
    display: flex;
    flex-direction: column;
    gap: 10px;
    border-top: 1px solid var(--border-soft);
    padding-top: 18px;

    h3 {
      font-size: 0.82rem;
      font-weight: 600;
      color: var(--text-muted);
    }
  }

  .chat-messages {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .chat-msg {
    display: flex;
    flex-direction: column;
    gap: 4px;
    padding: 10px 14px;
    border-radius: 10px;
    border: 1px solid var(--border-soft);
  }

  .chat-user {
    background: var(--surface-2);
    align-self: flex-end;
    max-width: 85%;
  }

  .chat-assistant {
    background: var(--surface-1);
    align-self: flex-start;
    max-width: 85%;
  }

  .chat-error {
    background: rgba(224, 108, 117, 0.08);
    border-color: #e06c75;
    align-self: flex-start;
    max-width: 85%;
  }

  .chat-role {
    font-size: 0.7rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.04em;
    color: var(--text-dim);
  }

  .chat-error .chat-role {
    color: #e06c75;
  }

  .chat-text {
    font-size: 0.86rem;
    color: var(--text-primary);
    line-height: 1.55;
    white-space: pre-wrap;
    word-break: break-word;
  }

  .chat-thinking {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 0.82rem;
    color: var(--text-dim);
  }

  .spinner-sm {
    width: 16px;
    height: 16px;
    border: 2px solid var(--border-soft);
    border-top-color: var(--text-muted);
    border-radius: 50%;
    animation: spin 0.7s linear infinite;
  }

  /* ── Empty / loading / error ─────────────────────── */

  .coach-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 10px;
    padding: 60px 20px;
    text-align: center;

    .empty-icon {
      font-size: 2.8rem;
      color: var(--text-dim);
    }

    p {
      font-size: 0.88rem;
      color: var(--text-dim);
      max-width: 320px;
    }
  }

  .coach-loading,
  .chat-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    padding: 40px 20px;
    text-align: center;

    p {
      font-size: 0.88rem;
      color: var(--text-muted);
    }
  }

  .loading-hint {
    font-size: 0.78rem !important;
    color: var(--text-dim) !important;
  }

  .coach-error {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    padding: 12px 14px;
    border-radius: 10px;
    border: 1px solid #e06c75;
    background: rgba(224, 108, 117, 0.08);

    .error-icon {
      color: #e06c75;
      font-size: 1.1rem;
      flex-shrink: 0;
      margin-top: 1px;
    }

    p {
      font-size: 0.84rem;
      color: var(--text-primary);
      line-height: 1.45;
    }
  }

  .spinner {
    width: 28px;
    height: 28px;
    border: 3px solid var(--border-soft);
    border-top-color: var(--text-muted);
    border-radius: 50%;
    animation: spin 0.7s linear infinite;
  }

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }

  @keyframes pulse {
    0%,
    100% {
      opacity: 0.4;
    }
    50% {
      opacity: 1;
    }
  }

  /* ── Chat input bar (pinned bottom) ─────────────── */

  .chat-input-bar {
    position: sticky;
    bottom: 0;
    display: flex;
    flex-direction: column;
    gap: 6px;
    padding: 12px 0 24px;
    background: var(--bg-editor);
    margin-top: auto;
  }

  .chat-input-row {
    display: flex;
    align-items: center;
    gap: 6px;
    border: 1px solid var(--border-soft);
    border-radius: 10px;
    background: var(--surface-1);
    padding: 6px 8px 6px 14px;

    input {
      flex: 1;
      min-width: 0;
      font-size: 0.86rem;
      color: var(--text-primary);

      &::placeholder {
        color: var(--text-dim);
      }

      &:disabled {
        opacity: 0.5;
      }
    }
  }

  .chat-send-btn {
    width: 32px;
    height: 32px;
    display: grid;
    place-items: center;
    border-radius: 8px;
    color: var(--text-muted);
    cursor: pointer;
    border: 1px solid transparent;
    flex-shrink: 0;

    .material-symbols-outlined {
      font-size: 1rem;
    }

    &:hover {
      background: var(--bg-hover);
      border-color: var(--border-soft);
      color: var(--text-primary);
    }

    &:disabled {
      opacity: 0.4;
      cursor: default;
    }
  }

  .chat-clear-btn {
    align-self: flex-start;
    padding: 4px 10px;
    border-radius: 6px;
    border: 1px solid var(--border-soft);
    background: transparent;
    color: var(--text-dim);
    font-size: 0.74rem;
    cursor: pointer;

    &:hover {
      color: var(--text-primary);
      border-color: var(--border-strong);
      background: var(--bg-hover);
    }
  }
</style>
