Files
shopify-ai-backup/chat/public/settings.html

2475 lines
75 KiB
HTML

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Account Settings - Plugin Compass</title>
<link rel="icon" type="image/png" href="/assets/Plugin.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" />
<!-- Dodo Payments -->
<script src="https://cdn.jsdelivr.net/npm/dodopayments-checkout@latest/dist/index.js"></script>
<!-- PostHog Analytics -->
<script src="/posthog.js"></script>
<style>
:root {
--green: #008060;
--green-dark: #004c3f;
--border: #e5e7eb;
--muted: #6b7280;
--panel: #ffffff;
--bg: #f8fafc;
--shopify-green: #008060;
--shopify-green-dark: #004c3f;
--shopify-green-light: #e3f5ef;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: 'Inter', system-ui, -apple-system, sans-serif;
background: radial-gradient(circle at 10% 20%, rgba(0, 128, 96, 0.06), transparent 25%),
radial-gradient(circle at 90% 0%, rgba(0, 76, 63, 0.05), transparent 22%),
var(--bg);
color: #0f172a;
min-height: 100vh;
}
a {
color: inherit;
text-decoration: none;
}
.shell {
max-width: 1100px;
margin: 0 auto;
padding: 32px 20px 48px;
}
.topbar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin-bottom: 20px;
}
.title {
font-size: 24px;
font-weight: 700;
margin: 0;
}
.crumb {
color: var(--muted);
font-size: 14px;
}
.actions {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 10px 18px;
border-radius: 8px;
border: 1px solid var(--border);
background: #fff;
font-weight: 600;
font-size: 14px;
cursor: pointer;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
color: #1e293b;
}
.btn:hover {
background: #f8fafc;
border-color: #cbd5e1;
transform: translateY(-1px);
}
.btn.primary {
background: var(--green);
color: #fff;
border: none;
box-shadow: 0 4px 12px rgba(0, 128, 96, 0.15);
}
.btn.primary:hover {
background: var(--green-dark);
box-shadow: 0 6px 16px rgba(0, 128, 96, 0.25);
}
.btn.ghost {
background: transparent;
border: 1px solid transparent;
}
.btn.ghost:hover {
background: rgba(0, 0, 0, 0.04);
border-color: rgba(0, 0, 0, 0.05);
}
.btn.danger {
color: #dc2626;
border-color: #fecaca;
}
.btn.danger:hover {
background: #fef2f2;
border-color: #dc2626;
}
.pill {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 4px 12px;
border-radius: 6px;
font-size: 12px;
font-weight: 600;
background: #f1f5f9;
color: #475569;
border: 1px solid #e2e8f0;
}
.pill.success {
background: #ecfdf5;
color: #059669;
border-color: #d1fae5;
}
.grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 24px;
}
@media (max-width: 768px) {
.grid {
grid-template-columns: 1fr;
}
}
.card {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 12px;
padding: 24px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
display: flex;
flex-direction: column;
}
.card h3 {
margin: 0 0 4px 0;
font-size: 18px;
font-weight: 700;
color: #1e293b;
}
.card-footer {
margin-top: auto;
padding-top: 20px;
display: flex;
justify-content: flex-end;
gap: 12px;
}
@media (max-width: 640px) {
.card-footer {
flex-direction: column;
align-items: stretch;
}
.card-footer .btn {
width: 100%;
}
}
.muted {
color: var(--muted);
font-size: 14px;
line-height: 1.5;
}
.field {
display: flex;
flex-direction: column;
gap: 8px;
margin-bottom: 20px;
}
label {
font-weight: 600;
font-size: 13px;
color: #475569;
text-transform: uppercase;
letter-spacing: 0.025em;
}
input,
select {
width: 100%;
padding: 10px 14px;
border-radius: 8px;
border: 1px solid var(--border);
font-size: 14px;
background: #fff;
color: #1e293b;
transition: all 0.2s;
}
select {
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%2364748b'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 12px center;
background-size: 16px;
padding-right: 40px;
}
input:focus,
select:focus {
outline: none;
border-color: var(--green);
box-shadow: 0 0 0 3px rgba(0, 128, 96, 0.1);
}
.status {
margin-top: 8px;
font-size: 13px;
color: var(--muted);
min-height: 18px;
}
.status.success {
color: #059669;
}
.status.error {
color: #b91c1c;
}
.stack {
display: flex;
flex-direction: column;
gap: 12px;
}
.badge-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.divider {
height: 1px;
background: var(--border);
margin: 16px 0;
}
.user-block {
display: flex;
align-items: center;
gap: 12px;
}
.avatar {
width: 46px;
height: 46px;
border-radius: 999px;
background: rgba(0, 128, 96, 0.1);
color: var(--green);
display: grid;
place-items: center;
font-weight: 800;
font-size: 18px;
letter-spacing: 0.02em;
text-transform: uppercase;
}
.list {
display: grid;
gap: 8px;
}
.list-row {
display: flex;
justify-content: space-between;
gap: 8px;
}
.list-row span:last-child {
font-weight: 600;
}
.payment-method-card {
background: #fff;
border: 1px solid var(--border);
border-radius: 12px;
padding: 16px;
display: flex;
align-items: center;
gap: 14px;
margin-bottom: 10px;
}
.payment-method-card.default {
border: 2px solid var(--green);
background: linear-gradient(to right, rgba(0, 128, 96, 0.03), transparent);
}
.payment-method-icon {
width: 48px;
height: 32px;
border-radius: 6px;
background: #f1f5f9;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
}
.payment-method-details {
flex: 1;
}
.payment-method-brand {
font-weight: 600;
font-size: 14px;
color: #0f172a;
}
.payment-method-number {
font-size: 13px;
color: var(--muted);
font-variant-numeric: tabular-nums;
}
.payment-method-expiry {
font-size: 12px;
color: var(--muted);
}
.payment-method-actions {
display: flex;
gap: 8px;
}
.payment-method-actions .btn {
padding: 8px 12px;
font-size: 13px;
}
.default-badge {
background: var(--green);
color: #fff;
font-size: 11px;
font-weight: 700;
padding: 4px 8px;
border-radius: 999px;
text-transform: uppercase;
letter-spacing: 0.03em;
}
.empty-state {
text-align: center;
padding: 32px 20px;
color: var(--muted);
}
.empty-state i {
font-size: 32px;
margin-bottom: 12px;
opacity: 0.5;
}
.invoice-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
background: #fff;
border: 1px solid var(--border);
border-radius: 8px;
margin-bottom: 8px;
transition: all 0.2s ease;
}
.invoice-item:hover {
border-color: var(--green);
box-shadow: 0 2px 8px rgba(0, 128, 96, 0.08);
}
.invoice-info {
display: flex;
flex-direction: column;
gap: 2px;
}
.invoice-number {
font-weight: 600;
font-size: 14px;
color: #1e293b;
}
.invoice-description {
font-size: 12px;
color: var(--muted);
}
.invoice-meta {
font-size: 11px;
color: #9ca3af;
}
.invoice-amount {
font-weight: 700;
font-size: 14px;
color: var(--green);
}
.invoice-actions {
display: flex;
gap: 8px;
}
.invoice-actions .btn {
padding: 6px 12px;
font-size: 12px;
}
/* Modal Styles */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(15, 23, 42, 0.6);
backdrop-filter: blur(4px);
display: flex;
align-items: center;
justify-content: center;
z-index: 10000;
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
}
.modal-overlay.active {
opacity: 1;
visibility: visible;
}
.modal {
background: #fff;
border-radius: 16px;
width: 100%;
max-width: 500px;
padding: 24px;
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
transform: scale(0.95);
transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
max-height: 90vh;
overflow: hidden;
}
.modal-overlay.active .modal {
transform: scale(1);
}
.modal-header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
.modal-icon {
width: 40px;
height: 40px;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
}
.modal-icon.warning {
background: #fff7ed;
color: #ea580c;
}
.nav-bar {
background: white;
border-bottom: 1px solid #e9ecef;
padding: 16px 24px;
margin-bottom: 32px;
}
.nav-content {
max-width: 1400px;
margin: 0 auto;
display: flex;
justify-content: space-between;
align-items: center;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
text-decoration: none;
}
.brand-mark {
width: 40px;
height: 40px;
border-radius: 10px;
background: linear-gradient(135deg, var(--green), var(--green-dark));
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: 700;
font-size: 16px;
}
.brand-text {
font-family: 'Space Grotesk', sans-serif;
font-size: 20px;
font-weight: 600;
color: #1a1a1a;
}
.nav-links {
display: flex;
gap: 24px;
align-items: center;
}
.user-chip {
display: inline-flex;
align-items: center;
gap: 10px;
padding: 8px 10px;
border: 1px solid #e9ecef;
border-radius: 12px;
text-decoration: none;
color: inherit;
background: #fff;
cursor: pointer;
transition: all 0.2s;
}
.user-chip:hover {
border-color: var(--green);
background: #f8f9fa;
}
.user-menu-container {
position: relative;
display: inline-block;
}
.user-menu-popup {
position: absolute;
top: calc(100% + 8px);
right: 0;
background: #fff;
border: 1px solid #e9ecef;
border-radius: 12px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
z-index: 1000;
min-width: 180px;
display: none;
padding: 6px;
animation: menuFadeIn 0.2s ease-out;
}
@keyframes menuFadeIn {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.user-menu-popup.active {
display: block;
}
.user-menu-item {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 12px;
text-decoration: none;
color: #495057;
font-size: 14px;
font-weight: 500;
border-radius: 8px;
transition: all 0.2s;
}
.user-menu-item:hover {
background: #f8f9fa;
color: var(--green);
}
.user-menu-item svg {
color: #6c757d;
}
.user-menu-item:hover svg {
color: var(--green);
}
.user-chip-avatar {
width: 34px;
height: 34px;
border-radius: 999px;
background: rgba(0, 128, 96, 0.1);
color: var(--green);
display: grid;
place-items: center;
font-weight: 700;
letter-spacing: 0.02em;
text-transform: uppercase;
flex-shrink: 0;
}
.user-chip-status {
font-size: 11px;
color: #6c757d;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.user-chip-email {
font-size: 13px;
font-weight: 700;
color: #1a1a1a;
max-width: 160px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Mobile portrait: show only avatar to save space */
@media (max-width: 640px) and (orientation: portrait) {
.user-chip .user-chip-status,
.user-chip .user-chip-email {
display: none !important;
}
.user-chip {
padding: 6px 8px;
}
.user-chip-avatar {
width: 32px;
height: 32px;
}
}
.modal-icon.info {
background: #eff6ff;
color: #2563eb;
}
.modal-title {
font-size: 18px;
font-weight: 700;
color: #1e293b;
}
.modal-body {
font-size: 15px;
color: #64748b;
line-height: 1.6;
margin-bottom: 24px;
}
.modal-actions {
display: flex;
gap: 12px;
justify-content: flex-end;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.payment-modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(15, 23, 42, 0.7);
backdrop-filter: blur(8px);
z-index: 100000;
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
display: flex;
align-items: center;
justify-content: center;
}
.payment-modal-overlay.active {
opacity: 1;
visibility: visible;
}
.payment-modal {
background: #fff;
border-radius: 12px;
width: 95vw;
max-width: 1100px;
max-height: 96vh;
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
transform: scale(0.95) translateY(8px);
transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
display: flex;
flex-direction: column;
overflow: hidden;
height: auto;
.payment-modal-overlay.active .payment-modal {
transform: scale(1) translateY(0);
}
.payment-modal-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px 24px;
border-bottom: 1px solid var(--border);
background: #fff;
flex-shrink: 0;
}
.payment-modal-header h3 {
margin: 0;
font-size: 18px;
font-weight: 700;
color: #1e293b;
}
.payment-modal-close {
background: none;
border: none;
font-size: 28px;
line-height: 1;
cursor: pointer;
color: var(--muted);
padding: 0;
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 8px;
transition: all 0.15s ease;
}
.payment-modal-close:hover {
background: rgba(0, 0, 0, 0.05);
color: #0f172a;
}
/* Make the frame container flexible and scrollable so iframe content fills the modal and isn't clipped */
.payment-frame-container {
display: flex;
flex: 1 1 auto;
overflow: auto; /* allow internal scrolling when needed */
min-height: 60vh;
background: #f8fafc;
height: auto;
}
.payment-frame-container iframe {
display: block;
width: 100%;
height: calc(96vh - 72px);
max-height: calc(96vh - 72px);
}
@media (max-width: 640px) {
.payment-modal {
max-width: 100%;
max-height: 100%;
border-radius: 0;
width: 100%;
height: 100%;
}
.payment-frame-container {
min-height: calc(100vh - 70px);
}
}
/* Invoice Modal Styles */
.invoice-modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(15, 23, 42, 0.6);
backdrop-filter: blur(4px);
display: flex;
align-items: center;
justify-content: center;
z-index: 10000;
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
}
.invoice-modal-overlay.active {
opacity: 1;
visibility: visible;
}
.invoice-modal {
background: #fff;
border-radius: 16px;
width: 100%;
max-width: 700px;
max-height: 85vh;
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
transform: scale(0.95);
transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
display: flex;
flex-direction: column;
overflow: hidden;
}
.invoice-modal-overlay.active .invoice-modal {
transform: scale(1);
}
.invoice-modal-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px 24px;
border-bottom: 1px solid var(--border);
background: #fff;
flex-shrink: 0;
}
.invoice-modal-header h3 {
margin: 0;
font-size: 18px;
font-weight: 700;
color: #1e293b;
}
.invoice-modal-close {
background: none;
border: none;
font-size: 28px;
line-height: 1;
cursor: pointer;
color: var(--muted);
padding: 0;
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 8px;
transition: all 0.15s ease;
}
.invoice-modal-close:hover {
background: rgba(0, 0, 0, 0.05);
color: #0f172a;
}
.invoice-modal-body {
flex: 1;
overflow-y: auto;
padding: 20px 24px;
}
.invoice-modal-footer {
padding: 16px 24px;
border-top: 1px solid var(--border);
background: #f8fafc;
flex-shrink: 0;
}
.pagination {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.pagination button {
padding: 8px 14px;
border: 1px solid var(--border);
background: #fff;
border-radius: 8px;
cursor: pointer;
font-weight: 500;
font-size: 14px;
color: #1e293b;
transition: all 0.2s ease;
}
.pagination button:hover:not(:disabled) {
background: #f8fafc;
border-color: var(--green);
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.pagination button.active {
background: var(--green);
color: #fff;
border-color: var(--green);
}
.pagination .page-info {
font-size: 14px;
color: var(--muted);
padding: 0 12px;
}
.view-all-btn {
width: 100%;
margin-top: 12px;
}
.invoice-modal-list {
display: flex;
flex-direction: column;
gap: 8px;
}
</style>
<!-- PostHog Analytics -->
<script src="/posthog.js"></script>
</head>
<body>
<nav class="nav-bar">
<div class="nav-content">
<a href="/" class="brand">
<img src="/assets/Plugin.png" alt="Plugin Compass" style="width: 32px; height: 32px; border-radius: 8px;">
<span class="brand-text">Plugin Compass</span>
</a>
<div class="nav-links">
<a class="btn ghost" href="/apps" style="margin-right: 12px;"><i class="fa-solid fa-grid-2"></i>Apps</a>
<div class="user-menu-container">
<div class="user-chip" id="settings-user-chip" title="Account & settings">
<div class="user-chip-avatar" id="settings-user-avatar">?</div>
<div style="display:flex; flex-direction:column; gap:2px; min-width:0;">
<span class="user-chip-status">Signed in</span>
<span class="user-chip-email" id="settings-user-email">Checking account…</span>
</div>
</div>
<div class="user-menu-popup" id="user-menu-popup">
<a href="/apps" class="user-menu-item">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="3" width="7" height="7"></rect>
<rect x="14" y="3" width="7" height="7"></rect>
<rect x="14" y="14" width="7" height="7"></rect>
<rect x="3" y="14" width="7" height="7"></rect>
</svg>
My Apps
</a>
<a href="/feature-requests" class="user-menu-item">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
stroke-linecap="round" stroke-linejoin="round">
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
</svg>
Feature Requests
</a>
<a href="/topup" class="user-menu-item">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"></circle>
<path d="M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"></path>
<path d="M12 18V6"></path>
</svg>
Tokens Top-up
</a>
<div style="margin: 4px 0; border-top: 1px solid #f1f3f5;"></div>
<a href="#" class="user-menu-item" id="logout-link">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
stroke-linecap="round" stroke-linejoin="round">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
<polyline points="16 17 21 12 16 7"></polyline>
<line x1="21" y1="12" x2="9" y2="12"></line>
</svg>
Logout
</a>
</div>
</div>
</div>
</div>
</nav>
<div class="shell">
<div class="topbar">
<div>
<div class="crumb">Account & Billing</div>
<h1 class="title">Account settings</h1>
</div>
<div class="actions">
</div>
</div>
<div class="grid">
<div class="card">
<div style="flex: 1;">
<h3>Account overview</h3>
<p class="muted">Signed-in identity and subscription details.</p>
<div class="divider"></div>
<div class="user-block">
<div class="avatar" id="settings-avatar">?</div>
<div>
<div class="pill success" id="settings-status">Signed in</div>
<div style="font-weight:700; font-size:15px; margin-top: 4px;" id="settings-email">Loading…</div>
</div>
</div>
<div class="divider"></div>
<div class="list">
<div class="list-row">
<span class="muted">Current plan</span>
<span id="settings-plan">-</span>
</div>
<div class="list-row">
<span class="muted">Billing status</span>
<span id="settings-billing-status">-</span>
</div>
<div class="list-row">
<span class="muted">Renews</span>
<span id="settings-renews">-</span>
</div>
</div>
</div>
</div>
<div class="card">
<form id="settings-form" style="display: flex; flex-direction: column; height: 100%;">
<div style="flex: 1;">
<h3>Plan & billing</h3>
<p class="muted">Update your plan and billing preferences.</p>
<div class="divider"></div>
<div class="field">
<label for="plan">Subscription Plan</label>
<select id="plan"></select>
</div>
<div class="field">
<label for="billing-cycle">Billing cycle</label>
<select id="billing-cycle">
<option value="monthly">Monthly</option>
<option value="yearly">Yearly (save 20%)</option>
</select>
</div>
<div class="field">
<label for="currency">Currency</label>
<select id="currency">
<option value="usd">USD - US Dollar</option>
<option value="gbp">GBP - British Pound</option>
<option value="eur">EUR - Euro</option>
</select>
</div>
<div class="field">
<label for="billing-email">Billing email</label>
<input id="billing-email" type="email" placeholder="you@example.com" autocomplete="email" required />
</div>
</div>
<div class="card-footer">
<div class="status" id="settings-status-line" style="margin-right: auto; margin-top: 0;"></div>
<button type="submit" class="btn primary">Save changes</button>
</div>
</form>
</div>
<div class="card">
<div style="flex: 1;">
<h3>Payment Methods</h3>
<p class="muted">Manage your saved payment methods for faster checkout.</p>
<div class="divider"></div>
<div id="payment-methods-list">
<div class="empty-state">
<i class="fa-regular fa-credit-card"></i>
<p>No payment methods saved yet</p>
</div>
</div>
</div>
</div>
<div class="card">
<div style="flex: 1;">
<h3>Billing actions</h3>
<p class="muted">Manage your subscription and top-ups.</p>
<div class="divider"></div>
</div>
<div class="card-footer" style="gap:12px;">
<a class="btn ghost" href="/topup"><i class="fa-solid fa-coins"></i> Buy top-ups</a>
<button class="btn danger ghost" id="cancel-plan"><i class="fa-solid fa-ban"></i> Cancel plan</button>
</div>
</div>
<div class="card">
<div style="flex: 1;">
<h3>Invoices</h3>
<p class="muted">View and download all your payment invoices.</p>
<div class="divider"></div>
<div id="invoices-list">
<div class="empty-state">
<i class="fa-solid fa-file-invoice"></i>
<p>No invoices yet</p>
</div>
</div>
</div>
</div>
</div>
<!-- Confirmation Modal -->
<div class="modal-overlay" id="confirm-modal">
<div class="modal">
<div class="modal-header">
<div class="modal-icon warning" id="modal-icon">
<i class="fa-solid fa-triangle-exclamation"></i>
</div>
<div class="modal-title" id="modal-title">Confirm Action</div>
</div>
<div class="modal-body" id="modal-body">
Are you sure you want to perform this action?
</div>
<div class="modal-actions">
<button class="btn" id="modal-cancel">Cancel</button>
<button class="btn primary" id="modal-confirm">Confirm</button>
</div>
</div>
</div>
<!-- Payment Modal -->
<div class="payment-modal-overlay" id="payment-modal">
<div class="payment-modal">
<div class="payment-modal-header">
<h3>Secure Checkout</h3>
<button type="button" class="payment-modal-close" id="payment-modal-close">&times;</button>
</div>
<div id="payment-frame-container" class="payment-frame-container"></div>
</div>
</div>
<script>
const el = {
email: document.getElementById('settings-email'),
avatar: document.getElementById('settings-avatar'),
plan: document.getElementById('settings-plan'),
billingStatus: document.getElementById('settings-billing-status'),
renews: document.getElementById('settings-renews'),
status: document.getElementById('settings-status'),
billingEmail: document.getElementById('billing-email'),
billingCycle: document.getElementById('billing-cycle'),
currency: document.getElementById('currency'),
planSelect: document.getElementById('plan'),
form: document.getElementById('settings-form'),
statusLine: document.getElementById('settings-status-line'),
cancel: document.getElementById('cancel-plan'),
paymentMethodsList: document.getElementById('payment-methods-list'),
addPaymentMethod: document.getElementById('add-payment-method'),
invoicesList: document.getElementById('invoices-list'),
};
let csrfToken = '';
let pendingAction = null;
let currentPlan = '';
let allInvoices = [];
let currentInvoicePage = 1;
const INVOICES_PER_PAGE = 10;
const PLAN_ALIASES = { business: 'professional' };
function showConfirmModal({ title, body, icon, onConfirm }) {
const modal = document.getElementById('confirm-modal');
const titleEl = document.getElementById('modal-title');
const bodyEl = document.getElementById('modal-body');
const iconEl = document.getElementById('modal-icon');
const confirmBtn = document.getElementById('modal-confirm');
const cancelBtn = document.getElementById('modal-cancel');
titleEl.textContent = title;
bodyEl.textContent = body;
iconEl.className = `modal-icon ${icon || 'warning'}`;
iconEl.innerHTML = icon === 'info' ? '<i class="fa-solid fa-circle-info"></i>' : '<i class="fa-solid fa-triangle-exclamation"></i>';
modal.classList.add('active');
const handleConfirm = () => {
onConfirm();
closeModal();
};
const closeModal = () => {
modal.classList.remove('active');
confirmBtn.removeEventListener('click', handleConfirm);
cancelBtn.removeEventListener('click', closeModal);
};
confirmBtn.addEventListener('click', handleConfirm);
cancelBtn.addEventListener('click', closeModal);
}
function setStatus(msg, type = '') {
if (!el.statusLine) return;
el.statusLine.textContent = msg || '';
el.statusLine.className = `status ${type}`;
}
function formatDate(iso) {
if (!iso) return 'Not scheduled';
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return 'Not scheduled';
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
}
function setAvatar(email) {
const initial = (email || '?').trim().charAt(0).toUpperCase() || '?';
el.avatar.textContent = initial;
}
function renderAccount(account) {
const email = account?.email || '';
el.email.textContent = email || 'Unknown';
setAvatar(email);
el.plan.textContent = account?.plan || 'hobby';
el.billingStatus.textContent = account?.billingStatus || 'active';
el.renews.textContent = formatDate(account?.subscriptionRenewsAt);
el.planSelect.value = account?.plan || 'hobby';
el.billingEmail.value = account?.billingEmail || email || '';
el.currency.value = account?.subscriptionCurrency || 'usd';
el.status.textContent = account?.billingStatus === 'canceled' ? 'Canceled' : 'Signed in';
currentPlan = account?.plan || 'hobby';
}
async function loadAccount() {
try {
const resp = await fetch('/api/account', { credentials: 'same-origin' });
if (resp.status === 401) {
window.location.href = '/login?next=/settings';
return;
}
const data = await resp.json().catch(() => ({}));
renderAccount(data.account || {});
} catch (err) {
setStatus('Unable to load account settings right now.', 'error');
}
}
async function loadPlans() {
try {
const resp = await fetch('/api/account/plans', { credentials: 'same-origin' });
const data = await resp.json().catch(() => ({}));
const plans = Array.isArray(data.plans) ? data.plans : ['hobby', 'starter', 'business', 'enterprise'];
el.planSelect.innerHTML = '';
plans.forEach((plan) => {
const option = document.createElement('option');
option.value = plan;
let label = plan.charAt(0).toUpperCase() + plan.slice(1);
if (plan === 'hobby') label = 'Hobby (free)';
if (plan === 'business') label = 'Professional';
option.textContent = label;
el.planSelect.appendChild(option);
});
if (data.defaultPlan && el.planSelect) {
el.planSelect.value = data.defaultPlan;
}
} catch (_) {
// Fallback to defaults if fetch fails
el.planSelect.innerHTML = `
<option value="hobby">Hobby (free)</option>
<option value="starter">Starter</option>
<option value="business">Professional</option>
<option value="enterprise">Enterprise</option>
`;
}
}
async function saveAccount(event) {
if (event) event.preventDefault();
const newPlan = el.planSelect.value;
const newBillingCycle = el.billingCycle.value;
const newCurrency = el.currency.value;
const newBillingEmail = el.billingEmail.value;
const isPlanChange = newPlan !== currentPlan;
const isDowngrade = isPlanChange && planRank(newPlan) < planRank(currentPlan);
const isPaidPlan = ['starter', 'business', 'professional', 'enterprise'].includes(currentPlan);
const isNewPaidPlan = ['starter', 'business', 'professional', 'enterprise'].includes(newPlan);
const isPaidToPaidChange = isPaidPlan && isNewPaidPlan && isPlanChange;
const isPaidToFree = isPaidPlan && newPlan === 'hobby';
// Handle paid-to-paid plan changes (use Change Plan API on server)
if (isPaidToPaidChange) {
const planLabel = newPlan === 'business' ? 'Professional' : newPlan.charAt(0).toUpperCase() + newPlan.slice(1);
const currentLabel = currentPlan === 'business' ? 'Professional' : currentPlan.charAt(0).toUpperCase() + currentPlan.slice(1);
showConfirmModal({
title: 'Change Subscription Plan',
body: isDowngrade
? `You are downgrading from ${currentLabel} to ${planLabel}. Any price difference will be credited to your account and applied to future renewals. Your subscription will continue without interruption.`
: `You are upgrading from ${currentLabel} to ${planLabel}. You will be charged the difference for the current billing period. Your subscription will update immediately.`,
icon: 'info',
onConfirm: async () => {
setStatus('Changing subscription plan...');
try {
const resp = await fetch('/api/account', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken,
},
credentials: 'same-origin',
body: JSON.stringify({
plan: newPlan,
billingCycle: newBillingCycle,
currency: newCurrency,
billingEmail: newBillingEmail,
}),
});
const data = await resp.json().catch(() => ({}));
if (!resp.ok) throw new Error(data.error || 'Unable to change plan');
renderAccount(data.account || {});
setStatus('Subscription plan changed successfully!', 'success');
} catch (err) {
setStatus(err.message, 'error');
}
}
});
return;
}
// Handle paid-to-free downgrade (cancel subscription)
if (isPaidToFree) {
showConfirmModal({
title: 'Downgrade to Free Plan',
body: 'You are moving to the free Hobby plan. Your subscription will be cancelled and you will lose premium features and limits. Are you sure you want to continue?',
icon: 'warning',
onConfirm: async () => {
setStatus('Cancelling subscription...');
try {
const resp = await fetch('/api/account', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken,
},
credentials: 'same-origin',
body: JSON.stringify({
plan: newPlan,
billingCycle: newBillingCycle,
currency: newCurrency,
billingEmail: newBillingEmail,
}),
});
const data = await resp.json().catch(() => ({}));
if (!resp.ok) throw new Error(data.error || 'Unable to downgrade plan');
renderAccount(data.account || {});
setStatus('Downgraded to free plan successfully', 'success');
} catch (err) {
setStatus(err.message, 'error');
}
}
});
return;
}
// Handle free-to-paid upgrade (requires checkout)
if (isPlanChange && isNewPaidPlan && !isPaidPlan) {
showConfirmModal({
title: 'Upgrade to Paid Plan',
body: `You are upgrading to ${newPlan.charAt(0).toUpperCase() + newPlan.slice(1)}. You will be redirected to complete your payment through our secure checkout.`,
icon: 'info',
onConfirm: async () => {
setStatus('Starting checkout...');
try {
const resp = await fetch('/api/subscription/checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken,
},
credentials: 'same-origin',
body: JSON.stringify({
plan: newPlan,
billingCycle: newBillingCycle,
currency: newCurrency,
inline: true,
}),
});
const data = await resp.json().catch(() => ({}));
if (!resp.ok) throw new Error(data.error || 'Unable to start checkout');
if (data.inlineCheckoutUrl) {
openInlineCheckout(data.inlineCheckoutUrl, data.sessionId, newPlan, newBillingCycle, newCurrency);
} else if (data.checkoutUrl) {
openInlineCheckout(data.checkoutUrl, data.sessionId, newPlan, newBillingCycle, newCurrency);
} else {
throw new Error('Checkout URL not returned');
}
} catch (err) {
setStatus(err.message, 'error');
}
}
});
return;
}
// Handle other account settings changes (billing email, currency, etc.)
const payload = {
plan: newPlan,
billingCycle: newBillingCycle,
currency: newCurrency,
billingEmail: newBillingEmail,
};
showConfirmModal({
title: 'Save Changes',
body: 'Are you sure you want to update your account settings?',
icon: 'info',
onConfirm: async () => {
setStatus('Saving...');
try {
const resp = await fetch('/api/account', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken,
},
credentials: 'same-origin',
body: JSON.stringify(payload),
});
const data = await resp.json().catch(() => ({}));
if (!resp.ok) throw new Error(data.error || 'Save failed');
renderAccount(data.account || {});
setStatus('Account updated successfully', 'success');
} catch (err) {
setStatus(err.message, 'error');
}
}
});
}
async function updateSubscription(action) {
const isCancel = action === 'cancel';
showConfirmModal({
title: isCancel ? 'Cancel Subscription' : 'Resume Subscription',
body: isCancel
? 'Before you go, we can help you find a cheaper plan. Are you sure you want to cancel? You will still have access until the end of your billing period.'
: 'Are you sure you want to resume your subscription?',
icon: isCancel ? 'warning' : 'info',
onConfirm: async () => {
setStatus('Updating subscription...');
try {
let resp;
if (isCancel) {
// Use dedicated cancel endpoint so server cancels Dodo subscription explicitly
resp = await fetch('/api/subscription/cancel', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken,
},
credentials: 'same-origin',
});
} else {
resp = await fetch('/api/account', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken,
},
credentials: 'same-origin',
body: JSON.stringify({ action, billingCycle: el.billingCycle.value }),
});
}
const data = await resp.json().catch(() => ({}));
if (!resp.ok) throw new Error(data.error || 'Unable to update subscription');
renderAccount(data.account || {});
setStatus(isCancel ? 'Subscription canceled' : 'Subscription resumed', 'success');
} catch (err) {
setStatus(err.message, 'error');
}
}
});
}
async function loadCsrfToken() {
const csrfResp = await fetch('/api/csrf', { credentials: 'same-origin' });
if (csrfResp.ok) {
const csrfData = await csrfResp.json().catch(() => ({}));
csrfToken = csrfData.csrfToken || '';
}
}
function getCardIcon(brand) {
const brandLower = (brand || '').toLowerCase();
if (brandLower.includes('visa')) return '<i class="fa-brands fa-cc-visa" style="color: #1a1f71;"></i>';
if (brandLower.includes('mastercard')) return '<i class="fa-brands fa-cc-mastercard" style="color: #eb001b;"></i>';
if (brandLower.includes('amex')) return '<i class="fa-brands fa-cc-amex" style="color: #006fcf;"></i>';
if (brandLower.includes('discover')) return '<i class="fa-brands fa-cc-discover" style="color: #ff6000;"></i>';
return '<i class="fa-regular fa-credit-card"></i>';
}
function renderPaymentMethods(methods) {
if (!el.paymentMethodsList) return;
if (!Array.isArray(methods) || methods.length === 0) {
el.paymentMethodsList.innerHTML = `
<div class="empty-state">
<i class="fa-regular fa-credit-card"></i>
<p>No payment methods saved yet</p>
</div>
`;
return;
}
el.paymentMethodsList.innerHTML = methods.map((method, index) => `
<div class="payment-method-card ${index === 0 ? 'default' : ''}">
<div class="payment-method-icon">
${getCardIcon(method.brand)}
</div>
<div class="payment-method-details">
<div class="payment-method-brand">
${method.brand || 'Card'} ${index === 0 ? '<span class="default-badge">Default</span>' : ''}
</div>
<div class="payment-method-number">•••• •••• •••• ${method.last4 || '••••'}</div>
<div class="payment-method-expiry">Expires ${method.expiresAt || 'N/A'}</div>
</div>
</div>
`).join('');
}
function planRank(plan) {
const normalized = (plan || '').toLowerCase();
const resolved = PLAN_ALIASES[normalized] || normalized;
if (resolved === 'enterprise') return 4;
if (resolved === 'professional') return 3;
if (resolved === 'starter') return 2;
return 1;
}
async function loadPaymentMethods() {
if (!el.paymentMethodsList) return;
try {
const resp = await fetch('/api/account/payment-methods', { credentials: 'same-origin' });
if (resp.status === 404 || resp.status === 401) {
renderPaymentMethods([]);
return;
}
const data = await resp.json().catch(() => ({}));
renderPaymentMethods(data.paymentMethods || []);
} catch (err) {
renderPaymentMethods([]);
}
}
function renderInvoices(invoices) {
if (!el.invoicesList) return;
allInvoices = invoices;
if (!Array.isArray(invoices) || invoices.length === 0) {
el.invoicesList.innerHTML = `
<div class="empty-state">
<i class="fa-solid fa-file-invoice"></i>
<p>No invoices yet</p>
</div>
`;
return;
}
const displayInvoices = invoices.slice(0, 4);
el.invoicesList.innerHTML = displayInvoices.map((invoice) => {
const date = new Date(invoice.createdAt).toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric'
});
const amount = invoice.amount / 100;
return `
<div class="invoice-item">
<div class="invoice-info">
<div class="invoice-number">${invoice.invoiceNumber}</div>
<div class="invoice-description">${invoice.description}</div>
<div class="invoice-meta">${date}</div>
</div>
<div class="invoice-amount">${invoice.currency} ${amount.toFixed(2)}</div>
<div class="invoice-actions">
<button class="btn" onclick="downloadInvoice('${invoice.id}')">
<i class="fa-solid fa-download"></i> Download
</button>
</div>
</div>
`;
}).join('');
if (invoices.length > 4) {
el.invoicesList.innerHTML += `
<button class="btn view-all-btn" id="view-all-invoices">
<i class="fa-solid fa-list"></i> View All (${invoices.length})
</button>
`;
document.getElementById('view-all-invoices').addEventListener('click', openInvoiceModal);
}
}
function renderInvoiceModalPage(page) {
const modalList = document.getElementById('invoice-modal-list');
const pagination = document.getElementById('invoice-pagination');
currentInvoicePage = page;
const totalPages = Math.ceil(allInvoices.length / INVOICES_PER_PAGE);
const startIndex = (page - 1) * INVOICES_PER_PAGE;
const endIndex = startIndex + INVOICES_PER_PAGE;
const pageInvoices = allInvoices.slice(startIndex, endIndex);
modalList.innerHTML = pageInvoices.map((invoice) => {
const date = new Date(invoice.createdAt).toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric'
});
const amount = invoice.amount / 100;
return `
<div class="invoice-item">
<div class="invoice-info">
<div class="invoice-number">${invoice.invoiceNumber}</div>
<div class="invoice-description">${invoice.description}</div>
<div class="invoice-meta">${date}</div>
</div>
<div class="invoice-amount">${invoice.currency} ${amount.toFixed(2)}</div>
<div class="invoice-actions">
<button class="btn" onclick="downloadInvoice('${invoice.id}')">
<i class="fa-solid fa-download"></i> Download
</button>
</div>
</div>
`;
}).join('');
let paginationHtml = `
<button onclick="changeInvoicePage(${page - 1})" ${page === 1 ? 'disabled' : ''}>
<i class="fa-solid fa-chevron-left"></i>
</button>
`;
for (let i = 1; i <= totalPages; i++) {
if (i === 1 || i === totalPages || (i >= page - 2 && i <= page + 2)) {
paginationHtml += `
<button onclick="changeInvoicePage(${i})" class="${i === page ? 'active' : ''}">${i}</button>
`;
} else if (i === page - 3 || i === page + 3) {
paginationHtml += `<span class="page-info">...</span>`;
}
}
paginationHtml += `
<button onclick="changeInvoicePage(${page + 1})" ${page === totalPages ? 'disabled' : ''}>
<i class="fa-solid fa-chevron-right"></i>
</button>
`;
pagination.innerHTML = paginationHtml;
}
window.changeInvoicePage = function(page) {
const totalPages = Math.ceil(allInvoices.length / INVOICES_PER_PAGE);
if (page >= 1 && page <= totalPages) {
renderInvoiceModalPage(page);
}
};
function openInvoiceModal() {
const modal = document.getElementById('invoice-modal');
modal.classList.add('active');
renderInvoiceModalPage(1);
}
function closeInvoiceModal() {
const modal = document.getElementById('invoice-modal');
modal.classList.remove('active');
}
window.closeInvoiceModal = closeInvoiceModal;
async function loadInvoices() {
if (!el.invoicesList) return;
try {
const resp = await fetch('/api/invoices', { credentials: 'same-origin' });
if (resp.status === 401) {
window.location.href = '/login?next=/settings';
return;
}
const data = await resp.json().catch(() => ({}));
renderInvoices(data.invoices || []);
} catch (err) {
renderInvoices([]);
}
}
async function downloadInvoice(invoiceId) {
try {
const resp = await fetch(`/api/invoices/${invoiceId}/download`, {
credentials: 'same-origin'
});
if (!resp.ok) {
const error = await resp.json().catch(() => ({}));
throw new Error(error.error || 'Failed to download invoice');
}
const blob = await resp.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `invoice-${invoiceId}.pdf`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
} catch (err) {
setStatus('Failed to download invoice: ' + err.message, 'error');
}
}
window.downloadInvoice = downloadInvoice;
function openPaymentOverlay(url) {
const modal = document.getElementById('payment-modal');
const container = document.getElementById('payment-frame-container');
container.innerHTML = `<iframe src="${url}" allowpaymentrequest="true"></iframe>`;
modal.classList.add('active');
setStatus('Complete your payment in the modal below...', '');
// Poll for payment method additions
let pollCount = 0;
const maxPolls = 120; // 2 minutes max
const pollInterval = 1500; // 1.5 seconds
const checkPaymentMethodStatus = async () => {
try {
pollCount++;
const resp = await fetch('/api/account/payment-methods', { credentials: 'same-origin' });
if (resp.ok) {
const data = await resp.json().catch(() => ({}));
const currentMethods = document.querySelectorAll('.payment-method-card').length;
const newMethods = data.paymentMethods?.length || 0;
// Check if a new payment method was added
if (newMethods > currentMethods) {
clearInterval(pollTimer);
modal.classList.remove('active');
container.innerHTML = '';
setStatus('Payment method added successfully', 'success');
loadPaymentMethods();
return;
}
}
if (pollCount >= maxPolls) {
clearInterval(pollTimer);
setStatus('Timeout waiting for payment method. Please check your payment methods.', 'error');
}
} catch (error) {
console.error('Error checking payment method status:', error);
}
};
const pollTimer = setInterval(checkPaymentMethodStatus, pollInterval);
}
function closePaymentOverlay() {
const modal = document.getElementById('payment-modal');
const container = document.getElementById('payment-frame-container');
modal.classList.remove('active');
container.innerHTML = '';
setStatus('Refreshing payment methods...', '');
loadPaymentMethods();
}
async function ensureDodoPaymentsLoaded() {
return new Promise((resolve) => {
if (typeof DodoPaymentsCheckout !== 'undefined' && DodoPaymentsCheckout.DodoPayments && DodoPaymentsCheckout.DodoPayments.Checkout) {
resolve();
return;
}
const existingScript = document.querySelector('script[src="https://cdn.jsdelivr.net/npm/dodopayments-checkout@latest/dist/index.js"]');
if (existingScript) {
const checkLoaded = () => {
if (typeof DodoPaymentsCheckout !== 'undefined' && DodoPaymentsCheckout.DodoPayments && DodoPaymentsCheckout.DodoPayments.Checkout) {
resolve();
} else {
setTimeout(checkLoaded, 100);
}
};
checkLoaded();
return;
}
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/dodopayments-checkout@latest/dist/index.js';
script.async = true;
const timeout = setTimeout(() => {
console.warn('DodoPayments script loading timed out, will use iframe fallback');
resolve();
}, 5000);
script.onload = () => {
clearTimeout(timeout);
console.log('DodoPayments script loaded');
resolve();
};
script.onerror = () => {
clearTimeout(timeout);
console.error('Failed to load DodoPayments script, will use iframe fallback');
resolve();
};
document.head.appendChild(script);
});
}
async function openInlineCheckout(checkoutUrl, sessionId, plan, billingCycle, currency) {
// Create a modal overlay for the inline checkout
const modalOverlay = document.createElement('div');
modalOverlay.id = 'checkout-modal-overlay';
modalOverlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
z-index: 9998;
display: flex;
align-items: center;
justify-content: center;
`;
// Create the checkout container
const checkoutContainer = document.createElement('div');
checkoutContainer.id = 'checkout-container';
checkoutContainer.style.cssText = `
width: 100%;
max-width: 500px;
height: 600px;
background: white;
border-radius: 16px;
position: relative;
overflow: hidden;
`;
// Create close button
const closeButton = document.createElement('button');
closeButton.innerHTML = '&times;';
closeButton.style.cssText = `
position: absolute;
top: 15px;
right: 15px;
width: 32px;
height: 32px;
border-radius: 50%;
background: rgba(255, 255, 255, 0.9);
border: 1px solid var(--border);
font-size: 20px;
cursor: pointer;
z-index: 10000;
display: flex;
align-items: center;
justify-content: center;
color: var(--muted);
transition: all 0.2s ease;
`;
closeButton.onmouseover = () => {
closeButton.style.background = '#f8fafc';
closeButton.style.color = '#1f2937';
};
closeButton.onmouseout = () => {
closeButton.style.background = 'rgba(255, 255, 255, 0.9)';
closeButton.style.color = 'var(--muted)';
};
modalOverlay.appendChild(checkoutContainer);
modalOverlay.appendChild(closeButton);
document.body.appendChild(modalOverlay);
const loadingIndicator = document.createElement('div');
loadingIndicator.style.cssText = `
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #6b7280;
font-size: 16px;
z-index: 1000;
`;
loadingIndicator.textContent = 'Loading secure payment...';
checkoutContainer.appendChild(loadingIndicator);
await ensureDodoPaymentsLoaded();
if (loadingIndicator.parentNode) {
checkoutContainer.removeChild(loadingIndicator);
}
if (typeof DodoPaymentsCheckout !== 'undefined' && DodoPaymentsCheckout.DodoPayments && DodoPaymentsCheckout.DodoPayments.Checkout) {
try {
if (!DodoPaymentsCheckout.DodoPayments.Initialize) {
console.warn('DodoPayments.Initialize not available, checking for Checkout.open directly');
} else {
DodoPaymentsCheckout.DodoPayments.Initialize({
mode: 'test'
});
}
DodoPaymentsCheckout.DodoPayments.Checkout.open({
checkoutUrl: checkoutUrl,
elementId: 'checkout-container',
options: {
themeConfig: {
light: {
bgPrimary: '#FFFFFF',
bgSecondary: '#F8FAFC',
textPrimary: '#0F172A',
textSecondary: '#6B7280',
textPlaceholder: '#9CA3AF',
textError: '#EF4444',
textSuccess: '#10B981',
borderPrimary: '#E5E7EB',
borderSecondary: '#D1D5DB',
inputFocusBorder: '#008060',
buttonPrimary: '#008060',
buttonPrimaryHover: '#004C3F',
buttonTextPrimary: '#FFFFFF',
buttonSecondary: '#FFFFFF',
buttonSecondaryHover: '#F8FAFC',
buttonTextSecondary: '#0F172A'
},
dark: {
bgPrimary: '#0D0D0D',
bgSecondary: '#1F2937',
textPrimary: '#F9FAFB',
textSecondary: '#9CA3AF',
textPlaceholder: '#6B7280',
textError: '#F87171',
textSuccess: '#34D399',
borderPrimary: '#374151',
borderSecondary: '#4B5563',
inputFocusBorder: '#10B981',
buttonPrimary: '#008060',
buttonPrimaryHover: '#10B981',
buttonTextPrimary: '#FFFFFF',
buttonSecondary: '#1F2937',
buttonSecondaryHover: '#374151',
buttonTextSecondary: '#F9FAFB'
},
radius: '8px'
},
payButtonText: 'Complete Payment',
fontSize: '14px',
fontWeight: '500',
showTimer: true,
showSecurityBadge: true
}
});
} catch (error) {
console.error('DodoPayments.Checkout.open failed:', error);
const errorMessage = document.createElement('div');
errorMessage.style.cssText = `
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
text-align: center;
max-width: 80%;
z-index: 1001;
`;
errorMessage.innerHTML = `
<h3 style="color: #ef4444; margin-bottom: 10px;">Payment Processing</h3>
<p style="color: #6b7280; margin-bottom: 15px;">
The secure payment method failed to load. Falling back to standard payment page.
</p>
<p style="color: #6b7280; font-size: 14px;">
This may take a moment to redirect...
</p>
`;
checkoutContainer.appendChild(errorMessage);
setTimeout(() => {
checkoutContainer.innerHTML = '';
const iframe = document.createElement('iframe');
iframe.src = checkoutUrl;
iframe.allowpaymentrequest = "true";
iframe.style.cssText = 'width: 100%; height: 100%; border: none;';
iframe.onload = () => {
if (loadingIndicator.parentNode) {
loadingIndicator.remove();
}
};
checkoutContainer.appendChild(iframe);
}, 2000);
}
} else {
console.warn('DodoPayments not available, using iframe fallback');
console.log('DodoPaymentsCheckout object:', typeof DodoPaymentsCheckout, DodoPaymentsCheckout);
console.log('DodoPayments object:', typeof DodoPaymentsCheckout?.DodoPayments, DodoPaymentsCheckout?.DodoPayments);
const fallbackMessage = document.createElement('div');
fallbackMessage.style.cssText = `
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
text-align: center;
max-width: 80%;
z-index: 1001;
`;
fallbackMessage.innerHTML = `
<h3 style="color: #008060; margin-bottom: 10px;">Processing Payment</h3>
<p style="color: #6b7280; margin-bottom: 15px;">
Loading secure payment page...
</p>
<p style="color: #6b7280; font-size: 14px;">
Please wait while we prepare your payment.
</p>
`;
checkoutContainer.appendChild(fallbackMessage);
setTimeout(() => {
checkoutContainer.innerHTML = '';
const iframe = document.createElement('iframe');
iframe.src = checkoutUrl;
iframe.allowpaymentrequest = "true";
iframe.style.cssText = 'width: 100%; height: 100%; border: none;';
iframe.onload = () => {
if (loadingIndicator.parentNode) {
loadingIndicator.remove();
}
};
checkoutContainer.appendChild(iframe);
}, 1500);
}
// Poll for payment completion
let pollCount = 0;
const maxPolls = 180; // 3 minutes max
const pollInterval = 1000; // 1 second
const checkPaymentStatus = async () => {
try {
pollCount++;
const resp = await fetch(`/api/subscription/confirm?session_id=${encodeURIComponent(sessionId)}`, {
credentials: 'same-origin'
});
if (resp.ok) {
const data = await resp.json();
if (data.ok) {
// Payment successful
clearInterval(pollTimer);
closeCheckoutModal();
setStatus('Payment successful! Updating your account...', 'success');
setTimeout(() => {
loadAccount(); // Refresh account data
}, 1000);
return;
} else if (data.pending) {
// Payment still pending, continue polling
// Show progress every 10 seconds
if (pollCount % 10 === 0) {
setStatus(`Payment processing... (${Math.floor(pollCount / 60)}:${(pollCount % 60).toString().padStart(2, '0')})`, '');
}
}
}
if (pollCount >= maxPolls) {
clearInterval(pollTimer);
closeCheckoutModal();
setStatus('Payment confirmation timeout. Please check your account status.', 'error');
}
} catch (error) {
console.error('Error checking payment status:', error);
// Continue polling on network errors
}
};
const pollTimer = setInterval(checkPaymentStatus, pollInterval);
// Handle close button click
closeButton.onclick = () => {
clearInterval(pollTimer);
closeCheckoutModal();
setStatus('Payment cancelled', 'error');
};
// Handle overlay click (close on background click)
modalOverlay.onclick = (e) => {
if (e.target === modalOverlay) {
closeButton.onclick();
}
};
// Handle ESC key
const handleEsc = (e) => {
if (e.key === 'Escape') {
closeButton.onclick();
}
};
document.addEventListener('keydown', handleEsc);
function closeCheckoutModal() {
document.removeEventListener('keydown', handleEsc);
if (modalOverlay && modalOverlay.parentNode) {
modalOverlay.parentNode.removeChild(modalOverlay);
}
}
}
async function addPaymentMethod() {
setStatus('Loading payment form...', '');
try {
const resp = await fetch('/api/account/payment-methods/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken,
},
credentials: 'same-origin',
});
const data = await resp.json().catch(() => ({}));
const checkoutUrl = data.checkoutUrl || data.url;
if (checkoutUrl) {
setStatus('Opening checkout in a new window...', '');
setTimeout(() => {
const popup = window.open(
checkoutUrl,
'dodo-payment-checkout',
'width=600,height=700,scrollbars=yes,resizable=yes'
);
if (!popup) {
setStatus('Please allow popups to add a payment method', 'error');
return;
}
setStatus('Complete payment method setup in popup window...', '');
let pollCount = 0;
const maxPolls = 180;
const pollInterval = 2000;
const pollTimer = setInterval(async () => {
try {
pollCount++;
if (popup.closed) {
clearInterval(pollTimer);
setStatus('Refreshing payment methods...', '');
await loadPaymentMethods();
return;
}
if (pollCount >= maxPolls) {
clearInterval(pollTimer);
setStatus('Payment portal session expired. Please try again.', 'error');
popup.close();
}
} catch (error) {
console.error('Error polling payment method status:', error);
}
}, pollInterval);
}, 500);
} else if (data.error) {
setStatus(data.error, 'error');
} else {
setStatus('Unable to add payment method', 'error');
}
} catch (err) {
setStatus(err.message, 'error');
}
}
window.setDefaultPaymentMethod = async function(methodId) {
showConfirmModal({
title: 'Set Default Payment',
body: 'Set this payment method as your primary for all future charges?',
icon: 'info',
onConfirm: async () => {
try {
const resp = await fetch('/api/account/payment-methods/' + methodId + '/default', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken,
},
credentials: 'same-origin',
});
if (resp.ok) {
setStatus('Default payment method updated', 'success');
loadPaymentMethods();
} else {
const data = await resp.json().catch(() => ({}));
setStatus(data.error || 'Unable to set default', 'error');
}
} catch (err) {
setStatus(err.message, 'error');
}
}
});
};
window.removePaymentMethod = async function(methodId) {
showConfirmModal({
title: 'Remove Payment Method',
body: 'Are you sure you want to remove this payment method? This action cannot be undone.',
icon: 'warning',
onConfirm: async () => {
try {
const resp = await fetch('/api/account/payment-methods/' + methodId, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken,
},
credentials: 'same-origin',
});
if (resp.ok) {
setStatus('Payment method removed', 'success');
loadPaymentMethods();
} else {
const data = await resp.json().catch(() => ({}));
setStatus(data.error || 'Unable to remove', 'error');
}
} catch (err) {
setStatus(err.message, 'error');
}
}
});
};
el.form.addEventListener('submit', saveAccount);
el.cancel.addEventListener('click', (e) => {
e.preventDefault();
updateSubscription('cancel');
});
if (el.addPaymentMethod) {
el.addPaymentMethod.addEventListener('click', addPaymentMethod);
}
// Payment modal close button
const paymentModalClose = document.getElementById('payment-modal-close');
if (paymentModalClose) {
paymentModalClose.addEventListener('click', () => {
const modal = document.getElementById('payment-modal');
const container = document.getElementById('payment-frame-container');
modal.classList.remove('active');
container.innerHTML = '';
setStatus('Payment cancelled', 'error');
});
}
// Close modal when clicking on overlay
const paymentModal = document.getElementById('payment-modal');
if (paymentModal) {
paymentModal.addEventListener('click', (e) => {
if (e.target.id === 'payment-modal') {
const modal = document.getElementById('payment-modal');
const container = document.getElementById('payment-frame-container');
modal.classList.remove('active');
container.innerHTML = '';
setStatus('Payment cancelled', 'error');
}
});
}
// Invoice modal close button
const invoiceModalClose = document.getElementById('invoice-modal-close');
if (invoiceModalClose) {
invoiceModalClose.addEventListener('click', closeInvoiceModal);
}
// Close invoice modal when clicking on overlay
const invoiceModal = document.getElementById('invoice-modal');
if (invoiceModal) {
invoiceModal.addEventListener('click', (e) => {
if (e.target.id === 'invoice-modal') {
closeInvoiceModal();
}
});
}
// Close invoice modal on Escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
const modal = document.getElementById('invoice-modal');
if (modal.classList.contains('active')) {
closeInvoiceModal();
}
}
});
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('payment_method_added') === '1') {
window.history.replaceState({}, '', window.location.pathname);
setStatus('Payment method added successfully', 'success');
}
Promise.all([loadPlans(), loadCsrfToken()]).then(() => {
loadAccount();
loadPaymentMethods();
loadInvoices();
});
// User menu functionality (similar to apps.html)
const userChip = document.getElementById('settings-user-chip');
const userChipEmail = document.getElementById('settings-user-email');
const userChipAvatar = document.getElementById('settings-user-avatar');
const userMenuPopup = document.getElementById('user-menu-popup');
const logoutLink = document.getElementById('logout-link');
if (userChip && userMenuPopup) {
userChip.addEventListener('click', (e) => {
e.stopPropagation();
userMenuPopup.classList.toggle('active');
});
document.addEventListener('click', (e) => {
if (!userMenuPopup.contains(e.target) && !userChip.contains(e.target)) {
userMenuPopup.classList.remove('active');
}
});
}
if (logoutLink) {
logoutLink.addEventListener('click', async (e) => {
e.preventDefault();
try {
const response = await fetch('/api/logout', { method: 'POST' });
if (response.ok) {
localStorage.removeItem('shopify_ai_user');
localStorage.removeItem('wordpress_plugin_ai_user');
localStorage.removeItem('plugin_compass_onboarding_completed');
window.location.href = '/login';
}
} catch (err) {
console.error('Logout failed:', err);
window.location.href = '/login';
}
});
}
// Load user data for the header
async function loadSettingsUserChip() {
try {
const resp = await fetch('/api/account', { credentials: 'same-origin' });
if (resp.ok) {
const data = await resp.json().catch(() => ({}));
const email = data?.account?.email || '';
if (userChipEmail) userChipEmail.textContent = email || 'Guest';
if (userChipAvatar) userChipAvatar.textContent = email ? email.charAt(0).toUpperCase() : '?';
}
} catch (err) {
console.error('Failed to load user data:', err);
}
}
// Initialize user data
loadSettingsUserChip();
</script>
<!-- Invoice Modal -->
<div class="invoice-modal-overlay" id="invoice-modal">
<div class="invoice-modal">
<div class="invoice-modal-header">
<h3>All Invoices</h3>
<button type="button" class="invoice-modal-close" id="invoice-modal-close">&times;</button>
</div>
<div class="invoice-modal-body">
<div id="invoice-modal-list" class="invoice-modal-list"></div>
</div>
<div class="invoice-modal-footer">
<div class="pagination" id="invoice-pagination"></div>
</div>
</div>
</div>
<footer style="margin-top: 80px; padding: 40px 24px; border-top: 1px solid #e1e3e5; text-align: center; color: #6d7175; font-size: 0.875rem;">
<p>&copy; 2026 Plugin Compass. All rights reserved.</p>
<div style="margin-top: 12px; display: flex; justify-content: center; gap: 16px;">
<a href="/terms" style="color: #008060; text-decoration: none;">Terms</a>
<a href="/privacy" style="color: #008060; text-decoration: none;">Privacy</a>
<a href="/contact" style="color: #008060; text-decoration: none;">Contact Us</a>
</div>
</footer>
</body>
</html>