import webview
import os

class App:
    def __init__(self):
        self.window = None

    def set_window(self, window):
        self.window = window

    def save_file(self, content, mode):
        """Project save and dialog window open function"""
        try:
            file_types = ('HTML files (*.html)', 'All files (*.*)')
            # Open the Save Path Selection window
            result = self.window.create_file_dialog(
                webview.SAVE_DIALOG, 
                file_types=file_types, 
                save_filename=f'genuine_project_{mode}.html'
            )
            
            if result:
                # Handle the chosen path (whether text or list)
                file_path = result[0] if isinstance(result, list) else result
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                return "Exported successfully, ya!"
            return "The operation has been cancelled"
        except Exception as e:
            return f": An error occurred while saving{str(e)}"

    def run(self):
        full_html = f"""
        <!DOCTYPE html>
        <html lang="ar">
        <head>
            <meta charset="UTF-8">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
            <style>
                :root {{ --neon: #00ffcc; --bg: #0a0a0a; }}
                body {{ display: flex; margin: 0; background: var(--bg); color: white; font-family: 'Segoe UI', sans-serif; height: 100vh; overflow: hidden; }}
                
                #toolbox, #props {{ width: 280px; background: #161616; padding: 15px; border: 1px solid #333; display: flex; flex-direction: column; overflow-y: auto; z-index: 100; }}
                #canvas-container {{ flex-grow: 1; background: #000; overflow: auto; position: relative; background-image: radial-gradient(#333 1px, transparent 1px); background-size: 30px 30px; }}
                #canvas-root {{ width: 5000px; height: 5000px; position: relative; transform-origin: 0 0; transition: transform 0.1s ease-out; }}

                /* شريط الزووم */
                #zoom-ctrl {{
                    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);
                    background: #161616; padding: 10px 20px; border-radius: 30px; border: 1px solid var(--neon);
                    display: flex; gap: 15px; align-items: center; z-index: 1000; box-shadow: 0 0 10px rgba(0,255,204,0.3);
                }}
                .zoom-btn {{ background: none; border: none; color: var(--neon); cursor: pointer; font-size: 18px; }}

                .device {{ position: absolute; background: #111; border: 10px solid #333; border-radius: 20px; display: flex; flex-direction: column; overflow: hidden; }}
                .device-header {{ background: #333; color: var(--neon); padding: 5px; font-size: 10px; text-align: center; cursor: move; }}
                .device-content {{ position: relative; width: 100%; height: 100%; background: #050505; }}

                .comp {{ position: absolute !important; cursor: pointer; display: flex; align-items: center; justify-content: center; border: 1px solid transparent; }}
                .selected {{ border: 2px solid var(--neon) !important; box-shadow: 0 0 15px var(--neon); }}
                
                @keyframes spin {{ from {{ transform: rotate(0deg); }} to {{ transform: rotate(360deg); }} }}
                @keyframes pulse {{ 0% {{ opacity: 1; }} 50% {{ opacity: 0.4; }} 100% {{ opacity: 1; }} }}
                @keyframes float {{ 0% {{ transform: translateY(0px); }} 50% {{ transform: translateY(-10px); }} 100% {{ transform: translateY(0px); }} }}
                .anim-spin {{ animation: spin 2s linear infinite; }}
                .anim-pulse {{ animation: pulse 1.5s infinite; }}
                .anim-float {{ animation: float 3s ease-in-out infinite; }}

                .tool-btn {{ background: #222; color: var(--neon); border: 1px solid #444; padding: 10px; cursor: pointer; margin-bottom: 5px; border-radius: 5px; font-size: 13px; }}
                .tool-btn:hover {{ background: #00ffcc22; }}
                input, select {{ background: #000; color: var(--neon); border: 1px solid #333; padding: 6px; width: 100%; margin-bottom: 10px; }}
                
                #preview-overlay {{ display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:black; z-index:10000; }}
                #exit-p {{ position:fixed; top:20px; right:20px; background:red; color:white; border:none; padding:10px; cursor:pointer; z-index:10001; }}
            </style>
        </head>
        <body>
            <div id="toolbox">
                <h3 style="color:var(--neon)">Genuine 2049</h3>
                <div class="tool-btn" onclick="addDevice('mobile')"><i class="fas fa-mobile"></i> هاتف</div>
                <div class="tool-btn" onclick="addDevice('pc')"><i class="fas fa-laptop"></i> حاسوب</div>
                <hr style="width:100%; border:0.5px solid #333">
                <div class="tool-btn" draggable="true" ondragstart="evDrag(event,'box')">⬛ مربع/زر</div>
                <div class="tool-btn" draggable="true" ondragstart="evDrag(event,'text')">T نص</div>
                <div class="tool-btn" draggable="true" ondragstart="evDrag(event,'img')">🖼 صورة</div>
                <div class="tool-btn" draggable="true" ondragstart="evDrag(event,'sticker')">✨ ملصق</div>
                <hr style="width:100%; border:0.5px solid #333">
                <button onclick="startPreview()" class="tool-btn" style="background:var(--neon); color:black"><b>تشغيل المعاينة</b></button>
                <select id="export-mode">
                    <option value="desktop">تطبيق سطح مكتب</option>
                    <option value="web">موقع ويب</option>
                </select>
                <button onclick="exportNow()" class="tool-btn" style="background:#005544; color:white">تصدير المشروع</button>
            </div>

            <div id="canvas-container" onwheel="wheelZoom(event)">
                <div id="canvas-root"></div>
            </div>

            <div id="zoom-ctrl">
                <button class="zoom-btn" onclick="setZoom(currentZoom - 0.1)"><i class="fas fa-minus"></i></button>
                <span id="zoom-val" style="color:var(--neon); font-weight:bold; min-width:50px; text-align:center;">100%</span>
                <button class="zoom-btn" onclick="setZoom(currentZoom + 0.1)"><i class="fas fa-plus"></i></button>
                <button class="zoom-btn" onclick="setZoom(1)" title="إعادة ضبط"><i class="fas fa-sync-alt"></i></button>
            </div>

            <div id="props">
                <h3 style="color:var(--neon)">الخصائص</h3>
                <div id="editor" style="display:none">
                    <label>المحتوى / النص:</label>
                    <input type="text" id="p-text" oninput="updateProp()">
                    <div id="img-upload-section" style="display:none">
                        <label>رفع صورة:</label>
                        <input type="file" id="p-file" accept="image/*" onchange="uploadImg(event)">
                    </div>
                    <label>الحركة:</label>
                    <select id="p-anim" onchange="updateProp()">
                        <option value="">بدون حركة</option>
                        <option value="anim-spin">دوران</option>
                        <option value="anim-pulse">نبض</option>
                        <option value="anim-float">طفو</option>
                    </select>
                    <label>ربط بـ ID الصفحة:</label>
                    <input type="text" id="p-link" placeholder="Page_1234" oninput="updateProp()">
                    <button onclick="deleteElement()" style="background:#400; color:red; border:1px solid red; width:100%; padding:8px; cursor:pointer">حذف العنصر</button>
                </div>
            </div>

            <div id="preview-overlay">
                <button id="exit-p" onclick="stopPreview()">خروج</button>
                <div id="preview-content" style="width:100%; height:100%; display:flex; justify-content:center; align-items:center"></div>
            </div>

            <script>
                let selId = null;
                let currentZoom = 1;

                function setZoom(val) {{
                    currentZoom = Math.min(Math.max(0.2, val), 3);
                    document.getElementById('canvas-root').style.transform = `scale(${{currentZoom}})`;
                    document.getElementById('zoom-val').innerText = Math.round(currentZoom * 100) + '%';
                }}

                function wheelZoom(e) {{
                    if (e.ctrlKey) {{
                        e.preventDefault();
                        setZoom(currentZoom + (e.deltaY > 0 ? -0.1 : 0.1));
                    }}
                }}

                function evDrag(ev, type) {{ ev.dataTransfer.setData("type", type); }}

                function addDevice(type) {{
                    const id = 'Page_' + Math.floor(Math.random()*9000+1000);
                    const dev = document.createElement('div');
                    dev.id = id; dev.className = 'device';
                    dev.style.width = type==='mobile'?'360px':'800px';
                    dev.style.height = type==='mobile'?'640px':'500px';
                    dev.style.left = '100px'; dev.style.top = '100px';
                    dev.innerHTML = `<div class="device-header" onmousedown="dragMove(event,'${{id}}')">${{id}}</div><div class="device-content" id="c-${{id}}" ondragover="event.preventDefault()" ondrop="dropIn(event,'c-${{id}}')"></div>`;
                    dev.onclick = (e) => {{ e.stopPropagation(); selectEl(id); }};
                    document.getElementById('canvas-root').appendChild(dev);
                }}

                function dropIn(ev, contId) {{
                    ev.preventDefault(); ev.stopPropagation();
                    const type = ev.dataTransfer.getData("type");
                    const id = 'el-' + Date.now();
                    const el = document.createElement('div');
                    el.id = id; el.className = 'comp';
                    el.setAttribute('data-type', type);
                    
                    const rect = document.getElementById(contId).getBoundingClientRect();
                    el.style.left = ((ev.clientX - rect.left) / currentZoom) + 'px';
                    el.style.top = ((ev.clientY - rect.top) / currentZoom) + 'px';

                    if(type==='img') el.innerHTML = '<img src="https://via.placeholder.com/100" style="width:100px; height:100px">';
                    else if(type==='sticker') el.innerHTML = '<span style="font-size:40px">🔥</span>';
                    else {{ el.innerText = 'عنصر'; el.style.background = '#333'; el.style.padding = '10px'; }}

                    el.onmousedown = (e) => dragMove(e, id);
                    el.onclick = (e) => {{ e.stopPropagation(); selectEl(id); }};
                    document.getElementById(contId).appendChild(el);
                    selectEl(id);
                }}

                function dragMove(e, id) {{
                    e.stopPropagation();
                    const el = document.getElementById(id);
                    let sx = e.clientX, sy = e.clientY, sl = el.offsetLeft, st = el.offsetTop;
                    document.onmousemove = (m) => {{
                        el.style.left = (sl + (m.clientX - sx) / currentZoom) + 'px';
                        el.style.top = (st + (m.clientY - sy) / currentZoom) + 'px';
                    }};
                    document.onmouseup = () => document.onmousemove = null;
                }}

                function uploadImg(ev) {{
                    const file = ev.target.files[0];
                    const reader = new FileReader();
                    reader.onload = (e) => {{
                        const el = document.getElementById(selId);
                        if(el.querySelector('img')) el.querySelector('img').src = e.target.result;
                    }};
                    reader.readAsDataURL(file);
                }}

                function selectEl(id) {{
                    if(selId) document.getElementById(selId)?.classList.remove('selected');
                    selId = id;
                    const el = document.getElementById(id);
                    if(!el) return;
                    el.classList.add('selected');
                    document.getElementById('editor').style.display = 'block';
                    document.getElementById('img-upload-section').style.display = el.getAttribute('data-type')==='img'?'block':'none';
                }}

                function updateProp() {{
                    const el = document.getElementById(selId);
                    const txt = document.getElementById('p-text').value;
                    const anim = document.getElementById('p-anim').value;
                    el.className = 'comp selected ' + anim;
                    el.setAttribute('data-link', document.getElementById('p-link').value);
                    if(el.getAttribute('data-type') !== 'img' && el.getAttribute('data-type') !== 'sticker') el.innerText = txt;
                }}

                function startPreview() {{
                    const pages = document.querySelectorAll('.device');
                    if(pages.length === 0) return alert("أضف صفحة أولاً");
                    const overlay = document.getElementById('preview-overlay');
                    const content = document.getElementById('preview-content');
                    overlay.style.display = 'block';
                    content.innerHTML = document.getElementById('canvas-root').innerHTML;
                    const pPages = content.querySelectorAll('.device');
                    pPages.forEach((p, i) => {{
                        p.style.display = i === 0 ? 'flex' : 'none';
                        p.style.position = 'relative'; p.style.left = '0'; p.style.top = '0'; p.style.transform = 'scale(1)';
                        p.querySelector('.device-header').style.display = 'none';
                    }});
                    content.querySelectorAll('.comp').forEach(c => {{
                        c.classList.remove('selected');
                        c.onclick = function() {{
                            const link = this.getAttribute('data-link');
                            if(link && content.querySelector('#'+link)) {{
                                pPages.forEach(p => p.style.display = 'none');
                                content.querySelector('#'+link).style.display = 'flex';
                            }}
                        }};
                    }});
                }}

                function stopPreview() {{ document.getElementById('preview-overlay').style.display = 'none'; }}

                function exportNow() {{
                    const mode = document.getElementById('export-mode').value;
                    // استدعاء دالة البايثون عبر API بطريقة صحيحة
                    window.pywebview.api.save_file(document.documentElement.outerHTML, mode).then(alert);
                }}

                function deleteElement() {{ document.getElementById(selId).remove(); document.getElementById('editor').style.display='none'; }}
            </script>
        </body>
        </html>
        """
        return full_html

if __name__ == "__main__":
    app = App()
    # Most important modification: Pass the app object as js_api here
    window = webview.create_window(
        "Genuine Studio 2049", 
        html=app.run(), 
        width=1400, 
        height=900,
        js_api=app
    )
    # Link the window to the object to use it to open the save dialog
    app.set_window(window)
    webview.start(debug=True)