// ==========================================
// 1. ממשק קומפקטי ואלגנטי
// ==========================================
const toggleBtn = document.createElement('button');
toggleBtn.innerHTML = '🛠️ כלים';
toggleBtn.style.cssText = 'position:fixed; bottom:20px; left:20px; z-index:999999; padding:8px 14px; background:#1e1e1e; color:#fff; border:1px solid #555; border-radius:20px; box-shadow:0 2px 10px rgba(0,0,0,0.3); cursor:pointer; font-size:13px; font-weight:bold; font-family:system-ui; direction:rtl; transition:0.2s;';
document.body.appendChild(toggleBtn);

const panel = document.createElement('div');
panel.style.cssText = 'position:fixed; bottom:60px; left:20px; z-index:999998; padding:15px; background:#1a1a1c; color:#eee; border-radius:12px; box-shadow:0 5px 25px rgba(0,0,0,0.5); width:260px; border:1px solid #333; display:none; flex-direction:column; gap:12px; direction:rtl; font-family:system-ui;';
panel.innerHTML = `
    <div style="display:flex; gap:5px;">
        <button id="foldAllBtn" style="flex:1; padding:8px; background:#333; color:#fff; border:none; border-radius:6px; cursor:pointer; font-size:12px; transition:0.2s;">📁 קפל קודים</button>
        <button id="unfoldAllBtn" style="flex:1; padding:8px; background:#333; color:#fff; border:none; border-radius:6px; cursor:pointer; font-size:12px; transition:0.2s;">📂 פתח קודים</button>
    </div>
    
    <div style="border-top:1px solid #333; margin:5px 0;"></div>
    
    <select id="extractFilter" style="padding:6px; border-radius:6px; border:1px solid #444; background:#222; color:#eee; font-size:12px; cursor:pointer;">
        <option value="both">📝 חלץ הכל (אני + AI)</option>
        <option value="user">👤 חלץ רק את הבקשות שלי</option>
        <option value="model">🤖 חלץ רק את התשובות</option>
    </select>
    
    <div id="statusText" style="font-size:11px; color:#8ab4f8; text-align:center; font-weight:bold;">סטטוס: ממתין</div>
    
    <div style="display:flex; gap:5px;">
        <button id="startBtn" style="flex:1; padding:8px; background:#1a73e8; color:white; border:none; border-radius:6px; cursor:pointer; font-size:12px; font-weight:bold;">▶️ טען סוף שיחה</button>
        <button id="extractBtn" style="flex:1; padding:8px; background:#34a853; color:white; border:none; border-radius:6px; cursor:pointer; font-size:12px; font-weight:bold;">⏹️ חלץ</button>
    </div>
`;
document.body.appendChild(panel);

toggleBtn.onclick = () => panel.style.display = panel.style.display === 'none' ? 'flex' : 'none';

// ==========================================
// 2. מנגנון קיפול קוד חכם (Code Folding)
// ==========================================
function injectFoldButtons() {
    const codeBlocks = document.querySelectorAll('pre:not(.has-fold-btn)');
    codeBlocks.forEach(pre => {
        pre.classList.add('has-fold-btn');
        
        const foldBtn = document.createElement('div');
        foldBtn.innerHTML = '👁️ הסתר/הצג קוד';
        foldBtn.style.cssText = 'background:#2d2d30; color:#8ab4f8; font-size:11px; padding:4px 8px; cursor:pointer; border-radius:4px; font-family:sans-serif; width:fit-content; margin-bottom:5px; border:1px solid #444; transition:0.2s; user-select:none;';
        
        foldBtn.onclick = (e) => {
            e.stopPropagation();
            const isHidden = pre.style.display === 'none';
            pre.style.display = isHidden ? 'block' : 'none';
            foldBtn.innerHTML = isHidden ? '👁️ הסתר קוד' : '📂 קוד מקופל (לחץ להצגה)';
            foldBtn.style.background = isHidden ? '#2d2d30' : '#1e3a5f';
        };
        
        pre.parentNode.insertBefore(foldBtn, pre);
    });
}
setInterval(injectFoldButtons, 1000);

panel.querySelector('#foldAllBtn').onclick = () => {
    document.querySelectorAll('pre.has-fold-btn').forEach(pre => {
        pre.style.display = 'none';
        const btn = pre.previousElementSibling;
        if(btn) { btn.innerHTML = '📂 קוד מקופל (לחץ להצגה)'; btn.style.background = '#1e3a5f'; }
    });
};

panel.querySelector('#unfoldAllBtn').onclick = () => {
    document.querySelectorAll('pre.has-fold-btn').forEach(pre => {
        pre.style.display = 'block';
        const btn = pre.previousElementSibling;
        if(btn) { btn.innerHTML = '👁️ הסתר קוד'; btn.style.background = '#2d2d30'; }
    });
};

// ==========================================
// 3. לוגיקת גלילה וחילוץ עמידה
// ==========================================
let isScrolling = false;

panel.querySelector('#startBtn').onclick = async () => {
    if (isScrolling) return;
    isScrolling = true;
    let cycle = 0;
    
    while (isScrolling) {
        cycle++;
        panel.querySelector('#statusText').innerText = `מגלגל למעלה (${cycle})...`;
        
        const messages = document.querySelectorAll('user-query, message-content, [data-message-author-role]');
        if (messages.length > 0) messages[0].scrollIntoView({ behavior: "smooth", block: "start" });
        
        const container = document.querySelector('main') || window;
        container.dispatchEvent(new WheelEvent('wheel', { deltaY: -5000, bubbles: true }));
        
        await new Promise(r => setTimeout(r, 2000));
    }
};

panel.querySelector('#extractBtn').onclick = () => {
    isScrolling = false;
    panel.querySelector('#statusText').innerText = "מעבד נתונים...";
    
    const filter = panel.querySelector('#extractFilter').value;
    const allMessages = document.querySelectorAll('user-query, message-content, [data-message-author-role]');
    let text = "";
    let count = 0;
    let seenTexts = new Set();
    
    allMessages.forEach(el => {
        let content = el.innerText || el.textContent;
        if (!content || content.trim() === "") return;
        content = content.trim();
        
        if (seenTexts.has(content)) return;
        seenTexts.add(content);
        
        let role = el.getAttribute('data-message-author-role');
        if (!role) role = el.tagName.toLowerCase() === 'user-query' ? 'user' : 'model';
        
        if (filter === 'both' || filter === role) {
            count++;
            const header = role === 'user' ? '👤 אני:' : '🤖 ג׳מיני:';
            text += `${header}\n${content}\n\n========================================\n\n`;
        }
    });

    if (count === 0) {
        panel.querySelector('#statusText').innerText = "❌ אין הודעות לחילוץ!";
        return;
    }

    let chatTitle = document.title.replace(/\s*-\s*Gemini/i, '').trim();
    chatTitle = chatTitle.replace(/[^a-z0-9א-ת\s\-_()]/gi, '_').substring(0, 80) || "שיחת_Gemini";

    const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `${chatTitle}_(${filter}).txt`;
    a.click();
    
    panel.querySelector('#statusText').innerText = `✅ נשמר! (${count} פריטים)`;
};