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

export interface SignInV2Props {
  redirect?: string;
  error?: string;
  csrfToken?: string;
  googleEnabled?: boolean;
  githubEnabled?: boolean;
}

export const SignInV2: FC<SignInV2Props> = (props) => {
  const { redirect = "", error = "", csrfToken, googleEnabled = true, githubEnabled = true } = props;

  return (
    <>
      <style dangerouslySetInnerHTML={{ __html: css }} />
      <div class="si-root">
        {/* Left: form panel */}
        <div class="si-left">
          <a href="/" class="si-logo">
            <span class="si-logo-mark"></span>gluecron
          </a>

          <div class="si-form-wrap">
            <h1 class="si-heading">Sign in</h1>
            <p class="si-subheading">Sign in with your password, or a connected provider.</p>

            {error && (
              <div class="si-error-banner">{error}</div>
            )}

            <form
              class="si-login-form"
              method="post"
              action={redirect ? `/login?redirect=${encodeURIComponent(redirect)}` : "/login"}
            >
              <label class="si-field-label" for="si-username">Username or email</label>
              <input
                id="si-username"
                class="si-email-input"
                type="text"
                name="username"
                autocomplete="username"
                placeholder="ccantynz or you@example.com"
                required
              />
              <label class="si-field-label" for="si-password">Password</label>
              <input
                id="si-password"
                class="si-email-input"
                type="password"
                name="password"
                autocomplete="current-password"
                placeholder="Your password"
                required
              />
              <button type="submit" class="si-btn si-btn-github si-submit">Sign in</button>
              <a href="/forgot-password" class="si-forgot">Forgot password?</a>
            </form>

            <div class="si-divider">
              <span class="si-divider-line"></span>
              <span class="si-divider-label">OR</span>
              <span class="si-divider-line"></span>
            </div>

            <div class="si-oauth-group">
              <a href="/login/github" class="si-btn si-btn-github">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true">
                  <path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8z" />
                </svg>
                Continue with GitHub
              </a>

              <a href="/login/google" class="si-btn si-btn-secondary">
                <svg width="16" height="16" viewBox="0 0 24 24" aria-hidden="true">
                  <path fill="#4285F4" d="M23.5 12.27c0-.85-.08-1.66-.22-2.45H12v4.63h6.45a5.52 5.52 0 0 1-2.39 3.62v3h3.87c2.26-2.09 3.57-5.16 3.57-8.8z" />
                  <path fill="#34A853" d="M12 24c3.24 0 5.96-1.07 7.94-2.91l-3.87-3c-1.07.72-2.45 1.15-4.07 1.15-3.13 0-5.78-2.11-6.73-4.96H1.29v3.1A12 12 0 0 0 12 24z" />
                  <path fill="#FBBC05" d="M5.27 14.28a7.2 7.2 0 0 1 0-4.56v-3.1H1.29a12 12 0 0 0 0 10.76l3.98-3.1z" />
                  <path fill="#EA4335" d="M12 4.76c1.76 0 3.34.61 4.59 1.8l3.44-3.44C17.95 1.19 15.24 0 12 0A12 12 0 0 0 1.29 6.62l3.98 3.1C6.22 6.87 8.87 4.76 12 4.76z" />
                </svg>
                Continue with Google
              </a>

              <button
                id="pk-signin-btn"
                type="button"
                class="si-btn si-btn-secondary"
                data-redirect={redirect || "/"}
              >
                <span class="si-passkey-icon" aria-hidden="true">⌘</span>
                Continue with a passkey
              </button>
              <p id="pk-signin-status" class="si-passkey-status" aria-live="polite"></p>
            </div>

            <div class="si-divider">
              <span class="si-divider-line"></span>
              <span class="si-divider-label">OR</span>
              <span class="si-divider-line"></span>
            </div>

            <div class="si-magic-row">
              <input
                id="si-email-input"
                type="email"
                placeholder="work@company.com"
                class="si-email-input"
                autocomplete="email"
              />
              <button
                id="si-magic-btn"
                type="button"
                class="si-magic-btn"
              >
                Email me a link
              </button>
            </div>
            <p class="si-magic-hint">Magic link — no password, expires in 10 minutes.</p>

            <div class="si-aux-links">
              <a href="/sso" class="si-aux-link si-aux-link-accent">Enterprise SSO (Okta, Azure AD, Google Workspace) →</a>
              <a href="/keys" class="si-aux-link">Just cloning? SSH keys work without signing in →</a>
              <a href="/play" class="si-aux-link">Try without an account at /play →</a>
            </div>
          </div>

          <p class="si-footer-note">TLS terminated on our own metal · no third-party proxy in the auth loop</p>
        </div>

        {/* Right: proof panel */}
        <div class="si-right">
          <div class="si-grid-overlay"></div>
          <div class="si-proof-inner">
            <div class="si-proof-eyebrow">Why teams switch</div>
            <h2 class="si-proof-heading">Sign in once.<br />Ship without waiting, forever.</h2>
            <div class="si-props-list">
              <div class="si-prop-item">
                <span class="si-green-dot"></span>
                <p class="si-prop-text">Sonnet 5 reviews every PR the moment it opens — with a manual path that's always one click away.</p>
              </div>
              <div class="si-prop-item">
                <span class="si-green-dot"></span>
                <p class="si-prop-text">Failures repair themselves in isolated sandboxes; everything is audited and reversible in one click.</p>
              </div>
              <div class="si-prop-item">
                <span class="si-green-dot"></span>
                <p class="si-prop-text">One-command GitHub import — bring your code, issues and PRs across, cut over when you're ready, leave any time.</p>
              </div>
            </div>
            <div class="si-proof-footer">quality numbers published live · gluecron.com/trust</div>
          </div>
        </div>
      </div>

      <script dangerouslySetInnerHTML={{ __html: js }} />
    </>
  );
};

export default SignInV2;

const js = `
(function () {
  /* ── Magic-link button ── */
  var emailInput = document.getElementById('si-email-input');
  var magicBtn = document.getElementById('si-magic-btn');
  if (emailInput && magicBtn) {
    var sent = false;
    function updateBtn() {
      if (sent) {
        magicBtn.textContent = '\\u2713 Link sent';
        magicBtn.classList.add('si-magic-btn--sent');
      } else {
        magicBtn.textContent = 'Email me a link';
        magicBtn.classList.remove('si-magic-btn--sent');
      }
    }
    emailInput.addEventListener('input', function () {
      if (sent) { sent = false; updateBtn(); }
    });
    magicBtn.addEventListener('click', function () {
      var val = emailInput.value;
      if (val && val.indexOf('@') !== -1) {
        sent = true;
        updateBtn();
      } else {
        emailInput.focus();
        emailInput.classList.add('si-email-input--shake');
        setTimeout(function () { emailInput.classList.remove('si-email-input--shake'); }, 400);
      }
    });
  }

  /* ── Passkey / WebAuthn ── */
  var pkBtn = document.getElementById('pk-signin-btn');
  var pkStatus = document.getElementById('pk-signin-status');
  if (!pkBtn || !pkStatus) return;

  function b64uToBuf(s) {
    s = s.replace(/-/g,'+').replace(/_/g,'/');
    while (s.length % 4) s += '=';
    var bin = atob(s);
    var buf = new Uint8Array(bin.length);
    for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
    return buf.buffer;
  }
  function bufToB64u(buf) {
    var bytes = new Uint8Array(buf), bin = '';
    for (var i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
    return btoa(bin).replace(/\\+/g,'-').replace(/\\//g,'_').replace(/=+$/,'');
  }

  pkBtn.addEventListener('click', async function () {
    if (!window.PublicKeyCredential) {
      pkStatus.textContent = 'Passkeys are not supported in this browser.';
      return;
    }
    var redirect = pkBtn.dataset.redirect || '/';
    pkStatus.textContent = 'Preparing\\u2026';
    try {
      var optsRes = await fetch('/api/passkeys/auth/options', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({})
      });
      if (!optsRes.ok) throw new Error('options request failed');
      var data = await optsRes.json();
      var options = data.options, sessionKey = data.sessionKey;
      options.challenge = b64uToBuf(options.challenge);
      if (options.allowCredentials) {
        options.allowCredentials = options.allowCredentials.map(function (c) {
          return Object.assign({}, c, { id: b64uToBuf(c.id) });
        });
      }
      pkStatus.textContent = 'Touch your authenticator\\u2026';
      var cred = await navigator.credentials.get({ publicKey: options });
      var resp = {
        id: cred.id,
        rawId: bufToB64u(cred.rawId),
        type: cred.type,
        response: {
          clientDataJSON: bufToB64u(cred.response.clientDataJSON),
          authenticatorData: bufToB64u(cred.response.authenticatorData),
          signature: bufToB64u(cred.response.signature),
          userHandle: cred.response.userHandle ? bufToB64u(cred.response.userHandle) : null
        },
        clientExtensionResults: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}
      };
      var verifyRes = await fetch('/api/passkeys/auth/verify', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ sessionKey: sessionKey, response: resp })
      });
      if (!verifyRes.ok) {
        var j = await verifyRes.json().catch(function () { return {}; });
        throw new Error(j.error || 'verify failed');
      }
      pkStatus.textContent = 'Signed in. Redirecting\\u2026';
      window.location.href = redirect;
    } catch (e) {
      pkStatus.textContent = 'Error: ' + (e && e.message ? e.message : String(e));
    }
  });
})();
`;

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

/* This view ships its own standalone stylesheet (it does not go through
   layout.tsx), so the browser default body margin of 8px still applied and
   pushed the document 8px wider than the viewport on mobile. */
html, body { margin: 0; padding: 0; }

.si-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: grid;
  grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
}

/* ── Left panel ── */

.si-left {
  display: flex;
  flex-direction: column;
  padding: 28px 32px;
  min-height: 100vh;
  /* Grid/flex items default to min-width:auto, so .si-magic-row
     ("Email me a link", min-content 358px) floored this column at 422px and
     forced a horizontal scrollbar at 390px. Let it shrink instead. */
  min-width: 0;
}

.si-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;
  align-self: flex-start;
}

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

.si-form-wrap {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  max-width: 380px;
  width: 100%;
  min-width: 0;
  margin: 0 auto;
  padding: 48px 0;
}

.si-heading {
  font-family: 'Inter Tight', sans-serif;
  font-size: 26px;
  font-weight: 600;
  letter-spacing: -0.024em;
  line-height: 1.15;
  margin: 0 0 6px;
  color: #111318;
}

.si-subheading {
  font-size: 13.5px;
  color: #6b7080;
  margin: 0 0 28px;
}

.si-error-banner {
  background: rgba(180, 35, 24, 0.08);
  border: 1px solid rgba(180, 35, 24, 0.18);
  border-radius: 10px;
  color: #b42318;
  font-size: 13.5px;
  padding: 10px 14px;
  margin-bottom: 18px;
}

/* ── Password form ── */

.si-login-form {
  display: flex;
  flex-direction: column;
  margin: 0 0 4px;
}

.si-field-label {
  font-size: 12.5px;
  font-weight: 600;
  color: #3a3d47;
  margin: 10px 0 5px;
}

.si-submit {
  width: 100%;
  margin-top: 16px;
  border: 0;
}

.si-forgot {
  font-size: 12.5px;
  color: #6b7080;
  text-decoration: none;
  margin-top: 12px;
  align-self: flex-start;
}

.si-forgot:hover {
  color: #4353c9;
}

/* ── OAuth buttons ── */

.si-oauth-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.si-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 11px 16px;
  border-radius: 10px;
  font-size: 14px;
  font-weight: 600;
  font-family: 'Inter', sans-serif;
  text-decoration: none;
  cursor: pointer;
  transition: box-shadow 0.15s ease, border-color 0.15s ease;
  letter-spacing: -0.008em;
}

.si-btn-github {
  background: #16181d;
  color: #fff;
  border: 1px solid #16181d;
}

.si-btn-github:hover {
  box-shadow: 0 8px 22px rgba(22, 24, 29, 0.18);
}

.si-btn-secondary {
  background: #ffffff;
  color: #16181d;
  border: 1px solid rgba(22, 24, 29, 0.14);
}

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

.si-passkey-icon {
  font-size: 15px;
  line-height: 1;
}

.si-passkey-status {
  font-size: 12px;
  color: #6b7080;
  margin: 4px 0 0;
  min-height: 16px;
  text-align: center;
}

/* ── OR divider ── */

.si-divider {
  display: flex;
  align-items: center;
  gap: 14px;
  margin: 22px 0;
}

.si-divider-line {
  flex: 1;
  height: 1px;
  background: rgba(22, 24, 29, 0.08);
}

.si-divider-label {
  font-size: 11.5px;
  color: #8a8d99;
  font-family: 'JetBrains Mono', monospace;
  letter-spacing: 0.08em;
}

/* ── Magic link row ── */

.si-magic-row {
  display: flex;
  gap: 8px;
}

.si-email-input {
  flex: 1;
  border: 1px solid rgba(22, 24, 29, 0.12);
  border-radius: 10px;
  padding: 10px 14px;
  outline: none;
  font-family: 'Inter', sans-serif;
  font-size: 14px;
  letter-spacing: -0.008em;
  color: #16181d;
  background: #ffffff;
  min-width: 0;
  transition: border-color 0.15s ease, box-shadow 0.15s ease;
}

.si-email-input:focus {
  border-color: rgba(22, 24, 29, 0.28);
  box-shadow: 0 0 0 3px rgba(67, 83, 201, 0.10);
}

.si-email-input::placeholder {
  color: #c4c6cf;
}

@keyframes si-shake {
  0%, 100% { transform: translateX(0); }
  20% { transform: translateX(-4px); }
  40% { transform: translateX(4px); }
  60% { transform: translateX(-3px); }
  80% { transform: translateX(3px); }
}

.si-email-input--shake {
  animation: si-shake 0.4s ease;
  border-color: rgba(180, 35, 24, 0.40);
}

.si-magic-btn {
  padding: 10px 16px;
  border-radius: 10px;
  font-size: 13.5px;
  font-weight: 600;
  font-family: 'Inter', sans-serif;
  letter-spacing: -0.008em;
  border: 1px solid rgba(22, 24, 29, 0.14);
  background: #ffffff;
  color: #16181d;
  cursor: pointer;
  white-space: nowrap;
  transition: background 0.18s ease, color 0.18s ease, border-color 0.18s ease;
}

.si-magic-btn:hover {
  border-color: rgba(22, 24, 29, 0.28);
}

.si-magic-btn--sent {
  background: #1e7f5c;
  color: #ffffff;
  border-color: #1e7f5c;
}

.si-magic-btn--sent:hover {
  border-color: #1e7f5c;
}

.si-magic-hint {
  font-size: 12px;
  color: #8a8d99;
  margin: 10px 0 0;
}

/* ── Auxiliary links ── */

.si-aux-links {
  border-top: 1px solid rgba(22, 24, 29, 0.07);
  margin-top: 28px;
  padding-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.si-aux-link {
  font-size: 13px;
  color: #6b7080;
  text-decoration: none;
  transition: color 0.12s ease;
}

.si-aux-link:hover {
  color: #16181d;
}

.si-aux-link-accent {
  color: #4353c9;
}

.si-aux-link-accent:hover {
  color: #3544b0;
  text-decoration: underline;
}

/* ── Footer note ── */

.si-footer-note {
  font-size: 11.5px;
  color: #8a8d99;
  margin: 0;
  font-family: 'JetBrains Mono', monospace;
  letter-spacing: 0.01em;
}

/* ── Right panel ── */

.si-right {
  background: radial-gradient(130% 130% at 50% -10%, #1b2030 0%, #12151f 45%, #0b0d13 100%);
  color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 64px 56px;
  position: relative;
  overflow: hidden;
}

.si-grid-overlay {
  position: absolute;
  inset: 0;
  opacity: 0.35;
  background-image:
    linear-gradient(rgba(255, 255, 255, 0.05) 1px, transparent 1px),
    linear-gradient(90deg, rgba(255, 255, 255, 0.05) 1px, transparent 1px);
  background-size: 56px 56px;
  -webkit-mask-image: radial-gradient(90% 90% at 50% 0%, #000, transparent 80%);
  mask-image: radial-gradient(90% 90% at 50% 0%, #000, transparent 80%);
  pointer-events: none;
}

.si-proof-inner {
  position: relative;
  max-width: 440px;
}

.si-proof-eyebrow {
  font-family: 'JetBrains Mono', monospace;
  font-size: 11px;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: #a9b4ee;
  margin-bottom: 16px;
}

.si-proof-heading {
  font-family: 'Inter Tight', sans-serif;
  font-size: 30px;
  font-weight: 600;
  letter-spacing: -0.024em;
  line-height: 1.15;
  margin: 0 0 28px;
  color: #fff;
}

.si-props-list {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.si-prop-item {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.si-green-dot {
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background: #1e7f5c;
  flex-shrink: 0;
  margin-top: 7px;
}

.si-prop-text {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.78);
  margin: 0;
  line-height: 1.6;
}

.si-proof-footer {
  border-top: 1px solid rgba(255, 255, 255, 0.10);
  margin-top: 32px;
  padding-top: 20px;
  font-family: 'JetBrains Mono', monospace;
  font-size: 11.5px;
  color: rgba(255, 255, 255, 0.45);
}

/* ── Responsive ── */

@media (max-width: 768px) {
  .si-root {
    grid-template-columns: 1fr;
  }

  .si-right {
    display: none;
  }

  .si-left {
    min-height: 100vh;
  }
}
`;
