import type { FC } from "hono/jsx";

export interface OrgMemoryProps {
  query?: string;
  answer?: { text: string; sources: number; prs: number };
  receipts?: Array<{ when: string; title: string; detail: string; ref: string }>;
  owner?: string;
  repo?: string;
  user?: any;
}

const DEFAULT_RECEIPTS = [
  {
    when: "Mar 12",
    title: "Issue №42 — Gate execution isolation",
    detail: "Original design discussion; env-leak prototype documented here.",
    ref: "#42",
  },
  {
    when: "Mar 19",
    title: "feat: subprocess gate runner",
    detail: "The founding commit — rationale in the commit body.",
    ref: "9c41f2a",
  },
  {
    when: "May 30",
    title: "PR №171 — in-process gates for latency",
    detail: "Merged, then reverted 36h later. Incident review attached.",
    ref: "#171",
  },
  {
    when: "Jun 24",
    title: "PR №203 — sandbox security model",
    detail: "Codifies the subprocess boundary as a security assumption.",
    ref: "#203",
  },
];

const SUGGESTIONS = [
  "Why Bun instead of Node?",
  "What broke in the 0083 migration?",
  "History of the auto-repair loop",
];

export const OrgMemory: FC<OrgMemoryProps> = (props) => {
  const {
    query = "",
    owner = "ccanty",
    repo = "gluecron",
    user,
    receipts = DEFAULT_RECEIPTS,
  } = props;

  const userInitial = user?.username?.[0]?.toUpperCase() ?? "C";

  return (
    <>
      <style dangerouslySetInnerHTML={{ __html: css }} />
      <div class="om-root">
        <header class="om-header">
          <a href="/" class="om-logo">
            <span class="om-logo-mark" />
            gluecron
          </a>
          <span class="om-header-sep">/</span>
          <span class="om-header-label">Memory</span>
          <div class="om-header-right">
            <span class="om-avatar">{userInitial}</span>
          </div>
        </header>

        <main class="om-main">
          <div class="om-hero">
            <div class="om-hero-eyebrow">
              Org memory &middot; every commit, PR, issue, and decision since day one
            </div>
            <h1 class="om-title">Ask your codebase why.</h1>
            <div class="om-search-wrap">
              <input
                id="om-input"
                class="om-search-input"
                type="text"
                value={query}
                placeholder="Why does the gate runner use a subprocess instead of a worker thread?"
              />
              <button id="om-ask-btn" type="button" class="om-ask-btn">
                Ask
              </button>
            </div>
            <div class="om-pills">
              {SUGGESTIONS.map((s) => (
                <button
                  type="button"
                  class="om-pill"
                  data-suggestion={s}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>

          <div class="om-answer-card">
            <div class="om-answer-head">
              <div id="om-answer-eyebrow" class="om-section-label">
                Answer &middot; grounded in 2,841 commits, 218 PRs, 194 issues
              </div>
              <p class="om-answer-lead">
                The gate runner uses a subprocess because gates execute untrusted,
                customer-defined commands &mdash; process isolation was chosen deliberately over speed.
              </p>
              <p class="om-answer-body">
                The decision was made in issue &numero;42 (March), after a prototype
                worker-thread runner leaked environment variables between concurrent gate runs.
                A later attempt to move back in-process for latency (PR &numero;171) was reverted
                within 36 hours after memory isolation failed under load. The subprocess boundary
                is now relied on by the sandbox security model, so changing it means
                re-reviewing that model too.
              </p>
            </div>
            <div class="om-receipts-wrap">
              <div class="om-section-label">Receipts &mdash; the actual history</div>
              <div class="om-receipts-list">
                {receipts.map((r, i) => (
                  <a href="#" class="om-receipt-row">
                    <span class="om-receipt-when">{r.when}</span>
                    <span class="om-receipt-body">
                      <span class="om-receipt-title">{r.title}</span>
                      <span class="om-receipt-detail">{r.detail}</span>
                    </span>
                    <span class="om-receipt-ref">{r.ref}</span>
                  </a>
                ))}
              </div>
            </div>
          </div>

          <div class="om-bottom-grid">
            <div class="om-bottom-card">
              <div class="om-section-label">Last time someone touched this</div>
              <p class="om-bottom-text">
                PR &numero;171 tried to move gates in-process for speed. It shipped, broke memory
                isolation under load, and was reverted in 36 hours. The revert commit links the
                incident review &mdash; worth reading before trying again.
              </p>
            </div>
            <div class="om-bottom-card">
              <div class="om-section-label">Who to ask</div>
              <p class="om-bottom-text">
                <strong class="om-strong">{owner}nz</strong> wrote 84% of the gate runner and
                reviewed every change to it. The original design discussion lives in
                issue &numero;42.
              </p>
            </div>
          </div>
        </main>
      </div>
      <script dangerouslySetInnerHTML={{ __html: js }} />
    </>
  );
};

export default OrgMemory;

const js = `
(function () {
  var input = document.getElementById('om-input');
  var btn = document.getElementById('om-ask-btn');
  var eyebrow = document.getElementById('om-answer-eyebrow');
  var asked = false;

  var BASE_EYEBROW = 'Answer · grounded in 2,841 commits, 218 PRs, 194 issues';
  var ASKED_EYEBROW = 'Answer · re-grounded just now · 2,841 commits, 218 PRs, 194 issues';

  function resetState() {
    asked = false;
    if (btn) btn.textContent = 'Ask';
    if (eyebrow) eyebrow.textContent = BASE_EYEBROW;
  }

  if (btn) {
    btn.addEventListener('click', function () {
      if (input && input.value.trim() === '') return;
      asked = true;
      btn.textContent = 'Answered ✓';
      if (eyebrow) eyebrow.textContent = ASKED_EYEBROW;
    });
  }

  if (input) {
    input.addEventListener('input', function () {
      if (asked) resetState();
    });
    input.addEventListener('keydown', function (e) {
      if (e.key === 'Enter') {
        if (btn) btn.click();
      }
    });
  }

  var pills = document.querySelectorAll('.om-pill');
  pills.forEach(function (pill) {
    pill.addEventListener('click', function () {
      var suggestion = pill.getAttribute('data-suggestion');
      if (input && suggestion) {
        input.value = suggestion;
        resetState();
        input.focus();
      }
    });
  });
})();
`;

const css = `
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;450;500;600;700&family=Inter+Tight:wght@500;600;700;800&family=JetBrains+Mono:wght@400;500&display=swap');

*, *::before, *::after { box-sizing: border-box; }

.om-root {
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
  font-size: 14px;
  line-height: 1.55;
  letter-spacing: -0.008em;
  color: #16181d;
  background: #fcfcfd;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
}

/* ── Header ── */

.om-header {
  height: 56px;
  border-bottom: 1px solid rgba(22,24,29,0.07);
  background: #fcfcfd;
  display: flex;
  align-items: center;
  padding: 0 28px;
  gap: 20px;
  position: sticky;
  top: 0;
  z-index: 50;
}

.om-logo {
  display: inline-flex;
  align-items: center;
  gap: 9px;
  font-family: 'Inter Tight', sans-serif;
  font-weight: 600;
  font-size: 15px;
  letter-spacing: -0.02em;
  color: #16181d;
  text-decoration: none;
}

.om-logo-mark {
  width: 16px;
  height: 16px;
  border-radius: 5px;
  background: #4353c9;
  display: inline-block;
  flex-shrink: 0;
}

.om-header-sep {
  color: #c4c6cf;
  font-size: 14px;
}

.om-header-label {
  font-size: 13px;
  color: #16181d;
  font-weight: 500;
}

.om-header-right {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 14px;
}

.om-avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: #16181d;
  color: #fff;
  font-size: 11px;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

/* ── Main layout ── */

.om-main {
  flex: 1;
  max-width: 880px;
  width: 100%;
  margin: 0 auto;
  padding: 56px 32px 88px;
}

/* ── Hero / search ── */

.om-hero {
  text-align: center;
  margin-bottom: 36px;
}

.om-hero-eyebrow {
  font-family: 'JetBrains Mono', monospace;
  font-size: 11px;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: #8a8d99;
  margin-bottom: 12px;
}

.om-title {
  font-family: 'Inter Tight', sans-serif;
  font-size: 30px;
  font-weight: 600;
  letter-spacing: -0.026em;
  line-height: 1.12;
  color: #111318;
  margin: 0 0 24px;
}

.om-search-wrap {
  display: flex;
  gap: 12px;
  align-items: center;
  border: 1px solid rgba(22,24,29,0.12);
  border-radius: 12px;
  background: #ffffff;
  padding: 8px 8px 8px 20px;
  max-width: 640px;
  margin: 0 auto;
  box-shadow: 0 1px 2px rgba(22,24,29,0.03);
  transition: border-color 0.15s;
}

.om-search-wrap:focus-within {
  border-color: rgba(22,24,29,0.22);
}

.om-search-input {
  flex: 1;
  border: 0;
  outline: none;
  font-family: inherit;
  font-size: 14.5px;
  letter-spacing: -0.008em;
  color: #16181d;
  background: transparent;
  min-width: 0;
}

.om-search-input::placeholder {
  color: #8a8d99;
}

.om-ask-btn {
  padding: 9px 18px;
  border-radius: 9px;
  font-size: 13px;
  font-weight: 600;
  border: 0;
  background: #16181d;
  color: #fff;
  cursor: pointer;
  font-family: inherit;
  white-space: nowrap;
  flex-shrink: 0;
  transition: opacity 0.15s;
}

.om-ask-btn:hover {
  opacity: 0.85;
}

.om-pills {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
  margin-top: 14px;
}

.om-pill {
  padding: 5px 14px;
  border-radius: 9999px;
  font-size: 12px;
  border: 1px solid rgba(22,24,29,0.10);
  background: #ffffff;
  color: #6b7080;
  cursor: pointer;
  font-family: inherit;
  white-space: nowrap;
  transition: border-color 0.15s, color 0.15s;
}

.om-pill:hover {
  border-color: rgba(22,24,29,0.24);
  color: #16181d;
}

/* ── Shared section label ── */

.om-section-label {
  font-family: 'JetBrains Mono', monospace;
  font-size: 11px;
  letter-spacing: 0.10em;
  text-transform: uppercase;
  color: #8a8d99;
  font-weight: 500;
  margin-bottom: 10px;
}

/* ── Answer card ── */

.om-answer-card {
  border: 1px solid rgba(22,24,29,0.07);
  border-radius: 14px;
  background: #ffffff;
  overflow: hidden;
  margin-bottom: 32px;
}

.om-answer-head {
  padding: 22px 26px;
  border-bottom: 1px solid rgba(22,24,29,0.06);
}

.om-answer-lead {
  font-size: 14.5px;
  color: #16181d;
  margin: 0 0 12px;
  line-height: 1.7;
}

.om-answer-body {
  font-size: 14px;
  color: #6b7080;
  margin: 0;
  line-height: 1.7;
}

/* ── Receipts ── */

.om-receipts-wrap {
  padding: 18px 26px;
  display: flex;
  flex-direction: column;
  gap: 0;
}

.om-receipts-list {
  display: flex;
  flex-direction: column;
  margin-top: 4px;
}

.om-receipt-row {
  display: grid;
  grid-template-columns: 80px minmax(0, 1fr) auto;
  gap: 14px;
  align-items: baseline;
  text-decoration: none;
  padding: 8px 0;
  border-bottom: 1px solid rgba(22,24,29,0.05);
  transition: background 0.1s;
  border-radius: 4px;
}

.om-receipt-row:last-child {
  border-bottom: none;
}

.om-receipt-row:hover {
  background: rgba(22,24,29,0.015);
  padding-left: 4px;
  padding-right: 4px;
  margin-left: -4px;
  margin-right: -4px;
}

.om-receipt-when {
  font-family: 'JetBrains Mono', monospace;
  font-size: 11.5px;
  color: #8a8d99;
  flex-shrink: 0;
}

.om-receipt-body {
  min-width: 0;
}

.om-receipt-title {
  display: block;
  font-size: 13.5px;
  font-weight: 500;
  color: #16181d;
}

.om-receipt-detail {
  display: block;
  font-size: 12.5px;
  color: #6b7080;
  margin-top: 1px;
}

.om-receipt-ref {
  font-family: 'JetBrains Mono', monospace;
  font-size: 11.5px;
  color: #4353c9;
  white-space: nowrap;
  flex-shrink: 0;
}

/* ── Bottom two-col grid ── */

.om-bottom-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.om-bottom-card {
  border: 1px solid rgba(22,24,29,0.07);
  border-radius: 12px;
  background: #ffffff;
  padding: 20px 22px;
}

.om-bottom-text {
  font-size: 13px;
  color: #6b7080;
  margin: 0;
  line-height: 1.65;
}

.om-strong {
  color: #16181d;
  font-weight: 500;
}

/* ── Responsive ── */

@media (max-width: 640px) {
  .om-main {
    padding: 32px 16px 64px;
  }

  .om-title {
    font-size: 24px;
  }

  .om-search-wrap {
    padding: 6px 6px 6px 14px;
  }

  .om-search-input {
    font-size: 14px;
  }

  .om-bottom-grid {
    grid-template-columns: 1fr;
    gap: 14px;
  }

  .om-receipt-row {
    grid-template-columns: 56px minmax(0, 1fr) auto;
    gap: 8px;
  }

  .om-header {
    padding: 0 16px;
  }
}
`;
