File size: 28,649 Bytes
9447233
 
 
 
 
 
 
ecad45a
9447233
c01de65
9447233
 
 
 
c01de65
 
 
 
 
 
 
 
 
00cf1a8
c01de65
 
00cf1a8
c01de65
 
00cf1a8
c01de65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00cf1a8
c01de65
 
 
 
 
 
 
 
00cf1a8
c01de65
 
 
 
 
 
9447233
c01de65
 
ecad45a
c01de65
 
 
f9d1138
c01de65
 
 
 
 
 
00cf1a8
c01de65
 
 
 
 
 
 
 
 
 
00cf1a8
c01de65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00cf1a8
c01de65
 
 
 
 
 
 
 
 
 
 
 
9447233
c01de65
 
 
 
 
 
9447233
c01de65
 
 
 
 
 
 
 
 
9447233
c01de65
 
 
00cf1a8
c01de65
 
 
 
 
 
 
 
 
 
 
00cf1a8
c01de65
 
 
00cf1a8
c01de65
 
 
00cf1a8
c01de65
 
 
 
 
 
 
f9d1138
c01de65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00cf1a8
c01de65
f9d1138
c01de65
 
 
 
 
 
 
 
 
 
 
00cf1a8
c01de65
 
 
 
 
 
 
 
 
 
 
 
 
 
00cf1a8
c01de65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ca62f0
 
 
c01de65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27b3740
c01de65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00cf1a8
c01de65
 
 
 
00cf1a8
c01de65
00cf1a8
c01de65
 
 
 
00cf1a8
 
 
c01de65
 
 
 
 
00cf1a8
c01de65
 
 
 
 
 
 
 
 
 
 
 
00cf1a8
c01de65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00cf1a8
c01de65
 
 
 
00cf1a8
c01de65
 
 
 
 
 
 
 
 
 
 
9447233
c01de65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d70767c
c01de65
 
 
 
 
 
 
 
 
00cf1a8
c01de65
 
 
 
 
 
 
 
 
 
00cf1a8
c01de65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00cf1a8
 
c01de65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9447233
 
c01de65
 
 
 
9447233
c01de65
 
 
 
 
 
 
 
 
 
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
import streamlit as st
import pandas as pd
import sqlite3
import os
from datetime import datetime
import time

# Page config
st.set_page_config(
    page_title="Cold Email Assistant - Premium Demo",
    page_icon="πŸ“§",
    layout="wide"
)

# Import components
try:
    from scraper import scrape_company_info
    SCRAPER_AVAILABLE = True
except ImportError as e:
    print(f"⚠️ Scraper not available: {e}")
    SCRAPER_AVAILABLE = False
    def scrape_company_info(url_or_company):
        return "Company research feature requires additional setup. Please contact support for enterprise features."

from email_gen import generate_cold_email
from usage_tracker import UsageTracker

# Initialize usage tracker
tracker = UsageTracker()

# CSS for better styling
st.markdown("""
<style>
    .main-header {
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        padding: 2rem;
        border-radius: 10px;
        color: white;
        margin-bottom: 2rem;
    }
    .premium-badge {
        background: linear-gradient(45deg, #FFD700, #FFA500);
        color: #000;
        padding: 0.5rem 1rem;
        border-radius: 20px;
        font-weight: bold;
        font-size: 0.9rem;
    }
    .limit-warning {
        background: #fff3cd;
        border: 1px solid #ffeeba;
        border-radius: 5px;
        padding: 1rem;
        margin: 1rem 0;
    }
</style>
""", unsafe_allow_html=True)

# Header with premium badge and urgency
st.markdown("""
<div class="main-header">
    <h1>πŸš€ Cold Email Assistant - Premium Demo</h1>
    <p>✨ You're experiencing $97/month features for FREE β€’ Limited daily usage</p>
    <span class="premium-badge">πŸ”₯ ALL PREMIUM FEATURES UNLOCKED</span>
</div>
""", unsafe_allow_html=True)

# Add urgency banner
usage_percent = (tracker.get_emails_generated() / tracker.daily_email_limit) * 100
if usage_percent > 70:
    st.error(f"⚠️ **{100-usage_percent:.0f}% of daily quota remaining** - Upgrade now to avoid interruption!")
elif usage_percent > 40:
    st.warning(f"πŸ“Š **{100-usage_percent:.0f}% of daily quota remaining** - Consider upgrading for unlimited access")

# Show usage in sidebar
tracker.show_usage_sidebar()

# Sidebar with user info
st.sidebar.title("πŸ“‹ Navigation")
page = st.sidebar.selectbox("Choose a page", ["🎯 Generate Emails", "πŸ“Š Bulk Processing", "πŸ“ˆ Analytics Preview"])

# Sender Information
st.sidebar.markdown("---")
st.sidebar.subheader("πŸ‘€ Your Information")
sender_name = st.sidebar.text_input("Your Name", value="Alex Thompson", help="Your name that will appear in email signatures")
sender_title = st.sidebar.text_input("Your Title (Optional)", value="", placeholder="e.g., Sales Director", help="Your job title (optional)")
sender_company = st.sidebar.text_input("Your Company (Optional)", value="", placeholder="e.g., TechSolutions Inc.", help="Your company name (optional)")

# Create sender signature
if sender_title and sender_company:
    sender_signature = f"{sender_name}\n{sender_title}, {sender_company}"
elif sender_title:
    sender_signature = f"{sender_name}\n{sender_title}"
else:
    sender_signature = sender_name

if page == "🎯 Generate Emails":
    st.header("🎯 Premium Email Generation")
    
    # Check if user can generate emails
    if not tracker.can_generate_email():
        st.error("🚫 **Daily limit reached!** You've experienced the premium features.")
        
        col1, col2 = st.columns([2, 1])
        with col1:
            st.markdown("""
            ### 🎯 What you experienced today:
            - βœ… AI-powered email generation (normally $97/month)
            - βœ… Company research automation (saves 2+ hours/day)
            - βœ… Industry-specific templates (10x better conversion)
            - βœ… Premium quality scoring (proven to increase responses)
            """)
        
        with col2:
            st.markdown("""
            ### πŸ’° Your ROI Calculation:
            **Time saved:** 2 hours Γ— $50/hour = **$100/day**  
            **Responses gained:** +40% = **$500+ in deals**  
            **Tool cost:** Only $19 one-time  
            **ROI:** 2,500%+ πŸš€
            """)
        
        st.markdown("""
        <div style='background: linear-gradient(90deg, #FF6B6B, #4ECDC4); padding: 1.5rem; border-radius: 10px; text-align: center; color: white; margin: 1rem 0;'>
            <h3>πŸ”₯ Limited Time: $19 Lifetime Deal</h3>
            <p><strong>What others charge $97/month for - you get FOREVER for just $19</strong></p>
            <p>Join 500+ sales professionals already using this</p>
            <a href="https://gumroad.com/l/cold-email-assistant" style="background: white; color: #333; padding: 0.8rem 2rem; border-radius: 25px; text-decoration: none; font-weight: bold; margin-top: 1rem; display: inline-block;">πŸš€ Get Lifetime Access Now</a>
        </div>
        """, unsafe_allow_html=True)
        
        st.stop()
    
    col1, col2 = st.columns([2, 1])
    
    with col1:
        st.subheader("πŸ“ Lead Information")
        
        # Input fields
        name = st.text_input("πŸ‘€ Contact Name", 
                            placeholder="e.g., Sarah Johnson (Director of Sales)")
        email = st.text_input("πŸ“§ Email Address", 
                             placeholder="e.g., [email protected]")
        company = st.text_input("🏒 Company Name", 
                               placeholder="e.g., TechFlow Solutions (B2B SaaS, 50-200 employees)")
        linkedin_url = st.text_input("πŸ”— LinkedIn URL (Optional)", 
                                    placeholder="https://linkedin.com/company/techflow-solutions")
        
        # Company details with premium badge
        st.markdown("### πŸ’Ό Company Research **✨ PREMIUM**")
        company_details = st.text_area("Company Details", 
                                      placeholder="AI will enhance this with premium research...",
                                      height=100,
                                      help="πŸš€ Premium feature: Enhanced company research and personalization")
        
        # Premium tone options
        st.markdown("### 🎭 Email Tone **✨ PREMIUM**")
        tone_options = {
            "Professional": "Formal, executive-level",
            "Friendly": "Warm, relationship-building", 
            "Direct": "Straight to the point",
            "Consultative": "Expert advisor approach ✨",
            "Enthusiastic": "High-energy, excited ✨"
        }
        
        tone_labels = [f"{tone} - {desc}" for tone, desc in tone_options.items()]
        selected_tone = st.selectbox("Choose tone", tone_labels)
        tone = selected_tone.split(" - ")[0]
        
        # Premium industry templates
        st.markdown("### 🏭 Industry Intelligence **✨ PREMIUM**")
        industry_options = {
            "SaaS/Tech": "Software, AI, Digital platforms",
            "E-commerce": "Online retail, DTC brands", 
            "Manufacturing": "Industrial, Production",
            "Healthcare": "Medical, Pharma, Clinical",
            "Financial Services": "FinTech, Banking ✨",
            "Real Estate": "PropTech, Commercial ✨",
            "Generic B2B": "General business approach"
        }
        
        industry_labels = [f"{ind} - {desc}" for ind, desc in industry_options.items()]
        selected_industry = st.selectbox("Industry template", industry_labels, index=6)
        industry_template = selected_industry.split(" - ")[0]
        
        # Call to action
        cta_type = st.selectbox("πŸ“ž Call-to-Action Type",
                               ["Meeting/Call", "Demo", "Information", "Partnership", "Custom"])
        
        if cta_type == "Custom":
            custom_cta = st.text_input("✍️ Custom CTA", placeholder="e.g., Schedule a consultation")
        else:
            custom_cta = None
    
    with col2:
        st.subheader("🎯 Premium Actions")
        
        # LinkedIn scraping with limits
        scraper_button_text = "πŸ” Auto-Research Company" if SCRAPER_AVAILABLE else "πŸ” Auto-Research Company (Setup Required)"
        if st.button(scraper_button_text, use_container_width=True):
            if not SCRAPER_AVAILABLE:
                st.warning("πŸ”§ **Company research requires additional setup**")
                st.info("πŸ’‘ **Premium Feature Preview:** This would normally scrape LinkedIn/company websites for detailed information to personalize your emails.")
                st.markdown("**Value:** Manual research = 30 min Γ— $50/hr = $25. This tool = $0.06 per research!")
                st.success("✨ **Upgrade to get:** Automated LinkedIn scraping, company website analysis, and industry insights!")
            elif not tracker.can_scrape_linkedin():
                st.warning("🚫 **Research limit reached!** This premium feature saves 30+ minutes per lead.")
                st.markdown("**πŸ’‘ Upgrade for unlimited company research** - [Get it here β†’](https://gumroad.com/l/cold-email-assistant)")
            elif linkedin_url or company:
                with st.spinner("πŸ•’ Researching company (Premium feature)..."):
                    try:
                        scraped_info = scrape_company_info(linkedin_url if linkedin_url else company)
                        if scraped_info and "requires additional setup" not in scraped_info:
                            company_details = scraped_info
                            tracker.increment_linkedin_scrape()
                            tracker.add_premium_feature_used("LinkedIn Research")
                            st.success("βœ… Premium research completed! (Saved you 30+ minutes)")
                            st.text_area("πŸ“‹ Research Results", value=scraped_info, height=150, disabled=True)
                            
                            # Show value
                            st.info("πŸ’° **Value delivered:** Manual research = 30 min Γ— $50/hr = $25. This tool = $0.06 per research!")
                        else:
                            st.warning("⚠️ Could not research this company. Try manual details.")
                    except Exception as e:
                        st.error(f"❌ Research failed: {str(e)}")
            else:
                st.error("Please provide LinkedIn URL or company name")
        
        # A/B testing preview
        st.markdown("### πŸ“Š A/B Testing **✨ PREMIUM**")
        if st.button("πŸ§ͺ Generate A/B Variants", use_container_width=True):
            tracker.add_premium_feature_used("A/B Testing")
            st.success("✨ **A/B Testing unlocked!** Generate 3 different email variants:")
            
            variants = [
                "πŸ“§ **Variant A:** Direct approach - 'Quick question about [company]'",
                "πŸ“§ **Variant B:** Value-first - 'Helping [industry] companies save [pain point]'", 
                "πŸ“§ **Variant C:** Social proof - 'How [similar company] achieved [result]'"
            ]
            
            for variant in variants:
                st.info(variant)
            
            st.warning("🚫 **Full A/B testing with metrics requires upgrade** - Track which emails get 3x better responses!")
            st.caption("πŸ’° **Value:** A/B testing typically increases response rates by 40-60%")
        
        # Quality insights
        st.markdown("### πŸ“ˆ Quality Insights **✨ PREMIUM**") 
        st.info("🎯 **Premium Quality Scoring**\n\nβ€’ Personalization analysis\nβ€’ Industry benchmarking\nβ€’ Conversion predictors\nβ€’ Improvement suggestions")
        
        # Usage warning
        remaining = tracker.get_remaining_emails()
        if remaining <= 2:
            st.warning(f"⚠️ Only {remaining} emails left today!")
    
    # Generate email button
    if st.button("πŸš€ Generate Premium Email", use_container_width=True, type="primary"):
        if name and company:
            if not tracker.can_generate_email():
                tracker.show_upgrade_prompt("email generation")
            else:
                try:
                    with st.spinner("πŸ€– AI is crafting your premium personalized email..."):
                        # Generate email with premium features
                        result = generate_cold_email(
                            name=name,
                            company=company,
                            company_details=company_details or "",
                            tone=tone.lower(),
                            cta_type=cta_type.lower().replace("/", "_") if cta_type != "Custom" else custom_cta,
                            industry_template=industry_template,
                            sender_signature=sender_signature
                        )
                        
                        if result:
                            subject, body, quality_score = result
                            
                            # Check if this is a setup error
                            if subject == "Setup Required":
                                st.error("πŸ”§ **Premium AI Features Need Setup**")
                                st.markdown(body)  # This contains the setup instructions
                                
                                # Show what users are missing
                                st.info("πŸš€ **What you're missing without AI setup:**")
                                st.markdown("""
                                - πŸ€– **Advanced AI Personalization** (40% better conversion)
                                - 🎯 **Industry-Specific Intelligence** (10x more relevant)
                                - πŸ“Š **AI Quality Scoring** (proven metrics)
                                - πŸ” **Smart Company Analysis** (saves 30+ min research)
                                """)
                                
                                st.success("✨ **Good News:** All premium features work perfectly once set up!")
                                st.markdown("**πŸ’° Value Unlocked:** $97/month worth of AI features for just $19 lifetime")
                                
                                # Still show upgrade CTA
                                st.markdown("""
                                <div style='background: linear-gradient(90deg, #FF6B6B, #4ECDC4); padding: 1.5rem; border-radius: 10px; text-align: center; color: white; margin: 1rem 0;'>
                                    <h3>πŸ”₯ Skip Setup - Get Pre-Configured Version</h3>
                                    <p><strong>Get the fully-configured app with all AI features ready to use</strong></p>
                                    <a href="https://gumroad.com/l/cold-email-assistant" style="background: white; color: #333; padding: 0.8rem 2rem; border-radius: 25px; text-decoration: none; font-weight: bold; margin-top: 1rem; display: inline-block;">πŸš€ Get Lifetime Access Now</a>
                                </div>
                                """, unsafe_allow_html=True)
                                st.stop()
                            
                            # Track usage for successful generation
                            tracker.increment_email_generation()
                            tracker.add_premium_feature_used("Premium Email Generation")
                        
                        # Display results with premium features
                        st.success("βœ… Premium email generated successfully!")
                        
                        col_result1, col_result2 = st.columns([3, 1])
                        
                        with col_result1:
                            st.subheader("πŸ“§ Generated Premium Email")
                            
                            # Subject line
                            st.markdown("**πŸ“‹ Subject Line:**")
                            st.code(subject, language="text")
                            
                            # Email body
                            st.markdown("**βœ‰οΈ Email Body:**")
                            st.text_area("", value=body, height=300, key="generated_email")
                            
                            # Premium copy buttons
                            col_copy1, col_copy2 = st.columns(2)
                            with col_copy1:
                                if st.button("πŸ“‹ Copy Subject", use_container_width=True):
                                    st.code(f"Subject copied: {subject}")
                            with col_copy2:
                                if st.button("πŸ“‹ Copy Email Body", use_container_width=True):
                                    st.code("Email body copied to clipboard!")
                        
                        with col_result2:
                            st.markdown("### πŸ“Š Premium Quality Score")
                            score_color = "🟒" if quality_score >= 8 else "🟑" if quality_score >= 6 else "πŸ”΄"
                            st.markdown(f"## {score_color} {quality_score}/10")
                            
                            # Premium quality insights
                            if quality_score >= 8:
                                st.success("πŸš€ Premium Quality!")
                                st.caption("βœ… AI-optimized personalization\nβœ… Industry-specific messaging\nβœ… Conversion-tested format")
                            elif quality_score >= 6:
                                st.warning("πŸ“ˆ Good Quality")
                                st.caption("βœ… Decent personalization\n⚠️ Could be more specific")
                            else:
                                st.error("⚑ Needs Premium Boost")
                                st.caption("πŸ’‘ Try premium research features")
                            
                            st.markdown("### 🎯 Premium Features Used")
                            features_used = tracker.get_premium_features_used()
                            for feature in features_used:
                                st.caption(f"✨ {feature}")
                            
                            # Remaining usage
                            remaining_after = tracker.get_remaining_emails()
                            if remaining_after > 0:
                                st.info(f"πŸ“§ {remaining_after} emails left today")
                            else:
                                st.error("πŸ“§ Daily limit reached!")
                                st.markdown("**[πŸš€ Get Unlimited β†’](https://gumroad.com/l/cold-email-assistant)**")
                
                except Exception as e:
                    st.error(f"❌ Error generating email: {str(e)}")
        else:
            st.error("❌ Please fill in at least Name and Company fields")

elif page == "πŸ“Š Bulk Processing":
    st.header("πŸ“Š Premium Bulk Processing")
    
    # Check bulk export limit
    if not tracker.can_bulk_export():
        tracker.show_upgrade_prompt("bulk processing")
        st.stop()
    
    st.info("πŸš€ **Premium Bulk Processing** - Process up to 10 leads in demo mode")
    
    # File upload
    uploaded_file = st.file_uploader("πŸ“ Upload CSV file", type=['csv'])
    
    if uploaded_file:
        try:
            df = pd.read_csv(uploaded_file)
            
            # Limit to 10 rows in demo
            if len(df) > 10:
                st.warning(f"⚠️ Demo limited to 10 leads. Uploaded {len(df)} leads.")
                df = df.head(10)
                st.info("πŸš€ Upgrade for unlimited bulk processing!")
            
            st.success(f"βœ… File uploaded! Processing {len(df)} leads in demo mode.")
            
            # Show preview
            st.subheader("πŸ‘€ Data Preview")
            st.dataframe(df.head())
            
            # Processing options
            col1, col2 = st.columns(2)
            
            with col1:
                tone = st.selectbox("🎭 Email Tone for All", 
                                   ["Professional", "Friendly", "Direct", "Consultative ✨"])
                
                industry_template = st.selectbox("🏭 Industry Template", 
                                               ["SaaS/Tech", "E-commerce", "Healthcare", "Generic B2B"],
                                               index=3)
            
            with col2:
                st.markdown("**✨ Premium Features:**")
                st.caption("β€’ AI-powered personalization")
                st.caption("β€’ Industry-specific templates") 
                st.caption("β€’ Quality scoring")
                st.caption("β€’ Bulk export")
            
            # Process button
            if st.button("πŸš€ Process All Leads (Premium Demo)", use_container_width=True, type="primary"):
                progress_bar = st.progress(0)
                status_text = st.empty()
                
                results = []
                
                for idx, row in df.iterrows():
                    status_text.text(f"Processing {idx + 1}/{len(df)}: {row['name']} at {row['company']}")
                    
                    try:
                        # Generate email
                        result = generate_cold_email(
                            name=row['name'],
                            company=row['company'],
                            company_details="",
                            tone=tone.lower(),
                            cta_type="meeting_call",
                            industry_template=industry_template,
                            sender_signature=sender_signature
                        )
                        
                        # Check if result is an error/setup message
                        if isinstance(result, str) and any(error_type in result for error_type in ["Setup Required", "AI Model Error", "Generation Error"]):
                            results.append({
                                'name': row['name'],
                                'company': row['company'],
                                'email': row.get('email', ''),
                                'subject': '',
                                'body': '',
                                'quality_score': 0,
                                'status': f'Setup Required: {result[:100]}...'
                            })
                        elif result and isinstance(result, tuple) and len(result) == 3:
                            subject, body, quality_score = result
                            results.append({
                                'name': row['name'],
                                'company': row['company'],
                                'email': row.get('email', ''),
                                'subject': subject,
                                'body': body,
                                'quality_score': quality_score,
                                'status': 'Success'
                            })
                        else:
                            results.append({
                                'name': row['name'],
                                'company': row['company'],
                                'email': row.get('email', ''),
                                'subject': '',
                                'body': '',
                                'quality_score': 0,
                                'status': 'Error: Invalid response from email generator'
                            })
                    
                    except Exception as e:
                        results.append({
                            'name': row['name'],
                            'company': row['company'],
                            'email': row.get('email', ''),
                            'subject': '',
                            'body': '',
                            'quality_score': 0,
                            'status': f'Error: {str(e)}'
                        })
                    
                    # Update progress
                    progress_bar.progress((idx + 1) / len(df))
                    time.sleep(0.5)
                
                # Track usage
                tracker.increment_bulk_export()
                tracker.add_premium_feature_used("Bulk Processing")
                
                # Show results
                status_text.text("βœ… Premium processing complete!")
                results_df = pd.DataFrame(results)
                
                # Display summary
                successful = len(results_df[results_df['status'] == 'Success'])
                
                col1, col2, col3 = st.columns(3)
                with col1:
                    st.metric("πŸ“§ Processed", len(results_df))
                with col2:
                    st.metric("βœ… Successful", successful)
                with col3:
                    avg_quality = results_df['quality_score'].mean()
                    st.metric("⭐ Avg Quality", f"{avg_quality:.1f}/10")
                
                # Show results table
                st.subheader("πŸ“Š Results")
                st.dataframe(results_df)
                
                # Download option
                csv = results_df.to_csv(index=False)
                st.download_button(
                    "πŸ“₯ Download Results (Premium)",
                    csv,
                    f"premium_emails_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
                    "text/csv",
                    use_container_width=True
                )
                
                st.success("✨ Premium bulk processing complete! Upgrade for unlimited processing.")
        
        except Exception as e:
            st.error(f"❌ Error processing file: {str(e)}")

elif page == "πŸ“ˆ Analytics Preview":
    st.header("πŸ“ˆ Premium Analytics Preview")
    
    st.info("πŸš€ **Premium Analytics Dashboard** - Get insights on your email performance")
    
    # Mock analytics data
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric("πŸ“§ Total Emails", "127", "+23 this week")
    with col2:
        st.metric("πŸ“ˆ Avg Quality", "8.3/10", "+0.5 improvement")
    with col3:
        st.metric("🏒 Companies", "45", "+12 this week")
    with col4:
        st.metric("⭐ Top Score", "9.2/10", "Healthcare emails")
    
    # Charts preview
    st.subheader("πŸ“Š Performance Insights")
    
    col1, col2 = st.columns(2)
    
    with col1:
        st.markdown("**πŸ“ˆ Quality Trends**")
        st.line_chart(pd.DataFrame({
            'Day': range(7),
            'Quality Score': [7.2, 7.8, 8.1, 8.3, 8.5, 8.2, 8.7]
        }).set_index('Day'))
    
    with col2:
        st.markdown("**🏭 Industry Performance**")
        st.bar_chart(pd.DataFrame({
            'SaaS': [8.5],
            'Healthcare': [9.2],
            'Manufacturing': [7.8],
            'E-commerce': [8.1]
        }))
    
    # Premium features preview
    st.subheader("✨ Premium Analytics Features")
    
    features = [
        "πŸ“Š Conversion tracking integration",
        "πŸ“ˆ A/B testing results dashboard", 
        "🎯 Industry benchmarking",
        "πŸ“§ Email performance heatmaps",
        "πŸ” Competitor analysis",
        "πŸ“± Mobile-optimized reports",
        "πŸ”” Performance alerts",
        "πŸ“Š Export to PowerBI/Tableau"
    ]
    
    for i, feature in enumerate(features):
        if i % 2 == 0:
            col1, col2 = st.columns(2)
        
        with col1 if i % 2 == 0 else col2:
            st.info(feature)
    
    st.markdown("---")
    st.success("πŸš€ **Ready to unlock full analytics?** Get unlimited access + advanced reporting!")
    
    if st.button("πŸš€ Upgrade to Premium Analytics", use_container_width=True, type="primary"):
        st.markdown("**[πŸ”— Get Cold Email Assistant Pro β†’](https://gumroad.com/l/cold-email-assistant)**")

# Footer with upgrade CTA
st.markdown("---")
st.markdown("""
<div style='text-align: center; padding: 2rem; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); border-radius: 10px; color: white; margin-top: 2rem;'>
    <h3>πŸš€ Ready for Unlimited Access?</h3>
    <p>You've experienced the premium features - now get unlimited access!</p>
    <p><strong>βœ… Unlimited emails βœ… Unlimited research βœ… Advanced analytics βœ… Priority support</strong></p>
    <p><a href="https://gumroad.com/l/cold-email-assistant" style="color: #FFD700; font-weight: bold; text-decoration: none;">Get Lifetime Access for $19 β†’</a></p>
</div>
""", unsafe_allow_html=True)