File size: 32,891 Bytes
f61cbc4
3cc12ad
 
 
 
 
 
 
f61cbc4
3cc12ad
 
 
 
 
 
 
 
 
 
 
 
 
 
9b1584b
3cc12ad
 
 
9b1584b
 
 
3cc12ad
 
 
 
 
9b1584b
 
 
3cc12ad
 
 
 
 
9b1584b
3cc12ad
9b1584b
 
 
3cc12ad
9b1584b
3cc12ad
 
 
9b1584b
3cc12ad
9b1584b
 
3cc12ad
 
 
 
9b1584b
3cc12ad
9b1584b
 
3cc12ad
 
 
 
9b1584b
3cc12ad
9b1584b
 
3cc12ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39f9752
3cc12ad
39f9752
3cc12ad
39f9752
3cc12ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10cd828
9b1584b
 
10cd828
 
3cc12ad
9b1584b
3cc12ad
 
9b1584b
 
 
 
3cc12ad
 
 
 
9b1584b
3cc12ad
9b1584b
3cc12ad
9b1584b
10cd828
 
3cc12ad
9b1584b
 
 
 
3cc12ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b1584b
3cc12ad
9b1584b
 
 
 
3cc12ad
 
9b1584b
3cc12ad
 
 
9b1584b
 
3cc12ad
 
 
 
 
 
 
 
 
 
 
9b1584b
3cc12ad
 
 
 
 
 
 
 
 
 
9b1584b
3cc12ad
 
 
 
 
9b1584b
3cc12ad
 
9b1584b
3cc12ad
 
 
 
 
9b1584b
 
3cc12ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
import streamlit as st
import requests
import json
import time
import os
from dotenv import load_dotenv
import openai
from typing import List, Dict, Any

# Load environment variables
load_dotenv()

# Set OpenAI API key
openai.api_key = os.getenv('OPENAI_API_KEY')

# Configure page
st.set_page_config(
    page_title="SEO Content Writer",
    page_icon="✨",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Simple CSS styling
st.markdown("""
<style>
    .metric-card {
        background: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 5px;
        padding: 1rem;
        margin: 0.5rem 0;
    }
    
    .success-card {
        background: #f8f9fa;
        border: 1px solid #28a745;
        border-radius: 5px;
        padding: 1rem;
        margin: 0.5rem 0;
    }
    
    .keyword-chip {
        background: #333;
        color: white;
        padding: 0.25rem 0.5rem;
        border-radius: 15px;
        font-size: 0.875rem;
        display: inline-block;
        margin: 0.25rem;
    }
    
    .seo-score-excellent {
        background: #333;
        color: white;
        padding: 0.5rem;
        border-radius: 5px;
        text-align: center;
    }
    
    .seo-score-good {
        background: #666;
        color: white;
        padding: 0.5rem;
        border-radius: 5px;
        text-align: center;
    }
    
    .seo-score-poor {
        background: #999;
        color: white;
        padding: 0.5rem;
        border-radius: 5px;
        text-align: center;
    }
</style>
""", unsafe_allow_html=True)

class SEOContentWriter:
    def __init__(self):
        self.openai_client = openai
        
    def generate_keywords(self, seed_keyword: str) -> List[str]:
        """Generate related keywords using OpenAI"""
        try:
            response = self.openai_client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": "You are an SEO expert. Generate related keywords for content optimization."},
                    {"role": "user", "content": f"Generate 8 related keywords for '{seed_keyword}' that would be useful for SEO content creation. Return only the keywords, one per line, without numbers or bullet points."}
                ],
                max_tokens=200,
                temperature=0.7
            )
            
            keywords = [line.strip() for line in response.choices[0].message.content.strip().split('\n') if line.strip()]
            return keywords[:8]
        except Exception as e:
            st.error(f"Error generating keywords: {str(e)}")
            return []
    
    def generate_titles(self, keyword: str, tone: str = "professional") -> List[str]:
        """Generate SEO-optimized titles"""
        try:
            response = self.openai_client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": f"You are an SEO expert. Generate compelling, SEO-optimized titles with a {tone} tone."},
                    {"role": "user", "content": f"Generate 6 SEO-optimized titles for the keyword '{keyword}'. Each title should be 30-60 characters, include the keyword naturally, and have a {tone} tone. Return only the titles, one per line."}
                ],
                max_tokens=300,
                temperature=0.8
            )
            
            titles = [line.strip() for line in response.choices[0].message.content.strip().split('\n') if line.strip()]
            return titles[:6]
        except Exception as e:
            st.error(f"Error generating titles: {str(e)}")
            return []
    
    def generate_topics(self, title: str, keyword: str) -> List[Dict[str, Any]]:
        """Generate topic outlines"""
        try:
            response = self.openai_client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": "You are a content strategist. Create detailed topic outlines for articles."},
                    {"role": "user", "content": f"Create 3 different topic outlines for an article with title '{title}' targeting keyword '{keyword}'. Each outline should have 4-6 main sections with brief descriptions. Format as JSON with structure: [{{\"title\": \"outline_name\", \"sections\": [{{\"heading\": \"section_title\", \"description\": \"brief_desc\"}}]}}]"}
                ],
                max_tokens=800,
                temperature=0.7
            )
            
            try:
                topics = json.loads(response.choices[0].message.content.strip())
                return topics
            except json.JSONDecodeError:
                # Fallback if JSON parsing fails
                return [{"title": "Standard Article Outline", "sections": [
                    {"heading": "Introduction", "description": "Overview of the topic"},
                    {"heading": "Main Content", "description": "Core information"},
                    {"heading": "Benefits/Examples", "description": "Practical applications"},
                    {"heading": "Conclusion", "description": "Summary and takeaways"}
                ]}]
        except Exception as e:
            st.error(f"Error generating topics: {str(e)}")
            return []
    
    def generate_content(self, title: str, keyword: str, outline: Dict[str, Any], content_type: str = "blog_intro", word_count: int = 150) -> str:
        """Generate SEO-optimized content"""
        try:
            outline_text = "\n".join([f"- {section['heading']}: {section['description']}" for section in outline.get('sections', [])])
            
            response = self.openai_client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": f"You are an expert content writer specializing in SEO-optimized {content_type} content."},
                    {"role": "user", "content": f"""Write SEO-optimized content for:
Title: {title}
Target Keyword: {keyword}
Content Type: {content_type}
Word Count: ~{word_count} words
Outline: {outline_text}

Requirements:
- Natural keyword integration (1-3% density)
- Engaging and informative
- Proper formatting with headers if needed
- High readability
- SEO best practices"""}
                ],
                max_tokens=word_count * 2,
                temperature=0.7
            )
            
            return response.choices[0].message.content.strip()
        except Exception as e:
            st.error(f"Error generating content: {str(e)}")
            return ""
    
    def analyze_seo(self, content: str, title: str, keyword: str) -> Dict[str, Any]:
        """Analyze SEO score of content"""
        if not all([content, title, keyword]):
            return {}
        
        # Calculate metrics
        word_count = len(content.split())
        keyword_count = content.lower().count(keyword.lower())
        keyword_density = (keyword_count / word_count * 100) if word_count > 0 else 0
        
        title_length = len(title)
        keyword_in_title = keyword.lower() in title.lower()
        
        sentences = content.split('.')
        avg_sentence_length = sum(len(s.split()) for s in sentences) / len(sentences) if sentences else 0
        
        # Calculate scores (0-100)
        keyword_density_score = min(100, max(0, 100 - abs(keyword_density - 2) * 20))  # Optimal: 2%
        title_length_score = min(100, max(0, 100 - abs(title_length - 45) * 2))  # Optimal: 45 chars
        keyword_in_title_score = 100 if keyword_in_title else 0
        content_length_score = min(100, word_count / 3)  # Optimal: 300+ words
        readability_score = min(100, max(0, 100 - abs(avg_sentence_length - 17) * 3))  # Optimal: 17 words/sentence
        
        # Calculate overall score with weights
        overall_score = (
            keyword_density_score * 0.3 +
            title_length_score * 0.25 +
            keyword_in_title_score * 0.2 +
            content_length_score * 0.15 +
            readability_score * 0.1
        )
        
        # Generate recommendations
        recommendations = []
        if keyword_density < 1:
            recommendations.append("Increase keyword density (aim for 1-3%)")
        elif keyword_density > 3:
            recommendations.append("Reduce keyword density to avoid over-optimization")
        
        if title_length < 30:
            recommendations.append("Consider making your title longer (30-60 characters)")
        elif title_length > 60:
            recommendations.append("Consider shortening your title (30-60 characters)")
        
        if not keyword_in_title:
            recommendations.append("Include your target keyword in the title")
        
        if word_count < 150:
            recommendations.append("Add more content (aim for 300+ words)")
        
        if avg_sentence_length > 25:
            recommendations.append("Use shorter sentences for better readability")
        
        return {
            "overall_score": round(overall_score),
            "scores": {
                "keyword_density": {"score": round(keyword_density_score), "value": f"{keyword_density:.1f}%"},
                "title_length": {"score": round(title_length_score), "value": f"{title_length} chars"},
                "keyword_in_title": {"score": round(keyword_in_title_score), "value": "Yes" if keyword_in_title else "No"},
                "content_length": {"score": round(content_length_score), "value": f"{word_count} words"},
                "readability": {"score": round(readability_score), "value": f"{avg_sentence_length:.1f} words/sentence"}
            },
            "recommendations": recommendations[:3]  # Limit to top 3
        }

def get_score_color_class(score: int) -> str:
    """Get CSS class based on score"""
    if score >= 80:
        return "seo-score-excellent"
    elif score >= 60:
        return "seo-score-good"
    else:
        return "seo-score-poor"

def get_score_emoji(score: int) -> str:
    """Get emoji based on score"""
    if score >= 80:
        return "⚫"  # Black circle for excellent
    elif score >= 60:
        return "βšͺ"  # White circle for good
    else:
        return "β—―"   # Empty circle for poor

def main():
    # Initialize the SEO Content Writer
    if 'seo_writer' not in st.session_state:
        st.session_state.seo_writer = SEOContentWriter()
    
    # Initialize session state
    if 'current_step' not in st.session_state:
        st.session_state.current_step = 0
    if 'seed_keyword' not in st.session_state:
        st.session_state.seed_keyword = ""
    if 'keywords' not in st.session_state:
        st.session_state.keywords = []
    if 'selected_keyword' not in st.session_state:
        st.session_state.selected_keyword = ""
    if 'titles' not in st.session_state:
        st.session_state.titles = []
    if 'selected_title' not in st.session_state:
        st.session_state.selected_title = ""
    if 'topics' not in st.session_state:
        st.session_state.topics = []
    if 'selected_topic' not in st.session_state:
        st.session_state.selected_topic = None
    if 'generated_content' not in st.session_state:
        st.session_state.generated_content = ""
    if 'seo_analysis' not in st.session_state:
        st.session_state.seo_analysis = {}    # Header
    st.title("SEO Content Writer")
    st.write("AI-powered content creation with real-time SEO optimization")
    
    # Sidebar with workflow progress
    with st.sidebar:
        st.subheader("Workflow Progress")
        
        steps = [
            "Keyword Research",
            "Title Generation", 
            "Topic Selection",
            "Content Creation"
        ]
        
        for i, step in enumerate(steps):
            if i < st.session_state.current_step:
                st.write(f"βœ“ {step}")
            elif i == st.session_state.current_step:
                st.write(f"β†’ **{step}**")
            else:
                st.write(f"β—‹ {step}")
        
        progress = (st.session_state.current_step + 1) / len(steps)
        st.progress(progress)
        st.write(f"**{int(progress * 100)}% Complete**")
        
        # Reset workflow button
        if st.button("Start New Project"):
            for key in ['current_step', 'seed_keyword', 'keywords', 'selected_keyword', 
                       'titles', 'selected_title', 'topics', 'selected_topic', 
                       'generated_content', 'seo_analysis']:
                if key in st.session_state:
                    if key == 'current_step':
                        st.session_state[key] = 0
                    elif key in ['keywords', 'titles', 'topics']:
                        st.session_state[key] = []
                    elif key == 'selected_topic':
                        st.session_state[key] = None
                    elif key == 'seo_analysis':
                        st.session_state[key] = {}
                    else:
                        st.session_state[key] = ""
            st.rerun()
        
        # Project info
        st.markdown("---")
        st.write("**Project Info**")
        st.write("[Full Project Repository](https://github.com/akshayram1/AI_Content_Writer_Prototype)")
        st.caption("Originally attempted deployment on Vercel and Railway, but free tier limitations prevented deploying the full LLM service stack.")
        st.caption("Built with Streamlit and OpenAI")
    
    # Main content area with tabs
    tab1, tab2, tab3, tab4, tab5 = st.tabs(["Keywords", "Titles", "Topics", "Content", "SEO Test"])
    
    # Tab 1: Keyword Research
    with tab1:
        st.subheader("Keyword Research")
        st.write("Discover high-impact keywords to boost your content's SEO potential")
        
        col1, col2 = st.columns([2, 1])
        
        with col1:
            seed_keyword = st.text_input(
                "Enter your seed keyword", 
                value=st.session_state.seed_keyword,
                placeholder="e.g., digital marketing, web development, content strategy"
            )
            
        with col2:
            research_button = st.button("Research Keywords", type="primary")
        
        if research_button and seed_keyword:
            with st.spinner("Analyzing your keyword and finding related suggestions..."):
                keywords = st.session_state.seo_writer.generate_keywords(seed_keyword)
                if keywords:
                    st.session_state.keywords = keywords
                    st.session_state.seed_keyword = seed_keyword
                    st.session_state.current_step = max(st.session_state.current_step, 1)
        
        if st.session_state.keywords:
            st.write("**Suggested Keywords**")
            st.markdown(f'<div class="keyword-chip">Based on: "{st.session_state.seed_keyword}"</div>', unsafe_allow_html=True)
            
            cols = st.columns(2)
            for i, keyword in enumerate(st.session_state.keywords):
                with cols[i % 2]:
                    if st.button(f"{keyword}", key=f"keyword_{i}", use_container_width=True):
                        st.session_state.selected_keyword = keyword
                        st.session_state.current_step = max(st.session_state.current_step, 1)
                        st.success(f"Selected keyword: **{keyword}**")
                        time.sleep(1)
                        st.rerun()
            
            if st.session_state.selected_keyword:
                st.markdown('<div class="success-card">', unsafe_allow_html=True)
                st.write(f"**Great choice!** Keyword selected: **{st.session_state.selected_keyword}**")
                st.write("Ready to generate titles! The workflow will continue automatically.")
                st.markdown('</div>', unsafe_allow_html=True)
    
    # Tab 2: Title Generation
    with tab2:
        st.markdown("## πŸ“ Title Generation")
        st.markdown("Generate SEO-optimized titles for your selected keyword")
        
        if not st.session_state.selected_keyword:
            st.warning("⚠️ Please select a keyword first in the Keywords tab.")
        else:
            st.markdown('<div class="metric-card">', unsafe_allow_html=True)
            st.markdown(f"**Selected Keyword:** {st.session_state.selected_keyword}")
            st.markdown('</div>', unsafe_allow_html=True)
            
            col1, col2, col3 = st.columns([2, 1, 1])
            
            with col1:
                tone = st.selectbox("Select tone", ["professional", "casual", "authoritative", "friendly", "technical"])
            
            with col2:
                generate_titles_button = st.button("πŸ“ Generate Titles", type="primary")
            
            with col3:
                if st.button("πŸ”™ Change Keyword"):
                    st.session_state.current_step = 0
                    st.rerun()
            
            if generate_titles_button:
                with st.spinner("Creating SEO-optimized titles for your keyword..."):
                    titles = st.session_state.seo_writer.generate_titles(st.session_state.selected_keyword, tone)
                    if titles:
                        st.session_state.titles = titles
                        st.session_state.current_step = max(st.session_state.current_step, 2)
            
            if st.session_state.titles:
                st.markdown("### 🏷️ Generated Titles")
                for i, title in enumerate(st.session_state.titles):
                    col1, col2 = st.columns([4, 1])
                    with col1:
                        st.markdown(f"**{title}**")
                        st.caption(f"{len(title)} characters")
                    with col2:
                        if st.button("Select", key=f"title_{i}"):
                            st.session_state.selected_title = title
                            st.session_state.current_step = max(st.session_state.current_step, 2)
                            st.success(f"βœ… Selected title: **{title}**")
                            time.sleep(1)
                            st.rerun()
                
                if st.session_state.selected_title:
                    st.markdown('<div class="success-card">', unsafe_allow_html=True)
                    st.markdown(f"βœ… **Selected title:** {st.session_state.selected_title}")
                    st.markdown("Ready to generate topic outline! The workflow will continue automatically.")
                    st.markdown('</div>', unsafe_allow_html=True)
    
    # Tab 3: Topic Selection
    with tab3:
        st.markdown("## πŸ“‹ Topic Selection & Outline")
        st.markdown("Choose a content structure and outline for your article")
        
        if not st.session_state.selected_title:
            st.warning("⚠️ Please select a title first in the Titles tab.")
        else:
            st.markdown('<div class="metric-card">', unsafe_allow_html=True)
            st.markdown(f"**Keyword:** {st.session_state.selected_keyword}")
            st.markdown(f"**Title:** {st.session_state.selected_title}")
            st.markdown('</div>', unsafe_allow_html=True)
            
            col1, col2 = st.columns([1, 1])
            
            with col1:
                generate_topics_button = st.button("πŸ“‹ Generate Topic Outlines", type="primary")
            
            with col2:
                if st.button("πŸ”™ Change Title"):
                    st.session_state.current_step = 1
                    st.rerun()
            
            if generate_topics_button:
                with st.spinner("Creating topic outlines and content structure..."):
                    topics = st.session_state.seo_writer.generate_topics(st.session_state.selected_title, st.session_state.selected_keyword)
                    if topics:
                        st.session_state.topics = topics
                        st.session_state.current_step = max(st.session_state.current_step, 3)
            
            if st.session_state.topics:
                st.markdown("### πŸ“„ Content Outlines")
                for i, topic in enumerate(st.session_state.topics):
                    with st.expander(f"πŸ“ {topic.get('title', f'Outline {i+1}')}"):
                        if 'sections' in topic:
                            for section in topic['sections']:
                                st.markdown(f"**{section.get('heading', 'Section')}**")
                                st.markdown(f"*{section.get('description', 'Description not available')}*")
                                st.markdown("---")
                        
                        if st.button(f"Select This Outline", key=f"topic_{i}"):
                            st.session_state.selected_topic = topic
                            st.session_state.current_step = max(st.session_state.current_step, 3)
                            st.success("βœ… Topic outline selected! Ready to generate your content.")
                            time.sleep(1)
                            st.rerun()
                
                if st.session_state.selected_topic:
                    st.markdown('<div class="success-card">', unsafe_allow_html=True)
                    st.markdown("βœ… **Topic outline selected!** Ready to generate your content.")
                    st.markdown('</div>', unsafe_allow_html=True)
    
    # Tab 4: Content Creation
    with tab4:
        st.markdown("## ✍️ Content Creation")
        st.markdown("Generate your final SEO-optimized content based on your selections")
        
        if not st.session_state.selected_topic:
            st.warning("⚠️ Please select a topic outline first in the Topics tab.")
        else:
            st.markdown('<div class="metric-card">', unsafe_allow_html=True)
            st.markdown(f"**Keyword:** {st.session_state.selected_keyword}")
            st.markdown(f"**Title:** {st.session_state.selected_title}")
            st.markdown("**Outline:** Selected")
            st.markdown('</div>', unsafe_allow_html=True)
            
            col1, col2, col3, col4 = st.columns([2, 1, 1, 1])
            
            with col1:
                content_type = st.selectbox("Content Type", [
                    "blog_intro", "meta_description", "product_description", 
                    "landing_page", "social_media"
                ])
            
            with col2:
                word_count = st.selectbox("Word Count", [100, 150, 200, 300, 500])
            
            with col3:
                generate_content_button = st.button("✍️ Generate Content", type="primary")
            
            with col4:
                if st.button("πŸ”™ Change Outline"):
                    st.session_state.current_step = 2
                    st.rerun()
            
            if generate_content_button:
                with st.spinner("Creating your SEO-optimized content..."):
                    content = st.session_state.seo_writer.generate_content(
                        st.session_state.selected_title,
                        st.session_state.selected_keyword,
                        st.session_state.selected_topic,
                        content_type,
                        word_count
                    )
                    if content:
                        st.session_state.generated_content = content
                        # Analyze SEO
                        seo_analysis = st.session_state.seo_writer.analyze_seo(
                            content, st.session_state.selected_title, st.session_state.selected_keyword
                        )
                        st.session_state.seo_analysis = seo_analysis
            
            if st.session_state.generated_content:
                st.markdown("### πŸ“„ Generated Content")
                
                # Display content in a nice box
                st.markdown('<div class="metric-card">', unsafe_allow_html=True)
                st.markdown(st.session_state.generated_content)
                st.markdown('</div>', unsafe_allow_html=True)
                
                # SEO Analysis
                if st.session_state.seo_analysis:
                    seo = st.session_state.seo_analysis
                    overall_score = seo.get('overall_score', 0)
                    
                    st.markdown("### πŸ“Š SEO Analysis")
                    
                    score_class = get_score_color_class(overall_score)
                    score_emoji = get_score_emoji(overall_score)
                    
                    st.markdown(f'<div class="{score_class}">', unsafe_allow_html=True)
                    st.markdown(f"## {score_emoji} Overall SEO Score: {overall_score}/100")
                    st.markdown('</div>', unsafe_allow_html=True)
                    
                    # Detailed metrics
                    st.markdown("#### πŸ“‹ Detailed Metrics")
                    
                    metrics_cols = st.columns(2)
                    scores = seo.get('scores', {})
                    
                    metric_names = {
                        'keyword_density': '🎯 Keyword Density',
                        'title_length': 'πŸ“ Title Length',
                        'keyword_in_title': '🏷️ Keyword in Title',
                        'content_length': 'πŸ“ Content Length',
                        'readability': 'πŸ“– Readability'
                    }
                    
                    for i, (metric, data) in enumerate(scores.items()):
                        with metrics_cols[i % 2]:
                            score = data.get('score', 0)
                            value = data.get('value', 'N/A')
                            emoji = get_score_emoji(score)
                            
                            st.markdown(f"**{metric_names.get(metric, metric)}**")
                            st.markdown(f"{emoji} {score}/100 - {value}")
                    
                    # Recommendations
                    recommendations = seo.get('recommendations', [])
                    if recommendations:
                        st.markdown("#### πŸ’‘ Recommendations")
                        for rec in recommendations:
                            st.markdown(f"β€’ {rec}")
                
                # Export options
                st.markdown("### πŸ“€ Export Options")
                col1, col2, col3 = st.columns(3)
                
                with col1:
                    if st.button("πŸ“‹ Copy to Clipboard"):
                        st.code(st.session_state.generated_content, language=None)
                        st.success("βœ… Content ready to copy!")
                
                with col2:
                    st.download_button(
                        label="πŸ’Ύ Download as Text",
                        data=st.session_state.generated_content,
                        file_name=f"seo-content-{int(time.time())}.txt",
                        mime="text/plain"
                    )
                
                with col3:
                    if st.button("πŸ”„ Start New Project"):
                        # Reset everything
                        for key in ['current_step', 'seed_keyword', 'keywords', 'selected_keyword', 
                                   'titles', 'selected_title', 'topics', 'selected_topic', 
                                   'generated_content', 'seo_analysis']:
                            if key in st.session_state:
                                if key == 'current_step':
                                    st.session_state[key] = 0
                                elif key in ['keywords', 'titles', 'topics']:
                                    st.session_state[key] = []
                                elif key == 'selected_topic':
                                    st.session_state[key] = None
                                elif key == 'seo_analysis':
                                    st.session_state[key] = {}
                                else:
                                    st.session_state[key] = ""
                        st.rerun()
    
    # Tab 5: SEO Test Page
    with tab5:
        st.markdown("## πŸ§ͺ SEO Scoring Test Page")
        st.markdown("Test the real-time SEO scoring feature with your own content")
        
        col1, col2 = st.columns([1, 1])
        
        with col1:
            st.markdown("### Content Input")
            
            if st.button("πŸ“ Load Demo Content"):
                st.session_state.test_keyword = "digital marketing"
                st.session_state.test_title = "The Complete Guide to Digital Marketing in 2024"
                st.session_state.test_content = """Digital marketing has become an essential component of modern business strategy. In today's competitive landscape, digital marketing techniques help businesses reach their target audience effectively.

This comprehensive guide covers all aspects of digital marketing, from social media marketing to search engine optimization. Digital marketing strategies have evolved significantly, and businesses must adapt to stay competitive.

Whether you're new to digital marketing or looking to enhance your existing digital marketing skills, this guide provides valuable insights. We'll explore various digital marketing channels and how they can boost your business growth."""
                st.rerun()
            
            test_keyword = st.text_input(
                "Keyword", 
                value=st.session_state.get('test_keyword', ''),
                placeholder="e.g., digital marketing"
            )
            
            test_title = st.text_input(
                "Title", 
                value=st.session_state.get('test_title', ''),
                placeholder="e.g., The Complete Guide to Digital Marketing"
            )
            
            test_content = st.text_area(
                "Content", 
                value=st.session_state.get('test_content', ''),
                height=300,
                placeholder="Enter your content here to see real-time SEO scoring..."
            )
            
            # Store in session state
            st.session_state.test_keyword = test_keyword
            st.session_state.test_title = test_title
            st.session_state.test_content = test_content
        
        with col2:
            st.markdown("### Instructions & SEO Analysis")
            
            st.markdown("""
            **How to use:**
            1. Enter a keyword, title, and content in the form
            2. Click "Load Demo Content" for sample data
            3. The SEO analysis will update automatically
            4. Modify the content to see scores update
            
            **SEO Metrics Analyzed:**
            - **Keyword Density:** 1-3% is optimal
            - **Title Length:** 30-60 characters ideal
            - **Content Length:** Longer content ranks better
            - **Keyword in Title:** Should include target keyword
            - **Readability:** Average sentence length analysis
            """)
            
            # Real-time SEO analysis
            if test_keyword and test_title and test_content:
                test_seo = st.session_state.seo_writer.analyze_seo(test_content, test_title, test_keyword)
                
                if test_seo:
                    overall_score = test_seo.get('overall_score', 0)
                    score_class = get_score_color_class(overall_score)
                    score_emoji = get_score_emoji(overall_score)
                    
                    st.markdown(f'<div class="{score_class}">', unsafe_allow_html=True)
                    st.markdown(f"### {score_emoji} SEO Score: {overall_score}/100")
                    st.markdown('</div>', unsafe_allow_html=True)
                    
                    # Quick metrics
                    scores = test_seo.get('scores', {})
                    for metric, data in scores.items():
                        score = data.get('score', 0)
                        value = data.get('value', 'N/A')
                        emoji = get_score_emoji(score)
                        metric_name = metric.replace('_', ' ').title()
                        st.markdown(f"**{metric_name}:** {emoji} {score}/100 ({value})")
                    
                    # Recommendations
                    recommendations = test_seo.get('recommendations', [])
                    if recommendations:
                        st.markdown("**πŸ’‘ Recommendations:**")
                        for rec in recommendations:
                            st.markdown(f"β€’ {rec}")

if __name__ == "__main__":
    main()