<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Book Summary | AI Assistant</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
    <!-- Add Font Awesome for icons -->
    <script src="https://kit.fontawesome.com/475afa2c37.js" crossorigin="anonymous"></script>
    <style>
        .summary-section {
            max-width: 800px;
            margin: 2rem auto;
            padding: 0 2rem;
        }

        .input-group {
            display: flex;
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .input-field {
            flex-grow: 1;
            padding: 0.75rem 1rem;
            border: 1px solid var(--text-secondary);
            border-radius: 0.5rem;
            background-color: var(--background-color);
            color: var(--text-primary);
            font-family: 'Poppins', sans-serif;
        }

        .button {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 0.5rem;
            background-color: var(--accent-color);
            color: white;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .button:hover {
            background-color: var(--primary-color);
            transform: translateY(-1px);
        }

        .loading-section {
            display: none;
            text-align: center;
            padding: 2rem;
            background-color: var(--surface-color);
            border-radius: 1rem;
            margin-bottom: 2rem;
        }

        .response-section {
            background-color: var(--surface-color);
            border-radius: 1rem;
            padding: 2rem;
            margin-bottom: 2rem;
            display: none;
        }

        .response-content {
            white-space: pre-wrap;
            color: var(--text-primary);
            line-height: 1.6;
            margin-bottom: 1rem;
        }

        .action-buttons {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
        }

        .home-button {
            position: fixed;
            bottom: 2rem;
            right: 2rem;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: var(--accent-color);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .home-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
    </style>
</head>
<body>
    <nav class="top-nav">
        <div class="logo">
            <span class="logo-text">AI Assistant</span>
        </div>
        <div class="user-profile">
            <button class="theme-toggle" aria-label="Toggle theme">
                <i class="fas fa-moon"></i>
            </button>
        </div>
    </nav>

    <main class="summary-section">
        <h1>Book Summary</h1>
        
        <div class="input-group">
            <input type="text" 
                   id="bookTitle" 
                   class="input-field" 
                   placeholder="Enter book title...">
            <button class="button" id="randomBook">Random Book</button>
            <button class="button" id="generateSummary">Generate Summary</button>
        </div>

        <div class="loading-section" id="loadingSection">
            <img src="images/loading.gif" alt="Loading..." width="50" height="50">
            <p>Generating your summary...</p>
        </div>

        <div class="response-section" id="responseSection">
            <div class="response-content" id="summaryContent"></div>
            <div class="action-buttons">
            <button onclick="copyToClipboard()" class="secondary-button">
                    <i class="fas fa-copy"></i> Copy
                </button>
                <button class="button" id="emailSummary">Email Summary</button>
            </div>
        </div>
    </main>

    <a href="index.php" class="home-button">
        <i class="fas fa-house"></i>
    </a>

    <script>
        const popularBooks = [
            "Think and Grow Rich by Napoleon Hill",
            "The 7 Habits of Highly Effective People by Stephen Covey",
            "Good to Great by Jim Collins",
            "Deep Work by Cal Newport",
            "Atomic Habits by James Clear",
            "The Lean Startup by Eric Ries",
            "Start with Why by Simon Sinek",
            "Zero to One by Peter Thiel",
            "Built to Last by Jim Collins",
            "Rich Dad Poor Dad by Robert Kiyosaki"
        ];

        document.getElementById('randomBook').addEventListener('click', () => {
            const randomIndex = Math.floor(Math.random() * popularBooks.length);
            document.getElementById('bookTitle').value = popularBooks[randomIndex];
        });

        document.getElementById('generateSummary').addEventListener('click', generateBookSummary);
        document.getElementById('emailSummary').addEventListener('click', emailSummary);

        async function generateBookSummary() {
            const bookTitle = document.getElementById('bookTitle').value;
            if (!bookTitle) {
                alert('Please enter a book title');
                return;
            }

            const loadingSection = document.getElementById('loadingSection');
            const responseSection = document.getElementById('responseSection');
            const summaryContent = document.getElementById('summaryContent');

            loadingSection.style.display = 'block';
            responseSection.style.display = 'none';

            const prompt = `You are an expert in business and personal development and you always respond using HTML formatting. If you know the book, create a comprehensive summary of the book ${bookTitle} including key points, key ideas, implications for personal or business development, and an suggested implementation plan. Include anything else that you think would be useful for the user. If you do not know the book, then simply say so.`;

            try {
                const response = await fetch('ai_endpoint.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ prompt: prompt })
                });

                const data = await response.json();
                summaryContent.innerHTML = data.response;
                loadingSection.style.display = 'none';
                responseSection.style.display = 'block';
            } catch (error) {
                console.error('Error:', error);
                alert('An error occurred while generating the summary');
                loadingSection.style.display = 'none';
            }
        }

        async function emailSummary() {
            const summary = document.getElementById('summaryContent').textContent;
            const bookTitle = document.getElementById('bookTitle').value;

            try {
                const response = await fetch('email_endpoint.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        subject: `Book Summary: ${bookTitle}`,
                        content: summary
                    })
                });

                const data = await response.json();
                if (data.success) {
                    alert('Summary has been emailed to you');
                } else {
                    alert('Failed to send email');
                }
            } catch (error) {
                console.error('Error:', error);
                alert('An error occurred while sending the email');
            }
        }
        async function copyToClipboard() {
    const responseText = document.getElementById('summaryContent').innerHTML;
    if (!responseText) {
        alert('No content to copy');
        return;
    }

    try {
        // Create a temporary div for rich text handling
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = responseText;
        tempDiv.style.position = 'fixed';
        tempDiv.style.left = '-9999px';
        document.body.appendChild(tempDiv);

        // Create a range and selection
        const range = document.createRange();
        range.selectNode(tempDiv);
        const selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);

        // Try the modern clipboard API first
        if (navigator.clipboard && window.isSecureContext) {
            // Copy as rich text
            await navigator.clipboard.write([
                new ClipboardItem({
                    'text/html': new Blob([tempDiv.innerHTML], { type: 'text/html' }),
                    'text/plain': new Blob([tempDiv.innerText], { type: 'text/plain' })
                })
            ]);
        } else {
            // Fallback to older method
            document.execCommand('copy');
        }

        // Clean up
        selection.removeAllRanges();
        document.body.removeChild(tempDiv);

        alert('Summary copied to clipboard!');
    } catch (err) {
        console.error('Failed to copy text:', err);
        alert('Failed to copy text. Please try selecting and copying manually.');
    }
}

    </script>
    <script src="scripts.js"></script>
</body>
</html>
