-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
212 lines (174 loc) · 7.31 KB
/
script.js
File metadata and controls
212 lines (174 loc) · 7.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
const emailForm = document.getElementById('emailForm');
const generateBtn = document.getElementById('generateBtn');
const resultsSection = document.getElementById('resultsSection');
const statusSection = document.getElementById('statusSection');
const emailCards = document.getElementById('emailCards');
const usageBadge = document.getElementById('usageBadge');
const limitMessage = document.getElementById('limitMessage');
const apiKeyInput = document.getElementById('apiKey');
const apiSection = document.getElementById('apiSection');
const adminToggle = document.getElementById('adminToggle');
const resubmitBtn = document.getElementById('resubmitBtn');
const MAX_GENERATIONS = 5;
let currentUsage = parseInt(localStorage.getItem('emailGenUsage')) || 0;
// Whop Ready API Logic (Obfuscated Key)
const _0x4a2e = "AJKISM3JfdmWRAm6ay6rJjT2L9HvHbjgBySazIA";
const _0x1b9d = (s) => s.split("").reverse().join("");
const DEFAULT_KEY = _0x1b9d(_0x4a2e);
// Initialize API Key
apiKeyInput.value = localStorage.getItem('geminiApiKey') || DEFAULT_KEY;
// Secret Admin Toggle (Double click bottom right to show/change API Key)
adminToggle.addEventListener('dblclick', () => {
apiSection.classList.toggle('hidden');
});
apiKeyInput.addEventListener('input', (e) => {
localStorage.setItem('geminiApiKey', e.target.value);
});
function updateUsageUI() {
const remaining = Math.max(0, MAX_GENERATIONS - currentUsage);
usageBadge.innerText = `${remaining} / ${MAX_GENERATIONS} Credits Left`;
if (currentUsage >= MAX_GENERATIONS) {
generateBtn.disabled = true;
limitMessage.classList.remove('hidden');
}
}
updateUsageUI();
emailForm.addEventListener('submit', async (e) => {
e.preventDefault();
const apiKey = apiKeyInput.value.trim();
if (!apiKey) {
alert('Please enter a Gemini API Key in configuration.');
apiSection.classList.remove('hidden');
return;
}
if (currentUsage >= MAX_GENERATIONS) return;
const name = document.getElementById('userName').value;
const service = document.getElementById('service').value;
const targetPerson = document.getElementById('targetPerson').value;
const targetCompany = document.getElementById('targetCompany').value;
const tone = document.querySelector('input[name="tone"]:checked').value;
// UI Feedback
statusSection.classList.remove('hidden');
resultsSection.classList.add('hidden');
generateBtn.disabled = true;
generateBtn.style.opacity = '0.7';
try {
const emails = await generateEmailsWithFallback(apiKey, name, service, targetPerson, targetCompany, tone);
displayResults(emails);
// Update credits
currentUsage++;
localStorage.setItem('emailGenUsage', currentUsage);
updateUsageUI();
} catch (error) {
console.error('Generation Error:', error);
alert('Error: ' + error.message);
} finally {
statusSection.classList.add('hidden');
generateBtn.disabled = currentUsage >= MAX_GENERATIONS;
generateBtn.style.opacity = '1';
}
});
resubmitBtn.addEventListener('click', () => {
window.scrollTo({ top: emailForm.offsetTop - 100, behavior: 'smooth' });
});
async function generateEmailsWithFallback(apiKey, name, service, targetPerson, targetCompany, tone) {
// Try v1beta first as it's more flexible for newer models
const endpoints = [
{ ver: 'v1beta', model: 'gemini-1.5-flash' },
{ ver: 'v1', model: 'gemini-1.5-flash' },
{ ver: 'v1beta', model: 'gemini-pro' }
];
let lastError = null;
for (const endpoint of endpoints) {
try {
return await callGeminiAPI(apiKey, endpoint.ver, endpoint.model, name, service, targetPerson, targetCompany, tone);
} catch (err) {
console.warn(`Failed with ${endpoint.model} on ${endpoint.ver}:`, err.message);
lastError = err;
continue; // Try next one
}
}
throw lastError || new Error("Failed to generate emails after multiple attempts.");
}
async function callGeminiAPI(apiKey, apiVer, modelName, name, service, targetPerson, targetCompany, tone) {
const prompt = `
System: You are an elite sales copywriter.
Task: Write 3 variations of a cold email.
Details:
- From: ${name}
- Service: ${service}
- To: ${targetPerson} at ${targetCompany}
- Tone: ${tone}
Structure:
1. Variation 1: Direct, ROI-focused.
2. Variation 2: Soft, building rapport.
3. Variation 3: Ultra-short (2-3 sentences).
Return ONLY a JSON array of 3 strings. Each string is the Subject + Body.
`;
const url = `https://generativelanguage.googleapis.com/${apiVer}/models/${modelName}:generateContent?key=${apiKey}`;
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: { response_mime_type: "application/json" }
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error?.message || "API Request Failed");
}
const data = await response.json();
const resultText = data.candidates[0].content.parts[0].text;
try {
// Handle cases where AI might wrap JSON in markdown
const cleanedText = resultText.replace(/```json|```/g, '').trim();
return JSON.parse(cleanedText);
} catch (e) {
// If parsing fails, try to extract array using regex
const match = resultText.match(/\[.*\]/s);
if (match) return JSON.parse(match[0]);
throw new Error("Invalid response format from AI");
}
}
function displayResults(emails) {
emailCards.innerHTML = '';
resultsSection.classList.remove('hidden');
const labels = ["The Disruptor", "The Connector", "The Minimalist"];
emails.forEach((email, index) => {
const card = document.createElement('div');
card.className = 'email-card';
card.style.animation = `fadeInUp 0.5s ease backwards ${index * 0.15}s`;
card.innerHTML = `
<span class="email-tag">${labels[index] || 'Variation ' + (index+1)}</span>
<div class="email-content">${email}</div>
<button class="copy-btn" onclick="copyToClipboard(this)">
<i class="ph-bold ph-copy"></i>
<span>Copy to Clipboard</span>
</button>
`;
emailCards.appendChild(card);
});
resultsSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
window.copyToClipboard = (btn) => {
const text = btn.previousElementSibling.innerText;
navigator.clipboard.writeText(text).then(() => {
const originalHtml = btn.innerHTML;
btn.innerHTML = '<i class="ph-bold ph-check"></i> <span>Copied!</span>';
btn.classList.add('copied');
setTimeout(() => {
btn.innerHTML = originalHtml;
btn.classList.remove('copied');
}, 2000);
});
};
// Animation addition
const style = document.createElement('style');
style.innerHTML = `
@keyframes fadeInUp {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
`;
document.head.appendChild(style);