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

export interface PlanStep {
  n: string;
  title: string;
  desc: string;
}

export interface Plan {
  id: number | string;
  spec: string;
  steps: PlanStep[];
}

export interface PlanApprovalProps {
  plan?: Plan;
  blastRadius?: any;
  costEstimate?: any;
  user?: any;
}

const DEFAULT_STEPS = [
  {
    n: "01",
    title: "Add plan-lapse state to the schema",
    detail:
      "New enum value 'lapsed' + lapsedAt timestamp. Additive migration, no backfill needed.",
    files: "drizzle/0108_plan_lapse.sql · src/db/schema.ts",
  },
  {
    n: "02",
    title: "Enforce read-only on lapsed orgs",
    detail:
      "Git push and web writes rejected with a clear message; clone, fetch, and browsing stay open. Internal orgs short-circuit before any check.",
    files: "src/middleware/plan-guard.ts · src/git/protocol.ts",
  },
  {
    n: "03",
    title: "Warning emails at 7 days and 1 day",
    detail:
      "Two templated emails via the existing notify pipeline, deduped per org, logged to the audit trail.",
    files: "src/lib/notify.ts · src/lib/autopilot.ts",
  },
  {
    n: "04",
    title: "Admin visibility",
    detail:
      "Lapsed orgs surface in the customers table with days-remaining, next to the existing exempt/current states.",
    files: "src/routes/admin.tsx",
  },
  {
    n: "05",
    title: "Tests",
    detail:
      "12 new tests: guard behavior, internal-org exemption, email dedupe, migration idempotence.",
    files: "src/__tests__/plan-guard.test.ts",
  },
];

const DEFAULT_SPEC =
  "When a customer's plan lapses, keep their repos read-only instead of blocking clone access. Send one warning email at 7 days and one at 1 day. Internal orgs are never affected.";

const STEP_COUNT = DEFAULT_STEPS.length;

const inlineJs = `
(function () {
  var manual = {};
  var approved = false;
  var editing = false;
  var STEP_COUNT = ${STEP_COUNT};

  function getManualCount() {
    var n = 0;
    for (var k in manual) { if (manual[k]) n++; }
    return n;
  }

  function updateUI() {
    var manualCount = getManualCount();
    var agentSteps = STEP_COUNT - manualCount;

    for (var i = 0; i < STEP_COUNT; i++) {
      var btn = document.getElementById('pa-step-btn-' + i);
      if (!btn) continue;
      if (manual[i]) {
        btn.textContent = 'Yours ✓';
        btn.style.border = '1px solid rgba(67,83,201,0.35)';
        btn.style.background = 'rgba(67,83,201,0.06)';
        btn.style.color = '#4353c9';
      } else {
        btn.textContent = "I’ll do this";
        btn.style.border = '1px solid rgba(22,24,29,0.12)';
        btn.style.background = '#ffffff';
        btn.style.color = '#6b7080';
      }
    }

    var filesTouched = document.getElementById('pa-files-touched');
    if (filesTouched) filesTouched.textContent = String(9 - manualCount);

    var yourTime = document.getElementById('pa-your-time');
    if (yourTime) {
      yourTime.textContent =
        manualCount > 0
          ? 'review + ' + manualCount + ' manual step' + (manualCount > 1 ? 's' : '')
          : '≈ 10 min review';
    }

    var approveBtn = document.getElementById('pa-approve-btn');
    if (approveBtn) {
      if (approved) {
        approveBtn.textContent = 'Plan approved — agent starting';
        approveBtn.style.background = '#1e7f5c';
      } else if (manualCount > 0) {
        approveBtn.textContent = 'Approve plan (' + agentSteps + ' agent step' + (agentSteps !== 1 ? 's' : '') + ')';
        approveBtn.style.background = '#16181d';
      } else {
        approveBtn.textContent = 'Approve plan';
        approveBtn.style.background = '#16181d';
      }
    }
  }

  for (var i = 0; i < STEP_COUNT; i++) {
    (function (idx) {
      var btn = document.getElementById('pa-step-btn-' + idx);
      if (btn) {
        btn.addEventListener('click', function () {
          manual[idx] = !manual[idx];
          updateUI();
        });
      }
    })(i);
  }

  var approveBtn = document.getElementById('pa-approve-btn');
  if (approveBtn) {
    approveBtn.addEventListener('click', function () {
      if (!approved) {
        approved = true;
        updateUI();
      }
    });
  }

  var editBtn = document.getElementById('pa-edit-btn');
  if (editBtn) {
    editBtn.addEventListener('click', function () {
      editing = !editing;
      editBtn.textContent = editing
        ? "Editing — tap ‘I’ll do this’ on any step"
        : 'Edit the plan';
    });
  }
})();
`;

export const PlanApprovalView: FC<PlanApprovalProps> = (props) => {
  const plan = props.plan;
  const spec = plan?.spec ?? DEFAULT_SPEC;
  const planId = plan?.id ?? 31;
  const steps = DEFAULT_STEPS;

  return (
    <>
      <style dangerouslySetInnerHTML={{ __html: css }} />
      <div class="pa-root">
        <header class="pa-header">
          <a href="/" class="pa-logo">
            <span class="pa-logo-mark"></span>
            gluecron
          </a>
          <nav class="pa-breadcrumb">
            <span class="pa-breadcrumb-item">ccantynz-alt</span>
            <span class="pa-breadcrumb-sep">/</span>
            <span class="pa-breadcrumb-item">gluecron</span>
            <span class="pa-breadcrumb-sep">/</span>
            <span class="pa-breadcrumb-item pa-breadcrumb-active">Specs</span>
          </nav>
          <div class="pa-header-right">
            <span class="pa-avatar">C</span>
          </div>
        </header>

        <main class="pa-main">
          <div class="pa-page-header">
            <div class="pa-eyebrow">Spec №{planId} · Plan review</div>
            <h1 class="pa-title">Approve the plan, not just the PR.</h1>
            <p class="pa-subtitle">
              Before a single line is written, here is exactly what the agent intends to do — the
              blast radius, the cost, and how to undo it. Approve it, edit it, or take any piece of
              it manually.
            </p>
          </div>

          <div class="pa-grid">
            {/* Left: the plan */}
            <section class="pa-left">
              {/* Spec quote card */}
              <div class="pa-spec-card">
                <div class="pa-spec-label">Your spec — as written</div>
                <p class="pa-spec-quote">"{spec}"</p>
              </div>

              {/* Plan steps */}
              <h2 class="pa-steps-heading">The plan · {steps.length} steps</h2>
              <div class="pa-steps-list">
                {steps.map((step, i) => (
                  <div class="pa-step-row" id={"pa-step-row-" + i}>
                    <span class="pa-step-num">{step.n}</span>
                    <div class="pa-step-body">
                      <div class="pa-step-title">{step.title}</div>
                      <div class="pa-step-detail">{step.detail}</div>
                      <div class="pa-step-files">{step.files}</div>
                    </div>
                    <button
                      type="button"
                      id={"pa-step-btn-" + i}
                      class="pa-step-btn"
                    >
                      I'll do this
                    </button>
                  </div>
                ))}
              </div>
              <p class="pa-steps-note">
                Steps marked{" "}
                <strong class="pa-steps-note-em">I'll do this</strong> are left out of the agent's
                branch — the PR arrives with those files untouched and a checklist for you.
              </p>
            </section>

            {/* Right: aside */}
            <aside class="pa-aside">
              {/* Blast radius */}
              <div class="pa-section">
                <h3 class="pa-section-label">Blast radius</h3>
                <div class="pa-card">
                  <div class="pa-card-rows">
                    <div class="pa-card-row">
                      <span class="pa-card-key">Files touched</span>
                      <span class="pa-card-val pa-mono" id="pa-files-touched">
                        9
                      </span>
                    </div>
                    <div class="pa-card-row">
                      <span class="pa-card-key">Repos affected</span>
                      <span class="pa-card-val pa-mono">1 · gluecron</span>
                    </div>
                    <div class="pa-card-row">
                      <span class="pa-card-key">DB migration</span>
                      <span class="pa-card-val pa-mono pa-amber">1 · additive only</span>
                    </div>
                    <div class="pa-card-row">
                      <span class="pa-card-key">Public API change</span>
                      <span class="pa-card-val pa-mono pa-green">none</span>
                    </div>
                    <div class="pa-card-row">
                      <span class="pa-card-key">Tests to write</span>
                      <span class="pa-card-val pa-mono">12</span>
                    </div>
                  </div>
                  <div class="pa-divider"></div>
                  <p class="pa-card-note">
                    <strong class="pa-card-note-em">Downstream:</strong> billing cron, email
                    digests, and the admin customers table read the plan-state column this plan
                    modifies.
                  </p>
                </div>
              </div>

              {/* Cost before code */}
              <div class="pa-section">
                <h3 class="pa-section-label">Cost before code</h3>
                <div class="pa-card">
                  <div class="pa-card-rows">
                    <div class="pa-card-row">
                      <span class="pa-card-key">Estimated AI spend</span>
                      <span class="pa-card-val pa-mono">$1.10 – $1.80</span>
                    </div>
                    <div class="pa-card-row">
                      <span class="pa-card-key">Model routing</span>
                      <span class="pa-card-val pa-mono">local first</span>
                    </div>
                    <div class="pa-card-row">
                      <span class="pa-card-key">Sandbox time</span>
                      <span class="pa-card-val pa-mono">≈ 25 min</span>
                    </div>
                    <div class="pa-card-row">
                      <span class="pa-card-key">Your time needed</span>
                      <span class="pa-card-val pa-mono" id="pa-your-time">
                        ≈ 10 min review
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              {/* How this reverses */}
              <div class="pa-section">
                <h3 class="pa-section-label">How this reverses</h3>
                <div class="pa-card">
                  <p class="pa-revert-text">
                    Single revert commit restores all code paths. The migration is additive, so
                    rollback needs no data repair. Warning emails already sent are logged but cannot
                    be unsent — flagged as this plan's only irreversible effect.
                  </p>
                </div>
              </div>

              {/* Actions */}
              <div class="pa-actions">
                <button type="button" id="pa-approve-btn" class="pa-btn-primary">
                  Approve plan
                </button>
                <button type="button" id="pa-edit-btn" class="pa-btn-secondary">
                  Edit the plan
                </button>
                <p class="pa-disclaimer">Nothing is written until you approve.</p>
              </div>
            </aside>
          </div>
        </main>
      </div>
      <script dangerouslySetInnerHTML={{ __html: inlineJs }} />
    </>
  );
};

export default PlanApprovalView;

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; margin: 0; padding: 0; }

.pa-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 ─────────────────────────────────────────────── */

.pa-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;
}

.pa-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;
  flex-shrink: 0;
}

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

.pa-breadcrumb {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #6b7080;
}

.pa-breadcrumb-item {
  padding: 5px 8px;
}

.pa-breadcrumb-sep {
  color: #c4c6cf;
}

.pa-breadcrumb-active {
  color: #16181d;
  font-weight: 500;
}

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

.pa-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 ───────────────────────────────────────────────── */

.pa-main {
  flex: 1;
  max-width: 1180px;
  width: 100%;
  margin: 0 auto;
  padding: 44px 32px 80px;
}

/* ── Page header ────────────────────────────────────────── */

.pa-page-header {
  max-width: 720px;
  margin-bottom: 40px;
}

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

.pa-title {
  font-family: 'Inter Tight', sans-serif;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: -0.025em;
  line-height: 1.15;
  color: #111318;
  margin: 0 0 10px;
}

.pa-subtitle {
  font-size: 14px;
  color: #6b7080;
  line-height: 1.6;
}

/* ── Two-column grid ────────────────────────────────────── */

.pa-grid {
  display: grid;
  grid-template-columns: minmax(0, 1.5fr) minmax(300px, 1fr);
  gap: 44px;
  align-items: start;
}

/* ── Left column ────────────────────────────────────────── */

.pa-left {}

/* Spec quote card */

.pa-spec-card {
  border: 1px solid rgba(22,24,29,0.07);
  border-left: 3px solid #4353c9;
  border-radius: 12px;
  background: #ffffff;
  padding: 20px 24px;
  margin-bottom: 28px;
}

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

.pa-spec-quote {
  font-size: 14px;
  color: #16181d;
  line-height: 1.65;
  font-style: italic;
}

/* Plan steps */

.pa-steps-heading {
  font-family: 'Inter Tight', sans-serif;
  font-size: 15px;
  font-weight: 600;
  letter-spacing: -0.015em;
  color: #16181d;
  margin: 0 0 16px;
}

.pa-steps-list {
  display: flex;
  flex-direction: column;
  margin-bottom: 8px;
}

.pa-step-row {
  display: grid;
  grid-template-columns: 24px minmax(0, 1fr) auto;
  gap: 14px;
  padding: 14px 4px;
  border-bottom: 1px solid rgba(22,24,29,0.06);
  align-items: start;
}

.pa-step-num {
  font-family: 'JetBrains Mono', monospace;
  font-size: 12px;
  color: #8a8d99;
  padding-top: 2px;
  line-height: 1.55;
}

.pa-step-body {
  min-width: 0;
}

.pa-step-title {
  font-size: 14px;
  font-weight: 500;
  color: #16181d;
  line-height: 1.4;
}

.pa-step-detail {
  font-size: 12.5px;
  color: #6b7080;
  margin-top: 2px;
  line-height: 1.5;
}

.pa-step-files {
  font-family: 'JetBrains Mono', monospace;
  font-size: 11.5px;
  color: #8a8d99;
  margin-top: 6px;
  line-height: 1.5;
}

.pa-step-btn {
  padding: 5px 12px;
  border-radius: 7px;
  font-size: 12px;
  font-weight: 500;
  border: 1px solid rgba(22,24,29,0.12);
  background: #ffffff;
  color: #6b7080;
  cursor: pointer;
  font-family: inherit;
  white-space: nowrap;
  transition: border-color 0.12s, background 0.12s, color 0.12s;
  flex-shrink: 0;
  align-self: start;
  margin-top: 2px;
}

.pa-step-btn:hover {
  border-color: rgba(22,24,29,0.22);
}

.pa-steps-note {
  font-size: 12.5px;
  color: #8a8d99;
  margin: 10px 0 0;
  line-height: 1.6;
}

.pa-steps-note-em {
  color: #16181d;
  font-weight: 500;
}

/* ── Right aside ────────────────────────────────────────── */

.pa-aside {
  display: flex;
  flex-direction: column;
  gap: 32px;
  position: sticky;
  top: 92px;
}

.pa-section {}

.pa-section-label {
  font-family: 'JetBrains Mono', monospace;
  font-size: 11px;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: #8a8d99;
  font-weight: 500;
  margin: 0 0 14px;
  display: block;
}

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

.pa-card-rows {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.pa-card-row {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  font-size: 13px;
  gap: 12px;
}

.pa-card-key {
  color: #6b7080;
  flex-shrink: 0;
}

.pa-card-val {
  color: #16181d;
  text-align: right;
}

.pa-mono {
  font-family: 'JetBrains Mono', monospace;
  font-variant-numeric: tabular-nums;
}

.pa-amber {
  color: #b45309;
}

.pa-green {
  color: #1e7f5c;
}

.pa-divider {
  height: 1px;
  background: rgba(22,24,29,0.06);
  margin: 16px 0;
}

.pa-card-note {
  font-size: 12.5px;
  color: #6b7080;
  line-height: 1.6;
}

.pa-card-note-em {
  color: #16181d;
  font-weight: 500;
}

.pa-revert-text {
  font-size: 12.5px;
  color: #6b7080;
  line-height: 1.65;
}

/* ── Actions ────────────────────────────────────────────── */

.pa-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.pa-btn-primary {
  padding: 10px 16px;
  border-radius: 9px;
  font-size: 13.5px;
  font-weight: 500;
  border: none;
  background: #16181d;
  color: #fff;
  cursor: pointer;
  font-family: inherit;
  white-space: nowrap;
  transition: background 0.18s;
  text-align: center;
  display: block;
  width: 100%;
}

.pa-btn-primary:hover {
  background: #2a2d38;
}

.pa-btn-secondary {
  padding: 10px 16px;
  border-radius: 9px;
  font-size: 13.5px;
  font-weight: 500;
  border: 1px solid rgba(22,24,29,0.12);
  background: #ffffff;
  color: #16181d;
  cursor: pointer;
  font-family: inherit;
  white-space: nowrap;
  transition: border-color 0.12s;
  text-align: center;
  display: block;
  width: 100%;
}

.pa-btn-secondary:hover {
  border-color: rgba(22,24,29,0.24);
}

.pa-disclaimer {
  font-size: 12px;
  color: #8a8d99;
  margin: 2px 0 0;
  text-align: center;
  line-height: 1.5;
}

/* ── Responsive ─────────────────────────────────────────── */

@media (max-width: 820px) {
  .pa-grid {
    grid-template-columns: 1fr;
  }
  .pa-aside {
    position: static;
  }
}

@media (max-width: 600px) {
  .pa-main {
    padding: 32px 20px 60px;
  }
  .pa-header {
    padding: 0 20px;
  }
}
`;
