---
import type { PulseRow, PulseWithCounts } from '../../lib/db';
import { fmtDateTime } from '../../lib/markdown';

interface Props {
  pulses: PulseRow[];
  editing: PulseRow | null;
  viewing: PulseWithCounts | null;
}

const { pulses, editing, viewing } = Astro.props;

const STATUS_LABEL: Record<string, string> = {
  draft:  'Draft',
  open:   'Open',
  closed: 'Closed',
};

/** Convert SQL UTC date "YYYY-MM-DD HH:MM:SS" → "YYYY-MM-DDTHH:MM" for datetime-local input. */
function toInputValue(sql: string | null | undefined): string {
  if (!sql) return '';
  return sql.replace(' ', 'T').slice(0, 16);
}

const formAction = editing ? 'update_pulse' : 'create_pulse';
const optionsForForm: string[] = editing ? [...editing.options] : [];
while (optionsForForm.length < 4) optionsForForm.push('');
---
<div class="tab-content">

  {viewing ? (
    <!-- ── Results view ─────────────────────────────────────────── -->
    <section class="section">
      <a href="/admin?tab=pulses" class="back-link label-sm">← Back to pulses</a>
      <h2 class="label-sm section-heading">Results — {STATUS_LABEL[viewing.status]}</h2>
      <p class="pulse-question-display">{viewing.question}</p>
      {viewing.context && <p class="body-md muted">{viewing.context}</p>}
      <p class="body-sm muted">Open {fmtDateTime(viewing.opens_at)} → {fmtDateTime(viewing.closes_at)} · {viewing.votes_total} vote{viewing.votes_total === 1 ? '' : 's'}</p>
      <div class="results-grid">
        {viewing.options.map((opt, i) => {
          const count = viewing.votes_by_option[i] ?? 0;
          const pct = viewing.votes_total > 0 ? (count / viewing.votes_total) * 100 : 0;
          return (
            <div class="result-row">
              <div class="result-meta">
                <span class="result-letter label-sm">{String.fromCharCode(65 + i)}</span>
                <span class="result-text">{opt}</span>
                <span class="result-count label-sm">{count} ({pct.toFixed(0)}%)</span>
              </div>
              <div class="result-bar"><span class="result-bar-fill" style={`width:${pct.toFixed(1)}%`}></span></div>
            </div>
          );
        })}
      </div>
    </section>
  ) : (
    <>
      <!-- ── Create / edit form ──────────────────────────────────── -->
      <section class="section">
        <h2 class="label-sm section-heading">{editing ? 'Edit pulse' : 'New pulse'}</h2>
        <form method="POST" class="invite-form" novalidate>
          <input type="hidden" name="action" value={formAction} />
          {editing && <input type="hidden" name="pulse_id" value={editing.id} />}

          <div class="field">
            <label for="question" class="label-sm field-label">Question</label>
            <input type="text" id="question" name="question" class="input body-md" required value={editing?.question ?? ''} />
          </div>

          <div class="field">
            <label for="context" class="label-sm field-label">Context (optional)</label>
            <textarea id="context" name="context" class="input body-md" rows="3">{editing?.context ?? ''}</textarea>
          </div>

          <fieldset class="option-grid">
            <legend class="label-sm field-label">Options (2–4)</legend>
            {optionsForForm.map((val, i) => (
              <input
                type="text"
                name={`option_${i}`}
                placeholder={`Option ${String.fromCharCode(65 + i)}`}
                class="input body-md"
                value={val}
                required={i < 2}
              />
            ))}
          </fieldset>

          <div class="form-grid">
            <div class="field">
              <label for="opens_at" class="label-sm field-label">Opens at (UTC)</label>
              <input type="datetime-local" id="opens_at" name="opens_at" class="input body-md" required value={toInputValue(editing?.opens_at)} />
            </div>
            <div class="field">
              <label for="closes_at" class="label-sm field-label">Closes at (UTC)</label>
              <input type="datetime-local" id="closes_at" name="closes_at" class="input body-md" required value={toInputValue(editing?.closes_at)} />
            </div>
          </div>

          <div class="form-actions">
            <button type="submit" class="btn-primary label-sm">{editing ? 'Save changes' : 'Save as draft'}</button>
            {!editing && (
              <button type="submit" name="publish" value="1" class="btn-secondary label-sm">Save and publish now</button>
            )}
            {editing && (
              <a href="/admin?tab=pulses" class="action-link label-sm">Cancel</a>
            )}
          </div>
        </form>
      </section>

      <!-- ── List ────────────────────────────────────────────────── -->
      <section class="section">
        <h2 class="label-sm section-heading">All pulses</h2>
        {pulses.length === 0 ? (
          <p class="body-sm empty-msg">No pulses yet.</p>
        ) : (
          <table class="data-table">
            <thead>
              <tr>
                <th class="label-sm">Question</th>
                <th class="label-sm">Status</th>
                <th class="label-sm">Opens / Closes</th>
                <th class="label-sm">Actions</th>
              </tr>
            </thead>
            <tbody>
              {pulses.map(p => (
                <tr>
                  <td class="body-sm">{p.question}</td>
                  <td class="body-sm"><span class:list={['status-pill', `status-${p.status}`]}>{STATUS_LABEL[p.status]}</span></td>
                  <td class="body-sm muted">{fmtDateTime(p.opens_at)} →<br />{fmtDateTime(p.closes_at)}</td>
                  <td class="action-cell">
                    <a href={`/admin?tab=pulses&view=${p.id}`} class="action-link label-sm">Results</a>
                    <a href={`/admin?tab=pulses&edit=${p.id}`} class="action-link label-sm">Edit</a>
                    {p.status === 'draft' && (
                      <form method="POST" class="inline-form">
                        <input type="hidden" name="action" value="publish_pulse" />
                        <input type="hidden" name="pulse_id" value={p.id} />
                        <button type="submit" class="action-link label-sm">Publish</button>
                      </form>
                    )}
                    {p.status === 'open' && (
                      <form method="POST" class="inline-form">
                        <input type="hidden" name="action" value="close_pulse" />
                        <input type="hidden" name="pulse_id" value={p.id} />
                        <button type="submit" class="action-link label-sm">Close</button>
                      </form>
                    )}
                    <form method="POST" class="inline-form">
                      <input type="hidden" name="action" value="delete_pulse" />
                      <input type="hidden" name="pulse_id" value={p.id} />
                      <button type="submit" class="danger-btn label-sm" onclick="return confirm('Delete this pulse and all votes?')">Delete</button>
                    </form>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </section>
    </>
  )}

</div>

<style>
  .back-link {
    color: var(--on-surface-muted);
    text-decoration: none;
    border-bottom: none;
    letter-spacing: var(--tracking-wide);
    text-transform: uppercase;
    align-self: flex-start;
  }
  .back-link:hover { color: var(--on-surface-variant); border-bottom: none; }

  .pulse-question-display {
    font-family: var(--font-serif);
    font-style: italic;
    font-size: 1.25rem;
    color: var(--on-surface);
    margin: var(--space-2) 0;
  }

  .results-grid { display: flex; flex-direction: column; gap: var(--space-4); margin-top: var(--space-4); }
  .result-row { display: flex; flex-direction: column; gap: var(--space-2); }
  .result-meta { display: flex; align-items: baseline; gap: var(--space-3); }
  .result-letter { font-weight: 600; color: var(--on-surface-muted); width: 1.5rem; }
  .result-text { flex: 1; color: var(--on-surface); }
  .result-count { color: var(--on-surface-muted); letter-spacing: var(--tracking-wide); }
  .result-bar { height: 4px; background: var(--surface-container); border-radius: var(--radius-full); overflow: hidden; }
  .result-bar-fill { display: block; height: 100%; background: var(--pigment-terracotta); opacity: 0.6; }

  .option-grid {
    border: none;
    padding: 0;
    margin: 0;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: var(--space-3);
  }
  .option-grid legend {
    grid-column: 1 / -1;
    letter-spacing: var(--tracking-wide);
    text-transform: uppercase;
    color: var(--on-surface-variant);
    padding: 0;
    margin-bottom: var(--space-1);
  }

  .form-actions { display: flex; gap: var(--space-3); align-items: center; }

  .btn-secondary {
    padding: var(--space-2) var(--space-6);
    background: var(--surface-container);
    color: var(--on-surface);
    border: var(--ghost-border);
    border-radius: var(--radius-md);
    font-family: var(--font-sans);
    font-weight: 500;
    letter-spacing: var(--tracking-wide);
    text-transform: uppercase;
    cursor: pointer;
  }
  .btn-secondary:hover { background: var(--surface-container-high); }

  .status-pill {
    display: inline-block;
    padding: 0.15em var(--space-3);
    border-radius: var(--radius-full);
    font-family: var(--font-sans);
    font-size: var(--text-label-sm);
    letter-spacing: var(--tracking-wide);
    text-transform: uppercase;
  }
  .status-draft { background: var(--surface-container); color: var(--on-surface-muted); }
  .status-open { background: rgba(185, 107, 88, 0.12); color: var(--pigment-terracotta); font-weight: 600; }
  .status-closed { background: var(--surface-container-low); color: var(--on-surface-muted); }

  .action-cell {
    display: flex;
    gap: var(--space-3);
    align-items: center;
    flex-wrap: wrap;
  }
  .action-link {
    background: none;
    border: none;
    color: var(--on-surface-muted);
    text-decoration: none;
    border-bottom: none;
    letter-spacing: var(--tracking-wide);
    text-transform: uppercase;
    cursor: pointer;
    font-family: var(--font-sans);
    transition: color var(--duration-fast) var(--ease-standard);
    padding: 0;
  }
  .action-link:hover { color: var(--on-surface-variant); border-bottom: none; }
</style>
