index.html.bak.20260304_0631

Code: DEV-EA8931FC Size: 597.0 KB Lines: 8583 Path: /home/prodconfig.wenesthosting.com/dev.solargroup.wenest.se/index.html.bak.20260304_0631

Task / Comment

Open report form
<!DOCTYPE html>
<html lang="sv">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Solar Sales Suite</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBJPnfNCe6un1J7ck6co7zr2uvGrxhFYXY&libraries=places,drawing,geometry&callback=Function.prototype" async defer></script>
    <style>
        *{margin:0;padding:0;box-sizing:border-box}
        body{font-family:'Inter',sans-serif;background:#f8f9fa;color:#1a1a1a;line-height:1.6;display:flex;min-height:100vh;-webkit-font-smoothing:antialiased}
        /* === LOGIN === */
        .login-screen{position:fixed;inset:0;z-index:9999;display:flex;background:#fff}
        .login-screen.hidden{display:none}
        .login-image{flex:1;background:url('https://easysolar.app/wp-content/uploads/2025/06/image_18a7112af2f0d5ffa710774468eadf9c-1024x683.jpeg') center/cover no-repeat;position:relative}
        .login-image::after{content:'';position:absolute;inset:0;background:linear-gradient(135deg,rgba(2,69,80,.4) 0%,rgba(0,0,0,.2) 100%)}
        .login-image-text{position:absolute;bottom:50px;left:50px;z-index:1;color:#fff}
        .login-image-text h2{font-size:32px;font-weight:700;margin-bottom:8px;text-shadow:0 2px 12px rgba(0,0,0,.3)}
        .login-image-text p{font-size:15px;opacity:.85;text-shadow:0 1px 8px rgba(0,0,0,.3)}
        .login-panel{width:480px;display:flex;flex-direction:column;justify-content:center;padding:60px 56px;background:#fff;flex-shrink:0}
        .login-logo{margin-bottom:48px}
        .login-logo img{width:180px;height:auto}
        .login-greeting{font-size:28px;font-weight:700;color:#1a1a1a;margin-bottom:6px}
        .login-subtitle{font-size:15px;color:#94a3b8;margin-bottom:36px}
        .login-form-group{margin-bottom:20px}
        .login-form-group label{display:block;font-size:13px;font-weight:600;color:#334155;margin-bottom:6px}
        .login-form-group input{width:100%;padding:12px 16px;border:1.5px solid #e5e7eb;border-radius:10px;font-size:15px;font-family:'Inter',sans-serif;transition:all .2s;background:#fafbfc}
        .login-form-group input:focus{outline:none;border-color:#024550;box-shadow:0 0 0 3px rgba(2,69,80,.1);background:#fff}
        .login-form-group input::placeholder{color:#c1c7cd}
        .login-remember{display:flex;align-items:center;justify-content:space-between;margin-bottom:28px}
        .login-remember label{display:flex;align-items:center;gap:8px;font-size:13px;color:#64748b;cursor:pointer}
        .login-remember input[type=checkbox]{width:16px;height:16px;accent-color:#024550;cursor:pointer}
        .login-forgot{font-size:13px;color:#024550;text-decoration:none;font-weight:500;transition:color .15s}
        .login-forgot:hover{color:#10b981}
        .login-btn{width:100%;padding:14px;background:#024550;color:#fff;border:none;border-radius:10px;font-size:15px;font-weight:600;cursor:pointer;font-family:'Inter',sans-serif;transition:all .2s;letter-spacing:.2px}
        .login-btn:hover{background:#035e6b;box-shadow:0 4px 14px rgba(2,69,80,.25)}
        .login-btn:active{transform:scale(.985)}
        .login-footer{margin-top:auto;padding-top:40px;text-align:center;font-size:12px;color:#c1c7cd}
        @media(max-width:900px){.login-image{display:none}.login-panel{width:100%}}

        /* === SIDEBAR === */
        .sidebar{position:fixed;top:0;left:0;bottom:0;width:220px;background:#024550;display:flex;flex-direction:column;z-index:100}
        .sidebar-brand{padding:20px 22px 18px;display:flex;align-items:center;justify-content:center}
        .sidebar-brand-icon{width:160px;height:auto;display:flex;align-items:center;justify-content:center}
        .sidebar-brand-icon img{width:100%;height:auto;object-fit:contain}
        .sidebar-menu{flex:1;padding:4px 0;overflow-y:auto}
        .sidebar-menu::-webkit-scrollbar{width:3px}
        .sidebar-menu::-webkit-scrollbar-thumb{background:rgba(255,255,255,.1);border-radius:3px}
        .nav-item{display:flex;align-items:center;gap:12px;padding:10px 22px;color:rgba(255,255,255,.55);text-decoration:none;font-size:13.5px;font-weight:500;transition:all .15s;cursor:pointer;margin:1px 10px;border-radius:8px}
        .nav-item:hover{color:rgba(255,255,255,.85);background:rgba(255,255,255,.05)}
        .nav-item.active{background:rgba(46,204,113,.18);color:#fff;font-weight:600}
        .nav-icon{width:18px;height:18px;display:flex;align-items:center;justify-content:center;flex-shrink:0}
        .nav-icon svg{width:17px;height:17px;stroke:currentColor;fill:none;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
        .sidebar-bottom{padding:16px 22px;border-top:1px solid rgba(255,255,255,.08)}
        .sidebar-user{display:flex;align-items:center;gap:10px;margin-bottom:10px}
        .sidebar-user-info{font-size:11px;color:rgba(255,255,255,.4);line-height:1.4}
        .sidebar-user-info strong{display:block;color:rgba(255,255,255,.7);font-size:12px;font-weight:500}
        .sidebar-logout{display:flex;align-items:center;gap:8px;color:rgba(255,255,255,.4);font-size:12px;cursor:pointer;transition:color .15s;background:none;border:none;font-family:inherit;padding:0}
        .sidebar-logout:hover{color:rgba(255,255,255,.7)}
        .sidebar-logout svg{width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}

        /* === MAIN === */
        .main-wrapper{margin-left:220px;padding:32px 40px;flex:1;min-height:100vh}
        .page-title{font-size:28px;font-weight:700;color:#1a1a1a;letter-spacing:-.5px;margin-bottom:4px}
        .page-subtitle{font-size:14px;color:#94a3b8;margin-bottom:28px;font-weight:400}
        .page-content{display:none}
        .page-content.active{display:block}

        /* === DASHBOARD STAT CARDS === */
        .stat-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:28px}
        .stat-card{background:#fff;border-radius:12px;padding:20px 22px;border:1px solid #e5e7eb;display:flex;justify-content:space-between;align-items:flex-start;transition:box-shadow .2s}
        .stat-card:hover{box-shadow:0 4px 12px rgba(0,0,0,.06)}
        .stat-card-info h4{font-size:13px;color:#94a3b8;font-weight:500;margin-bottom:10px}
        .stat-card-info .stat-value{font-size:26px;font-weight:700;color:#1a1a1a;letter-spacing:-.5px}
        .stat-card-icon{width:40px;height:40px;border-radius:10px;display:flex;align-items:center;justify-content:center;flex-shrink:0}
        .stat-card-icon svg{width:20px;height:20px;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;fill:none}
        .stat-card-icon.green{background:#ecfdf5}
        .stat-card-icon.green svg{stroke:#10b981}
        .stat-card-icon.blue{background:#eff6ff}
        .stat-card-icon.blue svg{stroke:#3b82f6}
        .stat-card-icon.purple{background:#faf5ff}
        .stat-card-icon.purple svg{stroke:#a855f7}
        .stat-card-icon.teal{background:#f0fdfa}
        .stat-card-icon.teal svg{stroke:#14b8a6}

        /* === DASHBOARD 2-COL === */
        .dash-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px}
        .dash-panel{background:#fff;border-radius:12px;border:1px solid #e5e7eb;overflow:hidden}
        .dash-panel-header{padding:18px 22px;display:flex;align-items:center;gap:10px;border-bottom:1px solid #f1f5f9}
        .dash-panel-header svg{width:18px;height:18px;stroke:#64748b;fill:none;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
        .dash-panel-header h3{font-size:16px;font-weight:600;color:#1a1a1a}
        .dash-panel-body{padding:0}
        .dash-panel-empty{padding:40px 22px;text-align:center;color:#94a3b8;font-size:14px}
        .offert-item{display:flex;justify-content:space-between;align-items:center;padding:14px 22px;border-bottom:1px solid #f1f5f9;transition:background .15s}
        .offert-item:last-child{border-bottom:none}
        .offert-item:hover{background:#fafbfc}
        .offert-item-left h4{font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:2px}
        .offert-item-left p{font-size:12px;color:#94a3b8}
        .offert-item-right{text-align:right}
        .offert-item-right .offert-price{font-size:15px;font-weight:700;color:#10b981}
        .offert-item-right .offert-status{font-size:11px;color:#94a3b8;margin-top:2px}

        /* === TABLES (other pages) === */
        .dummy-table{background:#fff;border-radius:12px;overflow:hidden;border:1px solid #e5e7eb}
        .dummy-table-header{padding:16px 22px;font-weight:600;font-size:15px;color:#1a1a1a;border-bottom:1px solid #f1f5f9}
        .dummy-table table{width:100%;border-collapse:collapse}
        .dummy-table th,.dummy-table td{padding:12px 22px;text-align:left;border-bottom:1px solid #f1f5f9}
        .dummy-table th{background:#fafbfc;font-weight:600;color:#64748b;font-size:12px;text-transform:uppercase;letter-spacing:.5px}
        .dummy-table td{font-size:13.5px;color:#334155}
        .dummy-table tr:last-child td{border-bottom:none}
        .dummy-table tr:hover td{background:#fafbfc}
        .status-badge{padding:4px 10px;border-radius:20px;font-size:11px;font-weight:600}
        .status-badge.green{background:#dcfce7;color:#166534}
        .status-badge.yellow{background:#fef9c3;color:#854d0e}
        .status-badge.blue{background:#dbeafe;color:#1e40af}
        .status-badge.gray{background:#f1f5f9;color:#64748b}
        .status-badge.purple{background:#ede9fe;color:#6d28d9}
        .progress-cell{min-width:120px}
        .progress-bar{height:20px;background:#f1f5f9;border-radius:10px;overflow:hidden;position:relative}
        .progress-fill{height:100%;background:linear-gradient(90deg,#2ecc71,#27ae60);border-radius:10px;transition:width .4s}
        .progress-text{position:absolute;top:0;left:0;right:0;height:100%;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;color:#333}
        .dummy-btn{padding:10px 20px;background:#024550;color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;display:inline-flex;align-items:center;gap:8px;transition:all .15s;font-family:'Inter',sans-serif}
        .dummy-btn:hover{background:#244a36}
        .dummy-btn.secondary{background:#f1f5f9;color:#334155}
        .dummy-btn.secondary:hover{background:#e2e8f0}
        .dummy-actions{display:flex;gap:10px;margin-bottom:20px}
        .dummy-form{background:#fff;border-radius:12px;padding:28px;border:1px solid #e5e7eb;max-width:500px}
        .dummy-form h3{margin-bottom:20px;color:#1a1a1a;font-size:18px}
        .dummy-form-group{margin-bottom:15px}
        .dummy-form-group label{display:block;font-weight:500;margin-bottom:6px;font-size:13px;color:#64748b}
        .dummy-form-group input,.dummy-form-group select{width:100%;padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:'Inter',sans-serif;transition:all .15s}
        .dummy-form-group input:focus,.dummy-form-group select:focus{outline:none;border-color:#2ecc71;box-shadow:0 0 0 3px rgba(46,204,113,.1)}

        /* === SETTINGS TABS === */
        .settings-tab{padding:12px 24px;background:none;border:none;border-bottom:2px solid transparent;font-size:14px;font-weight:600;color:#94a3b8;cursor:pointer;font-family:'Inter',sans-serif;transition:all .2s;margin-bottom:-2px}
        .settings-tab:hover{color:#1a1a1a}
        .settings-tab.active{color:#024550;border-bottom-color:#024550}
        .settings-panel{display:none}
        .settings-panel.active{display:block}

        /* === KONFIGURATOR === */
        .config-header{display:flex;align-items:center;gap:15px;margin-bottom:20px;flex-wrap:wrap}
        .config-label{font-size:14px;font-weight:600;color:#64748b}
        .product-select{padding:12px 40px 12px 15px;font-size:15px;font-weight:600;border:1px solid #e5e7eb;border-radius:10px;background:#fff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23334155'%3E%3Cpath d='M7 10l5 5 5-5z'/%3E%3C/svg%3E") no-repeat right 10px center/20px;appearance:none;cursor:pointer;min-width:320px;color:#1a1a1a;transition:all .15s;font-family:'Inter',sans-serif}
        .product-select:hover{border-color:#94a3b8}
        .product-select:focus{outline:none;border-color:#2ecc71;box-shadow:0 0 0 3px rgba(46,204,113,.1)}
        .config-layout{display:grid;grid-template-columns:1fr 350px;gap:20px;align-items:start}
        .config-main{display:flex;flex-direction:column;gap:15px}
        .config-sidebar{position:sticky;top:20px}
        .product-section{background:#fff;border-radius:12px;padding:25px;display:grid;grid-template-columns:1fr 1fr;gap:30px;border:1px solid #e5e7eb}
        .image-container{position:relative}
        .main-image{width:100%;display:flex;justify-content:center;align-items:center;min-height:250px}
        .main-image img{max-width:100%;max-height:300px;object-fit:contain}
        .thumbnail-strip{display:flex;gap:8px;margin-top:12px}
        .thumbnail{width:50px;height:50px;border:2px solid #e5e7eb;border-radius:6px;cursor:pointer;overflow:hidden;transition:border-color .15s}
        .thumbnail img{width:100%;height:100%;object-fit:cover}
        .thumbnail:hover{border-color:#94a3b8}
        .thumbnail.active{border-color:#024550}
        .image-note{font-size:11px;color:#94a3b8;margin-top:10px}
        .measure-section{padding-top:10px;display:flex;flex-direction:column;align-items:center}
        .measure-title{font-size:20px;font-weight:700;margin-bottom:5px;text-align:center;color:#1a1a1a}
        .measure-link{color:#3b82f6;font-size:13px;text-decoration:underline;cursor:pointer;display:block;text-align:center;margin-bottom:15px}
        .tab-switch{display:inline-flex;border:1px solid #e5e7eb;border-radius:20px;overflow:hidden;margin:0 auto 20px}
        .tab-btn{padding:10px 18px;background:#fff;border:none;cursor:pointer;font-size:13px;transition:all .15s;font-family:'Inter',sans-serif;font-weight:500;color:#64748b}
        .tab-btn:hover{background:#f8f9fa}
        .tab-btn.active{background:#024550;color:#fff}
        .dim-inputs{display:grid;grid-template-columns:1fr 1fr;gap:20px;max-width:280px;margin:0 auto}
        .dim-group label{display:block;font-weight:600;margin-bottom:6px;font-size:14px;color:#334155}
        .dim-group .req{color:#3b82f6}
        .input-wrap{display:flex;border:1px solid #e5e7eb;border-radius:8px;overflow:hidden;transition:all .15s}
        .input-wrap:focus-within{border-color:#2ecc71;box-shadow:0 0 0 3px rgba(46,204,113,.1)}
        .input-wrap input{flex:1;padding:10px 12px;border:none;font-size:15px;width:100%;font-family:'Inter',sans-serif}
        .input-wrap input:focus{outline:none}
        .input-wrap .unit{padding:10px 12px;background:#f8f9fa;border-left:1px solid #e5e7eb;font-weight:600;color:#64748b;font-size:13px}
        .dim-result{text-align:center;margin-top:5px;color:#94a3b8;font-size:13px}
        .options-section{background:#fff;border-radius:12px;padding:20px;border:1px solid #e5e7eb}
        .options-header{display:flex;align-items:center;gap:20px;margin-bottom:15px}
        .options-title{font-size:16px;font-weight:700;margin:0;color:#1a1a1a}
        .cheapest-btn{padding:8px 16px;background:#024550;color:#fff;border:none;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;transition:all .15s;font-family:'Inter',sans-serif}
        .cheapest-btn:hover{background:#244a36}
        .option-card{background:#fff;border:1px solid #e5e7eb;border-radius:10px;margin-bottom:8px;overflow:hidden;transition:all .2s}
        .option-card:last-child{margin-bottom:0}
        .option-card.expanded{border:2px solid #2ecc71;background:#fff}
        .option-card.required-error{border:2px solid #ef4444!important;animation:shake .3s}
        .option-card.required-error .option-header{background:#fef2f2}
        .option-card.is-valid .option-header::after{content:'';width:20px;height:20px;background:#dcfce7;border-radius:50%;margin-left:8px;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%2316a34a' stroke-width='3' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'/%3E%3C/svg%3E");background-size:12px;background-position:center;background-repeat:no-repeat;flex-shrink:0}
        @keyframes shake{0%,100%{transform:translateX(0)}25%{transform:translateX(-4px)}75%{transform:translateX(4px)}}
        @keyframes spin{to{transform:rotate(360deg)}}
        .option-header{display:flex;align-items:center;padding:12px 15px;cursor:pointer;background:#fff;transition:background .15s}
        .option-header:hover{background:#fafbfc}
        .option-image{width:42px;height:42px;background:#f8f9fa;border-radius:8px;margin-right:12px;display:flex;align-items:center;justify-content:center;font-size:18px;flex-shrink:0;overflow:hidden}
        .option-image img{width:100%;height:100%;object-fit:cover}
        .option-info{flex:1;min-width:0}
        .option-name{font-weight:600;font-size:14px;margin-bottom:1px;color:#1a1a1a}
        .option-value{color:#94a3b8;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
        .option-price{text-align:right;margin-right:10px;font-size:13px;color:#94a3b8;flex-shrink:0}
        .option-price.extra{color:#ef4444}
        .option-price.discount{color:#10b981}
        .option-edit{width:30px;height:30px;background:#f1f5f9;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:12px;flex-shrink:0;transition:all .15s}
        .option-edit:hover{background:#e2e8f0}
        .required-badge{display:none;background:#ef4444;color:#fff;font-size:10px;padding:2px 6px;border-radius:8px;margin-left:8px;font-weight:400}
        .option-card.required-error .required-badge{display:inline}
        .option-body{display:none;padding:15px 20px 20px;border-top:1px solid #f1f5f9;background:#fff}
        .option-card.expanded .option-body{display:block}
        .option-body-title{font-size:14px;color:#64748b;margin-bottom:15px}
        .option-choices{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:15px}
        .option-choice{position:relative;background:#fff;border:2px solid #e5e7eb;border-radius:10px;cursor:pointer;transition:all .15s;text-align:center;padding:12px 8px}
        .option-choice:hover{border-color:#94a3b8}
        .option-choice.selected{border-color:#2ecc71;box-shadow:0 0 0 3px rgba(46,204,113,.1)}
        .option-choice-info{position:absolute;top:6px;right:6px;width:18px;height:18px;background:#f1f5f9;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:600;color:#94a3b8}
        .option-choice-placeholder{width:100%;aspect-ratio:1/1;background:#f8f9fa;border-radius:5px;display:flex;align-items:center;justify-content:center;font-size:28px;margin-bottom:8px;overflow:hidden}
        .option-choice-placeholder img{width:100%;height:100%;object-fit:cover}
        .option-choice-radio{width:22px;height:22px;border:2px solid #d1d5db;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 6px;transition:all .15s}
        .option-choice.selected .option-choice-radio{border-color:#2ecc71;background:#2ecc71}
        .option-choice.selected .option-choice-radio::after{content:'';width:10px;height:10px;background:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23fff' stroke-width='3' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'/%3E%3C/svg%3E") center/contain no-repeat}
        .option-choice-name{font-size:12px;line-height:1.3;color:#64748b}
        .option-choice-price{font-size:11px;color:#94a3b8;margin-top:3px}
        .option-save-btn{display:block;margin:0 auto;padding:10px 30px;background:#024550;border:none;border-radius:8px;font-size:13px;color:#fff;cursor:pointer;transition:all .15s;font-family:'Inter',sans-serif;font-weight:600}
        .option-save-btn:hover{background:#244a36}
        .price-card{background:#fff;border-radius:12px;overflow:hidden;border:1px solid #e5e7eb}
        .price-header{background:#024550;color:#fff;padding:14px;font-weight:600;font-size:15px;text-align:center}
        .price-rows{padding:15px}
        .price-line{display:flex;justify-content:space-between;padding:8px 0;font-size:14px}
        .price-line-label{color:#94a3b8}
        .price-line-value{font-weight:600;color:#334155}
        .price-line.subtotal{border-top:1px solid #f1f5f9;margin-top:8px;padding-top:12px;font-weight:600}
        .rot-section{background:#ecfdf5;padding:12px 15px;border-top:1px solid #bbf7d0}
        .rot-line{display:flex;justify-content:space-between;color:#10b981;font-weight:600;font-size:14px}
        .total-section{background:#024550;color:#fff;padding:15px}
        .total-line{display:flex;justify-content:space-between;align-items:center}
        .total-label{font-size:15px}
        .total-value{font-size:24px;font-weight:700}
        .total-vat{font-size:11px;color:rgba(255,255,255,.5);text-align:right;margin-top:3px}
        .rot-info{background:#fffbeb;border-top:1px solid #fde68a;padding:12px 15px;font-size:12px;color:#92400e}
        .rot-info strong{display:block;margin-bottom:2px}
        .cart-section{padding:15px;border-top:1px solid #f1f5f9}
        .qty-row{display:flex;align-items:center;gap:12px;margin-bottom:12px}
        .qty-label{font-weight:600;font-size:13px;color:#334155}
        .qty-controls{display:flex;border:1px solid #e5e7eb;border-radius:8px;overflow:hidden}
        .qty-btn{width:36px;height:36px;border:none;background:#f8f9fa;font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background .15s;color:#334155}
        .qty-btn:hover{background:#e2e8f0}
        .qty-input{width:45px;height:36px;border:none;border-left:1px solid #e5e7eb;border-right:1px solid #e5e7eb;text-align:center;font-size:15px;font-weight:600;font-family:'Inter',sans-serif}
        .qty-input:focus{outline:none}
        .cart-btn{width:100%;background:#024550;color:#fff;border:none;border-radius:10px;padding:14px;font-size:14px;font-weight:600;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;transition:all .15s;font-family:'Inter',sans-serif}
        .cart-btn:hover{background:#244a36}
        .validation-msg{background:#ef4444;color:#fff;padding:10px 15px;border-radius:8px;margin-bottom:12px;display:none;align-items:center;gap:8px;font-size:13px}
        .validation-msg.show{display:flex}

        /* Modal */
        .modal-overlay{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);z-index:200;justify-content:center;align-items:center;padding:20px}
        .modal-overlay.active{display:flex}
        .modal{background:#fff;border-radius:16px;width:900px;max-width:95%;height:800px;max-height:90vh;overflow-y:auto;box-shadow:0 24px 80px rgba(0,0,0,.2);display:flex;flex-direction:column}
        .modal-header{background:#024550;color:#fff;padding:18px 22px;display:flex;justify-content:space-between;align-items:center}
        .modal-header h2{font-size:17px;font-weight:600}
        .modal-close{background:none;border:none;color:#fff;font-size:26px;cursor:pointer;opacity:.8}
        .modal-close:hover{opacity:1}
        .modal-body{padding:20px;flex:1;overflow-y:auto}
        .modal-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px}
        .modal-section{margin-bottom:20px}
        .modal-section:last-child{margin-bottom:0}
        .modal-section-title{font-size:12px;font-weight:600;color:#94a3b8;text-transform:uppercase;letter-spacing:.5px;margin-bottom:10px;padding-bottom:6px;border-bottom:1px solid #f1f5f9}
        .modal-product{display:flex;gap:12px;align-items:center}
        .modal-product-image{width:70px;height:70px;border-radius:8px;object-fit:cover;border:1px solid #e5e7eb}
        .modal-product-info h3{font-size:15px;font-weight:600;margin-bottom:3px}
        .modal-product-info p{color:#94a3b8;font-size:13px}
        .modal-cart{background:#f8f9fa;border-radius:8px;overflow:hidden}
        .modal-cart-item{display:flex;justify-content:space-between;align-items:center;padding:10px 12px;border-bottom:1px solid #e5e7eb;font-size:13px}
        .modal-cart-item:last-child{border-bottom:none}
        .modal-cart-item-name{color:#334155;font-weight:500;flex:0 0 auto}
        .modal-cart-item-value{color:#94a3b8;flex:1;text-align:center;padding:0 8px}
        .modal-cart-item-price{font-weight:600;min-width:70px;text-align:right}
        .modal-cart-item-price.has-price{color:#10b981}
        .modal-price-summary{background:#f8f9fa;border-radius:8px;padding:12px}
        .modal-price-row{display:flex;justify-content:space-between;padding:5px 0;font-size:13px}
        .modal-price-row.rot{color:#10b981;font-weight:500}
        .modal-price-row.total{border-top:2px solid #e5e7eb;margin-top:8px;padding-top:10px;font-size:16px;font-weight:700}
        .modal-form{display:grid;gap:12px}
        .modal-form-row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
        .modal-form-group{display:flex;flex-direction:column}
        .modal-form-group.full{grid-column:1/-1}
        .modal-form-group label{font-size:12px;font-weight:500;color:#64748b;margin-bottom:4px}
        .modal-form-group input,.modal-form-group textarea{padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:'Inter',sans-serif;transition:all .15s}
        .modal-form-group input:focus,.modal-form-group textarea:focus{outline:none;border-color:#2ecc71;box-shadow:0 0 0 3px rgba(46,204,113,.1)}
        .modal-form-group textarea{resize:vertical;min-height:60px}
        .modal-submit{width:100%;padding:14px;background:#024550;color:#fff;border:none;border-radius:10px;font-size:14px;font-weight:600;cursor:pointer;margin-top:8px;transition:all .15s;font-family:'Inter',sans-serif}
        .modal-submit:hover{background:#244a36}

        /* === KUNDER MAP === */
        .kunder-map-wrap{background:#fff;border-radius:12px;border:1px solid #e5e7eb;overflow:hidden;margin-bottom:16px}
        .kunder-map{height:380px;width:100%}
        .kunder-map .leaflet-control-attribution{font-size:10px}
        .kunder-filters{display:flex;align-items:center;gap:10px;padding:14px 20px;background:#fff;border-radius:12px;border:1px solid #e5e7eb;margin-bottom:16px;flex-wrap:wrap}
        .kunder-filters-label{font-size:13px;font-weight:600;color:#64748b;margin-right:4px}
        .filter-chip{display:flex;align-items:center;gap:6px;padding:6px 14px;border-radius:20px;font-size:12px;font-weight:600;cursor:pointer;border:2px solid #e5e7eb;background:#fff;transition:all .15s;font-family:'Inter',sans-serif;color:#334155}
        .filter-chip:hover{background:#f8f9fa}
        .filter-chip.active{border-color:currentColor;background:rgba(0,0,0,.03)}
        .filter-chip .dot{width:10px;height:10px;border-radius:50%;flex-shrink:0}
        .filter-chip.f-order .dot{background:#16a34a}
        .filter-chip.f-order.active{border-color:#16a34a;color:#16a34a}
        .filter-chip.f-offert .dot{background:#eab308}
        .filter-chip.f-offert.active{border-color:#eab308;color:#854d0e}
        .filter-chip.f-lost .dot{background:#ef4444}
        .filter-chip.f-lost.active{border-color:#ef4444;color:#ef4444}
        .filter-chip.f-lead .dot{background:#94a3b8}
        .filter-chip.f-lead.active{border-color:#94a3b8;color:#64748b}
        .filter-chip .count{background:rgba(0,0,0,.06);padding:1px 7px;border-radius:10px;font-size:11px;margin-left:2px}
        .kunder-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px}
        .kunder-stat{background:#fff;border-radius:10px;padding:14px 16px;border:1px solid #e5e7eb;display:flex;align-items:center;gap:12px}
        .kunder-stat .ks-dot{width:12px;height:12px;border-radius:50%;flex-shrink:0}
        .kunder-stat .ks-info{flex:1}
        .kunder-stat .ks-info h4{font-size:11px;color:#94a3b8;font-weight:500;text-transform:uppercase;letter-spacing:.3px}
        .kunder-stat .ks-info .ks-val{font-size:22px;font-weight:700;color:#1a1a1a}
        .kunder-stat .ks-info .ks-sum{font-size:12px;color:#64748b;margin-top:1px}
        .kunder-search{display:flex;gap:10px;margin-bottom:0}
        .kunder-search input{flex:1;padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:'Inter',sans-serif}
        .kunder-search input:focus{outline:none;border-color:#2ecc71;box-shadow:0 0 0 3px rgba(46,204,113,.1)}
        .map-marker-order{background:#16a34a;border:2px solid #fff;border-radius:50%;width:14px;height:14px;box-shadow:0 1px 4px rgba(0,0,0,.3)}
        .sidebar-section-label{padding:20px 22px 6px;font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:1px;color:rgba(255,255,255,.25)}
        .sidebar-divider{height:1px;background:rgba(255,255,255,.08);margin:8px 18px 4px}

        /* === KALENDER === */
        .cal-wrap{background:#fff;border-radius:12px;border:1px solid #e5e7eb;overflow:hidden;margin-bottom:20px}
        .cal-header{display:flex;justify-content:space-between;align-items:center;padding:16px 20px;border-bottom:1px solid #f1f5f9}
        .cal-header h3{font-size:16px;font-weight:600;color:#1a1a1a}
        .cal-nav{display:flex;gap:6px}
        .cal-nav button{width:32px;height:32px;border:1px solid #e5e7eb;border-radius:8px;background:#fff;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:14px;color:#64748b;transition:all .15s}
        .cal-nav button:hover{background:#f8f9fa;border-color:#94a3b8}
        .cal-grid{display:grid;grid-template-columns:repeat(7,1fr);text-align:center;padding:12px 16px 16px}
        .cal-day-header{font-size:11px;font-weight:600;color:#94a3b8;padding:4px 0 8px;text-transform:uppercase}
        .cal-day{padding:8px 4px;font-size:13px;color:#334155;border-radius:8px;cursor:pointer;transition:all .15s;position:relative}
        .cal-day:hover{background:#f1f5f9}
        .cal-day.today{background:#024550;color:#fff;font-weight:600}
        .cal-day.has-event::after{content:'';position:absolute;bottom:3px;left:50%;transform:translateX(-50%);width:5px;height:5px;background:#eab308;border-radius:50%}
        .cal-day.other-month{color:#d1d5db}
        .cal-events{margin-top:0}
        .cal-event-item{display:flex;align-items:center;gap:12px;padding:12px 16px;background:#fff;border-radius:10px;border:1px solid #e5e7eb;margin-bottom:8px;transition:all .15s}
        .cal-event-item:hover{box-shadow:0 2px 8px rgba(0,0,0,.05)}
        .cal-event-time{font-size:12px;font-weight:600;color:#64748b;min-width:50px}
        .cal-event-info h4{font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:1px}
        .cal-event-info p{font-size:12px;color:#94a3b8}
        .cal-event-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0}

        /* === DAGRAPPORT === */
        .dr-summary{display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin-bottom:20px}
        .dr-card{background:#fff;border-radius:12px;padding:18px 20px;border:1px solid #e5e7eb}
        .dr-card h4{font-size:12px;color:#94a3b8;font-weight:500;margin-bottom:6px;text-transform:uppercase;letter-spacing:.3px}
        .dr-card .dr-val{font-size:24px;font-weight:700;color:#1a1a1a}
        .dr-card .dr-sub{font-size:12px;color:#64748b;margin-top:2px}
        .dr-form{background:#fff;border-radius:12px;border:1px solid #e5e7eb;padding:24px;margin-bottom:20px}
        .dr-form h3{font-size:16px;font-weight:600;color:#1a1a1a;margin-bottom:16px}
        .dr-form-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
        .dr-form-group{display:flex;flex-direction:column}
        .dr-form-group.full{grid-column:1/-1}
        .dr-form-group label{font-size:12px;font-weight:500;color:#64748b;margin-bottom:5px}
        .dr-form-group input,.dr-form-group textarea,.dr-form-group select{padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:'Inter',sans-serif;transition:all .15s}
        .dr-form-group input:focus,.dr-form-group textarea:focus,.dr-form-group select:focus{outline:none;border-color:#2ecc71;box-shadow:0 0 0 3px rgba(46,204,113,.1)}
        .dr-form-group textarea{resize:vertical;min-height:80px}
        .dr-log-item{display:flex;gap:14px;padding:16px 20px;background:#fff;border-radius:10px;border:1px solid #e5e7eb;margin-bottom:8px}
        .dr-log-date{font-size:12px;font-weight:600;color:#64748b;min-width:80px}
        .dr-log-info{flex:1}
        .dr-log-info h4{font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:3px}
        .dr-log-info p{font-size:13px;color:#64748b;line-height:1.5}
        .dr-log-tag{font-size:11px;padding:3px 10px;border-radius:12px;font-weight:600}

        /* === MIN LÖN === */
        .lon-overview{display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px;margin-bottom:20px}
        .lon-card{background:#fff;border-radius:12px;padding:20px;border:1px solid #e5e7eb}
        .lon-card.highlight{background:#024550;border-color:#024550}
        .lon-card.highlight h4{color:rgba(255,255,255,.6)}
        .lon-card.highlight .lon-val{color:#fff}
        .lon-card.highlight .lon-sub{color:rgba(255,255,255,.4)}
        .lon-card h4{font-size:12px;color:#94a3b8;font-weight:500;margin-bottom:6px;text-transform:uppercase;letter-spacing:.3px}
        .lon-card .lon-val{font-size:26px;font-weight:700;color:#1a1a1a}
        .lon-card .lon-sub{font-size:12px;color:#64748b;margin-top:3px}
        .lon-breakdown{background:#fff;border-radius:12px;border:1px solid #e5e7eb;overflow:hidden;margin-bottom:20px}
        .lon-breakdown-header{padding:16px 20px;font-weight:600;font-size:15px;color:#1a1a1a;border-bottom:1px solid #f1f5f9;display:flex;align-items:center;gap:10px}
        .lon-row{display:flex;justify-content:space-between;align-items:center;padding:12px 20px;border-bottom:1px solid #f1f5f9;font-size:14px}
        .lon-row:last-child{border-bottom:none}
        .lon-row-label{color:#64748b}
        .lon-row-val{font-weight:600;color:#1a1a1a}
        .lon-row.total{background:#f8f9fa;font-weight:700}
        .lon-row.total .lon-row-label{color:#1a1a1a}
        .lon-row.total .lon-row-val{color:#10b981;font-size:16px}
        .lon-row.deduction .lon-row-val{color:#ef4444}
        /* === EVA AI CHAT (compact) === */
        .eko-layout{display:grid;grid-template-columns:1fr 340px;gap:20px;align-items:start}
        .eko-main{display:flex;flex-direction:column;gap:16px}
        .eko-tabs{display:flex;gap:4px;background:#fff;border-radius:10px;padding:4px;border:1px solid #e5e7eb;margin-bottom:4px}
        .eko-tab{padding:9px 16px;border-radius:8px;font-size:13px;font-weight:500;color:#64748b;cursor:pointer;border:none;background:none;font-family:'Inter',sans-serif;transition:all .15s}
        .eko-tab:hover{color:#334155;background:#f8f9fa}
        .eko-tab.active{background:#024550;color:#fff;font-weight:600}
        .eko-panel{display:none}
        .eko-panel.active{display:block}
        .eva-chat-wrap{background:#fff;border-radius:12px;border:1px solid #e5e7eb;display:flex;flex-direction:column;overflow:hidden;height:520px;position:sticky;top:20px}
        .eva-chat-header{display:flex;align-items:center;gap:10px;padding:12px 16px;border-bottom:1px solid #f1f5f9;background:#fff}
        .eva-avatar{width:34px;height:34px;border-radius:50%;object-fit:cover;border:2px solid #e5e7eb;flex-shrink:0}
        .eva-header-info h3{font-size:13px;font-weight:600;color:#1a1a1a;margin-bottom:0}
        .eva-header-info p{font-size:11px;color:#64748b}
        .eva-online{display:inline-block;width:7px;height:7px;background:#10b981;border-radius:50%;margin-left:4px;vertical-align:middle}
        .eva-messages{flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;gap:10px}
        .eva-messages::-webkit-scrollbar{width:3px}
        .eva-messages::-webkit-scrollbar-thumb{background:#e5e7eb;border-radius:3px}
        .eva-msg{display:flex;gap:8px;max-width:92%;animation:msgIn .3s ease}
        .eva-msg.eva{align-self:flex-start}
        .eva-msg.user{align-self:flex-end;flex-direction:row-reverse}
        .eva-msg-avatar{width:26px;height:26px;border-radius:50%;object-fit:cover;flex-shrink:0;margin-top:2px}
        .eva-msg-bubble{padding:8px 12px;border-radius:14px;font-size:12.5px;line-height:1.5;color:#1a1a1a}
        .eva-msg.eva .eva-msg-bubble{background:#f1f5f9;border-bottom-left-radius:4px}
        .eva-msg.user .eva-msg-bubble{background:#024550;color:#fff;border-bottom-right-radius:4px}
        .eva-msg-time{font-size:9px;color:#94a3b8;margin-top:2px;padding:0 4px}
        .eva-msg.user .eva-msg-time{text-align:right}
        .eva-input-wrap{display:flex;align-items:center;gap:8px;padding:10px 14px;border-top:1px solid #f1f5f9;background:#fff}
        .eva-input{flex:1;padding:8px 12px;border:1px solid #e5e7eb;border-radius:20px;font-size:12.5px;font-family:'Inter',sans-serif;resize:none;max-height:60px;line-height:1.4}
        .eva-input:focus{outline:none;border-color:#024550;box-shadow:0 0 0 2px rgba(2,69,80,.1)}
        .eva-send{width:34px;height:34px;border-radius:50%;background:#024550;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .15s;flex-shrink:0}
        .eva-send:hover{background:#035a6b}
        .eva-send:disabled{background:#94a3b8;cursor:not-allowed}
        .eva-send svg{width:15px;height:15px;stroke:#fff;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
        .eva-typing{display:flex;gap:4px;padding:8px 12px;background:#f1f5f9;border-radius:14px;border-bottom-left-radius:4px;align-self:flex-start}
        .eva-typing span{width:6px;height:6px;background:#94a3b8;border-radius:50%;animation:typingDot 1.4s infinite}
        .eva-typing span:nth-child(2){animation-delay:.2s}
        .eva-typing span:nth-child(3){animation-delay:.4s}
        @keyframes typingDot{0%,60%,100%{transform:translateY(0);opacity:.4}30%{transform:translateY(-5px);opacity:1}}
        @keyframes msgIn{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}
        .eva-suggestions{display:flex;flex-wrap:wrap;gap:5px;padding:0 14px 10px}
        .eva-suggestion{padding:5px 10px;background:#f1f5f9;border:1px solid #e5e7eb;border-radius:14px;font-size:10.5px;color:#64748b;cursor:pointer;transition:all .15s;font-family:'Inter',sans-serif}
        .eva-suggestion:hover{background:#e2e8f0;color:#334155;border-color:#94a3b8}

        .lon-month-select{padding:8px 30px 8px 12px;border:1px solid #e5e7eb;border-radius:8px;font-size:13px;font-weight:500;font-family:'Inter',sans-serif;appearance:none;background:#fff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23334155'%3E%3Cpath d='M7 10l5 5 5-5z'/%3E%3C/svg%3E") no-repeat right 8px center/16px;cursor:pointer}
        .map-marker-offert{background:#eab308;border:2px solid #fff;border-radius:50%;width:14px;height:14px;box-shadow:0 1px 4px rgba(0,0,0,.3)}
        .map-marker-lost{background:#ef4444;border:2px solid #fff;border-radius:50%;width:14px;height:14px;box-shadow:0 1px 4px rgba(0,0,0,.3)}
        .map-marker-lead{background:#94a3b8;border:2px solid #fff;border-radius:50%;width:14px;height:14px;box-shadow:0 1px 4px rgba(0,0,0,.3)}

        @media(max-width:1100px){.config-layout{grid-template-columns:1fr}.config-sidebar{position:static}.stat-grid{grid-template-columns:repeat(2,1fr)}}
        @media(max-width:900px){.sidebar{display:none}.main-wrapper{margin-left:0}}
        /* === TOP SELLERS === */
        .top-sellers-list{padding:0}
        .top-seller-item{display:flex;align-items:center;gap:14px;padding:14px 22px;border-bottom:1px solid #f1f5f9;transition:background .15s}
        .top-seller-item:last-child{border-bottom:none}
        .top-seller-item:hover{background:#fafbfc}
        .top-seller-medal{width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:16px;font-weight:700;flex-shrink:0}
        .medal-gold{background:linear-gradient(135deg,#fbbf24,#f59e0b);color:#78350f}
        .medal-silver{background:linear-gradient(135deg,#d1d5db,#9ca3af);color:#374151}
        .medal-bronze{background:linear-gradient(135deg,#d97706,#b45309);color:#fff}
        .top-seller-info{flex:1;min-width:0}
        .top-seller-name{font-size:14px;font-weight:600;color:#1a1a1a}
        .top-seller-detail{font-size:12px;color:#94a3b8}
        .top-seller-amount{text-align:right;font-size:15px;font-weight:700;color:#10b981}
        /* === DASHBOARD CHARTS === */
        .dash-charts{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-top:20px}
        .dash-chart-panel{background:#fff;border-radius:12px;border:1px solid #e5e7eb;overflow:hidden}
        .dash-chart-panel .dash-panel-header{padding:18px 22px;display:flex;align-items:center;gap:10px;border-bottom:1px solid #f1f5f9}
        .dash-chart-panel .dash-panel-header svg{width:18px;height:18px;stroke:#64748b;fill:none;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
        .dash-chart-panel .dash-panel-header h3{font-size:16px;font-weight:600;color:#1a1a1a}
        .dash-chart-body{padding:20px}
        .dash-chart-body canvas{max-height:250px}
        /* === FÄLTSÄLJ === */
        .falt-layout{display:grid;grid-template-columns:1fr 360px;gap:20px;align-items:start}
        .falt-left{display:flex;flex-direction:column;gap:20px;min-width:0}
        .falt-map{height:500px;width:100%;border-radius:12px;border:1px solid #e5e7eb;overflow:hidden}
        .falt-stats{display:grid;grid-template-columns:repeat(5,1fr);gap:10px;margin-bottom:16px}
        .falt-stat{background:#fff;border-radius:10px;border:1px solid #e5e7eb;padding:12px 14px;text-align:center}
        .falt-stat h4{font-size:10px;font-weight:600;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px}
        .falt-stat .fval{font-size:22px;font-weight:700;color:#1a1a1a}
        .falt-stat .fsub{font-size:11px;color:#94a3b8;margin-top:2px}
        .falt-sidebar{background:#fff;border-radius:12px;border:1px solid #e5e7eb;overflow:hidden}
        .falt-sidebar-header{padding:16px 18px;border-bottom:1px solid #f1f5f9;font-size:15px;font-weight:600;color:#1a1a1a}
        .falt-list{max-height:450px;overflow-y:auto}
        .falt-list::-webkit-scrollbar{width:4px}
        .falt-list::-webkit-scrollbar-thumb{background:#e5e7eb;border-radius:4px}
        .falt-item{display:flex;align-items:center;gap:12px;padding:10px 18px;border-bottom:1px solid #f8f9fa;cursor:pointer;transition:background .15s}
        .falt-item:hover{background:#fafbfc}
        .falt-item-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0}
        .falt-item-info{flex:1;min-width:0}
        .falt-item-addr{font-size:13px;font-weight:500;color:#1a1a1a;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
        .falt-item-detail{font-size:11px;color:#94a3b8}
        .falt-item-status{font-size:11px;font-weight:600;padding:3px 8px;border-radius:10px;flex-shrink:0}
        .falt-popup-btns{display:flex;gap:4px;margin-top:8px;flex-wrap:wrap}
        .falt-popup-btn{padding:4px 10px;border:none;border-radius:6px;font-size:11px;font-weight:600;cursor:pointer;font-family:'Inter',sans-serif;transition:all .15s}
        .falt-popup-btn:hover{opacity:.85}
        .falt-kalkyler{overflow-x:auto}
        .falt-kalkyler-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}
        .falt-kalkyler-header h3{font-size:16px;font-weight:700;color:#1a1a1a}
        .falt-kalkyler-header .fk-count{font-size:13px;color:#94a3b8;font-weight:400}
        .falt-kalkyler table{width:100%;border-collapse:collapse;background:#fff;border-radius:12px;overflow:hidden;border:1px solid #e5e7eb}
        .falt-kalkyler thead th{background:#f8f9fa;font-size:11px;font-weight:600;color:#64748b;text-transform:uppercase;letter-spacing:.5px;padding:8px 10px;text-align:left;border-bottom:1px solid #e5e7eb;white-space:nowrap}
        .falt-kalkyler tbody td{padding:8px 10px;font-size:12px;color:#1a1a1a;border-bottom:1px solid #f1f5f9;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
        .falt-kalkyler tbody td.addr-cell{max-width:180px}
        .falt-kalkyler tbody tr:hover{background:#fafbfc}
        .fk-badge{font-size:11px;font-weight:600;padding:3px 10px;border-radius:10px;display:inline-block}
        .fk-badge.ny{background:#e0f2fe;color:#0284c7}
        .fk-badge.skickad{background:#fef3c7;color:#b45309}
        .fk-badge.godkand{background:#dcfce7;color:#15803d}
        .fk-badge.forlorad{background:#fee2e2;color:#dc2626}
        .fk-action{padding:4px 12px;border:1px solid #e5e7eb;border-radius:6px;font-size:11px;font-weight:500;cursor:pointer;background:#fff;font-family:'Inter',sans-serif;transition:all .15s;color:#1a1a1a}
        .fk-action:hover{background:#f1f5f9;border-color:#cbd5e1}
        /* === PRODUCT CATALOG === */
        .catalog-header{display:flex;align-items:center;gap:15px;margin-bottom:20px;flex-wrap:wrap}
        .catalog-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}
        .catalog-card{background:#fff;border-radius:12px;border:1px solid #e5e7eb;overflow:hidden;transition:all .2s;cursor:pointer}
        .catalog-card:hover{box-shadow:0 4px 16px rgba(0,0,0,.08);transform:translateY(-2px)}
        .catalog-card-img{width:100%;aspect-ratio:4/3;background:#f8f9fa;display:flex;align-items:center;justify-content:center;overflow:hidden}
        .catalog-card-img img{width:100%;height:100%;object-fit:cover}
        .catalog-card-img svg{width:48px;height:48px;stroke:#cbd5e1;fill:none;stroke-width:1.2}
        .catalog-card-body{padding:14px 16px}
        .catalog-card-cat{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:#64748b;margin-bottom:4px}
        .catalog-card-name{font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:6px;line-height:1.3}
        .catalog-card-desc{font-size:12px;color:#94a3b8;margin-bottom:8px;line-height:1.4}
        .catalog-card-footer{display:flex;justify-content:space-between;align-items:center}
        .catalog-card-price{font-size:16px;font-weight:700;color:#024550}
        .catalog-card-badge{padding:3px 8px;border-radius:12px;font-size:10px;font-weight:600}
        @media(max-width:768px){
            .product-section{grid-template-columns:1fr;gap:20px}.option-choices{grid-template-columns:repeat(2,1fr)}.modal-grid{grid-template-columns:1fr}.stat-grid{grid-template-columns:1fr}.dash-grid{grid-template-columns:1fr}.dash-charts{grid-template-columns:1fr}.catalog-grid{grid-template-columns:repeat(2,1fr)}.kunder-stats{grid-template-columns:repeat(2,1fr)}.kunder-map{height:250px}
            .main-wrapper{padding:16px 10px;margin-left:0 !important}
            /* FältSälj mobil */
            .falt-layout{grid-template-columns:1fr !important;gap:12px}
            .falt-map{height:50vh !important;border-radius:10px}
            .falt-stats{grid-template-columns:repeat(3,1fr) !important;gap:6px}
            .falt-stat{padding:8px 6px}
            .falt-stat .fval{font-size:18px}
            .falt-stat h4{font-size:9px}
            .falt-sidebar{border-radius:10px}
            .falt-list{max-height:300px !important}
            .falt-kalkyler{overflow-x:auto}
            .falt-left{gap:12px}
            .falt-kalkyler table{min-width:500px;font-size:11px}
            .page-title{font-size:20px}
            .page-subtitle{font-size:12px;margin-bottom:12px}
            /* Mobil bottom nav */
            .mobile-nav{display:flex !important}
            body{padding-bottom:60px}
        }
        .mobile-nav{display:none;position:fixed;bottom:0;left:0;right:0;background:#024550;z-index:200;justify-content:space-around;padding:6px 0 env(safe-area-inset-bottom,6px);box-shadow:0 -2px 12px rgba(0,0,0,.15)}
        .mobile-nav a{display:flex;flex-direction:column;align-items:center;gap:2px;color:rgba(255,255,255,.5);text-decoration:none;font-size:10px;font-weight:500;padding:4px 8px;transition:color .15s}
        .mobile-nav a.active{color:#fff}
        .mobile-nav a svg{width:20px;height:20px;stroke:currentColor;fill:none;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
    </style>
</head>
<body>
    <!-- LOGIN SCREEN -->
    <div class="login-screen" id="loginScreen">
        <div class="login-image">
            <div class="login-image-text">
                <h2 id="loginGreetingBig" style="font-size:44px;font-weight:700;margin-bottom:16px">God morgon</h2>
                <p id="loginQuote" style="font-size:18px;opacity:.9;font-style:italic;max-width:480px;line-height:1.6"></p>
            </div>
        </div>
        <div class="login-panel">
            <div class="login-logo">
                <img src="https://www.solargroup.se/wp-content/uploads/2024/02/Solar_Energy_Group_26_-removebg-preview.png" alt="Solar Energy Group">
            </div>
            <h1 class="login-greeting" id="loginGreeting" style="font-size:22px">Välkommen tillbaka</h1>
            <p class="login-subtitle">Logga in för att fortsätta</p>
            <form onsubmit="doLogin(event)">
                <div class="login-form-group">
                    <label>E-postadress</label>
                    <input type="text" id="loginEmail" placeholder="namn@solargroup.se eller admin" autocomplete="email">
                </div>
                <div class="login-form-group">
                    <label>Lösenord</label>
                    <input type="password" id="loginPassword" placeholder="Ange lösenord" autocomplete="current-password">
                </div>
                <div class="login-remember">
                    <label><input type="checkbox" checked> Kom ihåg mig</label>
                    <a href="#" class="login-forgot" onclick="alert('En återställningslänk har skickats till din e-post.\n\n(DEMO)');return false">Glömt lösenord?</a>
                </div>
                <button type="submit" class="login-btn">Logga in</button>
            </form>
            <div style="display:flex;align-items:center;gap:12px;margin:20px 0">
                <div style="flex:1;height:1px;background:#e5e7eb"></div>
                <span style="font-size:12px;color:#94a3b8;font-weight:500">eller</span>
                <div style="flex:1;height:1px;background:#e5e7eb"></div>
            </div>
            <button onclick="googleLoginFromScreen()" style="width:100%;padding:12px 20px;background:#fff;border:1.5px solid #e5e7eb;border-radius:10px;font-size:15px;font-weight:600;cursor:pointer;font-family:inherit;color:#1a1a1a;display:flex;align-items:center;justify-content:center;gap:10px;transition:all .2s" onmouseover="this.style.background='#f8fafc';this.style.borderColor='#024550'" onmouseout="this.style.background='#fff';this.style.borderColor='#e5e7eb'">
                <svg width="20" height="20" viewBox="0 0 24 24"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>
                Logga in med Google
            </button>
            <div id="loginError" style="display:none;background:#fef2f2;border:1px solid #fecaca;color:#dc2626;padding:10px 14px;border-radius:8px;font-size:13px;margin-top:12px;text-align:center"></div>
            <div id="loginPending" style="display:none;background:#fffbeb;border:1px solid #fde68a;color:#92400e;padding:10px 14px;border-radius:8px;font-size:13px;margin-top:12px;text-align:center"></div>
            <p style="text-align:center;margin-top:16px;font-size:13px;color:#64748b">Inget konto? <a href="#" onclick="showRegisterForm();return false" style="color:#024550;font-weight:600;text-decoration:none">Skapa konto</a></p>
            <!-- Registreringsformulär (dolt) -->
            <div id="registerForm" style="display:none;margin-top:16px;padding:16px;background:#f8fafc;border-radius:12px;border:1px solid #e5e7eb">
                <h3 style="margin:0 0 12px;font-size:16px;color:#1e293b">Skapa konto</h3>
                <div class="login-form-group"><label>Namn</label><input type="text" id="regName" placeholder="Ditt namn"></div>
                <div class="login-form-group"><label>E-postadress</label><input type="email" id="regEmail" placeholder="namn@solargroup.se"></div>
                <div class="login-form-group"><label>Lösenord</label><input type="password" id="regPassword" placeholder="Minst 4 tecken"></div>
                <button onclick="doRegister()" class="login-btn" style="margin-top:8px">Skapa konto</button>
                <div id="regError" style="display:none;background:#fef2f2;border:1px solid #fecaca;color:#dc2626;padding:8px 12px;border-radius:8px;font-size:12px;margin-top:8px;text-align:center"></div>
                <div id="regSuccess" style="display:none;background:#f0fdf4;border:1px solid #bbf7d0;color:#166534;padding:8px 12px;border-radius:8px;font-size:12px;margin-top:8px;text-align:center"></div>
                <p style="text-align:center;margin-top:10px;font-size:12px;color:#64748b"><a href="#" onclick="hideRegisterForm();return false" style="color:#024550;text-decoration:none">&larr; Tillbaka till inloggning</a></p>
            </div>
            <div class="login-footer">Solar Energy Group AB &bull; Solar Sales Suite v1.0</div>
        </div>
    </div>

    <!-- SIDEBAR -->
    <nav class="sidebar" style="display:none" id="appSidebar">
        <div class="sidebar-brand">
            <div class="sidebar-brand-icon"><img src="https://www.solargroup.se/wp-content/uploads/2024/02/Solar_Energy_Group_26_-removebg-preview.png" alt="Solar Energy Group"></div>
        </div>
        <div class="sidebar-menu">
            <div class="sidebar-section-label">Försäljning</div>
            <a class="nav-item active" data-page="oversikt"><span class="nav-icon"><svg viewBox="0 0 24 24"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg></span>Dashboard</a>
            <a class="nav-item" data-page="faltsalj"><span class="nav-icon"><svg viewBox="0 0 24 24"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg></span>FältSälj</a>
            <a class="nav-item" data-page="kunder"><span class="nav-icon"><svg viewBox="0 0 24 24"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg></span>Kunder</a>
            <a class="nav-item" data-page="projektering"><span class="nav-icon"><svg viewBox="0 0 24 24"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></svg></span>Projektering</a>
            <a class="nav-item" data-page="projekt"><span class="nav-icon"><svg viewBox="0 0 24 24"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg></span>Affärer</a>
            <a class="nav-item" data-page="konfigurator"><span class="nav-icon"><svg viewBox="0 0 24 24"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></svg></span>Kalkyler</a>
            <a class="nav-item" data-page="produkter"><span class="nav-icon"><svg viewBox="0 0 24 24"><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg></span>Produktkatalog</a>

            <a class="nav-item" data-page="ekonomi"><span class="nav-icon"><svg viewBox="0 0 24 24"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg></span>Ekonomi</a>
            <a class="nav-item" data-page="bildgen"><span class="nav-icon"><svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg></span>Bildgenerering</a>
            <a class="nav-item" data-page="personal"><span class="nav-icon"><svg viewBox="0 0 24 24"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg></span>Personal</a>
            <div class="sidebar-divider"></div>
            <div class="sidebar-section-label">Mina Sidor</div>
            <a class="nav-item" data-page="kalender"><span class="nav-icon"><svg viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg></span>Kalender</a>
            <a class="nav-item" data-page="inkorg"><span class="nav-icon"><svg viewBox="0 0 24 24"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg></span>Inkorg</a>
            <a class="nav-item" data-page="dagrapport"><span class="nav-icon"><svg viewBox="0 0 24 24"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg></span>Dagrapport</a>
            <a class="nav-item" data-page="minlon"><span class="nav-icon"><svg viewBox="0 0 24 24"><rect x="1" y="4" width="22" height="16" rx="2" ry="2"/><line x1="1" y1="10" x2="23" y2="10"/></svg></span>Min Lön</a>
            <div class="sidebar-divider"></div>
            <a class="nav-item" data-page="admin" id="navAdmin" style="display:none"><span class="nav-icon"><svg viewBox="0 0 24 24"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg></span>Admin <span id="adminPendingBadge" style="display:none;background:#ef4444;color:#fff;border-radius:10px;padding:1px 7px;font-size:10px;font-weight:700;margin-left:4px"></span></a>
            <a class="nav-item" data-page="settings"><span class="nav-icon"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg></span>Inställningar</a>
        </div>
        <div class="sidebar-bottom">
            <div class="sidebar-user">
                <div class="sidebar-user-info"><span>Inloggad som</span><strong>admin@solargroup.se</strong></div>
            </div>
            <button class="sidebar-logout"><svg viewBox="0 0 24 24"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>Logga ut</button>
        </div>
    </nav>

    <!-- MAIN -->
    <main class="main-wrapper" style="display:none" id="appMain">

        <!-- DASHBOARD -->
        <div class="page-content active" id="page-oversikt">
            <h1 class="page-title">Dashboard</h1>
            <p class="page-subtitle">Översikt över din försäljning och aktiviteter</p>
            <div class="stat-grid">
                <div class="stat-card">
                    <div class="stat-card-info"><h4>Totalt Värde</h4><div class="stat-value">248 500 kr</div></div>
                    <div class="stat-card-icon green"><svg viewBox="0 0 24 24"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg></div>
                </div>
                <div class="stat-card">
                    <div class="stat-card-info"><h4>Pågående Offerter</h4><div class="stat-value">12</div></div>
                    <div class="stat-card-icon blue"><svg viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg></div>
                </div>
                <div class="stat-card">
                    <div class="stat-card-info"><h4>Kunder</h4><div class="stat-value">47</div></div>
                    <div class="stat-card-icon purple"><svg viewBox="0 0 24 24"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg></div>
                </div>
                <div class="stat-card">
                    <div class="stat-card-info"><h4>Accepterade</h4><div class="stat-value">8</div></div>
                    <div class="stat-card-icon teal"><svg viewBox="0 0 24 24"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg></div>
                </div>
            </div>
            <div class="dash-grid" style="grid-template-columns:1fr 1fr 1fr">
                <div class="dash-panel">
                    <div class="dash-panel-header">
                        <svg viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                        <h3>Kommande Möten</h3>
                    </div>
                    <div class="dash-panel-body">
                        <div class="offert-item">
                            <div class="offert-item-left"><h4>Andersson Bygg AB</h4><p>Inmätning &bull; Kungsholmen 14</p></div>
                            <div class="offert-item-right"><div class="offert-price" style="color:#024550">09:00</div><div class="offert-status">idag</div></div>
                        </div>
                        <div class="offert-item">
                            <div class="offert-item-left"><h4>Svensson Fastigheter</h4><p>Offertpresentation &bull; Teams</p></div>
                            <div class="offert-item-right"><div class="offert-price" style="color:#024550">13:30</div><div class="offert-status">idag</div></div>
                        </div>
                        <div class="offert-item">
                            <div class="offert-item-left"><h4>Berg Fastigheter AB</h4><p>Besiktning &bull; Södermalm 8</p></div>
                            <div class="offert-item-right"><div class="offert-price" style="color:#024550">10:00</div><div class="offert-status">imorgon</div></div>
                        </div>
                        <div class="offert-item">
                            <div class="offert-item-left"><h4>Karlsson Entreprenad</h4><p>Kundmöte &bull; Kontoret</p></div>
                            <div class="offert-item-right"><div class="offert-price" style="color:#024550">14:00</div><div class="offert-status">tor 20/2</div></div>
                        </div>
                    </div>
                </div>
                <div class="dash-panel">
                    <div class="dash-panel-header">
                        <svg viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                        <h3>Senaste Offerter</h3>
                    </div>
                    <div class="dash-panel-body">
                        <div class="offert-item">
                            <div class="offert-item-left"><h4>Andersson Bygg AB</h4><p>Fönster 2-luft &bull; 2026-02-15</p></div>
                            <div class="offert-item-right"><div class="offert-price">80 250 kr</div><div class="offert-status">Utkast</div></div>
                        </div>
                        <div class="offert-item">
                            <div class="offert-item-left"><h4>Svensson Fastigheter</h4><p>Balkongdörr &bull; 2026-02-12</p></div>
                            <div class="offert-item-right"><div class="offert-price">269 718,75 kr</div><div class="offert-status">Utkast</div></div>
                        </div>
                        <div class="offert-item">
                            <div class="offert-item-left"><h4>Johansson & Co</h4><p>Kontorsfönster &bull; 2026-02-10</p></div>
                            <div class="offert-item-right"><div class="offert-price">87 187,50 kr</div><div class="offert-status">Skickad</div></div>
                        </div>
                        <div class="offert-item">
                            <div class="offert-item-left"><h4>Nilsson Renovering</h4><p>Fönster + dörr &bull; 2026-02-08</p></div>
                            <div class="offert-item-right"><div class="offert-price">92 718,75 kr</div><div class="offert-status">Godkänd</div></div>
                        </div>
                    </div>
                </div>
                <div class="dash-panel">
                    <div class="dash-panel-header">
                        <svg viewBox="0 0 24 24"><path d="M6 9l6-6 6 6"/><path d="M12 3v14"/><circle cx="6" cy="20" r="1"/><circle cx="12" cy="20" r="1"/><circle cx="18" cy="20" r="1"/></svg>
                        <h3>Top Säljare</h3>
                    </div>
                    <div class="dash-panel-body top-sellers-list">
                        <div class="top-seller-item">
                            <div class="top-seller-medal medal-gold">1</div>
                            <div class="top-seller-info"><div class="top-seller-name">Erik Lindström</div><div class="top-seller-detail">14 order &bull; 92% hitrate</div></div>
                            <div class="top-seller-amount">1 245 000 kr</div>
                        </div>
                        <div class="top-seller-item">
                            <div class="top-seller-medal medal-silver">2</div>
                            <div class="top-seller-info"><div class="top-seller-name">Anna Bergman</div><div class="top-seller-detail">11 order &bull; 85% hitrate</div></div>
                            <div class="top-seller-amount">985 400 kr</div>
                        </div>
                        <div class="top-seller-item">
                            <div class="top-seller-medal medal-bronze">3</div>
                            <div class="top-seller-info"><div class="top-seller-name">Marcus Holm</div><div class="top-seller-detail">9 order &bull; 78% hitrate</div></div>
                            <div class="top-seller-amount">742 800 kr</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="dash-charts">
                <div class="dash-chart-panel">
                    <div class="dash-panel-header">
                        <svg viewBox="0 0 24 24"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>
                        <h3>Försäljning Februari 2026</h3>
                    </div>
                    <div class="dash-chart-body"><canvas id="chartMonthly"></canvas></div>
                </div>
                <div class="dash-chart-panel">
                    <div class="dash-panel-header">
                        <svg viewBox="0 0 24 24"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
                        <h3>Helårsöversikt 2026</h3>
                    </div>
                    <div class="dash-chart-body"><canvas id="chartYearly"></canvas></div>
                </div>
            </div>
        </div>

        <!-- FÄLTSÄLJ -->
        <div class="page-content" id="page-faltsalj">
            <h1 class="page-title">FältSälj</h1>
            <p class="page-subtitle">Sök adress, se solpotential och prospektera</p>

            <!-- Adresssökning -->
            <div style="display:flex;gap:12px;margin-bottom:16px;align-items:center">
                <div style="flex:1;position:relative" id="faltSearchWrap">
                    <input type="text" id="faltAddressInput" placeholder="Skriv adress..." autocomplete="off" onfocus="showAddressHistory()" style="width:100%;padding:12px 16px 12px 40px;border:1.5px solid #e5e7eb;border-radius:10px;font-size:15px;font-family:'Inter',sans-serif">
                    <svg style="position:absolute;left:12px;top:50%;transform:translateY(-50%);width:18px;height:18px;stroke:#94a3b8;fill:none;stroke-width:2" viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                    <div id="addressHistoryDropdown" style="display:none;position:absolute;top:100%;left:0;right:0;background:#fff;border:1px solid #e5e7eb;border-radius:0 0 10px 10px;box-shadow:0 8px 24px rgba(0,0,0,.12);z-index:500;max-height:260px;overflow-y:auto"></div>
                </div>
                <button class="dummy-btn" onclick="faltUseMyLocation()"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2v4m0 12v4m10-10h-4M6 12H2"/><circle cx="12" cy="12" r="3"/></svg> Min plats</button>
                <button class="dummy-btn" id="btnDrawArea" onclick="startDrawArea()" style="background:#024550;color:#fff"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/></svg> Markera område</button>
            </div>

            <!-- Stats -->
            <div class="falt-stats">
                <div class="falt-stat"><h4>Planerade</h4><div class="fval" id="faltTotal">0</div><div class="fsub">att besöka</div></div>
                <div class="falt-stat"><h4>Besökta</h4><div class="fval" id="faltVisited">0</div><div class="fsub" id="faltVisitedPct">0%</div></div>
                <div class="falt-stat"><h4>Leads</h4><div class="fval" id="faltInterested">0</div><div class="fsub" style="color:#10b981">intresserade</div></div>
                <div class="falt-stat"><h4>Avböjt</h4><div class="fval" id="faltNotInt">0</div><div class="fsub" style="color:#ef4444">ej intresserad</div></div>
                <div class="falt-stat"><h4>Återbesök</h4><div class="fval" id="faltNotHome">0</div><div class="fsub" style="color:#eab308">ej hemma</div></div>
            </div>

            <div class="falt-layout">
                <div class="falt-left">
                    <div class="falt-map" id="faltMap"></div>
                    <!-- Leads / Kalkyler (fast under kartan) -->
                    <div class="falt-kalkyler">
                        <div class="falt-kalkyler-header">
                            <h3>Leads & Kalkyler <span class="fk-count" id="fkCount"></span></h3>
                        </div>
                        <table>
                            <thead><tr><th>Status</th><th>Adress</th><th>Kund</th><th>Tel</th><th>Datum</th><th></th></tr></thead>
                            <tbody id="faltKalkylBody"></tbody>
                        </table>
                    </div>
                </div>
                <div class="falt-sidebar">
                    <!-- Fastighetsinformation vid klick -->
                    <div class="falt-sidebar-header">Fastighet</div>
                    <div id="solarDataPanel" style="padding:18px">
                        <div style="text-align:center;padding:40px 20px;color:#94a3b8;font-size:14px">
                            Klicka på ett hus på kartan eller sök adress
                        </div>
                    </div>
                    <!-- Prospektlista -->
                    <div class="falt-sidebar-header" style="border-top:1px solid #e5e7eb;display:flex;align-items:center;justify-content:space-between">
                        <span>Planerad rutt <span id="faltListCount" style="color:#94a3b8;font-weight:400;font-size:13px;margin-left:4px"></span></span>
                        <div style="display:flex;gap:4px;align-items:center">
                            <button onclick="faltListFilter='all';renderFaltList()" id="fltAll" style="padding:2px 8px;border:1px solid #e5e7eb;border-radius:6px;font-size:11px;cursor:pointer;background:#024550;color:#fff;font-family:inherit">Alla</button>
                            <button onclick="faltListFilter='unvisited';renderFaltList()" id="fltPlan" style="padding:2px 8px;border:1px solid #e5e7eb;border-radius:6px;font-size:11px;cursor:pointer;background:#fff;color:#64748b;font-family:inherit">Planerade</button>
                            <button onclick="faltListFilter='interested';renderFaltList()" id="fltLead" style="padding:2px 8px;border:1px solid #e5e7eb;border-radius:6px;font-size:11px;cursor:pointer;background:#fff;color:#64748b;font-family:inherit">Leads</button>
                            <button onclick="clearAllProspects()" style="padding:2px 8px;border:1px solid #fee2e2;border-radius:6px;font-size:11px;cursor:pointer;background:#fff;color:#ef4444;font-family:inherit" title="Rensa alla">Rensa</button>
                        </div>
                    </div>
                    <div class="falt-list" id="faltList" style="max-height:400px;overflow-y:auto"></div>
                    <!-- Ruttknappar -->
                    <div style="padding:12px;display:flex;gap:6px;border-top:1px solid #e5e7eb;flex-wrap:wrap">
                        <button onclick="showSaveRouteModal()" style="flex:1;padding:8px 10px;background:#024550;color:#fff;border:none;border-radius:8px;font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;display:flex;align-items:center;justify-content:center;gap:5px"><svg viewBox="0 0 24 24" style="width:13px;height:13px;stroke:currentColor;fill:none;stroke-width:2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>Spara</button>
                        <button onclick="showLoadRouteModal()" style="flex:1;padding:8px 10px;background:#f0f9ff;color:#1e40af;border:1px solid #bfdbfe;border-radius:8px;font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;display:flex;align-items:center;justify-content:center;gap:5px"><svg viewBox="0 0 24 24" style="width:13px;height:13px;stroke:currentColor;fill:none;stroke-width:2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>Ladda</button>
                        <button onclick="startStreetViewRoute()" style="flex:1;padding:8px 10px;background:#f5f3ff;color:#6d28d9;border:1px solid #ddd6fe;border-radius:8px;font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;display:flex;align-items:center;justify-content:center;gap:5px"><svg viewBox="0 0 24 24" style="width:13px;height:13px;fill:none;stroke:currentColor;stroke-width:2"><circle cx="12" cy="5" r="3"/><path d="M12 8v4"/><path d="M8 20l4-8 4 8"/></svg>SV-rutt</button>
                    </div>
                    <div id="currentRouteInfo" style="display:none;padding:8px 12px;background:#ecfdf5;border-top:1px solid #bbf7d0;font-size:11px;color:#166534"></div>
                </div>
            </div>

            <!-- Check-in modal -->
            <div id="checkinModal" style="display:none;position:fixed;inset:0;z-index:9000;background:rgba(0,0,0,.5);display:none;align-items:center;justify-content:center">
                <div style="background:#fff;border-radius:16px;padding:28px;width:440px;max-width:95vw;max-height:90vh;overflow-y:auto;box-shadow:0 20px 60px rgba(0,0,0,.2)">
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px">
                        <h3 style="font-size:18px;font-weight:700" id="checkinTitle">Incheckning</h3>
                        <button onclick="closeCheckin()" style="background:none;border:none;font-size:22px;cursor:pointer;color:#94a3b8">&times;</button>
                    </div>
                    <div id="checkinAddr" style="font-size:14px;color:#64748b;margin-bottom:16px"></div>

                    <!-- Snabbknapp: Ny Kalkyl -->
                    <div id="checkinStep0">
                        <button onclick="checkinDirectToKalkyl()" style="width:100%;padding:16px;background:linear-gradient(135deg,#024550,#035e6b);color:#fff;border:none;border-radius:12px;font-size:15px;font-weight:700;cursor:pointer;font-family:inherit;display:flex;align-items:center;justify-content:center;gap:10px;margin-bottom:16px;box-shadow:0 4px 12px rgba(2,69,80,.25)"><svg viewBox="0 0 24 24" style="width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg> Ny Kalkyl</button>
                    </div>

                    <!-- Steg 1: Resultat -->
                    <div id="checkinStep1">
                        <p style="font-size:14px;font-weight:600;margin-bottom:12px">Hur gick besöket?</p>
                        <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
                            <button onclick="checkinResult('interested')" style="padding:16px;border:2px solid #dcfce7;border-radius:10px;background:#f0fdf4;cursor:pointer;font-family:inherit;font-size:14px;font-weight:600;color:#166534">Intresserad</button>
                            <button onclick="checkinResult('not_interested')" style="padding:16px;border:2px solid #fee2e2;border-radius:10px;background:#fef2f2;cursor:pointer;font-family:inherit;font-size:14px;font-weight:600;color:#991b1b">Ej intresserad</button>
                            <button onclick="checkinResult('not_home')" style="padding:16px;border:2px solid #fef9c3;border-radius:10px;background:#fffbeb;cursor:pointer;font-family:inherit;font-size:14px;font-weight:600;color:#854d0e">Ej hemma</button>
                            <button onclick="checkinResult('callback')" style="padding:16px;border:2px solid #dbeafe;border-radius:10px;background:#eff6ff;cursor:pointer;font-family:inherit;font-size:14px;font-weight:600;color:#1e40af">Boka återbesök</button>
                        </div>
                    </div>

                    <!-- Steg 2: Lead-info (visas vid intresserad) -->
                    <div id="checkinStep2" style="display:none">
                        <p style="font-size:14px;font-weight:600;margin-bottom:12px;color:#10b981">Kunden är intresserad! Fyll i uppgifter:</p>
                        <div style="display:grid;gap:10px">
                            <div><label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">Kundens namn</label><input type="text" id="ciName" placeholder="Förnamn Efternamn" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit"></div>
                            <div><label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">Telefon</label><input type="tel" id="ciPhone" placeholder="070-123 45 67" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit"></div>
                            <div><label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">E-post (valfritt)</label><input type="email" id="ciEmail" placeholder="kund@email.se" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit"></div>
                            <div><label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">Intresserad av</label>
                                <select id="ciProduct" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">
                                    <option value="">Välj produkt...</option>
                                    <option value="Solceller">Solceller</option>
                                    <option value="Takbyte">Takbyte</option>
                                    <option value="Fönster">Fönster</option>
                                    <option value="Fasad">Fasadrenovering</option>
                                    <option value="Laddbox">Laddbox</option>
                                    <option value="Batteri">Batteri</option>
                                    <option value="Värmepump">Värmepump</option>
                                    <option value="Kombination">Kombination</option>
                                </select>
                            </div>
                            <div><label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">Anteckning</label><textarea id="ciNote" rows="2" placeholder="T.ex. 'Vill ha offert inom 2 veckor, gammalt tak'" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;resize:vertical"></textarea></div>
                        </div>
                        <button onclick="saveCheckinLead()" style="width:100%;margin-top:14px;padding:12px;background:#10b981;color:#fff;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit">Spara lead</button>
                    </div>

                    <!-- Steg 2b: Notering (vid ej intresserad / ej hemma) -->
                    <div id="checkinStep2b" style="display:none">
                        <div style="margin-top:12px">
                            <label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">Anteckning (valfritt)</label>
                            <textarea id="ciNoteSimple" rows="2" placeholder="T.ex. 'Hade redan solceller' eller 'Prova igen torsdag'" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;resize:vertical"></textarea>
                        </div>
                        <button onclick="saveCheckinSimple()" style="width:100%;margin-top:12px;padding:12px;background:#024550;color:#fff;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit">Spara & nästa</button>
                    </div>

                    <!-- Steg 2c: Boka återbesök med datum/tid -->
                    <div id="checkinStep2c" style="display:none">
                        <p style="font-size:14px;font-weight:600;margin-bottom:12px;color:#1e40af">Boka återbesök</p>
                        <div style="display:grid;gap:10px">
                            <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
                                <div><label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">Datum</label><input type="date" id="ciCallbackDate" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit"></div>
                                <div><label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">Tid</label><input type="time" id="ciCallbackTime" value="10:00" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit"></div>
                            </div>
                            <div><label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">Anteckning</label><textarea id="ciCallbackNote" rows="2" placeholder="T.ex. 'Ring innan', 'Prata med frun'" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;resize:vertical"></textarea></div>
                        </div>
                        <button onclick="saveCheckinCallback()" style="width:100%;margin-top:12px;padding:12px;background:#3b82f6;color:#fff;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit">Spara & lägg i kalender</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- KUNDER -->
        <div class="page-content" id="page-kunder">
            <h1 class="page-title">Kunder</h1>
            <p class="page-subtitle">Hantera dina kundrelationer</p>
            <div class="dummy-actions">
                <button class="dummy-btn">+ Ny kund</button>
                <button class="dummy-btn secondary">Exportera</button>
            </div>
            <div style="margin-bottom:16px">
                <div class="kunder-search"><input type="text" placeholder="Sök kund (namn, ort, e-post)..." id="customerSearch" oninput="filterCustomers()" style="width:100%;padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:'Inter',sans-serif;transition:all .15s"></div>
            </div>
            <div class="dummy-table">
                <div class="dummy-table-header">Kundregister <span id="customerCount" style="color:#94a3b8;font-weight:400;font-size:13px;margin-left:8px"></span></div>
                <table>
                    <thead><tr><th>Kundnr</th><th>Namn</th><th>Ort</th><th>E-post</th><th>Telefon</th><th>Status</th></tr></thead>
                    <tbody id="customerTableBody"></tbody>
                </table>
            </div>
        </div>

        <!-- PROJEKTERING -->
        <div class="page-content" id="page-projektering">
            <h1 class="page-title">Projektering</h1>
            <p class="page-subtitle">Aktiva projekteringar och inmätningar</p>
            <div class="dummy-actions">
                <button class="dummy-btn">+ Ny projektering</button>
                <button class="dummy-btn secondary">Exportera</button>
            </div>
            <div class="dummy-table">
                <div class="dummy-table-header">Projekteringsöversikt</div>
                <table>
                    <thead><tr><th>Proj.nr</th><th>Kund</th><th>Adress</th><th>Typ</th><th>Antal</th><th>Inmätning</th><th>Ritning</th><th>Status</th></tr></thead>
                    <tbody>
                        <tr><td>PEK-2026-001</td><td>Andersson Bygg AB</td><td>Kungsholmen 14, Stockholm</td><td>Fönster + dörrar</td><td>14 st</td><td><span class="status-badge green">Klar</span></td><td><span class="status-badge green">Godkänd</span></td><td><span class="status-badge green">Klar för order</span></td></tr>
                        <tr><td>PEK-2026-002</td><td>Svensson Fastigheter</td><td>Majorna 8, Göteborg</td><td>Fönster</td><td>8 st</td><td><span class="status-badge green">Klar</span></td><td><span class="status-badge green">Godkänd</span></td><td><span class="status-badge green">Klar för order</span></td></tr>
                        <tr><td>PEK-2026-003</td><td>Karlsson Entreprenad</td><td>Luthagen 22, Uppsala</td><td>Fönster</td><td>48 st</td><td><span class="status-badge green">Klar</span></td><td><span class="status-badge yellow">Under granskning</span></td><td><span class="status-badge yellow">Pågår</span></td></tr>
                        <tr><td>PEK-2026-004</td><td>Berg Fastigheter AB</td><td>Södermalm 15, Stockholm</td><td>Fönster + tak</td><td>32 st</td><td><span class="status-badge yellow">Bokad 24/2</span></td><td><span class="status-badge gray">Väntar</span></td><td><span class="status-badge yellow">Pågår</span></td></tr>
                        <tr><td>PEK-2026-005</td><td>Pettersson & Söner</td><td>Rå 7, Helsingborg</td><td>Solceller</td><td>16 paneler</td><td><span class="status-badge green">Klar</span></td><td><span class="status-badge green">Godkänd</span></td><td><span class="status-badge blue">Offert skickad</span></td></tr>
                        <tr><td>PEK-2026-006</td><td>Dahlberg Hus AB</td><td>Fröslunda 3, Eskilstuna</td><td>Tak</td><td>180 m²</td><td><span class="status-badge yellow">Bokad 26/2</span></td><td><span class="status-badge gray">Väntar</span></td><td><span class="status-badge gray">Ny</span></td></tr>
                        <tr><td>PEK-2026-007</td><td>Wallin Fastigheter</td><td>Herrhagen 11, Karlstad</td><td>Fönster</td><td>6 st</td><td><span class="status-badge green">Klar</span></td><td><span class="status-badge yellow">Under granskning</span></td><td><span class="status-badge yellow">Pågår</span></td></tr>
                        <tr><td>PEK-2026-008</td><td>Nordin Husrenovering</td><td>Brynäs 5, Gävle</td><td>Fönster + dörrar</td><td>10 st</td><td><span class="status-badge blue">Planerad v.10</span></td><td><span class="status-badge gray">Väntar</span></td><td><span class="status-badge gray">Ny</span></td></tr>
                        <tr><td>PEK-2026-009</td><td>Åkerman Fastigheter</td><td>Huskvarna 18, Jönköping</td><td>Solceller + batteri</td><td>24 paneler</td><td><span class="status-badge green">Klar</span></td><td><span class="status-badge green">Godkänd</span></td><td><span class="status-badge green">Klar för order</span></td></tr>
                        <tr><td>PEK-2026-010</td><td>Sjöberg & Co</td><td>Stenstaden 9, Sundsvall</td><td>Fönster</td><td>12 st</td><td><span class="status-badge blue">Planerad v.11</span></td><td><span class="status-badge gray">Väntar</span></td><td><span class="status-badge gray">Ny</span></td></tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- PROJEKT/AFFÄRER -->
        <div class="page-content" id="page-projekt">
            <h1 class="page-title">Affärer</h1>
            <p class="page-subtitle">Spåra projektframsteg och leveranser</p>
            <div class="kunder-stats">
                <div class="kunder-stat"><div class="ks-dot" style="background:#16a34a"></div><div class="ks-info"><h4>Order</h4><div class="ks-val" id="statOrderA">0</div><div class="ks-sum" id="sumOrderA">0 kr</div></div></div>
                <div class="kunder-stat"><div class="ks-dot" style="background:#eab308"></div><div class="ks-info"><h4>Offert</h4><div class="ks-val" id="statOffertA">0</div><div class="ks-sum" id="sumOffertA">0 kr</div></div></div>
                <div class="kunder-stat"><div class="ks-dot" style="background:#ef4444"></div><div class="ks-info"><h4>Ej order</h4><div class="ks-val" id="statLostA">0</div><div class="ks-sum" id="sumLostA">0 kr</div></div></div>
                <div class="kunder-stat"><div class="ks-dot" style="background:#94a3b8"></div><div class="ks-info"><h4>Leads</h4><div class="ks-val" id="statLeadA">0</div><div class="ks-sum" id="sumLeadA">0 kr</div></div></div>
            </div>
            <div class="kunder-map-wrap"><div class="kunder-map" id="customerMap"></div></div>
            <div class="kunder-filters" style="margin-bottom:16px">
                <span class="kunder-filters-label">Visa:</span>
                <button class="filter-chip f-order active" data-filter="order" onclick="toggleFilter(this)"><span class="dot"></span>Order <span class="count" id="countOrderA">0</span></button>
                <button class="filter-chip f-offert active" data-filter="offert" onclick="toggleFilter(this)"><span class="dot"></span>Offert <span class="count" id="countOffertA">0</span></button>
                <button class="filter-chip f-lost active" data-filter="lost" onclick="toggleFilter(this)"><span class="dot"></span>Ej order <span class="count" id="countLostA">0</span></button>
                <button class="filter-chip f-lead active" data-filter="lead" onclick="toggleFilter(this)"><span class="dot"></span>Leads <span class="count" id="countLeadA">0</span></button>
            </div>
            <div class="dummy-actions">
                <button class="dummy-btn">+ Ny affär</button>
                <button class="dummy-btn secondary">Filtrera</button>
            </div>
            <div class="dummy-table">
                <div class="dummy-table-header">Projektöversikt</div>
                <table>
                    <thead><tr><th>Projekt #</th><th>Kund</th><th>Beskrivning</th><th>Offert</th><th>Order</th><th>Inmätning</th><th>Leverans</th><th>Montering</th><th>Besiktning</th></tr></thead>
                    <tbody>
                        <tr><td>PRJ-2024-001</td><td>Andersson Bygg AB</td><td>12 st fönster + 2 balkongdörrar</td><td><span class="status-badge green">Godkänd</span></td><td><span class="status-badge green">Bekräftad</span></td><td><span class="status-badge green">Bekräftad</span></td><td><span class="status-badge green">Mottagen</span></td><td class="progress-cell"><div class="progress-bar"><div class="progress-fill" style="width:100%"></div><span class="progress-text">100%</span></div></td><td><span class="status-badge green">Godkänd</span></td></tr>
                        <tr><td>PRJ-2024-002</td><td>Svensson Fastigheter</td><td>8 st fönster villa</td><td><span class="status-badge green">Godkänd</span></td><td><span class="status-badge green">Bekräftad</span></td><td><span class="status-badge green">Bekräftad</span></td><td><span class="status-badge green">Mottagen</span></td><td class="progress-cell"><div class="progress-bar"><div class="progress-fill" style="width:75%"></div><span class="progress-text">75%</span></div></td><td><span class="status-badge gray">Väntar</span></td></tr>
                        <tr><td>PRJ-2024-003</td><td>Johansson & Co</td><td>Kontorsfönster 24 st</td><td><span class="status-badge green">Godkänd</span></td><td><span class="status-badge green">Bekräftad</span></td><td><span class="status-badge green">Bekräftad</span></td><td><span class="status-badge green">Mottagen</span></td><td class="progress-cell"><div class="progress-bar"><div class="progress-fill" style="width:30%"></div><span class="progress-text">30%</span></div></td><td><span class="status-badge gray">Väntar</span></td></tr>
                        <tr><td>PRJ-2024-004</td><td>Nilsson Renovering</td><td>6 st fönster + entredörr</td><td><span class="status-badge green">Godkänd</span></td><td><span class="status-badge green">Bekräftad</span></td><td><span class="status-badge yellow">Pågår</span></td><td><span class="status-badge blue">Packat</span></td><td class="progress-cell"><div class="progress-bar"><div class="progress-fill" style="width:0%"></div><span class="progress-text">0%</span></div></td><td><span class="status-badge gray">Väntar</span></td></tr>
                        <tr><td>PRJ-2024-005</td><td>Karlsson Entreprenad</td><td>Flerfamiljshus 48 fönster</td><td><span class="status-badge yellow">Skickad</span></td><td><span class="status-badge gray">Väntar</span></td><td><span class="status-badge gray">Väntar</span></td><td><span class="status-badge gray">Väntar</span></td><td class="progress-cell"><div class="progress-bar"><div class="progress-fill" style="width:0%"></div><span class="progress-text">0%</span></div></td><td><span class="status-badge gray">Väntar</span></td></tr>
                        <tr><td>PRJ-2024-006</td><td>Berg Fastigheter AB</td><td>BRF renovering 32 fönster</td><td><span class="status-badge purple">Utkast</span></td><td><span class="status-badge gray">Väntar</span></td><td><span class="status-badge gray">Väntar</span></td><td><span class="status-badge gray">Väntar</span></td><td class="progress-cell"><div class="progress-bar"><div class="progress-fill" style="width:0%"></div><span class="progress-text">0%</span></div></td><td><span class="status-badge gray">Väntar</span></td></tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- PRODUKTKATALOG -->
        <div class="page-content" id="page-produkter">
            <h1 class="page-title">Produktkatalog</h1>
            <p class="page-subtitle">Utforska vårt sortiment av produkter</p>
            <div class="catalog-header">
                <label class="config-label">Kategori:</label>
                <select class="product-select" id="catalogCatSelect" onchange="filterCatalog()" style="min-width:200px">
                    <option value="">Alla kategorier</option>
                    <option value="fonster">Fönster</option>
                    <option value="dorrar">Dörrar</option>
                    <option value="solceller">Solceller</option>
                    <option value="tak">Tak</option>
                    <option value="tillbehor">Tillbehör</option>
                </select>
                <label class="config-label" style="margin-left:10px">Modell:</label>
                <select class="product-select" id="catalogModelSelect" onchange="filterCatalog()" style="min-width:250px">
                    <option value="">Alla modeller</option>
                </select>
                <div style="flex:1"></div>
                <span id="catalogCount" style="font-size:13px;color:#94a3b8;margin-right:12px"></span>
                <button onclick="showAddProductModal()" style="padding:8px 16px;background:#024550;color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;display:flex;align-items:center;gap:6px"><svg viewBox="0 0 24 24" style="width:16px;height:16px;stroke:currentColor;fill:none;stroke-width:2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>Ny produkt</button>
            </div>
            <div class="catalog-grid" id="catalogGrid"></div>
        </div>

        <!-- KONFIGURATOR -->
        <div class="page-content" id="page-konfigurator">
            <!-- KALKYL-LISTA (visas först) -->
            <div id="kalkylListView">
                <h1 class="page-title">Kalkyler</h1>
                <p class="page-subtitle">Dina sparade kalkyler och offerter</p>
                <div style="display:flex;gap:10px;margin-bottom:20px;align-items:center;flex-wrap:wrap">
                    <button class="dummy-btn" onclick="showKalkylConfig()">+ Ny Kalkyl</button>
                    <select id="quotesFilterStatus" onchange="loadQuotesList()" style="padding:8px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;background:#fff">
                        <option value="">Alla statusar</option>
                        <option value="utkast">Utkast</option>
                        <option value="skickad">Skickad</option>
                        <option value="godkänd">Godkänd</option>
                        <option value="förlorad">Förlorad</option>
                    </select>
                    <input id="quotesSearch" type="text" placeholder="Sök kund/adress..." oninput="loadQuotesList()" style="padding:8px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;min-width:200px">
                </div>
                <div style="background:#fff;border:1px solid #e5e7eb;border-radius:14px;overflow:hidden">
                    <table style="width:100%;border-collapse:collapse">
                        <thead><tr style="background:#f8f9fa">
                            <th style="padding:10px 14px;text-align:left;font-size:11px;font-weight:600;color:#64748b;text-transform:uppercase;letter-spacing:.5px">Kalkyl</th>
                            <th style="padding:10px 14px;text-align:left;font-size:11px;font-weight:600;color:#64748b;text-transform:uppercase;letter-spacing:.5px">Kund</th>
                            <th style="padding:10px 14px;text-align:left;font-size:11px;font-weight:600;color:#64748b;text-transform:uppercase;letter-spacing:.5px">Produkt</th>
                            <th style="padding:10px 14px;text-align:right;font-size:11px;font-weight:600;color:#64748b;text-transform:uppercase;letter-spacing:.5px">Belopp</th>
                            <th style="padding:10px 14px;text-align:left;font-size:11px;font-weight:600;color:#64748b;text-transform:uppercase;letter-spacing:.5px">Bilder</th>
                            <th style="padding:10px 14px;text-align:left;font-size:11px;font-weight:600;color:#64748b;text-transform:uppercase;letter-spacing:.5px">Säljare</th>
                            <th style="padding:10px 14px;text-align:left;font-size:11px;font-weight:600;color:#64748b;text-transform:uppercase;letter-spacing:.5px">Datum</th>
                            <th style="padding:10px 14px;text-align:left;font-size:11px;font-weight:600;color:#64748b;text-transform:uppercase;letter-spacing:.5px">Status</th>
                            <th style="padding:10px 14px;font-size:11px"></th>
                        </tr></thead>
                        <tbody id="quotesListBody">
                            <tr><td colspan="9" style="padding:40px;text-align:center;color:#94a3b8;font-size:14px">Laddar kalkyler...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- KONFIGURATOR (dold tills man klickar Ny Kalkyl) -->
            <div id="kalkylConfigView" style="display:none">
                <div style="display:flex;align-items:center;gap:12px;margin-bottom:20px">
                    <button class="dummy-btn secondary" onclick="showKalkylList()" style="padding:8px 14px"><svg viewBox="0 0 24 24" style="width:16px;height:16px;stroke:currentColor;fill:none;stroke-width:2"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg> Tillbaka</button>
                    <div><h1 class="page-title" style="margin-bottom:0">Ny Kalkyl</h1></div>
                </div>
                <!-- Kundbanner (fylls av populateKalkylFromCustomer) -->
                <div id="kalkylCustomerBanner"></div>
                <!-- Prospektbilder (expanderbar) -->
                <div id="kalkylPhotosSection" style="background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:18px 20px;margin-bottom:20px;display:none">
                    <div style="display:flex;align-items:center;justify-content:space-between;cursor:pointer" onclick="toggleKalkylPhotos()">
                        <div style="display:flex;align-items:center;gap:8px">
                            <svg viewBox="0 0 24 24" style="width:18px;height:18px;fill:none;stroke:#f59e0b;stroke-width:2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                            <span style="font-size:14px;font-weight:700;color:#1a1a1a">Prospektbilder</span>
                            <span id="kpCount" style="font-size:12px;color:#64748b;font-weight:400;margin-left:4px"></span>
                        </div>
                        <svg id="kpChevron" viewBox="0 0 24 24" style="width:18px;height:18px;fill:none;stroke:#94a3b8;stroke-width:2;transition:transform .2s"><polyline points="6 9 12 15 18 9"/></svg>
                    </div>
                    <!-- Collapsed: thumbnails of selected images -->
                    <div id="kpThumbsCollapsed" style="margin-top:10px;display:flex;gap:8px;flex-wrap:wrap;overflow:hidden;max-height:72px"></div>
                    <!-- Expanded: full bildgenerering -->
                    <div id="kpExpanded" style="display:none;margin-top:14px">
                        <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
                            <!-- Vänster: Prospektbilder + Bildgenerering -->
                            <div>
                                <!-- Prospektbilder från fältsälj -->
                                <div id="kpProspectPhotos" style="margin-bottom:14px"></div>

                                <!-- Steg 1: Foto av huset -->
                                <div style="margin-bottom:14px">
                                    <label style="display:block;font-size:13px;font-weight:600;color:#334155;margin-bottom:6px">1. Foto av huset</label>
                                    <div style="display:flex;gap:8px">
                                        <input type="file" id="kpBgFileInput" accept="image/*" style="display:none" onchange="handleKpBgUpload(this)">
                                        <input type="file" id="kpBgCameraInput" accept="image/*" capture="environment" style="display:none" onchange="handleKpBgUpload(this)">
                                        <button onclick="document.getElementById('kpBgFileInput').click()" style="flex:1;padding:8px;border:1.5px solid #e5e7eb;border-radius:8px;background:#fafbfc;cursor:pointer;font-family:inherit;font-size:12px">Ladda upp</button>
                                        <button onclick="document.getElementById('kpBgCameraInput').click()" style="flex:1;padding:8px;border:1.5px solid #e5e7eb;border-radius:8px;background:#fafbfc;cursor:pointer;font-family:inherit;font-size:12px">Ta foto</button>
                                    </div>
                                    <div id="kpBgPreview" style="margin-top:8px;display:none;position:relative">
                                        <img id="kpBgPreviewImg" style="width:100%;height:100px;object-fit:cover;border-radius:8px">
                                        <button onclick="clearKpBgUpload()" style="position:absolute;top:4px;right:4px;background:#ef4444;color:#fff;border:none;border-radius:6px;width:24px;height:24px;cursor:pointer;font-size:12px">&#10005;</button>
                                    </div>
                                </div>

                                <!-- Steg 2: Vad vill du visa? -->
                                <div style="margin-bottom:14px">
                                    <label style="display:block;font-size:13px;font-weight:600;color:#334155;margin-bottom:6px">2. Vad vill du visa?</label>
                                    <input type="hidden" id="kpProjectType" value="">
                                    <input type="hidden" id="kpPrompt" value="">
                                    <div id="kpOptionGrid" style="display:grid;grid-template-columns:1fr 1fr;gap:6px"></div>
                                </div>

                                <!-- Steg 3: Stil -->
                                <div id="kpDetailsPanel" style="display:none;margin-bottom:14px">
                                    <label style="display:block;font-size:13px;font-weight:600;color:#334155;margin-bottom:6px">3. Välj stil</label>
                                    <div id="kpSubOptions" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:5px"></div>
                                    <div id="kpCountPanel" style="display:none;margin-top:10px">
                                        <label id="kpCountLabel" style="display:block;font-size:13px;font-weight:600;color:#334155;margin-bottom:6px">Antal paneler</label>
                                        <div id="kpCountOptions" style="display:flex;flex-wrap:wrap;gap:5px"></div>
                                    </div>
                                </div>

                                <!-- Extra detaljer -->
                                <div style="margin-bottom:10px">
                                    <label style="display:block;font-size:12px;font-weight:600;color:#334155;margin-bottom:4px">Extra detaljer (valfritt)</label>
                                    <input type="text" id="kpExtraPrompt" placeholder="T.ex. 'sommardag, blå himmel'" style="width:100%;padding:8px 10px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;box-sizing:border-box">
                                </div>

                                <!-- Motor + Generera -->
                                <div style="display:flex;gap:8px;align-items:center;margin-bottom:10px">
                                    <select id="kpProvider" style="padding:7px 10px;border:1px solid #e5e7eb;border-radius:8px;font-size:11px;font-family:inherit;color:#64748b">
                                        <option value="openai">OpenAI GPT Image</option>
                                        <option value="gemini">Google Gemini</option>
                                    </select>
                                    <button id="kpGenerateBtn" onclick="generateKpImage()" style="flex:1;padding:10px;background:#024550;color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit">Generera bild</button>
                                </div>
                            </div>

                            <!-- Höger: Resultat + Galleri -->
                            <div>
                                <div id="kpResultArea">
                                    <div id="kpPlaceholder" style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:280px;border:2px dashed #e5e7eb;border-radius:12px;color:#94a3b8">
                                        <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                                        <p style="margin-top:10px;font-size:13px">Genererad bild visas här</p>
                                        <p style="margin-top:2px;font-size:11px">Välj typ och klicka "Generera bild"</p>
                                    </div>
                                    <div id="kpLoading" style="display:none;flex-direction:column;align-items:center;justify-content:center;height:280px;border:2px dashed #e5e7eb;border-radius:12px;color:#024550">
                                        <div style="width:36px;height:36px;border:3px solid #e5e7eb;border-top:3px solid #024550;border-radius:50%;animation:spin 1s linear infinite"></div>
                                        <p style="margin-top:12px;font-size:13px;font-weight:500">Genererar bild...</p>
                                        <p style="margin-top:2px;font-size:11px;color:#94a3b8">Kan ta upp till 30 sekunder</p>
                                    </div>
                                    <div id="kpResult" style="display:none">
                                        <img id="kpResultImg" style="width:100%;border-radius:10px;border:1px solid #e5e7eb;cursor:pointer" onclick="openLightbox(this.src)">
                                        <div style="display:flex;gap:6px;margin-top:8px">
                                            <button onclick="saveKpResultToGallery()" style="flex:1;padding:8px;border:1.5px solid #059669;border-radius:8px;background:#f0fdf4;cursor:pointer;font-family:inherit;font-size:12px;font-weight:600;color:#059669">&#10003; Spara i kalkyl</button>
                                            <button onclick="downloadKpResult()" style="flex:1;padding:8px;border:1.5px solid #e5e7eb;border-radius:8px;background:#fafbfc;cursor:pointer;font-family:inherit;font-size:12px">Ladda ner</button>
                                            <button onclick="resetKpResult()" style="flex:1;padding:8px;border:1.5px solid #e5e7eb;border-radius:8px;background:#fafbfc;cursor:pointer;font-family:inherit;font-size:12px">Ny bild</button>
                                        </div>
                                    </div>
                                </div>
                                <!-- Sparade bilder i kalkylen -->
                                <div id="kpSavedGallery" style="margin-top:14px">
                                    <h4 style="font-size:13px;font-weight:600;margin-bottom:8px;color:#334155">Bilder i kalkylen</h4>
                                    <div id="kpGallery" style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px"></div>
                                    <div id="kpEmpty" style="padding:16px;text-align:center;color:#94a3b8;font-size:12px;border:2px dashed #e5e7eb;border-radius:8px">
                                        Inga bilder sparade ännu.
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <p class="page-subtitle">Konfigurera och prissätt solcellsanläggning</p>
                <div class="config-header" style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:20px">
                    <label class="config-label" style="font-size:12px;font-weight:600;color:#64748b">Kategori:</label>
                    <select class="product-select" id="categorySelect" onchange="changeCategory()" style="min-width:200px;padding:10px 14px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">
                        <option value="">Välj kategori...</option>
                        <option value="solceller" selected>Solceller</option>
                        <option value="fonster">Fönster</option>
                        <option value="tak">Tak</option>
                        <option value="dorrar">Dörrar</option>
                    </select>
                </div>

                <!-- SOLCELLS-KONFIGURATOR -->
                <div id="solarConfigView">
                <div style="display:grid;grid-template-columns:1fr 380px;gap:24px;align-items:start">
                    <div>
                        <!-- Steg 1: Välj solpanel -->
                        <div style="background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:24px;margin-bottom:16px">
                            <div style="display:flex;align-items:center;gap:10px;margin-bottom:16px">
                                <div style="width:32px;height:32px;background:#ecfdf5;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:14px;color:#059669">1</div>
                                <h3 style="font-size:16px;font-weight:700;color:#1a1a1a;margin:0">Välj solpanel</h3>
                            </div>
                            <div id="solarPanelCards" style="display:grid;gap:10px"></div>
                        </div>

                        <!-- Steg 2: Antal paneler -->
                        <div style="background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:24px;margin-bottom:16px">
                            <div style="display:flex;align-items:center;gap:10px;margin-bottom:16px">
                                <div style="width:32px;height:32px;background:#eff6ff;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:14px;color:#3b82f6">2</div>
                                <h3 style="font-size:16px;font-weight:700;color:#1a1a1a;margin:0">Antal paneler</h3>
                            </div>
                            <div style="display:flex;align-items:center;gap:16px;margin-bottom:12px">
                                <input type="range" id="solPanelCount" min="8" max="80" step="2" value="14" oninput="updateSolarCalc()" style="flex:1;accent-color:#024550">
                                <div style="background:#f0f9ff;border:2px solid #3b82f6;border-radius:10px;padding:8px 16px;text-align:center;min-width:80px">
                                    <div id="solPanelCountVal" style="font-size:24px;font-weight:700;color:#1e40af">14</div>
                                    <div style="font-size:10px;color:#64748b;font-weight:600">PANELER</div>
                                </div>
                            </div>
                            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px">
                                <div style="background:#f8fafc;padding:10px;border-radius:8px;text-align:center">
                                    <div style="font-size:10px;color:#64748b;font-weight:600">EFFEKT</div>
                                    <div id="solKwpVal" style="font-size:16px;font-weight:700;color:#1a1a1a">6.0 kWp</div>
                                </div>
                                <div style="background:#f8fafc;padding:10px;border-radius:8px;text-align:center">
                                    <div style="font-size:10px;color:#64748b;font-weight:600">TAKYTA</div>
                                    <div id="solRoofVal" style="font-size:16px;font-weight:700;color:#1a1a1a">24 m²</div>
                                </div>
                                <div style="background:#f8fafc;padding:10px;border-radius:8px;text-align:center">
                                    <div style="font-size:10px;color:#64748b;font-weight:600">PRODUKTION</div>
                                    <div id="solProdVal" style="font-size:16px;font-weight:700;color:#1a1a1a">~5 400 kWh</div>
                                </div>
                            </div>
                        </div>

                        <!-- Steg 3: Batteri -->
                        <div style="background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:24px;margin-bottom:16px">
                            <div style="display:flex;align-items:center;gap:10px;margin-bottom:16px">
                                <div style="width:32px;height:32px;background:#faf5ff;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:14px;color:#a855f7">3</div>
                                <h3 style="font-size:16px;font-weight:700;color:#1a1a1a;margin:0">Batteri <span style="font-size:12px;color:#94a3b8;font-weight:400">(valfritt)</span></h3>
                            </div>
                            <div id="solarBatteryCards" style="display:grid;gap:10px">
                                <div class="sol-addon-card" data-battery="0" onclick="selectBattery(this)" style="padding:14px 16px;border:2px solid #3b82f6;border-radius:10px;cursor:pointer;display:flex;align-items:center;gap:12px;background:#f0f9ff">
                                    <div style="width:20px;height:20px;border:2px solid #3b82f6;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0"><div style="width:10px;height:10px;background:#3b82f6;border-radius:50%"></div></div>
                                    <div style="flex:1"><div style="font-weight:600;font-size:14px">Inget batteri</div></div>
                                    <div style="font-weight:700;font-size:14px;color:#1a1a1a">0 kr</div>
                                </div>
                            </div>
                        </div>

                        <!-- Steg 4: Elbilsladdare -->
                        <div style="background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:24px;margin-bottom:16px">
                            <div style="display:flex;align-items:center;gap:10px;margin-bottom:16px">
                                <div style="width:32px;height:32px;background:#fef9c3;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:14px;color:#ca8a04">4</div>
                                <h3 style="font-size:16px;font-weight:700;color:#1a1a1a;margin:0">Elbilsladdare <span style="font-size:12px;color:#94a3b8;font-weight:400">(valfritt)</span></h3>
                            </div>
                            <div id="solarChargerCards" style="display:grid;gap:10px">
                                <div class="sol-addon-card" data-charger="0" onclick="selectCharger(this)" style="padding:14px 16px;border:2px solid #3b82f6;border-radius:10px;cursor:pointer;display:flex;align-items:center;gap:12px;background:#f0f9ff">
                                    <div style="width:20px;height:20px;border:2px solid #3b82f6;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0"><div style="width:10px;height:10px;background:#3b82f6;border-radius:50%"></div></div>
                                    <div style="flex:1"><div style="font-weight:600;font-size:14px">Ingen laddare</div></div>
                                    <div style="font-weight:700;font-size:14px;color:#1a1a1a">0 kr</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- PRISSIDEBAR -->
                    <div style="position:sticky;top:20px">
                        <div class="price-card">
                            <div class="price-header">Prissammanställning</div>
                            <div class="price-rows">
                                <div class="price-line"><span class="price-line-label">Material <span style="font-size:10px;color:#94a3b8">(paneler, inverter, montering)</span></span><span class="price-line-value" id="solPrMaterial">0 kr</span></div>
                                <div class="price-line"><span class="price-line-label">Installation <span style="font-size:10px;color:#94a3b8">(arbete, el, projekt)</span></span><span class="price-line-value" id="solPrLabor">0 kr</span></div>
                                <div class="price-line"><span class="price-line-label">Batteri</span><span class="price-line-value" id="solPrBattery">0 kr</span></div>
                                <div class="price-line"><span class="price-line-label">Elbilsladdare</span><span class="price-line-value" id="solPrCharger">0 kr</span></div>
                                <div class="price-line subtotal"><span class="price-line-label">Totalt före avdrag</span><span class="price-line-value" id="solPrSubtotal">0 kr</span></div>
                            </div>
                            <div class="rot-section" style="background:#ecfdf5;padding:14px 16px">
                                <!-- Välj avdragstyp -->
                                <div style="margin-bottom:10px">
                                    <div style="font-size:11px;color:#6b7280;margin-bottom:6px;font-weight:600">SKATTEAVDRAG</div>
                                    <div style="display:flex;gap:4px">
                                        <button onclick="setDeductionType('green')" class="deduct-btn" data-dt="green" style="flex:1;padding:7px 4px;border:1.5px solid #059669;border-radius:6px;font-size:11px;font-weight:600;cursor:pointer;background:#059669;color:#fff;font-family:inherit;line-height:1.2">Grönt teknik<br><span style="font-size:9px;font-weight:400;opacity:.8">20% av allt</span></button>
                                        <button onclick="setDeductionType('rot')" class="deduct-btn" data-dt="rot" style="flex:1;padding:7px 4px;border:1.5px solid #bbf7d0;border-radius:6px;font-size:11px;font-weight:600;cursor:pointer;background:#fff;color:#059669;font-family:inherit;line-height:1.2">ROT-avdrag<br><span style="font-size:9px;font-weight:400;opacity:.8">30% av arbete</span></button>
                                        <button onclick="setDeductionType('both')" class="deduct-btn" data-dt="both" style="flex:1;padding:7px 4px;border:1.5px solid #bbf7d0;border-radius:6px;font-size:11px;font-weight:600;cursor:pointer;background:#fff;color:#059669;font-family:inherit;line-height:1.2">Båda<br><span style="font-size:9px;font-weight:400;opacity:.8">max av båda</span></button>
                                        <button onclick="setDeductionType('none')" class="deduct-btn" data-dt="none" style="flex:1;padding:7px 4px;border:1.5px solid #bbf7d0;border-radius:6px;font-size:11px;font-weight:600;cursor:pointer;background:#fff;color:#059669;font-family:inherit;line-height:1.2">Inget<br><span style="font-size:9px;font-weight:400;opacity:.8">&nbsp;</span></button>
                                    </div>
                                </div>
                                <!-- Avdragssumma -->
                                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
                                    <span id="solDeductLabel" style="font-size:12px;font-weight:700;color:#059669">GRÖNT TEKNIK-AVDRAG</span>
                                    <span id="solPrGreenTech" style="font-size:16px;font-weight:700;color:#059669">0 kr</span>
                                </div>
                                <div id="solDeductDetail" style="font-size:11px;color:#6b7280;margin-bottom:8px"></div>
                                <!-- Antal ägare -->
                                <div id="solOwnerSection" style="margin-bottom:10px">
                                    <div style="font-size:11px;color:#6b7280;margin-bottom:4px">Antal ägare</div>
                                    <div style="display:flex;gap:6px">
                                        <button onclick="setOwnerCount(1)" class="owner-btn" data-oc="1" style="flex:1;padding:6px;border:1.5px solid #059669;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;background:#059669;color:#fff;font-family:inherit">1 person</button>
                                        <button onclick="setOwnerCount(2)" class="owner-btn" data-oc="2" style="flex:1;padding:6px;border:1.5px solid #bbf7d0;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;background:#fff;color:#059669;font-family:inherit">2 personer</button>
                                    </div>
                                </div>
                                <!-- Slider -->
                                <div id="solSliderSection">
                                    <div style="display:flex;justify-content:space-between;font-size:11px;color:#6b7280;margin-bottom:4px">
                                        <span>Kvarvarande avdrag</span>
                                        <span id="solGreenSliderVal" style="font-weight:600;color:#059669">50 000 kr</span>
                                    </div>
                                    <input type="range" id="solGreenSlider" min="0" max="50000" step="5000" value="50000" oninput="updateGreenSlider()" style="width:100%;accent-color:#059669">
                                    <div style="display:flex;justify-content:space-between;font-size:10px;color:#94a3b8"><span>0 kr</span><span id="solGreenSliderMax">50 000 kr</span></div>
                                </div>
                            </div>
                            <div class="total-section">
                                <div class="total-line"><span class="total-label">Att betala</span><span class="total-value" id="solPrTotal">0 kr</span></div>
                                <div class="total-vat">Inkl. moms</div>
                            </div>
                            <div style="padding:0 16px 16px">
                                <!-- Finansiering -->
                                <div style="background:#f0f9ff;border-radius:10px;padding:14px;margin-bottom:12px">
                                    <div style="font-size:11px;color:#3b82f6;font-weight:600;margin-bottom:8px">FINANSIERING</div>
                                    <div style="display:flex;gap:6px;margin-bottom:10px;flex-wrap:wrap">
                                        <button onclick="setFinanceYears(5)" class="fin-yr-btn" data-yr="5" style="padding:4px 10px;border:1.5px solid #bfdbfe;border-radius:6px;font-size:11px;font-weight:600;cursor:pointer;background:#fff;color:#3b82f6;font-family:inherit">5 år</button>
                                        <button onclick="setFinanceYears(10)" class="fin-yr-btn" data-yr="10" style="padding:4px 10px;border:1.5px solid #bfdbfe;border-radius:6px;font-size:11px;font-weight:600;cursor:pointer;background:#fff;color:#3b82f6;font-family:inherit">10 år</button>
                                        <button onclick="setFinanceYears(15)" class="fin-yr-btn" data-yr="15" style="padding:4px 10px;border:1.5px solid #3b82f6;border-radius:6px;font-size:11px;font-weight:600;cursor:pointer;background:#3b82f6;color:#fff;font-family:inherit">15 år</button>
                                        <button onclick="setFinanceYears(20)" class="fin-yr-btn" data-yr="20" style="padding:4px 10px;border:1.5px solid #bfdbfe;border-radius:6px;font-size:11px;font-weight:600;cursor:pointer;background:#fff;color:#3b82f6;font-family:inherit">20 år</button>
                                        <button onclick="setFinanceYears(25)" class="fin-yr-btn" data-yr="25" style="padding:4px 10px;border:1.5px solid #bfdbfe;border-radius:6px;font-size:11px;font-weight:600;cursor:pointer;background:#fff;color:#3b82f6;font-family:inherit">25 år</button>
                                    </div>
                                    <div style="display:flex;justify-content:space-between;align-items:baseline">
                                        <span style="font-size:13px;color:#334155">Månadskostnad <span id="solFinanceInfo" style="font-size:10px;color:#64748b">(15 år, 4.9%)</span></span>
                                        <span id="solPrMonthly" style="font-size:20px;font-weight:700;color:#1e40af">0 kr/mån</span>
                                    </div>
                                </div>
                                <!-- Uppskattad besparing -->
                                <div style="background:#ecfdf5;border-radius:10px;padding:14px;margin-bottom:16px">
                                    <div style="font-size:11px;color:#059669;font-weight:600;margin-bottom:4px">UPPSKATTAD BESPARING</div>
                                    <div style="display:flex;justify-content:space-between;align-items:baseline">
                                        <span style="font-size:13px;color:#334155">Per år</span>
                                        <span id="solPrSaving" style="font-size:20px;font-weight:700;color:#166534">0 kr/år</span>
                                    </div>
                                    <div style="display:flex;justify-content:space-between;align-items:baseline;margin-top:4px">
                                        <span style="font-size:13px;color:#334155">Återbetalningstid</span>
                                        <span id="solPrPayback" style="font-size:16px;font-weight:700;color:#166534">- år</span>
                                    </div>
                                </div>
                                <button id="saveKalkylBtn" onclick="saveKalkylDraft()" style="width:100%;padding:12px;background:#f59e0b;color:#fff;border:none;border-radius:10px;font-size:14px;font-weight:700;cursor:pointer;font-family:inherit;display:flex;align-items:center;justify-content:center;gap:8px;margin-bottom:8px">
                                    <svg viewBox="0 0 24 24" style="width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
                                    Spara kalkyl
                                </button>
                                <button class="cart-btn" onclick="goToAffar()" style="width:100%;padding:14px;background:linear-gradient(135deg,#024550,#035e6b);color:#fff;border:none;border-radius:10px;font-size:15px;font-weight:700;cursor:pointer;font-family:inherit;display:flex;align-items:center;justify-content:center;gap:8px">
                                    <svg viewBox="0 0 24 24" style="width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:2"><path d="M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2M9 5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2M9 5h6"/><path d="M9 12h6M9 16h6"/></svg>
                                    Lägg till i affär
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                </div>

                <!-- FÖNSTER/ÖVRIG KONFIGURATOR (dold vid solceller) -->
                <div id="genericConfigView" style="display:none">
                    <div style="padding:40px;text-align:center;color:#94a3b8">
                        <svg viewBox="0 0 24 24" style="width:48px;height:48px;stroke:currentColor;fill:none;stroke-width:1.5;margin-bottom:12px"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>
                        <p style="font-size:16px;font-weight:600">Konfigurator för denna kategori kommer snart</p>
                        <p style="font-size:13px">Solceller-konfiguratorn är aktiv — välj Solceller ovan.</p>
                    </div>
                </div>

                <!-- AFFÄR-VY (efter kalkyl) -->
                <div id="affarView" style="display:none">
                    <div style="display:flex;align-items:center;gap:12px;margin-bottom:20px">
                        <button class="dummy-btn secondary" onclick="backToKalkylFromAffar()" style="padding:8px 14px"><svg viewBox="0 0 24 24" style="width:16px;height:16px;stroke:currentColor;fill:none;stroke-width:2"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg> Tillbaka till kalkyl</button>
                        <div><h1 class="page-title" style="margin-bottom:0">Affär</h1></div>
                        <div id="affarStatus" style="margin-left:auto;padding:4px 12px;border-radius:20px;font-size:12px;font-weight:600;background:#fef3c7;color:#92400e">Utkast</div>
                    </div>

                    <!-- Kundbanner i affär -->
                    <div id="affarCustomerBanner" style="margin-bottom:16px"></div>

                    <div style="display:grid;grid-template-columns:1fr 400px;gap:24px;align-items:start">
                        <div>
                            <!-- Sammanfattning från kalkyl -->
                            <div style="background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:24px;margin-bottom:16px">
                                <h3 style="font-size:16px;font-weight:700;margin:0 0 16px;display:flex;align-items:center;gap:8px">
                                    <svg viewBox="0 0 24 24" style="width:20px;height:20px;fill:none;stroke:#059669;stroke-width:2"><circle cx="12" cy="12" r="10"/><path d="M9 12l2 2 4-4"/></svg>
                                    Konfiguration
                                </h3>
                                <div id="affarConfigSummary" style="display:grid;gap:8px"></div>
                            </div>

                            <!-- Extrakostnader -->
                            <div style="background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:24px;margin-bottom:16px">
                                <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px">
                                    <h3 style="font-size:16px;font-weight:700;margin:0;display:flex;align-items:center;gap:8px">
                                        <svg viewBox="0 0 24 24" style="width:20px;height:20px;fill:none;stroke:#3b82f6;stroke-width:2"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
                                        Extrakostnader
                                    </h3>
                                    <button onclick="addExtraCost()" style="padding:6px 14px;background:#3b82f6;color:#fff;border:none;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;display:flex;align-items:center;gap:4px">
                                        <svg viewBox="0 0 24 24" style="width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                                        Lägg till
                                    </button>
                                </div>
                                <div id="affarExtraCosts"></div>
                                <div id="affarExtraCostsEmpty" style="padding:16px;text-align:center;color:#94a3b8;font-size:13px">
                                    Inga extrakostnader tillagda. Klicka "Lägg till" för takunderhåll, extra kabelarbete etc.
                                </div>
                            </div>

                            <!-- Marginal -->
                            <div style="background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:24px;margin-bottom:16px">
                                <h3 style="font-size:16px;font-weight:700;margin:0 0 16px;display:flex;align-items:center;gap:8px">
                                    <svg viewBox="0 0 24 24" style="width:20px;height:20px;fill:none;stroke:#a855f7;stroke-width:2"><path d="M16 8v8M12 11v5M8 14v2M3 3v18h18"/></svg>
                                    Marginal
                                </h3>
                                <div style="display:flex;align-items:center;gap:16px;margin-bottom:12px">
                                    <input type="range" id="affarMarginSlider" min="0" max="40" step="1" value="0" oninput="updateAffarCalc()" style="flex:1;accent-color:#a855f7">
                                    <div style="background:#faf5ff;border:2px solid #a855f7;border-radius:10px;padding:8px 16px;text-align:center;min-width:80px">
                                        <div id="affarMarginVal" style="font-size:24px;font-weight:700;color:#7c3aed">0%</div>
                                        <div style="font-size:10px;color:#64748b;font-weight:600">MARGINAL</div>
                                    </div>
                                </div>
                                <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
                                    <div style="background:#f8fafc;padding:10px;border-radius:8px;text-align:center">
                                        <div style="font-size:10px;color:#64748b;font-weight:600">MARGINALKOSTNAD</div>
                                        <div id="affarMarginKr" style="font-size:16px;font-weight:700;color:#1a1a1a">0 kr</div>
                                    </div>
                                    <div style="background:#f8fafc;padding:10px;border-radius:8px;text-align:center">
                                        <div style="font-size:10px;color:#64748b;font-weight:600">VINST</div>
                                        <div id="affarProfit" style="font-size:16px;font-weight:700;color:#059669">0 kr</div>
                                    </div>
                                </div>
                            </div>

                            <!-- Bilder för offert -->
                            <div style="background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:24px;margin-bottom:16px">
                                <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px">
                                    <h3 style="font-size:16px;font-weight:700;margin:0;display:flex;align-items:center;gap:8px">
                                        <svg viewBox="0 0 24 24" style="width:20px;height:20px;fill:none;stroke:#f59e0b;stroke-width:2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                                        Bilder för offert
                                    </h3>
                                    <div style="display:flex;gap:6px">
                                        <button onclick="addProspectPhotosToAffar()" id="affarAddProspectBtn" style="padding:6px 14px;background:#024550;color:#fff;border:none;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;display:flex;align-items:center;gap:4px">
                                            <svg viewBox="0 0 24 24" style="width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                                            Hämta prospektbilder
                                        </button>
                                    </div>
                                </div>
                                <div id="affarImages" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px"></div>
                                <div id="affarImagesEmpty" style="padding:20px;text-align:center;color:#94a3b8;font-size:13px;border:2px dashed #e5e7eb;border-radius:10px">
                                    Inga bilder ännu. Hämta prospektbilder eller skapa en prospektbild för offerten.
                                </div>
                            </div>

                            <!-- Anteckningar -->
                            <div style="background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:24px;margin-bottom:16px">
                                <h3 style="font-size:16px;font-weight:700;margin:0 0 12px">Anteckningar</h3>
                                <textarea id="affarNotes" rows="3" placeholder="Interna anteckningar om affären..." style="width:100%;padding:12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;resize:vertical"></textarea>
                            </div>
                        </div>

                        <!-- AFFÄR PRISSIDEBAR -->
                        <div style="position:sticky;top:20px">
                            <div class="price-card">
                                <div class="price-header" style="background:linear-gradient(135deg,#024550,#035e6b)">Affärssammanställning</div>
                                <div class="price-rows">
                                    <div class="price-line"><span class="price-line-label">Material</span><span class="price-line-value" id="affarPrMaterial">0 kr</span></div>
                                    <div class="price-line"><span class="price-line-label">Installation</span><span class="price-line-value" id="affarPrLabor">0 kr</span></div>
                                    <div class="price-line"><span class="price-line-label">Batteri</span><span class="price-line-value" id="affarPrBattery">0 kr</span></div>
                                    <div class="price-line"><span class="price-line-label">Laddare</span><span class="price-line-value" id="affarPrCharger">0 kr</span></div>
                                    <div class="price-line" id="affarPrExtraRow" style="display:none"><span class="price-line-label">Extrakostnader</span><span class="price-line-value" id="affarPrExtra">0 kr</span></div>
                                    <div class="price-line" id="affarPrMarginRow" style="display:none"><span class="price-line-label">Marginal <span id="affarPrMarginPct" style="font-size:10px;color:#94a3b8"></span></span><span class="price-line-value" id="affarPrMargin">0 kr</span></div>
                                    <div class="price-line subtotal"><span class="price-line-label">Totalt före avdrag</span><span class="price-line-value" id="affarPrSubtotal">0 kr</span></div>
                                </div>
                                <div id="affarDeductionRow" style="background:#ecfdf5;padding:14px 16px">
                                    <div style="display:flex;justify-content:space-between;align-items:center">
                                        <span id="affarDeductLabel" style="font-size:12px;font-weight:700;color:#059669">AVDRAG</span>
                                        <span id="affarPrGreenTech" style="font-size:16px;font-weight:700;color:#059669">0 kr</span>
                                    </div>
                                </div>
                                <div class="total-section">
                                    <div class="total-line"><span class="total-label">Kunden betalar</span><span class="total-value" id="affarPrTotal">0 kr</span></div>
                                    <div class="total-vat">Inkl. moms</div>
                                </div>
                                <div style="padding:0 16px 16px">
                                    <div style="background:#f0f9ff;border-radius:10px;padding:14px;margin-bottom:12px">
                                        <div style="font-size:11px;color:#3b82f6;font-weight:600;margin-bottom:4px">FINANSIERING</div>
                                        <div style="display:flex;justify-content:space-between;align-items:baseline">
                                            <span style="font-size:13px;color:#334155">Månadskostnad</span>
                                            <span id="affarPrMonthly" style="font-size:20px;font-weight:700;color:#1e40af">0 kr/mån</span>
                                        </div>
                                    </div>
                                    <div style="display:grid;gap:8px">
                                        <button onclick="saveQuoteAsDraft()" style="width:100%;padding:14px;background:#f59e0b;color:#fff;border:none;border-radius:10px;font-size:15px;font-weight:700;cursor:pointer;font-family:inherit;display:flex;align-items:center;justify-content:center;gap:8px">
                                            <svg viewBox="0 0 24 24" style="width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
                                            Spara som utkast
                                        </button>
                                        <button onclick="createFinalQuote()" style="width:100%;padding:14px;background:#166534;color:#fff;border:none;border-radius:10px;font-size:15px;font-weight:700;cursor:pointer;font-family:inherit;display:flex;align-items:center;justify-content:center;gap:8px">
                                            <svg viewBox="0 0 24 24" style="width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
                                            Skapa offert
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- KALENDER -->
        <div class="page-content" id="page-kalender">
            <h1 class="page-title">Kalender</h1>
            <p class="page-subtitle">Din Google Kalender — bädda in genom att ange din e-post</p>
            <div id="calSetup" style="max-width:500px">
                <div style="display:flex;gap:8px;margin-bottom:16px">
                    <input type="email" id="calEmail" placeholder="din.email@gmail.com" value="" style="flex:1;padding:10px 14px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">
                    <button onclick="loadGoogleCalendar()" style="padding:10px 20px;background:#024550;color:#fff;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit;white-space:nowrap">Ladda kalender</button>
                </div>
                <p style="font-size:12px;color:#94a3b8">Obs: Din Google Kalender måste vara publik eller så måste du vara inloggad i Google i samma webbläsare.</p>
            </div>
            <div id="calEmbed" style="display:none;margin-top:16px;border-radius:12px;overflow:hidden;border:1px solid #e5e7eb">
                <iframe id="calIframe" src="" style="width:100%;height:700px;border:none"></iframe>
            </div>
            <div style="margin-top:20px">
                <h3 style="font-size:16px;font-weight:600;color:#1a1a1a;margin-bottom:14px">Återbesök att boka</h3>
                <div id="callbackList" style="display:flex;flex-direction:column;gap:8px">
                    <div style="padding:16px;background:#f8fafc;border-radius:10px;color:#94a3b8;text-align:center;font-size:13px">Inga planerade återbesök</div>
                </div>
            </div>
        </div>

        <!-- INKORG -->
        <div class="page-content" id="page-inkorg">
            <h1 class="page-title">Inkorg</h1>
            <p class="page-subtitle">Din e-post direkt i CRM:et</p>

            <!-- Mail Login -->
            <div id="mailLogin" style="max-width:500px">
                <div style="padding:28px;background:#fff;border-radius:12px;border:1px solid #e5e7eb">
                    <h3 style="font-size:16px;font-weight:600;margin-bottom:16px">Anslut din e-post</h3>
                    <div style="display:grid;gap:10px">
                        <div><label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">E-postadress</label><input type="email" id="mailEmail" placeholder="dittnamn@solargroup.se" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit"></div>
                        <div><label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">Lösenord</label><input type="password" id="mailPass" placeholder="E-postlösenord" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit"></div>
                        <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
                            <div><label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">IMAP-server</label><input type="text" id="mailImapHost" value="localhost" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit"></div>
                            <div><label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">Port</label><input type="number" id="mailImapPort" value="993" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit"></div>
                        </div>
                        <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
                            <div><label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">SMTP-server</label><input type="text" id="mailSmtpHost" value="localhost" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit"></div>
                            <div><label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">Port</label><input type="number" id="mailSmtpPort" value="587" style="width:100%;padding:10px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit"></div>
                        </div>
                        <div id="mailLoginError" style="display:none;padding:8px 12px;background:#fef2f2;border-radius:6px;color:#991b1b;font-size:13px"></div>
                        <button onclick="mailConnect()" id="mailConnectBtn" style="width:100%;padding:12px;background:#024550;color:#fff;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit;margin-top:4px">Anslut</button>
                    </div>
                    <p style="font-size:11px;color:#94a3b8;margin-top:12px">Dina uppgifter sparas lokalt i webbläsaren och skickas säkert till servern vid varje anrop.</p>
                </div>
            </div>

            <!-- Mail Client -->
            <div id="mailClient" style="display:none">
                <!-- Toolbar -->
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;flex-wrap:wrap;gap:8px">
                    <div style="display:flex;gap:8px;align-items:center">
                        <select id="mailFolderSelect" onchange="mailSwitchFolder()" style="padding:8px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit"></select>
                        <button onclick="mailRefresh()" style="padding:8px 14px;background:#f1f5f9;border:1px solid #e5e7eb;border-radius:8px;font-size:13px;cursor:pointer;font-family:inherit">Uppdatera</button>
                        <span id="mailCount" style="font-size:12px;color:#94a3b8"></span>
                    </div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="text" id="mailSearch" placeholder="Sök..." onkeydown="if(event.key==='Enter')mailRefresh()" style="padding:8px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;width:200px">
                        <button onclick="mailCompose()" style="padding:8px 16px;background:#024550;color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit">Skriv nytt</button>
                        <button onclick="mailDisconnect()" style="padding:8px 12px;background:#f1f5f9;border:1px solid #e5e7eb;border-radius:8px;font-size:13px;cursor:pointer;font-family:inherit;color:#ef4444" title="Logga ut">Logga ut</button>
                    </div>
                </div>

                <!-- Mail layout: list + reader -->
                <div style="display:grid;grid-template-columns:380px 1fr;gap:0;border:1px solid #e5e7eb;border-radius:12px;overflow:hidden;background:#fff;min-height:600px">
                    <!-- Message list -->
                    <div style="border-right:1px solid #e5e7eb;overflow-y:auto;max-height:700px" id="mailListContainer">
                        <div id="mailList" style="display:flex;flex-direction:column"></div>
                        <div id="mailListLoading" style="display:none;padding:20px;text-align:center;color:#94a3b8;font-size:13px">Laddar...</div>
                        <div id="mailPagination" style="display:flex;justify-content:center;gap:8px;padding:12px;border-top:1px solid #f1f5f9"></div>
                    </div>
                    <!-- Reader pane -->
                    <div style="overflow-y:auto;max-height:700px" id="mailReaderContainer">
                        <div id="mailReader" style="padding:24px">
                            <div id="mailReaderEmpty" style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:400px;color:#94a3b8">
                                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
                                <p style="margin-top:12px;font-size:14px">Välj ett meddelande att läsa</p>
                            </div>
                            <div id="mailReaderContent" style="display:none"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Compose modal -->
            <div id="mailComposeModal" style="display:none;position:fixed;inset:0;z-index:9000;background:rgba(0,0,0,.5);align-items:center;justify-content:center">
                <div style="background:#fff;border-radius:16px;padding:0;width:640px;max-width:95vw;max-height:90vh;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.2);display:flex;flex-direction:column">
                    <div style="display:flex;justify-content:space-between;align-items:center;padding:16px 20px;border-bottom:1px solid #e5e7eb">
                        <h3 style="font-size:16px;font-weight:600" id="composeTitle">Nytt meddelande</h3>
                        <button onclick="mailCloseCompose()" style="background:none;border:none;font-size:22px;cursor:pointer;color:#94a3b8">&times;</button>
                    </div>
                    <div style="padding:16px 20px;overflow-y:auto;flex:1;display:grid;gap:8px">
                        <div style="display:flex;align-items:center;gap:8px"><label style="font-size:12px;font-weight:600;color:#334155;width:40px">Till</label><input type="text" id="composeTo" style="flex:1;padding:8px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit"></div>
                        <div style="display:flex;align-items:center;gap:8px"><label style="font-size:12px;font-weight:600;color:#334155;width:40px">Cc</label><input type="text" id="composeCc" style="flex:1;padding:8px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit"></div>
                        <div style="display:flex;align-items:center;gap:8px"><label style="font-size:12px;font-weight:600;color:#334155;width:40px">Ämne</label><input type="text" id="composeSubject" style="flex:1;padding:8px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit"></div>
                        <input type="hidden" id="composeReplyUid" value="0">
                        <input type="hidden" id="composeReplyFolder" value="">
                        <input type="hidden" id="composeReplyTo" value="">
                        <textarea id="composeBody" rows="14" placeholder="Skriv ditt meddelande..." style="width:100%;padding:12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;resize:vertical;min-height:200px"></textarea>
                        <div style="padding:8px 0">
                            <label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:4px">Signatur</label>
                            <textarea id="composeSignature" rows="4" placeholder="--&#10;Med vänliga hälsningar&#10;Ditt namn&#10;Solargroup AB" style="width:100%;padding:10px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;resize:vertical;background:#f8fafc;color:#64748b"></textarea>
                        </div>
                    </div>
                    <div style="padding:12px 20px;border-top:1px solid #e5e7eb;display:flex;justify-content:space-between;align-items:center">
                        <button onclick="mailCloseCompose()" style="padding:10px 20px;background:#f1f5f9;color:#334155;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;cursor:pointer;font-family:inherit">Avbryt</button>
                        <button onclick="mailSend()" id="composeSendBtn" style="padding:10px 24px;background:#024550;color:#fff;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit">Skicka</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- DAGRAPPORT -->
        <div class="page-content" id="page-dagrapport">
            <h1 class="page-title">Dagrapport</h1>
            <p class="page-subtitle">Rapportera dina dagliga aktiviteter</p>
            <div class="dr-summary">
                <div class="dr-card"><h4>Kundbesök idag</h4><div class="dr-val">3</div><div class="dr-sub">Av 4 planerade</div></div>
                <div class="dr-card"><h4>Offerter skapade</h4><div class="dr-val">2</div><div class="dr-sub">Totalt 87 500 kr</div></div>
                <div class="dr-card"><h4>Körsträcka</h4><div class="dr-val">145 km</div><div class="dr-sub">18,50 kr/km</div></div>
            </div>
            <div class="dr-form">
                <h3>Ny dagrapport</h3>
                <div class="dr-form-grid">
                    <div class="dr-form-group"><label>Datum</label><input type="date" value="2026-02-18"></div>
                    <div class="dr-form-group"><label>Typ av aktivitet</label><select><option>Kundbesök</option><option>Inmätning</option><option>Montering</option><option>Offertarbete</option><option>Intern</option><option>Utbildning</option></select></div>
                    <div class="dr-form-group"><label>Kund</label><select><option value="">Välj kund...</option><option>Andersson Bygg AB</option><option>Svensson Fastigheter</option><option>Johansson &amp; Co</option><option>Nilsson Renovering</option><option>Karlsson Entreprenad</option><option>Berg Fastigheter AB</option></select></div>
                    <div class="dr-form-group"><label>Körsträcka (km)</label><input type="number" placeholder="0"></div>
                    <div class="dr-form-group"><label>Starttid</label><input type="time" value="08:00"></div>
                    <div class="dr-form-group"><label>Sluttid</label><input type="time" value="17:00"></div>
                    <div class="dr-form-group full"><label>Kommentar</label><textarea placeholder="Beskriv dagens aktiviteter..."></textarea></div>
                </div>
                <button class="dummy-btn" style="margin-top:16px">Spara rapport</button>
            </div>
            <div>
                <h3 style="font-size:16px;font-weight:600;color:#1a1a1a;margin-bottom:14px">Senaste rapporter</h3>
                <div class="dr-log-item">
                    <div class="dr-log-date">17 feb</div>
                    <div class="dr-log-info"><h4>Kundbesök - Svensson Fastigheter</h4><p>Offertpresentation villa Kungälv. Kunden nöjd, vill ha komplettering med balkongdörr. 87 km.</p></div>
                    <span class="dr-log-tag" style="background:#dcfce7;color:#166534">Godkänd</span>
                </div>
                <div class="dr-log-item">
                    <div class="dr-log-date">14 feb</div>
                    <div class="dr-log-info"><h4>Inmätning - Andersson Bygg AB</h4><p>Inmätning av 12 fönster + 2 balkongdörrar. Kungsholmen 14. Allt stämde med offert. 23 km.</p></div>
                    <span class="dr-log-tag" style="background:#dcfce7;color:#166534">Godkänd</span>
                </div>
                <div class="dr-log-item">
                    <div class="dr-log-date">13 feb</div>
                    <div class="dr-log-info"><h4>Montering - Nilsson Renovering</h4><p>Monterade 4 av 6 fönster. Återstående 2 kräver specialbeslag. Beställt. 156 km.</p></div>
                    <span class="dr-log-tag" style="background:#fef9c3;color:#854d0e">Pågår</span>
                </div>
                <div class="dr-log-item">
                    <div class="dr-log-date">12 feb</div>
                    <div class="dr-log-info"><h4>Offertarbete - Berg Fastigheter</h4><p>Skapade offert BRF renovering 32 fönster. Skickade för granskning. Kontoret.</p></div>
                    <span class="dr-log-tag" style="background:#dcfce7;color:#166534">Godkänd</span>
                </div>
            </div>
        </div>

        <!-- MIN LÖN -->
        <div class="page-content" id="page-minlon">
            <h1 class="page-title">Min Lön</h1>
            <p class="page-subtitle">Lönespecifikation och provisioner</p>
            <div style="display:flex;align-items:center;gap:12px;margin-bottom:20px">
                <span style="font-size:14px;font-weight:500;color:#64748b">Period:</span>
                <select class="lon-month-select">
                    <option>Februari 2026</option>
                    <option>Januari 2026</option>
                    <option>December 2025</option>
                    <option>November 2025</option>
                </select>
            </div>
            <div class="lon-overview">
                <div class="lon-card highlight"><h4>Nettolön</h4><div class="lon-val">34 280 kr</div><div class="lon-sub">Betalas ut 25 feb</div></div>
                <div class="lon-card"><h4>Bruttolön</h4><div class="lon-val">48 500 kr</div><div class="lon-sub">Grundlön + provision</div></div>
                <div class="lon-card"><h4>Provision denna månad</h4><div class="lon-val">12 500 kr</div><div class="lon-sub">5 stängda affärer</div></div>
            </div>
            <div class="lon-breakdown">
                <div class="lon-breakdown-header">
                    <svg viewBox="0 0 24 24" style="width:18px;height:18px;stroke:#64748b;fill:none;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                    Lönespecifikation
                </div>
                <div class="lon-row"><span class="lon-row-label">Grundlön</span><span class="lon-row-val">36 000 kr</span></div>
                <div class="lon-row"><span class="lon-row-label">Provision (5 affärer)</span><span class="lon-row-val">12 500 kr</span></div>
                <div class="lon-row"><span class="lon-row-label">Milersättning (823 km)</span><span class="lon-row-val">15 226 kr</span></div>
                <div class="lon-row"><span class="lon-row-label">Traktamente (3 dagar)</span><span class="lon-row-val">1 080 kr</span></div>
                <div class="lon-row" style="border-top:2px solid #e5e7eb"><span class="lon-row-label" style="font-weight:600">Bruttolön</span><span class="lon-row-val">48 500 kr</span></div>
                <div class="lon-row deduction"><span class="lon-row-label">Skatt (30%)</span><span class="lon-row-val">-14 220 kr</span></div>
                <div class="lon-row total"><span class="lon-row-label">Nettolön</span><span class="lon-row-val">34 280 kr</span></div>
            </div>
            <div class="lon-breakdown">
                <div class="lon-breakdown-header">
                    <svg viewBox="0 0 24 24" style="width:18px;height:18px;stroke:#64748b;fill:none;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>
                    Provisionhistorik
                </div>
                <div class="lon-row"><span class="lon-row-label">Andersson Bygg - 12 fönster + 2 dörrar</span><span class="lon-row-val" style="color:#10b981">3 200 kr</span></div>
                <div class="lon-row"><span class="lon-row-label">Nilsson Renovering - 6 fönster + dörr</span><span class="lon-row-val" style="color:#10b981">2 800 kr</span></div>
                <div class="lon-row"><span class="lon-row-label">Johansson & Co - Kontorsfönster 24 st</span><span class="lon-row-val" style="color:#10b981">3 500 kr</span></div>
                <div class="lon-row"><span class="lon-row-label">Pettersson & Söner - 8 fönster</span><span class="lon-row-val" style="color:#10b981">1 800 kr</span></div>
                <div class="lon-row"><span class="lon-row-label">Gustafsson Bygg - 6 fönster</span><span class="lon-row-val" style="color:#10b981">1 200 kr</span></div>
            </div>
        </div>

        <!-- ADMIN -->
        <div class="page-content" id="page-admin">
            <h1 class="page-title">Admin</h1>
            <p class="page-subtitle">Användarhantering och roller</p>

            <div style="display:flex;gap:0;margin-bottom:24px;border-bottom:2px solid #e5e7eb">
                <button class="admin-tab active" data-admin-tab="users" onclick="switchAdminTab('users')" style="padding:10px 20px;font-size:14px;font-weight:600;border:none;background:none;cursor:pointer;border-bottom:2px solid #024550;color:#024550;margin-bottom:-2px;font-family:inherit">Användare</button>
                <button class="admin-tab" data-admin-tab="pending" onclick="switchAdminTab('pending')" style="padding:10px 20px;font-size:14px;font-weight:600;border:none;background:none;cursor:pointer;border-bottom:2px solid transparent;color:#64748b;margin-bottom:-2px;font-family:inherit">Väntande <span id="adminPendingCount" style="background:#ef4444;color:#fff;border-radius:10px;padding:1px 7px;font-size:10px;font-weight:700;margin-left:4px;display:none"></span></button>
                <button class="admin-tab" data-admin-tab="permissions" onclick="switchAdminTab('permissions')" style="padding:10px 20px;font-size:14px;font-weight:600;border:none;background:none;cursor:pointer;border-bottom:2px solid transparent;color:#64748b;margin-bottom:-2px;font-family:inherit">Behörighet</button>
            </div>

            <!-- Användare-tab -->
            <div id="adminUsersPanel">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;gap:12px;flex-wrap:wrap">
                    <div style="display:flex;gap:10px;align-items:center;flex:1;min-width:200px">
                        <input type="text" id="adminUserSearch" oninput="filterAdminUsers()" placeholder="Sök namn eller e-post..." style="padding:8px 14px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;width:100%;max-width:280px;transition:border-color .2s" onfocus="this.style.borderColor='#024550'" onblur="this.style.borderColor='#e5e7eb'">
                        <select id="adminUserRoleFilter" onchange="filterAdminUsers()" style="padding:8px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;background:#fff;cursor:pointer">
                            <option value="">Alla roller</option>
                            <option value="admin">Admin</option>
                            <option value="saljchef">Säljchef</option>
                            <option value="saljare">Säljare</option>
                            <option value="installator">Installatör</option>
                            <option value="projektledare">Projektledare</option>
                            <option value="ekonomi">Ekonomi</option>
                        </select>
                    </div>
                    <div style="font-size:13px;color:#64748b" id="adminUserCount"></div>
                </div>
                <div style="overflow-x:auto">
                    <table style="width:100%;border-collapse:collapse;font-size:13px">
                        <thead>
                            <tr style="background:#f8fafc;border-bottom:2px solid #e5e7eb">
                                <th style="text-align:left;padding:10px 12px;font-weight:600;color:#64748b">Namn</th>
                                <th style="text-align:left;padding:10px 12px;font-weight:600;color:#64748b">E-post</th>
                                <th style="text-align:left;padding:10px 12px;font-weight:600;color:#64748b">Roll</th>
                                <th style="text-align:left;padding:10px 12px;font-weight:600;color:#64748b">Telefon</th>
                                <th style="text-align:center;padding:10px 12px;font-weight:600;color:#64748b">Aktiv</th>
                                <th style="text-align:left;padding:10px 12px;font-weight:600;color:#64748b">Senaste inlogg</th>
                                <th style="text-align:center;padding:10px 12px;font-weight:600;color:#64748b"></th>
                            </tr>
                        </thead>
                        <tbody id="adminUsersBody"></tbody>
                    </table>
                </div>
            </div>

            <!-- Väntande-tab -->
            <div id="adminPendingPanel" style="display:none">
                <div id="adminPendingEmpty" style="text-align:center;padding:40px;color:#94a3b8;display:none">
                    <svg viewBox="0 0 24 24" style="width:48px;height:48px;stroke:#cbd5e1;fill:none;stroke-width:1.2;margin-bottom:12px"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
                    <p style="font-size:15px;font-weight:600;margin-bottom:4px">Inga väntande</p>
                    <p style="font-size:13px">Alla ansökningar är behandlade</p>
                </div>
                <div id="adminPendingList" style="display:flex;flex-direction:column;gap:12px"></div>
            </div>
</div>            <!-- Behörighet-tab -->            <div id="adminPermissionsPanel" style="display:none">                <div style="margin-bottom:16px">                    <p style="font-size:13px;color:#64748b;margin-bottom:16px">Välj vilka menyer varje roll ska se. Ändringar sparas direkt.</p>                    <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:20px" id="permRoleTabs"></div>                </div>                <div id="permMatrixContainer" style="overflow-x:auto"></div>            </div>
        </div>

        <!-- EKONOMI / EVA AI -->
        <div class="page-content" id="page-ekonomi">
            <h1 class="page-title">Ekonomi</h1>
            <p class="page-subtitle">Leveranser, fakturor, kundreskontra och utlägg</p>
            <div class="eko-layout">
                <div class="eko-main">
                    <div class="eko-tabs">
                        <button class="eko-tab active" onclick="ekoTab(this,'eko-leverans')">Leveranser</button>
                        <button class="eko-tab" onclick="ekoTab(this,'eko-order')">Order</button>
                        <button class="eko-tab" onclick="ekoTab(this,'eko-faktura')">Fakturor</button>
                        <button class="eko-tab" onclick="ekoTab(this,'eko-plock')">Montering</button>
                        <button class="eko-tab" onclick="ekoTab(this,'eko-reskontra')">Kundreskontra</button>
                        <button class="eko-tab" onclick="ekoTab(this,'eko-utlagg')">Utlägg</button>
                        <button class="eko-tab" onclick="ekoTab(this,'eko-inkop')">Inköp</button>
                    </div>

                    <!-- LEVERANSER -->
                    <div class="eko-panel active" id="eko-leverans">
                        <div style="display:grid;grid-template-columns:repeat(6,1fr);gap:10px;margin-bottom:20px;text-align:center">
                            <div class="dr-card" style="padding:10px 8px"><h4 style="font-size:10px">Offert</h4><div class="dr-val" style="font-size:18px">2</div></div>
                            <div class="dr-card" style="padding:10px 8px"><h4 style="font-size:10px">Order</h4><div class="dr-val" style="font-size:18px">4</div></div>
                            <div class="dr-card" style="padding:10px 8px"><h4 style="font-size:10px">Produktion</h4><div class="dr-val" style="font-size:18px">2</div></div>
                            <div class="dr-card" style="padding:10px 8px"><h4 style="font-size:10px">Leverans</h4><div class="dr-val" style="font-size:18px">1</div></div>
                            <div class="dr-card" style="padding:10px 8px"><h4 style="font-size:10px">Montering</h4><div class="dr-val" style="font-size:18px">3</div></div>
                            <div class="dr-card" style="padding:10px 8px"><h4 style="font-size:10px">Klart</h4><div class="dr-val" style="font-size:18px;color:#10b981">1</div></div>
                        </div>
                        <div style="display:flex;flex-direction:column;gap:10px">
                            <div style="background:#fff;border-radius:10px;border:1px solid #e5e7eb;padding:16px 20px;display:flex;align-items:center;gap:16px">
                                <div style="width:10px;height:10px;border-radius:50%;background:#10b981;flex-shrink:0"></div>
                                <div style="flex:1">
                                    <div style="font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:2px">Andersson Bygg AB</div>
                                    <div style="font-size:12px;color:#64748b">12 fönster + 2 balkongdörrar &bull; PRJ-2024-001</div>
                                </div>
                                <div style="text-align:right">
                                    <span class="status-badge green">Levererad</span>
                                    <div style="font-size:11px;color:#94a3b8;margin-top:4px">Montering 100% &bull; Besiktning godkänd</div>
                                </div>
                            </div>
                            <div style="background:#fff;border-radius:10px;border:1px solid #e5e7eb;padding:16px 20px;display:flex;align-items:center;gap:16px">
                                <div style="width:10px;height:10px;border-radius:50%;background:#3b82f6;flex-shrink:0"></div>
                                <div style="flex:1">
                                    <div style="font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:2px">Svensson Fastigheter</div>
                                    <div style="font-size:12px;color:#64748b">8 fönster villa &bull; PRJ-2024-002</div>
                                </div>
                                <div style="text-align:right">
                                    <span class="status-badge blue">Under produktion</span>
                                    <div style="font-size:11px;color:#94a3b8;margin-top:4px">Montering 75% klar &bull; Väntar besiktning</div>
                                </div>
                                <div style="min-width:80px"><div class="progress-bar" style="height:16px"><div class="progress-fill" style="width:75%"></div><span class="progress-text" style="font-size:10px">75%</span></div></div>
                            </div>
                            <div style="background:#fff;border-radius:10px;border:1px solid #e5e7eb;padding:16px 20px;display:flex;align-items:center;gap:16px">
                                <div style="width:10px;height:10px;border-radius:50%;background:#eab308;flex-shrink:0"></div>
                                <div style="flex:1">
                                    <div style="font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:2px">Johansson & Co</div>
                                    <div style="font-size:12px;color:#64748b">Kontorsfönster 24 st &bull; PRJ-2024-003</div>
                                </div>
                                <div style="text-align:right">
                                    <span class="status-badge yellow">Väntar godkännande</span>
                                    <div style="font-size:11px;color:#94a3b8;margin-top:4px">Montering 30% klar</div>
                                </div>
                                <div style="min-width:80px"><div class="progress-bar" style="height:16px"><div class="progress-fill" style="width:30%"></div><span class="progress-text" style="font-size:10px">30%</span></div></div>
                            </div>
                            <div style="background:#fff;border-radius:10px;border:2px solid #ef4444;padding:16px 20px;display:flex;align-items:center;gap:16px">
                                <div style="width:10px;height:10px;border-radius:50%;background:#ef4444;flex-shrink:0"></div>
                                <div style="flex:1">
                                    <div style="font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:2px">Nilsson Renovering</div>
                                    <div style="font-size:12px;color:#64748b">6 fönster + entredörr &bull; PRJ-2024-004</div>
                                </div>
                                <div style="text-align:right">
                                    <span class="status-badge" style="background:#fee2e2;color:#991b1b">Försenad</span>
                                    <div style="font-size:11px;color:#ef4444;font-weight:500;margin-top:4px">Specialbeslag saknas &bull; +1 vecka försening</div>
                                </div>
                            </div>
                            <div style="background:#fff;border-radius:10px;border:1px solid #e5e7eb;padding:16px 20px;display:flex;align-items:center;gap:16px">
                                <div style="width:10px;height:10px;border-radius:50%;background:#94a3b8;flex-shrink:0"></div>
                                <div style="flex:1">
                                    <div style="font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:2px">Karlsson Entreprenad</div>
                                    <div style="font-size:12px;color:#64748b">Flerfamiljshus 48 fönster &bull; PRJ-2024-005</div>
                                </div>
                                <div style="text-align:right">
                                    <span class="status-badge gray">Offert skickad</span>
                                    <div style="font-size:11px;color:#94a3b8;margin-top:4px">Väntar svar sedan 2 veckor</div>
                                </div>
                            </div>
                            <div style="background:#fff;border-radius:10px;border:1px solid #e5e7eb;padding:16px 20px;display:flex;align-items:center;gap:16px;opacity:.7">
                                <div style="width:10px;height:10px;border-radius:50%;background:#d1d5db;flex-shrink:0"></div>
                                <div style="flex:1">
                                    <div style="font-size:14px;font-weight:600;color:#1a1a1a;margin-bottom:2px">Berg Fastigheter AB</div>
                                    <div style="font-size:12px;color:#64748b">BRF renovering 32 fönster &bull; PRJ-2024-006</div>
                                </div>
                                <div style="text-align:right">
                                    <span class="status-badge gray">Utkast</span>
                                    <div style="font-size:11px;color:#94a3b8;margin-top:4px">Offert ej skickad</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- ORDER -->
                    <div class="eko-panel" id="eko-order">
                        <div class="dummy-actions"><button class="dummy-btn">+ Ny order</button><button class="dummy-btn secondary">Exportera</button></div>
                        <div class="dummy-table">
                            <div class="dummy-table-header">Orderöversikt</div>
                            <table>
                                <thead><tr><th>Order #</th><th>Kund</th><th>Beskrivning</th><th>Belopp</th><th>Orderdatum</th><th>Leveransdatum</th><th>Status</th></tr></thead>
                                <tbody>
                                    <tr><td>ORD-2026-018</td><td>Andersson Bygg AB</td><td>12 fönster + 2 balkongdörrar</td><td>185 400 kr</td><td>2026-01-15</td><td>2026-02-28</td><td><span class="status-badge green">Levererad</span></td></tr>
                                    <tr><td>ORD-2026-017</td><td>Svensson Fastigheter</td><td>8 fönster villa</td><td>92 500 kr</td><td>2026-01-22</td><td>2026-03-05</td><td><span class="status-badge blue">Under produktion</span></td></tr>
                                    <tr><td>ORD-2026-016</td><td>Johansson & Co</td><td>24 kontorsfönster</td><td>287 200 kr</td><td>2026-02-01</td><td>2026-03-15</td><td><span class="status-badge blue">Under produktion</span></td></tr>
                                    <tr><td>ORD-2026-015</td><td>Nilsson Renovering</td><td>6 fönster + entredörr</td><td>67 300 kr</td><td>2026-01-28</td><td>2026-03-01</td><td><span class="status-badge yellow">Försenad</span></td></tr>
                                    <tr><td>ORD-2026-014</td><td>Pettersson & Söner</td><td>Solpaneler 16st + inverter</td><td>165 000 kr</td><td>2026-02-05</td><td>2026-03-10</td><td><span class="status-badge blue">Bekräftad</span></td></tr>
                                    <tr><td>ORD-2026-013</td><td>Wallin Fastigheter</td><td>6 fönster + foder</td><td>112 000 kr</td><td>2026-02-03</td><td>2026-03-12</td><td><span class="status-badge green">Levererad</span></td></tr>
                                    <tr><td>ORD-2026-012</td><td>Larsson & Partners</td><td>10 fönster radhus</td><td>134 200 kr</td><td>2026-02-08</td><td>2026-03-20</td><td><span class="status-badge blue">Bekräftad</span></td></tr>
                                    <tr><td>ORD-2026-011</td><td>Olsson Bygg & Mål</td><td>4 fönster + balkongdörr</td><td>58 300 kr</td><td>2026-02-10</td><td>2026-03-18</td><td><span class="status-badge gray">Väntar material</span></td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- FAKTUROR -->
                    <div class="eko-panel" id="eko-faktura">
                        <div class="dummy-actions"><button class="dummy-btn">+ Ny faktura</button><button class="dummy-btn secondary">Exportera</button></div>
                        <div class="dummy-table">
                            <div class="dummy-table-header">Fakturor</div>
                            <table>
                                <thead><tr><th>Faktura #</th><th>Kund</th><th>Belopp</th><th>Förfaller</th><th>Status</th></tr></thead>
                                <tbody>
                                    <tr><td>FAK-2026-041</td><td>Andersson Bygg AB</td><td>185 400 kr</td><td>2026-03-10</td><td><span class="status-badge green">Betald</span></td></tr>
                                    <tr><td>FAK-2026-040</td><td>Nilsson Renovering</td><td>67 300 kr</td><td>2026-03-08</td><td><span class="status-badge green">Betald</span></td></tr>
                                    <tr><td>FAK-2026-039</td><td>Svensson Fastigheter</td><td>92 500 kr</td><td>2026-03-14</td><td><span class="status-badge yellow">Förfaller snart</span></td></tr>
                                    <tr><td>FAK-2026-038</td><td>Johansson & Co</td><td>287 200 kr</td><td>2026-03-20</td><td><span class="status-badge blue">Skickad</span></td></tr>
                                    <tr><td>FAK-2026-037</td><td>Wallin Fastigheter</td><td>112 000 kr</td><td>2026-02-28</td><td><span class="status-badge yellow">Förfallen</span></td></tr>
                                    <tr><td>FAK-2026-036</td><td>Pettersson & Söner</td><td>78 900 kr</td><td>2026-03-05</td><td><span class="status-badge blue">Skickad</span></td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- PLOCK -->
                    <div class="eko-panel" id="eko-plock">
                        <div class="dummy-table">
                            <div class="dummy-table-header">Monteringsöversikt</div>
                            <table>
                                <thead><tr><th>Mont. #</th><th>Kund</th><th>Beskrivning</th><th>Montör</th><th>Datum</th><th>Progress</th><th>Status</th></tr></thead>
                                <tbody>
                                    <tr><td>MNT-012</td><td>Andersson Bygg AB</td><td>12 fönster + 2 dörrar</td><td>Erik Lundström</td><td>2026-02-10</td><td class="progress-cell"><div class="progress-bar"><div class="progress-fill" style="width:100%"></div><span class="progress-text">100%</span></div></td><td><span class="status-badge green">Klar</span></td></tr>
                                    <tr><td>MNT-013</td><td>Svensson Fastigheter</td><td>8 fönster villa</td><td>Johan Bergman</td><td>2026-02-14</td><td class="progress-cell"><div class="progress-bar"><div class="progress-fill" style="width:75%"></div><span class="progress-text">75%</span></div></td><td><span class="status-badge blue">Pågår</span></td></tr>
                                    <tr><td>MNT-014</td><td>Johansson & Co</td><td>Kontorsfönster 24 st</td><td>Erik Lundström</td><td>2026-02-18</td><td class="progress-cell"><div class="progress-bar"><div class="progress-fill" style="width:30%"></div><span class="progress-text">30%</span></div></td><td><span class="status-badge blue">Pågår</span></td></tr>
                                    <tr><td>MNT-015</td><td>Nilsson Renovering</td><td>6 fönster + entredörr</td><td>Sofia Nilsson</td><td>2026-02-20</td><td class="progress-cell"><div class="progress-bar"><div class="progress-fill" style="width:0%"></div><span class="progress-text">0%</span></div></td><td><span class="status-badge yellow">Väntar beslag</span></td></tr>
                                    <tr><td>MNT-016</td><td>Pettersson & Söner</td><td>8 fönster</td><td>Johan Bergman</td><td>2026-02-24</td><td class="progress-cell"><div class="progress-bar"><div class="progress-fill" style="width:0%"></div><span class="progress-text">0%</span></div></td><td><span class="status-badge gray">Planerad</span></td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- KUNDRESKONTRA -->
                    <div class="eko-panel" id="eko-reskontra">
                        <div class="dummy-table">
                            <div class="dummy-table-header">Kundreskontra - Utestående fordringar</div>
                            <table>
                                <thead><tr><th>Kund</th><th>Fakturor</th><th>Utestående</th><th>Förfallet</th><th>Senaste betalning</th><th>Kreditgräns</th></tr></thead>
                                <tbody>
                                    <tr><td>Svensson Fastigheter</td><td>2 st</td><td>92 500 kr</td><td style="color:#ef4444;font-weight:600">0 kr</td><td>2026-02-01</td><td>200 000 kr</td></tr>
                                    <tr><td>Johansson & Co</td><td>1 st</td><td>287 200 kr</td><td style="color:#ef4444;font-weight:600">0 kr</td><td>2026-01-28</td><td>400 000 kr</td></tr>
                                    <tr><td>Wallin Fastigheter</td><td>1 st</td><td>112 000 kr</td><td style="color:#ef4444;font-weight:600">112 000 kr</td><td>2026-01-15</td><td>150 000 kr</td></tr>
                                    <tr><td>Pettersson & Söner</td><td>1 st</td><td>78 900 kr</td><td style="color:#ef4444;font-weight:600">0 kr</td><td>2026-02-05</td><td>100 000 kr</td></tr>
                                    <tr><td>Karlsson Entreprenad</td><td>1 st</td><td>35 900 kr</td><td style="color:#ef4444;font-weight:600">0 kr</td><td>2026-02-10</td><td>300 000 kr</td></tr>
                                </tbody>
                            </table>
                        </div>
                        <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px;margin-top:16px">
                            <div class="dr-card"><h4>Totalt utestående</h4><div class="dr-val">606 500 kr</div></div>
                            <div class="dr-card"><h4>Förfallet</h4><div class="dr-val" style="color:#ef4444">112 000 kr</div></div>
                            <div class="dr-card"><h4>Snitt betaltid</h4><div class="dr-val">24 dagar</div></div>
                        </div>
                    </div>

                    <!-- UTLÄGG -->
                    <div class="eko-panel" id="eko-utlagg">
                        <div class="dummy-actions"><button class="dummy-btn">+ Nytt utlägg</button><button class="dummy-btn secondary">Exportera</button></div>
                        <div class="dummy-table">
                            <div class="dummy-table-header">Utlägg</div>
                            <table>
                                <thead><tr><th>Datum</th><th>Säljare</th><th>Kategori</th><th>Beskrivning</th><th>Belopp</th><th>Status</th></tr></thead>
                                <tbody>
                                    <tr><td>2026-02-17</td><td>Erik Lundström</td><td>Drivmedel</td><td>Tankning kundbesök Göteborg</td><td>1 245 kr</td><td><span class="status-badge yellow">Granskas</span></td></tr>
                                    <tr><td>2026-02-16</td><td>Maria Andersson</td><td>Parkering</td><td>P-hus Kungsholmen</td><td>180 kr</td><td><span class="status-badge green">Godkänd</span></td></tr>
                                    <tr><td>2026-02-15</td><td>Erik Lundström</td><td>Representation</td><td>Lunch med kund Svensson</td><td>890 kr</td><td><span class="status-badge green">Godkänd</span></td></tr>
                                    <tr><td>2026-02-14</td><td>Johan Bergman</td><td>Material</td><td>Provbitar till kundvisning</td><td>2 340 kr</td><td><span class="status-badge green">Godkänd</span></td></tr>
                                    <tr><td>2026-02-13</td><td>Sofia Nilsson</td><td>Drivmedel</td><td>Resa Lund-Malmö</td><td>680 kr</td><td><span class="status-badge green">Godkänd</span></td></tr>
                                    <tr><td>2026-02-12</td><td>Erik Lundström</td><td>Hotell</td><td>Övernattning Umeå</td><td>1 490 kr</td><td><span class="status-badge green">Godkänd</span></td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- INKÖP -->
                    <div class="eko-panel" id="eko-inkop">
                        <div class="dummy-actions"><button class="dummy-btn">+ Ny beställning</button><button class="dummy-btn secondary">Exportera</button></div>
                        <div class="dummy-table">
                            <div class="dummy-table-header">Inköpsöversikt</div>
                            <table>
                                <thead><tr><th>Inköp #</th><th>Leverantör</th><th>Beskrivning</th><th>Belopp</th><th>Beställd</th><th>Lev.datum</th><th>Status</th></tr></thead>
                                <tbody>
                                    <tr><td>INK-2026-034</td><td>Optima Fönster AB</td><td>Spröjsade fönster 2-luft, 24 st</td><td>154 800 kr</td><td>2026-02-01</td><td>2026-03-10</td><td><span class="status-badge blue">Under produktion</span></td></tr>
                                    <tr><td>INK-2026-033</td><td>Optima Fönster AB</td><td>Balkongdörrar 2-glas, 4 st</td><td>35 800 kr</td><td>2026-01-28</td><td>2026-03-05</td><td><span class="status-badge yellow">Packas</span></td></tr>
                                    <tr><td>INK-2026-032</td><td>SolarTech Nordic</td><td>Solpaneler 410W Mono, 40 st</td><td>168 000 kr</td><td>2026-02-05</td><td>2026-02-25</td><td><span class="status-badge green">Levererad</span></td></tr>
                                    <tr><td>INK-2026-031</td><td>Tak & Fasad Grossist</td><td>Betongtakpannor, 320 m²</td><td>272 000 kr</td><td>2026-02-03</td><td>2026-03-01</td><td><span class="status-badge blue">Fraktad</span></td></tr>
                                    <tr><td>INK-2026-030</td><td>Dörr & Port Sverige</td><td>Ytterdörrar ek massiv, 3 st</td><td>37 500 kr</td><td>2026-02-08</td><td>2026-03-15</td><td><span class="status-badge blue">Under produktion</span></td></tr>
                                    <tr><td>INK-2026-029</td><td>Isolerings Experten</td><td>Monteringskit + isolering, 50 set</td><td>38 500 kr</td><td>2026-02-10</td><td>2026-02-20</td><td><span class="status-badge green">Levererad</span></td></tr>
                                    <tr><td>INK-2026-028</td><td>Huawei Energy</td><td>Hybridinverter 8kW, 3 st</td><td>67 500 kr</td><td>2026-02-12</td><td>2026-03-08</td><td><span class="status-badge gray">Väntar bekräftelse</span></td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- EVA CHAT (compact sidebar) -->
                <div class="eva-chat-wrap">
                    <div class="eva-chat-header">
                        <img src="eva.png" alt="Eva" class="eva-avatar">
                        <div class="eva-header-info"><h3>Eva Andersson <span class="eva-online"></span></h3><p>Solar Energy Group</p></div>
                    </div>
                    <div class="eva-messages" id="evaMessages">
                        <div class="eva-msg eva">
                            <img src="eva.png" alt="Eva" class="eva-msg-avatar">
                            <div><div class="eva-msg-bubble">Hej! Fråga mig om ekonomi, leveranser eller försäljning.</div><div class="eva-msg-time">nu</div></div>
                        </div>
                    </div>
                    <div class="eva-suggestions" id="evaSuggestions">
                        <button class="eva-suggestion" onclick="evaSuggest(this)">Försäljning?</button>
                        <button class="eva-suggestion" onclick="evaSuggest(this)">Leveransplan?</button>
                        <button class="eva-suggestion" onclick="evaSuggest(this)">Problem?</button>
                        <button class="eva-suggestion" onclick="evaSuggest(this)">Bästa säljare?</button>
                    </div>
                    <div class="eva-input-wrap">
                        <textarea class="eva-input" id="evaInput" placeholder="Fråga Eva..." rows="1" onkeydown="if(event.key==='Enter'&&!event.shiftKey){event.preventDefault();evaSend()}"></textarea>
                        <button class="eva-send" id="evaSendBtn" onclick="evaSend()"><svg viewBox="0 0 24 24"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg></button>
                    </div>
                </div>
            </div>
        </div>

        <!-- BILDGENERERING -->
        <div class="page-content" id="page-bildgen">
            <h1 class="page-title">Bildgenerering</h1>
            <p class="page-subtitle">Generera visualiseringar av renovationsprojekt med AI</p>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:24px">
                <div style="background:#fff;border-radius:12px;padding:25px;border:1px solid #e5e7eb">
                    <h3 style="font-size:16px;font-weight:600;margin-bottom:16px">Skapa visualization</h3>

                    <!-- Steg 1: Foto -->
                    <div style="margin-bottom:18px">
                        <label style="display:block;font-size:13px;font-weight:600;color:#334155;margin-bottom:6px">1. Foto av huset</label>
                        <div style="display:flex;gap:8px">
                            <input type="file" id="bgFileInput" accept="image/*" style="display:none" onchange="handleBgUpload(this)">
                            <input type="file" id="bgCameraInput" accept="image/*" capture="environment" style="display:none" onchange="handleBgUpload(this)">
                            <button onclick="document.getElementById('bgFileInput').click()" style="flex:1;padding:10px;border:1.5px solid #e5e7eb;border-radius:8px;background:#fafbfc;cursor:pointer;font-family:inherit;font-size:13px">Ladda upp</button>
                            <button onclick="document.getElementById('bgCameraInput').click()" style="flex:1;padding:10px;border:1.5px solid #e5e7eb;border-radius:8px;background:#fafbfc;cursor:pointer;font-family:inherit;font-size:13px">Ta foto</button>
                        </div>
                        <div id="bgPreview" style="margin-top:8px;display:none;position:relative">
                            <img id="bgPreviewImg" style="width:100%;height:120px;object-fit:cover;border-radius:8px">
                            <button onclick="clearBgUpload()" style="position:absolute;top:6px;right:6px;background:#ef4444;color:#fff;border:none;border-radius:6px;width:28px;height:28px;cursor:pointer;font-size:14px">✕</button>
                        </div>
                    </div>

                    <!-- Steg 2: Välj typ -->
                    <div style="margin-bottom:18px">
                        <label style="display:block;font-size:13px;font-weight:600;color:#334155;margin-bottom:8px">2. Vad vill du visa?</label>
                        <input type="hidden" id="bgProjectType" value="">
                        <input type="hidden" id="bgPrompt" value="">
                        <div id="bgOptionGrid" style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
                        </div>
                    </div>

                    <!-- Steg 3: Detaljer (visas efter val) -->
                    <div id="bgDetailsPanel" style="display:none;margin-bottom:18px">
                        <label style="display:block;font-size:13px;font-weight:600;color:#334155;margin-bottom:8px">3. Välj stil</label>
                        <div id="bgSubOptions" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px"></div>
                        <div id="bgCountPanel" style="display:none;margin-top:12px">
                            <label id="bgCountLabel" style="display:block;font-size:13px;font-weight:600;color:#334155;margin-bottom:8px">Antal paneler</label>
                            <div id="bgCountOptions" style="display:flex;flex-wrap:wrap;gap:6px"></div>
                        </div>
                    </div>

                    <!-- Steg 4: Extra (valfritt) -->
                    <div style="margin-bottom:14px">
                        <label style="display:block;font-size:13px;font-weight:600;color:#334155;margin-bottom:6px">Extra detaljer (valfritt)</label>
                        <input type="text" id="bgExtraPrompt" placeholder="T.ex. 'sommardag, blå himmel, grön trädgård'" style="width:100%;padding:10px 14px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">
                    </div>

                    <!-- AI-motor -->
                    <div style="margin-bottom:14px">
                        <select id="bgProvider" style="width:100%;padding:8px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:12px;font-family:inherit;color:#64748b">
                            <option value="openai">OpenAI GPT Image</option>
                            <option value="gemini">Google Gemini</option>
                        </select>
                    </div>

                    <button id="bgGenerateBtn" onclick="generateBgImage()" style="width:100%;padding:12px;background:#024550;color:#fff;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit;transition:all .2s">Generera bild</button>
                </div>
                <div style="background:#fff;border-radius:12px;padding:25px;border:1px solid #e5e7eb">
                    <h3 style="font-size:16px;font-weight:600;margin-bottom:16px">Genererad bild</h3>
                    <div id="bgResultArea">
                        <div id="bgPlaceholder" style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:400px;border:2px dashed #e5e7eb;border-radius:12px;color:#94a3b8">
                            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                            <p style="margin-top:12px;font-size:14px">Din genererade bild visas här</p>
                            <p style="margin-top:4px;font-size:12px">Fyll i formuläret och klicka på "Generera bild"</p>
                        </div>
                        <div id="bgLoading" style="display:none;flex-direction:column;align-items:center;justify-content:center;height:400px;border:2px dashed #e5e7eb;border-radius:12px;color:#024550">
                            <div style="width:40px;height:40px;border:3px solid #e5e7eb;border-top:3px solid #024550;border-radius:50%;animation:bgspin 1s linear infinite"></div>
                            <p style="margin-top:16px;font-size:14px;font-weight:500">Genererar bild...</p>
                            <p style="margin-top:4px;font-size:12px;color:#94a3b8">Detta kan ta upp till 30 sekunder</p>
                        </div>
                        <div id="bgResult" style="display:none">
                            <img id="bgResultImg" style="width:100%;border-radius:12px;border:1px solid #e5e7eb">
                            <div style="display:flex;gap:8px;margin-top:12px">
                                <button onclick="downloadBgImage()" style="flex:1;padding:10px;border:1.5px solid #e5e7eb;border-radius:8px;background:#fafbfc;cursor:pointer;font-family:inherit;font-size:13px;font-weight:500">⬇ Ladda ner</button>
                                <button onclick="resetBgResult()" style="flex:1;padding:10px;border:1.5px solid #e5e7eb;border-radius:8px;background:#fafbfc;cursor:pointer;font-family:inherit;font-size:13px;font-weight:500">🔄 Ny bild</button>
                            </div>
                        </div>
                    </div>
                    <!-- Galleri -->
                    <div id="bgGallery" style="margin-top:20px;display:none">
                        <h4 style="font-size:14px;font-weight:600;margin-bottom:10px">Sparade bilder</h4>
                        <div id="bgGalleryGrid" style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px"></div>
                    </div>
                </div>
            </div>
            <style>@keyframes bgspin{to{transform:rotate(360deg)}}</style>
        </div>

        <!-- PERSONAL -->
        <div class="page-content" id="page-personal">
            <h1 class="page-title">Personal</h1>
            <p class="page-subtitle">Hantera teammedlemmar och roller</p>

            <div class="dummy-actions" style="margin-bottom:20px;display:flex;gap:10px;align-items:center">
                <button class="dummy-btn" onclick="showStaffModal()"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> Lägg till personal</button>
                <select id="staffRoleFilter" onchange="loadStaff()" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:'Inter',sans-serif">
                    <option value="">Alla roller</option>
                    <option value="admin">Admin</option>
                    <option value="saljare">Säljare</option>
                    <option value="installator">Installatör</option>
                    <option value="projektledare">Projektledare</option>
                    <option value="ekonomi">Ekonomi</option>
                </select>
                <div style="flex:1"></div>
                <span id="staffCount" style="font-size:13px;color:#94a3b8"></span>
            </div>

            <div class="dummy-table">
                <table>
                    <thead>
                        <tr>
                            <th style="width:50px"></th>
                            <th>Namn</th>
                            <th>E-post</th>
                            <th>Roll</th>
                            <th>Telefon</th>
                            <th>Google</th>
                            <th>Status</th>
                            <th style="width:100px">Åtgärder</th>
                        </tr>
                    </thead>
                    <tbody id="staffTableBody">
                        <tr><td colspan="8" style="text-align:center;padding:40px;color:#94a3b8">Laddar personal...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Staff Modal -->
        <div id="staffModal" style="display:none;position:fixed;inset:0;z-index:9000;background:rgba(0,0,0,.5);display:none;align-items:center;justify-content:center">
            <div style="background:#fff;border-radius:16px;padding:32px;width:480px;max-width:90vw;box-shadow:0 20px 60px rgba(0,0,0,.2)">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:24px">
                    <h3 id="staffModalTitle" style="font-size:18px;font-weight:700;color:#1a1a1a">Lägg till personal</h3>
                    <button onclick="closeStaffModal()" style="background:none;border:none;cursor:pointer;font-size:20px;color:#94a3b8;padding:4px">&times;</button>
                </div>
                <input type="hidden" id="staffEditId">
                <div class="dummy-form-group"><label>Namn *</label><input type="text" id="staffName" placeholder="Anna Andersson"></div>
                <div class="dummy-form-group"><label>E-post *</label><input type="email" id="staffEmail" placeholder="anna@foretag.se"></div>
                <div class="dummy-form-group">
                    <label>Roll</label>
                    <select id="staffRole" style="width:100%;padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:'Inter',sans-serif">
                        <option value="saljare">Säljare</option>
                        <option value="admin">Admin</option>
                        <option value="installator">Installatör</option>
                        <option value="projektledare">Projektledare</option>
                        <option value="ekonomi">Ekonomi</option>
                    </select>
                </div>
                <div class="dummy-form-group"><label>Telefon</label><input type="tel" id="staffPhone" placeholder="070-123 45 67"></div>
                <div class="dummy-form-group"><label>Titel</label><input type="text" id="staffTitle" placeholder="Projektledare Syd"></div>
                <div style="display:flex;gap:10px;margin-top:24px">
                    <button class="dummy-btn" onclick="saveStaff()" style="flex:1">Spara</button>
                    <button class="dummy-btn secondary" onclick="closeStaffModal()">Avbryt</button>
                </div>
                <div id="staffModalError" style="display:none;margin-top:12px;padding:10px;background:#fef2f2;color:#991b1b;border-radius:8px;font-size:13px"></div>
            </div>
        </div>

        <!-- INSTÄLLNINGAR -->
        <div class="page-content" id="page-settings">
            <h1 class="page-title">Inställningar</h1>
            <p class="page-subtitle">Hantera ditt konto och preferenser</p>

            <!-- Settings Tabs -->
            <div style="display:flex;gap:0;margin-bottom:24px;border-bottom:2px solid #e5e7eb">
                <button class="settings-tab active" data-settings-tab="profil" onclick="switchSettingsTab('profil')">Profil</button>
                <button class="settings-tab" data-settings-tab="ai" onclick="switchSettingsTab('ai')">AI Bildgenerering</button>
                <button class="settings-tab" data-settings-tab="foretag" onclick="switchSettingsTab('foretag')">Företag</button>
                <button class="settings-tab" data-settings-tab="google" onclick="switchSettingsTab('google')">Google API</button>
                <button class="settings-tab" data-settings-tab="notiser" onclick="switchSettingsTab('notiser')">Notifieringar</button>
                <button class="settings-tab" data-settings-tab="monday" onclick="switchSettingsTab('monday')">Monday.com</button>
            </div>

            <!-- Tab: Profil -->
            <div class="settings-panel active" id="settings-profil">
                <div class="dummy-form">
                    <h3>Profilinställningar</h3>
                    <div class="dummy-form-group"><label>Namn</label><input type="text" value="Admin User"></div>
                    <div class="dummy-form-group"><label>E-post</label><input type="email" value="admin@solargroup.se"></div>
                    <div class="dummy-form-group"><label>Telefon</label><input type="tel" value="070-123 45 67"></div>
                    <div class="dummy-form-group">
                        <label>Roll</label>
                        <select><option>Administratör</option><option>Säljare</option><option>Installatör</option><option>Projektledare</option><option>Ekonomi</option></select>
                    </div>
                    <div class="dummy-form-group"><label>Språk</label><select><option>Svenska</option><option>English</option></select></div>
                    <button class="dummy-btn" style="margin-top:10px">Spara ändringar</button>
                </div>
                <div class="dummy-form" style="margin-top:20px">
                    <h3>Byt lösenord</h3>
                    <div class="dummy-form-group"><label>Nuvarande lösenord</label><input type="password"></div>
                    <div class="dummy-form-group"><label>Nytt lösenord</label><input type="password"></div>
                    <div class="dummy-form-group"><label>Bekräfta nytt lösenord</label><input type="password"></div>
                    <button class="dummy-btn" style="margin-top:10px">Uppdatera lösenord</button>
                </div>
            </div>

            <!-- Tab: AI Bildgenerering -->
            <div class="settings-panel" id="settings-ai">
                <div class="dummy-form">
                    <h3>AI Bildgenerering</h3>
                    <p style="font-size:13px;color:#64748b;margin-bottom:20px">Konfigurera API-nycklar och modeller för bildgenerering. Alla nycklar sparas i databasen.</p>

                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:24px">
                        <div style="background:#f8fafc;border-radius:10px;padding:20px;border:1px solid #e5e7eb">
                            <h4 style="font-size:15px;margin-bottom:12px;display:flex;align-items:center;gap:8px"><span style="background:#000;color:#fff;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:700">OpenAI</span> GPT Image</h4>
                            <div class="dummy-form-group" style="margin-bottom:12px">
                                <label style="font-size:12px">API-nyckel</label>
                                <input type="password" id="settOpenaiKey" placeholder="sk-proj-..." style="font-family:monospace;font-size:12px">
                            </div>
                            <div class="dummy-form-group" style="margin-bottom:12px">
                                <label style="font-size:12px">Modell</label>
                                <select id="settOpenaiModel" style="font-size:12px">
                                    <option value="gpt-image-1">gpt-image-1</option>
                                    <option value="dall-e-3">DALL-E 3</option>
                                </select>
                            </div>
                            <div id="openaiTestStatus" style="font-size:12px;margin-top:8px"></div>
                        </div>

                        <div style="background:#f8fafc;border-radius:10px;padding:20px;border:1px solid #e5e7eb">
                            <h4 style="font-size:15px;margin-bottom:12px;display:flex;align-items:center;gap:8px"><span style="background:#4285f4;color:#fff;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:700">Google</span> Gemini</h4>
                            <div class="dummy-form-group" style="margin-bottom:12px">
                                <label style="font-size:12px">API-nyckel</label>
                                <input type="password" id="settGeminiKey" placeholder="AIzaSy..." style="font-family:monospace;font-size:12px">
                            </div>
                            <div class="dummy-form-group" style="margin-bottom:12px">
                                <label style="font-size:12px">Modell</label>
                                <select id="settGeminiModel" style="font-size:12px">
                                    <option value="gemini-2.5-flash-preview-04-17">Gemini 2.5 Flash</option>
                                    <option value="gemini-2.0-flash-exp">Gemini 2.0 Flash Exp</option>
                                </select>
                            </div>
                            <div id="geminiTestStatus" style="font-size:12px;margin-top:8px"></div>
                        </div>
                    </div>

                    <div style="margin-top:16px;display:flex;gap:8px;align-items:center">
                        <label style="font-size:13px;font-weight:600;color:#334155">Standard-provider:</label>
                        <select id="settDefaultProvider" style="padding:6px 12px;border:1px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;background:#fff">
                            <option value="openai">OpenAI</option>
                            <option value="gemini">Google Gemini</option>
                        </select>
                    </div>

                    <button class="dummy-btn" style="margin-top:16px" onclick="saveAiSettings()">Spara AI-inställningar</button>
                </div>
            </div>

            <!-- Tab: Företag -->
            <div class="settings-panel" id="settings-foretag">
                <div class="dummy-form">
                    <h3>Företagsinformation</h3>
                    <div class="dummy-form-group"><label>Företagsnamn</label><input type="text" value="Solar Group AB"></div>
                    <div class="dummy-form-group"><label>Org.nummer</label><input type="text" placeholder="556xxx-xxxx"></div>
                    <div class="dummy-form-group"><label>Adress</label><input type="text" placeholder="Gatan 1, 123 45 Stad"></div>
                    <div class="dummy-form-group"><label>Telefon</label><input type="tel" placeholder="08-xxx xx xx"></div>
                    <div class="dummy-form-group"><label>E-post</label><input type="email" placeholder="info@solargroup.se"></div>
                    <div class="dummy-form-group"><label>Hemsida</label><input type="url" placeholder="https://solargroup.se"></div>
                    <button class="dummy-btn" style="margin-top:10px">Spara företagsinfo</button>
                </div>
                <div class="dummy-form" style="margin-top:20px">
                    <h3>Logotyp</h3>
                    <div style="display:flex;align-items:center;gap:16px">
                        <div style="width:80px;height:80px;background:#f1f5f9;border-radius:12px;display:flex;align-items:center;justify-content:center;border:1px solid #e5e7eb">
                            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                        </div>
                        <button class="dummy-btn secondary">Ladda upp logotyp</button>
                    </div>
                </div>
            </div>

            <!-- Tab: Google API -->
            <div class="settings-panel" id="settings-google">
                <div class="dummy-form">
                    <h3>Google OAuth & API-nycklar</h3>
                    <p style="font-size:13px;color:#64748b;margin-bottom:16px">Skapa OAuth-uppgifter i <a href="https://console.cloud.google.com/apis/credentials" target="_blank" style="color:#024550;font-weight:600">Google Cloud Console</a>. Aktivera Gmail API och Google Calendar API.</p>
                    <div style="background:#eff6ff;border:1px solid #dbeafe;border-radius:8px;padding:12px 16px;margin-bottom:16px">
                        <p style="font-size:12px;color:#1e40af;margin:0"><strong>Redirect URI att lägga till i Google Console:</strong></p>
                        <code id="googleRedirectUri" style="font-size:12px;color:#1e40af;background:#dbeafe;padding:2px 6px;border-radius:4px;display:inline-block;margin-top:4px"></code>
                    </div>
                    <div class="dummy-form-group">
                        <label>Google Client ID</label>
                        <input type="text" id="settGoogleClientId" placeholder="xxxxxx.apps.googleusercontent.com" style="font-family:monospace;font-size:12px">
                    </div>
                    <div class="dummy-form-group">
                        <label>Google Client Secret</label>
                        <input type="password" id="settGoogleClientSecret" placeholder="GOCSPX-xxxxxxxx" style="font-family:monospace;font-size:12px">
                        <span id="settGoogleSecretStatus" style="font-size:11px;color:#10b981;margin-left:8px"></span>
                    </div>
                    <div class="dummy-form-group">
                        <label>Google Maps API-nyckel</label>
                        <input type="text" id="settGoogleMapsKey" placeholder="AIzaSy..." style="font-family:monospace;font-size:12px">
                    </div>
                    <button class="dummy-btn" style="margin-top:10px" onclick="saveGoogleSettings()">Spara Google-inställningar</button>
                    <div id="googleSettingsMsg" style="margin-top:8px;font-size:13px"></div>
                </div>
                <div class="dummy-form" style="margin-top:20px">
                    <h3>Scopes som begärs vid inloggning</h3>
                    <p style="font-size:13px;color:#64748b;margin-bottom:12px">Dessa behörigheter begärs automatiskt när en användare loggar in med Google:</p>
                    <div style="display:flex;flex-direction:column;gap:8px">
                        <div style="display:flex;align-items:center;gap:10px;padding:8px 12px;background:#f0fdf4;border-radius:8px;border:1px solid #dcfce7">
                            <span style="font-size:18px">📧</span>
                            <div><strong style="font-size:13px">Gmail</strong><br><span style="font-size:11px;color:#64748b">Läsa, skicka och hantera e-post</span></div>
                        </div>
                        <div style="display:flex;align-items:center;gap:10px;padding:8px 12px;background:#f0fdf4;border-radius:8px;border:1px solid #dcfce7">
                            <span style="font-size:18px">📅</span>
                            <div><strong style="font-size:13px">Google Kalender</strong><br><span style="font-size:11px;color:#64748b">Visa och skapa kalenderhändelser</span></div>
                        </div>
                        <div style="display:flex;align-items:center;gap:10px;padding:8px 12px;background:#f0fdf4;border-radius:8px;border:1px solid #dcfce7">
                            <span style="font-size:18px">👤</span>
                            <div><strong style="font-size:13px">Profil & E-post</strong><br><span style="font-size:11px;color:#64748b">Grundläggande profilinfo och e-postadress</span></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tab: Notifieringar -->
            <div class="settings-panel" id="settings-notiser">
                <div class="dummy-form">
                    <h3>Notifieringsinställningar</h3>
                    <div style="display:flex;flex-direction:column;gap:16px">
                        <label style="display:flex;align-items:center;gap:12px;cursor:pointer">
                            <input type="checkbox" checked style="width:18px;height:18px;accent-color:#024550">
                            <div><strong style="font-size:14px">E-postnotifieringar</strong><br><span style="font-size:12px;color:#94a3b8">Få e-post vid nya offertförfrågningar</span></div>
                        </label>
                        <label style="display:flex;align-items:center;gap:12px;cursor:pointer">
                            <input type="checkbox" checked style="width:18px;height:18px;accent-color:#024550">
                            <div><strong style="font-size:14px">Nya kunder</strong><br><span style="font-size:12px;color:#94a3b8">Notifiera vid nya kundregistreringar</span></div>
                        </label>
                        <label style="display:flex;align-items:center;gap:12px;cursor:pointer">
                            <input type="checkbox" style="width:18px;height:18px;accent-color:#024550">
                            <div><strong style="font-size:14px">Daglig sammanfattning</strong><br><span style="font-size:12px;color:#94a3b8">Daglig rapport via e-post kl 08:00</span></div>
                        </label>
                        <label style="display:flex;align-items:center;gap:12px;cursor:pointer">
                            <input type="checkbox" checked style="width:18px;height:18px;accent-color:#024550">
                            <div><strong style="font-size:14px">Projektuppdateringar</strong><br><span style="font-size:12px;color:#94a3b8">Notifiera vid statusändringar i projekt</span></div>
                        </label>
                    </div>
                    <button class="dummy-btn" style="margin-top:20px">Spara notifieringar</button>
                </div>
            </div>

            <!-- Tab: Monday.com -->
            <div class="settings-panel" id="settings-monday">
                <div class="dummy-form">
                    <h3>Monday.com Integration</h3>
                    <p style="font-size:13px;color:#64748b;margin-bottom:16px">Koppla ihop med Monday.com för att synka projekt, affärer och kontakter.</p>
                    
                    <div class="dummy-form-group">
                        <label>API Token</label>
                        <div style="display:flex;gap:8px">
                            <input type="password" id="settMondayToken" placeholder="eyJhbGciOiJIUzI1NiJ9..." style="font-family:monospace;font-size:12px;flex:1">
                            <button onclick="testMondayConnection()" style="padding:8px 16px;background:#024550;color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;white-space:nowrap">Testa</button>
                        </div>
                        <div id="mondayConnectionStatus" style="margin-top:8px;font-size:12px"></div>
                    </div>

                    <button onclick="saveMondaySettings()" class="dummy-btn" style="margin-top:12px;margin-bottom:24px">Spara</button>

                    <div id="mondayBoardsSection" style="display:none">
                        <h3 style="margin-top:0">Boards</h3>
                        <p style="font-size:12px;color:#94a3b8;margin-bottom:12px">Alla boards i ert Monday-konto</p>
                        <div id="mondayBoardsList" style="display:flex;flex-direction:column;gap:6px"></div>
                    </div>
                </div>
            </div>
        </div>

    </main>

    <!-- MODAL -->
    <div class="modal-overlay" id="quoteModal">
        <div class="modal">
            <div class="modal-header"><h2>Offertförfrågan</h2><button class="modal-close" onclick="closeModal()">x</button></div>
            <div class="modal-body">
                <div class="modal-grid">
                    <div class="modal-left">
                        <div class="modal-section"><div class="modal-section-title">Produkt</div><div class="modal-product"><img src="Photo/2glasspj600.webp" alt="" class="modal-product-image" id="modalProductImage"><div class="modal-product-info"><h3 id="modalProductName">Spröjsat fönster 2-luft</h3><p id="modalDimensions">1190 x 1390 mm</p><p id="modalQuantity" style="color:#10b981;font-weight:600">Antal: 1 st</p></div></div></div>
                        <div class="modal-section"><div class="modal-section-title">Varukorg</div><div class="modal-cart" id="modalCart"></div></div>
                        <div class="modal-section"><div class="modal-section-title">Pris</div><div class="modal-price-summary" id="modalPrices"></div></div>
                    </div>
                    <div class="modal-right">
                        <div class="modal-section"><div class="modal-section-title">Kontakt</div>
                            <form class="modal-form" onsubmit="submitQuote(event)">
                                <div class="modal-form-row"><div class="modal-form-group"><label>Förnamn *</label><input type="text" id="firstName" required></div><div class="modal-form-group"><label>Efternamn *</label><input type="text" id="lastName" required></div></div>
                                <div class="modal-form-group full"><label>E-post *</label><input type="email" id="email" required></div>
                                <div class="modal-form-group full"><label>Telefon *</label><input type="tel" id="phone" required></div>
                                <div class="modal-form-group full"><label>Adress</label><input type="text" id="address"></div>
                                <div class="modal-form-group full"><label>Meddelande</label><textarea id="message"></textarea></div>
                                <button type="submit" class="modal-submit">Skicka offertförfrågan</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function navigateTo(page){
            document.querySelectorAll('.nav-item').forEach(n=>n.classList.remove('active'));
            document.querySelectorAll('.nav-item[data-page="'+page+'"]').forEach(n=>n.classList.add('active'));
            document.querySelectorAll('.page-content').forEach(p=>p.classList.remove('active'));
            const el = document.getElementById('page-'+page);
            if(el) el.classList.add('active');
            // Update mobile nav
            document.querySelectorAll('.mobile-nav a').forEach(a=>{
                a.classList.toggle('active', a.dataset.page===page);
            });
            if(page === 'admin') initAdminPage();
            // Kalkyler: visa listan om inte redan i konfiguratorvyn
            if(page === 'konfigurator'){
                const configView = document.getElementById('kalkylConfigView');
                const affarView = document.getElementById('affarView');
                const configActive = configView && configView.style.display !== 'none';
                const affarActive = affarView && affarView.style.display !== 'none';
                if(!configActive && !affarActive){
                    showKalkylList();
                }
            }
        }
        document.querySelectorAll('.nav-item').forEach(item=>{
            item.addEventListener('click',function(){
                navigateTo(this.dataset.page);
            });
        });
        document.querySelectorAll('.mobile-nav a').forEach(item=>{
            item.addEventListener('click',function(e){
                e.preventDefault();
                navigateTo(this.dataset.page);
            });
        });

        /* Kalkyl list/config view toggle */
        function showKalkylConfig(){
            document.getElementById('kalkylListView').style.display='none';
            document.getElementById('kalkylConfigView').style.display='block';
            const afv = document.getElementById('affarView');
            if(afv) afv.style.display='none';
            const cat = document.getElementById('categorySelect')?.value;
            if(cat) changeCategory();
        }
        function showKalkylList(){
            document.getElementById('kalkylConfigView').style.display='none';
            const afv = document.getElementById('affarView');
            if(afv) afv.style.display='none';
            document.getElementById('kalkylListView').style.display='block';
            kalkylImages = [];
            const kpSec = document.getElementById('kalkylPhotosSection');
            if(kpSec) kpSec.style.display = 'none';
            loadQuotesList();
        }
        function changeCategory(){
            const cat=document.getElementById('categorySelect').value;
            const solar=document.getElementById('solarConfigView');
            const generic=document.getElementById('genericConfigView');
            const afv=document.getElementById('affarView');
            if(afv) afv.style.display='none';
            if(cat==='solceller'){
                solar.style.display='block';
                generic.style.display='none';
                initSolarConfig();
            } else {
                solar.style.display='none';
                generic.style.display='block';
            }
        }

        function fmt(p){return p.toLocaleString('sv-SE')+' kr'}
        function fmtOpt(p){return p===0?'0,00 kr':p>0?'+'+p.toLocaleString('sv-SE')+' kr':p.toLocaleString('sv-SE')+' kr'}

        // === SOLAR CONFIGURATOR ===
        // Pricing from SimCRM: full price 116,250 for 8 panels (before green tech deduction)
        // Green tech = 20% → customer pays 93,000 (=116,250 × 0.80)
        const SOL_FULL_BASE_PRICE = 116250; // Full price before deduction for 8 panels
        const SOL_BASE_PANELS = 8;
        const SOL_FULL_PRICE_PER_PANEL = 3688; // Full price per extra panel
        const SOL_MATERIAL_RATIO = 0.65; // 65% material, 35% installation
        const SOL_LABOR_RATIO = 0.35;
        const SOL_PANEL_AREA = 1.87; // m² per panel
        const SOL_ELECTRICITY_PRICE = 1.50; // kr/kWh
        const SOL_SELF_USE = 0.70;
        const SOL_SELL_PRICE = 0.50; // kr/kWh for surplus
        const SOL_FINANCE_RATE = 0.049; // 4.9% annual
        let SOL_FINANCE_YEARS = 15;
        const GREEN_TECH_RATE = 0.20; // 20% of total (material+labor+battery+charger)
        const ROT_RATE = 0.30; // 30% of labor only

        let solSelectedPanel = null;
        let solSelectedBattery = 0;
        let solSelectedBatteryPrice = 0;
        let solSelectedCharger = null;
        let solSelectedChargerPrice = 0;
        let solOwnerCount = 1;
        let solGreenTechMax = 50000;
        let solDeductionType = 'green'; // 'green', 'rot', 'both', 'none'

        // Current calc state for Affär
        let currentCalcState = {};

        // EV chargers from SimCRM
        const evChargers = [
            {brand:'Garo',model:'22kW',price:26000,desc:'Inkl. lastbalans'},
            {brand:'Zaptec',model:'GO',price:26000,desc:'Inkl. lastbalans'},
            {brand:'Zaptec',model:'PRO 22kW',price:33000,desc:'Inkl. lastbalans'},
            {brand:'Charge Amps',model:'Aura 22kW (2 uttag)',price:40000,desc:'Inkl. lastbalans'}
        ];

        // Battery options from SimCRM
        const batteryOptions = [
            {kwh:5,price:35000,label:'5 kWh'},
            {kwh:10,price:50000,label:'10 kWh'},
            {kwh:15,price:65000,label:'15 kWh'},
            {kwh:20,price:85000,label:'20 kWh'}
        ];

        function initSolarConfig(){
            // Get solar panels from catalog
            const panels = catalogProducts.filter(p => p.watt && p.watt > 0 && p.cat === 'solceller');
            const container = document.getElementById('solarPanelCards');
            if(!panels.length){
                // Retry after catalog loads
                container.innerHTML='<div style="padding:20px;color:#94a3b8;text-align:center"><div class="spinner" style="display:inline-block;width:20px;height:20px;border:2px solid #e5e7eb;border-top-color:#024550;border-radius:50%;animation:bgspin .6s linear infinite"></div><p style="margin-top:6px;font-size:12px">Laddar paneler...</p></div>';
                if(!window._solarRetryCount) window._solarRetryCount = 0;
                if(window._solarRetryCount < 10){
                    window._solarRetryCount++;
                    setTimeout(initSolarConfig, 500);
                } else {
                    container.innerHTML='<div style="padding:20px;color:#94a3b8;text-align:center">Inga solpaneler i katalogen. Lägg till via Produkter.</div>';
                }
                // Still run updateSolarCalc with defaults so price shows
                updateSolarCalc();
                return;
            }
            window._solarRetryCount = 0;

            // Calculate per-panel system cost (inkl. arbete/installation)
            const avgSystemPricePerPanel = Math.round(SOL_FULL_BASE_PRICE / SOL_BASE_PANELS);

            container.innerHTML = panels.map((p,i) => {
                const sel = i===0 ? 'border-color:#3b82f6;background:#f0f9ff' : 'border-color:#e5e7eb;background:#fff';
                const dot = i===0 ? '<div style="width:10px;height:10px;background:#3b82f6;border-radius:50%"></div>' : '';
                const greenTag = p.greenTechEligible ? '<span style="background:#dcfce7;color:#166534;font-size:10px;font-weight:600;padding:2px 6px;border-radius:4px;margin-left:6px">Grönt avdrag</span>' : '';
                return '<div class="sol-panel-card" data-panel-id="'+p.id+'" onclick="selectPanel(this,\''+p.id+'\')" style="padding:14px 16px;border:2px solid;border-radius:10px;cursor:pointer;display:flex;align-items:center;gap:12px;'+sel+'">'
                    +'<div style="width:20px;height:20px;border:2px solid '+(i===0?'#3b82f6':'#cbd5e1')+';border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0">'+dot+'</div>'
                    +(p.img?'<img src="'+p.img+'" style="width:48px;height:48px;object-fit:cover;border-radius:6px;flex-shrink:0">':'<div style="width:48px;height:48px;background:#f1f5f9;border-radius:6px;flex-shrink:0"></div>')
                    +'<div style="flex:1"><div style="font-weight:600;font-size:14px">'+p.name+greenTag+'</div><div style="font-size:12px;color:#64748b">'+p.watt+'W per panel'+(p.desc?' — '+p.desc:'')+'</div></div>'
                    +'<div style="text-align:right"><div style="font-weight:700;font-size:14px;color:#1a1a1a">'+avgSystemPricePerPanel.toLocaleString('sv-SE')+' kr/st</div><div style="font-size:10px;color:#94a3b8">inkl. installation</div></div>'
                    +'</div>';
            }).join('');
            if(panels.length) solSelectedPanel = panels[0];

            // Render battery options
            const batContainer = document.getElementById('solarBatteryCards');
            batContainer.innerHTML = '<div class="sol-addon-card" data-battery="0" onclick="selectBattery(this)" style="padding:14px 16px;border:2px solid #3b82f6;border-radius:10px;cursor:pointer;display:flex;align-items:center;gap:12px;background:#f0f9ff">'
                +'<div style="width:20px;height:20px;border:2px solid #3b82f6;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0"><div style="width:10px;height:10px;background:#3b82f6;border-radius:50%"></div></div>'
                +'<div style="flex:1"><div style="font-weight:600;font-size:14px">Inget batteri</div></div>'
                +'<div style="font-weight:700;font-size:14px;color:#1a1a1a">0 kr</div></div>'
                + batteryOptions.map(b => '<div class="sol-addon-card" data-battery="'+b.kwh+'" data-price="'+b.price+'" onclick="selectBattery(this)" style="padding:14px 16px;border:2px solid #e5e7eb;border-radius:10px;cursor:pointer;display:flex;align-items:center;gap:12px">'
                    +'<div style="width:20px;height:20px;border:2px solid #cbd5e1;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0"></div>'
                    +'<div style="flex:1"><div style="font-weight:600;font-size:14px">'+b.label+' batteri</div><div style="font-size:12px;color:#64748b">Lagra överskottsel'+
                    '<span style="background:#dcfce7;color:#166534;font-size:10px;font-weight:600;padding:2px 6px;border-radius:4px;margin-left:6px">Grönt avdrag</span></div></div>'
                    +'<div style="font-weight:700;font-size:14px;color:#1a1a1a">'+b.price.toLocaleString('sv-SE')+' kr</div></div>').join('');

            // Render EV charger options
            const chgContainer = document.getElementById('solarChargerCards');
            chgContainer.innerHTML = '<div class="sol-addon-card" data-charger="0" onclick="selectCharger(this)" style="padding:14px 16px;border:2px solid #3b82f6;border-radius:10px;cursor:pointer;display:flex;align-items:center;gap:12px;background:#f0f9ff">'
                +'<div style="width:20px;height:20px;border:2px solid #3b82f6;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0"><div style="width:10px;height:10px;background:#3b82f6;border-radius:50%"></div></div>'
                +'<div style="flex:1"><div style="font-weight:600;font-size:14px">Ingen laddare</div></div>'
                +'<div style="font-weight:700;font-size:14px;color:#1a1a1a">0 kr</div></div>'
                + evChargers.map(c => '<div class="sol-addon-card" data-charger="'+c.brand+'-'+c.model+'" data-price="'+c.price+'" onclick="selectCharger(this)" style="padding:14px 16px;border:2px solid #e5e7eb;border-radius:10px;cursor:pointer;display:flex;align-items:center;gap:12px">'
                    +'<div style="width:20px;height:20px;border:2px solid #cbd5e1;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0"></div>'
                    +'<div style="flex:1"><div style="font-weight:600;font-size:14px">'+c.brand+' '+c.model+'</div><div style="font-size:12px;color:#64748b">'+c.desc+
                    '<span style="background:#dcfce7;color:#166534;font-size:10px;font-weight:600;padding:2px 6px;border-radius:4px;margin-left:6px">Grönt avdrag</span></div></div>'
                    +'<div style="font-weight:700;font-size:14px;color:#1a1a1a">'+c.price.toLocaleString('sv-SE')+' kr</div></div>').join('');

            // Sync owner count from customer data if available
            if(pendingKalkylCustomer){
                const ot = pendingKalkylCustomer.ownerType;
                if(ot === '2' || ot === 2) setOwnerCount(2);
                else if(ot === 'brf') { setOwnerCount(1); document.getElementById('solGreenSlider').value = 0; updateGreenSlider(); }
            }

            updateSolarCalc();
        }

        function selectPanel(el, id){
            const p = catalogProducts.find(x => x.id === id);
            if(!p) return;
            solSelectedPanel = p;
            document.querySelectorAll('.sol-panel-card').forEach(c => {
                const isSel = c.dataset.panelId === id;
                c.style.borderColor = isSel ? '#3b82f6' : '#e5e7eb';
                c.style.background = isSel ? '#f0f9ff' : '#fff';
                const dot = c.querySelector('div > div');
                dot.style.borderColor = isSel ? '#3b82f6' : '#cbd5e1';
                dot.innerHTML = isSel ? '<div style="width:10px;height:10px;background:#3b82f6;border-radius:50%"></div>' : '';
            });
            updateSolarCalc();
        }

        function selectBattery(el){
            const kwh = parseInt(el.dataset.battery)||0;
            solSelectedBattery = kwh;
            solSelectedBatteryPrice = parseInt(el.dataset.price)||0;
            document.querySelectorAll('#solarBatteryCards .sol-addon-card').forEach(c => {
                const isSel = c === el;
                c.style.borderColor = isSel ? '#3b82f6' : '#e5e7eb';
                c.style.background = isSel ? '#f0f9ff' : '#fff';
                const dot = c.firstElementChild;
                dot.style.borderColor = isSel ? '#3b82f6' : '#cbd5e1';
                dot.innerHTML = isSel ? '<div style="width:10px;height:10px;background:#3b82f6;border-radius:50%"></div>' : '';
            });
            updateSolarCalc();
        }

        function selectCharger(el){
            const val = el.dataset.charger;
            solSelectedCharger = val === '0' ? null : val;
            solSelectedChargerPrice = parseInt(el.dataset.price)||0;
            document.querySelectorAll('#solarChargerCards .sol-addon-card').forEach(c => {
                const isSel = c === el;
                c.style.borderColor = isSel ? '#3b82f6' : '#e5e7eb';
                c.style.background = isSel ? '#f0f9ff' : '#fff';
                const dot = c.firstElementChild;
                dot.style.borderColor = isSel ? '#3b82f6' : '#cbd5e1';
                dot.innerHTML = isSel ? '<div style="width:10px;height:10px;background:#3b82f6;border-radius:50%"></div>' : '';
            });
            updateSolarCalc();
        }

        function updateSolarCalc(){
            const count = parseInt(document.getElementById('solPanelCount').value)||14;
            document.getElementById('solPanelCountVal').textContent = count;

            const watt = solSelectedPanel ? solSelectedPanel.watt : 430;
            const kwp = (count * watt / 1000).toFixed(1);
            const roofArea = Math.round(count * SOL_PANEL_AREA);
            const yearlyKwh = Math.round(parseFloat(kwp) * 900);
            document.getElementById('solKwpVal').textContent = kwp + ' kWp';
            document.getElementById('solRoofVal').textContent = roofArea + ' m²';
            document.getElementById('solProdVal').textContent = '~' + yearlyKwh.toLocaleString('sv-SE') + ' kWh';

            // Full system price (before green tech deduction)
            let systemFullPrice;
            if(count <= SOL_BASE_PANELS){
                systemFullPrice = SOL_FULL_BASE_PRICE;
            } else {
                systemFullPrice = SOL_FULL_BASE_PRICE + (count - SOL_BASE_PANELS) * SOL_FULL_PRICE_PER_PANEL;
            }

            // Split into material and labor
            const materialCost = Math.round(systemFullPrice * SOL_MATERIAL_RATIO);
            const laborCost = systemFullPrice - materialCost;

            const batteryPrice = solSelectedBatteryPrice;
            const chargerPrice = solSelectedChargerPrice;
            const subtotal = systemFullPrice + batteryPrice + chargerPrice;

            // Deduction calculation based on type
            let sliderMax = parseInt(document.getElementById('solGreenSlider')?.value);
            if(isNaN(sliderMax)) sliderMax = solGreenTechMax;

            let totalDeduction = 0;
            let deductDetail = '';
            const totalLabor = laborCost; // Labor portion of system price

            if(solDeductionType === 'green'){
                const greenCalc = Math.round(subtotal * GREEN_TECH_RATE);
                totalDeduction = Math.min(greenCalc, sliderMax);
                deductDetail = '20% av ' + fmt(subtotal) + ' = ' + fmt(greenCalc) + (greenCalc > sliderMax ? ' (begränsat till ' + fmt(sliderMax) + ')' : '');
            } else if(solDeductionType === 'rot'){
                const rotCalc = Math.round(totalLabor * ROT_RATE);
                totalDeduction = Math.min(rotCalc, sliderMax);
                deductDetail = '30% av arbete ' + fmt(totalLabor) + ' = ' + fmt(rotCalc) + (rotCalc > sliderMax ? ' (begränsat till ' + fmt(sliderMax) + ')' : '');
            } else if(solDeductionType === 'both'){
                // Green tech on material+battery+charger, ROT on labor
                const greenBase = materialCost + batteryPrice + chargerPrice;
                const greenCalc = Math.round(greenBase * GREEN_TECH_RATE);
                const rotCalc = Math.round(totalLabor * ROT_RATE);
                const bothTotal = greenCalc + rotCalc;
                totalDeduction = Math.min(bothTotal, sliderMax);
                deductDetail = 'Grönt: ' + fmt(greenCalc) + ' + ROT: ' + fmt(rotCalc) + ' = ' + fmt(bothTotal);
            } else {
                totalDeduction = 0;
                deductDetail = 'Inget avdrag valt';
            }

            const total = subtotal - totalDeduction;

            document.getElementById('solPrMaterial').textContent = fmt(materialCost);
            document.getElementById('solPrLabor').textContent = fmt(laborCost);
            document.getElementById('solPrBattery').textContent = batteryPrice > 0 ? fmt(batteryPrice) : '0 kr';
            document.getElementById('solPrCharger').textContent = chargerPrice > 0 ? fmt(chargerPrice) : '0 kr';
            document.getElementById('solPrSubtotal').textContent = fmt(subtotal);
            document.getElementById('solPrGreenTech').textContent = totalDeduction > 0 ? '-' + fmt(totalDeduction) : '0 kr';
            const detailEl = document.getElementById('solDeductDetail');
            if(detailEl) detailEl.textContent = deductDetail;

            const el = document.getElementById('solPrTotal');
            if(el) el.textContent = fmt(total);

            // Monthly financing
            const r = SOL_FINANCE_RATE / 12;
            const n = SOL_FINANCE_YEARS * 12;
            const monthly = total > 0 ? Math.round(total * r * Math.pow(1+r,n) / (Math.pow(1+r,n)-1)) : 0;
            document.getElementById('solPrMonthly').textContent = monthly.toLocaleString('sv-SE') + ' kr/mån';

            // Yearly savings
            const selfUseKwh = yearlyKwh * SOL_SELF_USE;
            const surplusKwh = yearlyKwh * (1 - SOL_SELF_USE);
            const yearlySaving = Math.round(selfUseKwh * SOL_ELECTRICITY_PRICE + surplusKwh * SOL_SELL_PRICE);
            const payback = total > 0 ? (total / yearlySaving).toFixed(1) : 0;
            document.getElementById('solPrSaving').textContent = yearlySaving.toLocaleString('sv-SE') + ' kr/år';
            document.getElementById('solPrPayback').textContent = payback + ' år';

            // Store state for Affär
            currentCalcState = {
                panelId: solSelectedPanel?.id,
                panelName: solSelectedPanel?.name || 'Okänd',
                panelWatt: watt,
                panelCount: count,
                kwp: parseFloat(kwp),
                roofArea,
                yearlyKwh,
                materialCost,
                laborCost,
                systemFullPrice,
                batteryKwh: solSelectedBattery,
                batteryPrice,
                chargerName: solSelectedCharger,
                chargerPrice,
                subtotal,
                greenTechDeduction: totalDeduction,
                deductionType: solDeductionType,
                total,
                monthly,
                yearlySaving,
                payback: parseFloat(payback),
                financeYears: SOL_FINANCE_YEARS,
                financeRate: SOL_FINANCE_RATE,
                ownerCount: solOwnerCount
            };
        }

        function setDeductionType(type){
            solDeductionType = type;
            const label = document.getElementById('solDeductLabel');
            const ownerSection = document.getElementById('solOwnerSection');
            const sliderSection = document.getElementById('solSliderSection');
            const colors = {green:'#059669', rot:'#2563eb', both:'#7c3aed', none:'#94a3b8'};
            const labels = {green:'GRÖNT TEKNIK-AVDRAG', rot:'ROT-AVDRAG', both:'GRÖNT TEKNIK + ROT', none:'INGET AVDRAG'};
            const col = colors[type] || '#059669';

            if(label){ label.textContent = labels[type] || ''; label.style.color = col; }
            document.getElementById('solPrGreenTech').style.color = col;

            // Show/hide owner + slider for all except 'none'
            if(ownerSection) ownerSection.style.display = type === 'none' ? 'none' : '';
            if(sliderSection) sliderSection.style.display = type === 'none' ? 'none' : '';

            // Update slider accent color
            const slider = document.getElementById('solGreenSlider');
            if(slider) slider.style.accentColor = col;

            // Update button styles
            document.querySelectorAll('.deduct-btn').forEach(b => {
                const dt = b.dataset.dt;
                if(dt === type){
                    b.style.background = col; b.style.color = '#fff'; b.style.borderColor = col;
                } else {
                    b.style.background = '#fff'; b.style.color = col; b.style.borderColor = '#e5e7eb';
                }
            });

            updateSolarCalc();
        }

        function setOwnerCount(count){
            solOwnerCount = count;
            const maxPerPerson = 50000;
            const newMax = count * maxPerPerson;
            const slider = document.getElementById('solGreenSlider');
            if(slider){
                slider.max = newMax;
                // If current value exceeds new max, or was at old max, set to new max
                if(parseInt(slider.value) > newMax || parseInt(slider.value) === solGreenTechMax){
                    slider.value = newMax;
                }
            }
            solGreenTechMax = newMax;
            document.getElementById('solGreenSliderMax').textContent = newMax.toLocaleString('sv-SE') + ' kr';
            document.querySelectorAll('.owner-btn').forEach(b => {
                const oc = parseInt(b.dataset.oc);
                if(oc === count){
                    b.style.background = '#059669'; b.style.color = '#fff'; b.style.borderColor = '#059669';
                } else {
                    b.style.background = '#fff'; b.style.color = '#059669'; b.style.borderColor = '#bbf7d0';
                }
            });
            updateGreenSlider();
        }

        function updateGreenSlider(){
            const val = parseInt(document.getElementById('solGreenSlider').value)||0;
            document.getElementById('solGreenSliderVal').textContent = val.toLocaleString('sv-SE') + ' kr';
            updateSolarCalc();
        }

        function setFinanceYears(yrs){
            SOL_FINANCE_YEARS = yrs;
            document.querySelectorAll('.fin-yr-btn').forEach(b => {
                const y = parseInt(b.dataset.yr);
                if(y === yrs){
                    b.style.background = '#3b82f6';
                    b.style.color = '#fff';
                    b.style.borderColor = '#3b82f6';
                } else {
                    b.style.background = '#fff';
                    b.style.color = '#3b82f6';
                    b.style.borderColor = '#bfdbfe';
                }
            });
            const info = document.getElementById('solFinanceInfo');
            if(info) info.textContent = '('+yrs+' år, 4.9%)';
            updateSolarCalc();
        }

        // === AFFÄR (DEAL) FUNCTIONS ===
        let currentQuoteId = null;
        let affarExtraCosts = [];
        let affarImages = [];

        function goToAffar(){
            if(!currentCalcState.panelCount){
                alert('Välj panel och antal först');
                return;
            }
            // Hide kalkyl views, show affär
            document.getElementById('solarConfigView').style.display='none';
            document.getElementById('affarView').style.display='block';

            // Fill customer banner
            const banner = document.getElementById('affarCustomerBanner');
            const c = pendingKalkylCustomer;
            if(c){
                banner.innerHTML='<div style="background:linear-gradient(135deg,#ecfdf5,#f0f9ff);border:1px solid #bbf7d0;border-radius:12px;padding:14px 18px;display:flex;align-items:center;gap:16px;flex-wrap:wrap">'
                    +'<div style="flex:1;min-width:200px"><div style="font-weight:700;font-size:15px;color:#1a1a1a">'+c.name+'</div><div style="font-size:12px;color:#64748b">'+c.address+'</div></div>'
                    +(c.phone?'<div style="font-size:13px;color:#334155">'+c.phone+'</div>':'')
                    +(c.email?'<div style="font-size:13px;color:#334155">'+c.email+'</div>':'')
                    +'</div>';
            } else {
                banner.innerHTML='';
            }

            // Fill config summary
            const cs = currentCalcState;
            const summary = document.getElementById('affarConfigSummary');
            let rows = '<div style="display:flex;justify-content:space-between;padding:8px 12px;background:#f8fafc;border-radius:8px"><span style="font-size:13px;color:#64748b">Solpaneler</span><span style="font-size:13px;font-weight:600">'+cs.panelName+' × '+cs.panelCount+' ('+cs.kwp+' kWp)</span></div>';
            if(cs.batteryKwh>0) rows += '<div style="display:flex;justify-content:space-between;padding:8px 12px;background:#f8fafc;border-radius:8px"><span style="font-size:13px;color:#64748b">Batteri</span><span style="font-size:13px;font-weight:600">'+cs.batteryKwh+' kWh</span></div>';
            if(cs.chargerName) rows += '<div style="display:flex;justify-content:space-between;padding:8px 12px;background:#f8fafc;border-radius:8px"><span style="font-size:13px;color:#64748b">Laddare</span><span style="font-size:13px;font-weight:600">'+cs.chargerName+'</span></div>';
            rows += '<div style="display:flex;justify-content:space-between;padding:8px 12px;background:#f8fafc;border-radius:8px"><span style="font-size:13px;color:#64748b">Takyta</span><span style="font-size:13px;font-weight:600">'+cs.roofArea+' m²</span></div>';
            rows += '<div style="display:flex;justify-content:space-between;padding:8px 12px;background:#ecfdf5;border-radius:8px"><span style="font-size:13px;color:#059669;font-weight:600">Uppsk. produktion</span><span style="font-size:13px;font-weight:700;color:#059669">~'+cs.yearlyKwh.toLocaleString('sv-SE')+' kWh/år</span></div>';
            summary.innerHTML = rows;

            // Reset extras
            affarExtraCosts = [];
            // Överför valda kalkylbilder till affär
            affarImages = kalkylImages.filter(i => i.selected).map(i => ({ url: i.url, type: i.type, created: i.created }));
            currentQuoteId = null;
            document.getElementById('affarNotes').value = '';
            document.getElementById('affarMarginSlider').value = 0;
            renderAffarExtras();
            renderAffarImages();
            updateAffarCalc();
        }

        function backToKalkylFromAffar(){
            document.getElementById('affarView').style.display='none';
            document.getElementById('solarConfigView').style.display='block';
        }

        function addExtraCost(){
            affarExtraCosts.push({name:'',amount:0});
            renderAffarExtras();
        }

        function removeExtraCost(idx){
            affarExtraCosts.splice(idx,1);
            renderAffarExtras();
            updateAffarCalc();
        }

        function renderAffarExtras(){
            const container = document.getElementById('affarExtraCosts');
            const empty = document.getElementById('affarExtraCostsEmpty');
            if(affarExtraCosts.length===0){
                container.innerHTML='';
                empty.style.display='block';
                return;
            }
            empty.style.display='none';
            container.innerHTML = affarExtraCosts.map((ec,i) =>
                '<div style="display:flex;gap:8px;align-items:center;margin-bottom:8px">'
                +'<input type="text" value="'+(ec.name||'').replace(/"/g,'&quot;')+'" placeholder="Beskrivning (t.ex. Extra kabelarbete)" oninput="affarExtraCosts['+i+'].name=this.value" style="flex:1;padding:8px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit">'
                +'<input type="number" value="'+(ec.amount||0)+'" placeholder="Belopp" oninput="affarExtraCosts['+i+'].amount=parseInt(this.value)||0;updateAffarCalc()" style="width:120px;padding:8px 12px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;text-align:right">'
                +'<span style="font-size:12px;color:#64748b;flex-shrink:0">kr</span>'
                +'<button onclick="removeExtraCost('+i+')" style="background:none;border:none;cursor:pointer;padding:4px;color:#ef4444;flex-shrink:0"><svg viewBox="0 0 24 24" style="width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>'
                +'</div>'
            ).join('');
        }

        function updateAffarCalc(){
            const cs = currentCalcState;
            if(!cs.subtotal) return;

            const margin = parseInt(document.getElementById('affarMarginSlider').value)||0;
            document.getElementById('affarMarginVal').textContent = margin + '%';

            const extrasTotal = affarExtraCosts.reduce((sum,ec)=>sum+(ec.amount||0),0);
            const baseBeforeMargin = cs.subtotal + extrasTotal;
            const marginAmount = Math.round(baseBeforeMargin * margin / 100);
            const totalBeforeDeduction = baseBeforeMargin + marginAmount;

            // Use same deduction logic as kalkyl based on deductionType
            const dt = cs.deductionType || 'green';
            const sliderMax = cs.greenTechDeduction > 0 ? (cs.total + cs.greenTechDeduction - cs.subtotal + cs.greenTechDeduction) : 50000;
            const ownerMax = (cs.ownerCount || 1) * 50000;
            let totalDeduction = 0;
            const totalLabor = cs.laborCost + Math.round(extrasTotal * SOL_LABOR_RATIO) + Math.round(marginAmount * SOL_LABOR_RATIO);
            const totalMaterial = totalBeforeDeduction - totalLabor;

            if(dt === 'green'){
                totalDeduction = Math.min(Math.round(totalBeforeDeduction * GREEN_TECH_RATE), ownerMax);
            } else if(dt === 'rot'){
                totalDeduction = Math.min(Math.round(totalLabor * ROT_RATE), ownerMax);
            } else if(dt === 'both'){
                const greenCalc = Math.round(totalMaterial * GREEN_TECH_RATE);
                const rotCalc = Math.round(totalLabor * ROT_RATE);
                totalDeduction = Math.min(greenCalc + rotCalc, ownerMax);
            }
            const dealTotal = totalBeforeDeduction - totalDeduction;

            // Update sidebar
            document.getElementById('affarPrMaterial').textContent = fmt(cs.materialCost);
            document.getElementById('affarPrLabor').textContent = fmt(cs.laborCost);
            document.getElementById('affarPrBattery').textContent = cs.batteryPrice > 0 ? fmt(cs.batteryPrice) : '0 kr';
            document.getElementById('affarPrCharger').textContent = cs.chargerPrice > 0 ? fmt(cs.chargerPrice) : '0 kr';

            const extraRow = document.getElementById('affarPrExtraRow');
            if(extrasTotal > 0){ extraRow.style.display=''; document.getElementById('affarPrExtra').textContent = fmt(extrasTotal); }
            else extraRow.style.display='none';

            const marginRow = document.getElementById('affarPrMarginRow');
            if(margin > 0){ marginRow.style.display=''; document.getElementById('affarPrMargin').textContent = fmt(marginAmount); document.getElementById('affarPrMarginPct').textContent='('+margin+'%)'; }
            else marginRow.style.display='none';

            document.getElementById('affarPrSubtotal').textContent = fmt(totalBeforeDeduction);
            document.getElementById('affarPrGreenTech').textContent = totalDeduction > 0 ? '-' + fmt(totalDeduction) : '0 kr';
            // Update deduction label and colors in affär
            const deductLabels = {green:'GRÖNT TEKNIK-AVDRAG', rot:'ROT-AVDRAG', both:'GRÖNT TEKNIK + ROT', none:'INGET AVDRAG'};
            const deductColors = {green:'#059669', rot:'#2563eb', both:'#7c3aed', none:'#94a3b8'};
            const deductBgs = {green:'#ecfdf5', rot:'#eff6ff', both:'#f5f3ff', none:'#f8fafc'};
            const dLabel = document.getElementById('affarDeductLabel');
            const dRow = document.getElementById('affarDeductionRow');
            if(dLabel){ dLabel.textContent = deductLabels[dt] || 'AVDRAG'; dLabel.style.color = deductColors[dt] || '#059669'; }
            if(dRow) dRow.style.background = deductBgs[dt] || '#ecfdf5';
            document.getElementById('affarPrGreenTech').style.color = deductColors[dt] || '#059669';
            document.getElementById('affarPrTotal').textContent = fmt(dealTotal);

            // Monthly
            const r = SOL_FINANCE_RATE / 12;
            const n = SOL_FINANCE_YEARS * 12;
            const monthly = dealTotal > 0 ? Math.round(dealTotal * r * Math.pow(1+r,n) / (Math.pow(1+r,n)-1)) : 0;
            document.getElementById('affarPrMonthly').textContent = monthly.toLocaleString('sv-SE') + ' kr/mån';

            // Margin info
            document.getElementById('affarMarginKr').textContent = fmt(marginAmount);
            const profit = marginAmount + extrasTotal;
            document.getElementById('affarProfit').textContent = fmt(profit);
        }

        // Hämta prospektbilder från fältsälj
        function addProspectPhotosToAffar(){
            const c = pendingKalkylCustomer;
            if(!c || c.prospectIdx === undefined) { alert('Ingen prospekt kopplad'); return; }
            const p = faltProspects[c.prospectIdx];
            if(!p || !p.photos || p.photos.length === 0) { alert('Inga bilder finns på prospektet. Ta bilder i FältSälj först.'); return; }

            let added = 0;
            p.photos.forEach(ph => {
                const url = ph.full || ph.url || ph.dataUrl || ph.thumb;
                if(url && !affarImages.find(ai => ai.url === url)){
                    affarImages.push({ url: url, type: ph.type || 'photo', created: ph.created || new Date().toISOString() });
                    added++;
                }
            });
            if(added > 0) renderAffarImages();
            else alert('Alla prospektbilder finns redan i offerten.');
        }

        // Skapa prospektbild (med husbilder + solceller)
        async function createProspectImage(){
            const btn = document.getElementById('affarGenImgBtn');
            const cs = currentCalcState;
            const c = pendingKalkylCustomer;
            const addr = c ? c.address : 'Svenskt hus';

            btn.disabled = true;
            btn.innerHTML = '<svg style="width:14px;height:14px;animation:spin 1s linear infinite" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg> Skapar bild...';

            try {
                const prompt = 'Photorealistic image of a Swedish residential house at '+addr+' with '+cs.panelCount+' modern black solar panels installed on the roof. Sunny day, blue sky, Swedish neighborhood. Professional real estate photography style.';
                const resp = await fetch('/api/generate-image.php', {
                    method:'POST',
                    headers:{'Content-Type':'application/json'},
                    body: JSON.stringify({prompt, size:'1024x1024'})
                });
                const data = await resp.json();
                if(data.success && data.image_url){
                    affarImages.push({url: data.image_url, type: 'prospect', created: new Date().toISOString()});
                    renderAffarImages();
                } else {
                    alert('Kunde inte skapa bild: ' + (data.error || 'Okänt fel'));
                }
            } catch(e){
                alert('Kunde inte skapa bild: ' + e.message);
            } finally {
                btn.disabled = false;
                btn.innerHTML = '<svg viewBox="0 0 24 24" style="width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:2"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg> Skapa prospektbild';
            }
        }

        function renderAffarImages(){
            const container = document.getElementById('affarImages');
            const empty = document.getElementById('affarImagesEmpty');
            if(affarImages.length===0){
                container.innerHTML='';
                empty.style.display='block';
                return;
            }
            empty.style.display='none';
            container.innerHTML = affarImages.map((img,i) =>
                '<div style="position:relative;border-radius:10px;overflow:hidden;border:1px solid #e5e7eb">'
                +'<img src="'+img.url+'" style="width:100%;height:140px;object-fit:cover;cursor:pointer" onclick="openLightbox(\''+img.url.replace(/'/g,"\\'")+'\')">'
                +'<button onclick="affarImages.splice('+i+',1);renderAffarImages()" style="position:absolute;top:6px;right:6px;width:24px;height:24px;background:rgba(0,0,0,.5);color:#fff;border:none;border-radius:50%;cursor:pointer;font-size:14px;display:flex;align-items:center;justify-content:center">&times;</button>'
                +'</div>'
            ).join('');
        }

        // Lightbox
        function openLightbox(url){
            const lb = document.getElementById('imgLightbox');
            const img = document.getElementById('imgLightboxImg');
            if(lb && img){ img.src = url; lb.style.display = 'flex'; }
        }
        function closeLightbox(){
            const lb = document.getElementById('imgLightbox');
            if(lb) lb.style.display = 'none';
        }

        // Spara kalkyl från steg 1 (konfiguratorn, utan affär)
        async function saveKalkylDraft(){
            const cs = currentCalcState;
            if(!cs.panelCount){ alert('Välj panel och antal först'); return; }
            const c = pendingKalkylCustomer || {};
            const selectedImages = kalkylImages.filter(i => i.selected);

            const payload = {
                customer_name: c.name || null,
                customer_address: c.address || null,
                customer_email: c.email || null,
                customer_phone: c.phone || null,
                customer_personnummer: (c.owner1 && c.owner1.pnr) || null,
                owner_count: cs.ownerCount || 1,
                panel_id: cs.panelId,
                panel_name: cs.panelName,
                panel_count: cs.panelCount,
                panel_watt: cs.panelWatt,
                battery_kwh: cs.batteryKwh || 0,
                battery_price: cs.batteryPrice || 0,
                charger_name: cs.chargerName || null,
                charger_price: cs.chargerPrice || 0,
                material_cost: cs.materialCost,
                labor_cost: cs.laborCost,
                subtotal: cs.subtotal,
                green_tech_deduction: cs.greenTechDeduction || 0,
                total_price: cs.totalPrice || cs.subtotal,
                extra_costs: [],
                margin_percent: 0,
                deal_total: cs.totalPrice || cs.subtotal,
                images: selectedImages,
                notes: null,
                status: 'utkast',
                created_by: gStaffId || null,
                finance_years: SOL_FINANCE_YEARS,
                finance_rate: SOL_FINANCE_RATE,
                yearly_kwh: cs.yearlyKwh,
                roof_area: cs.roofArea,
                prospect_data: c.solarData || null
            };

            if(currentQuoteId) payload.id = currentQuoteId;

            const btn = document.getElementById('saveKalkylBtn');
            btn.disabled = true;
            btn.innerHTML = '<svg style="width:14px;height:14px;animation:spin 1s linear infinite" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg> Sparar...';

            try {
                const resp = await fetch('/api/quotes.php', {
                    method:'POST',
                    headers:{'Content-Type':'application/json'},
                    body: JSON.stringify(payload)
                });
                const data = await resp.json();
                if(data.success){
                    currentQuoteId = data.id || currentQuoteId;
                    btn.innerHTML = '<svg viewBox="0 0 24 24" style="width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:2"><circle cx="12" cy="12" r="10"/><path d="M9 12l2 2 4-4"/></svg> Sparad!';
                    btn.style.background = '#059669';
                    setTimeout(()=>{ btn.innerHTML='<svg viewBox="0 0 24 24" style="width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg> Spara kalkyl'; btn.style.background='#f59e0b'; }, 2000);
                    // Uppdatera prospektstatus
                    const pIdx = (pendingKalkylCustomer||{}).prospectIdx;
                    if(pIdx >= 0 && faltProspects[pIdx] && faltProspects[pIdx].status !== 'offert'){
                        faltProspects[pIdx].status = 'kalkyl';
                        faltProspects[pIdx].quoteId = currentQuoteId;
                        localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
                        renderFaltMarkers(); renderFaltList(); updateFaltStats(); renderLeadsTable();
                    }
                    loadQuotesList();
                } else {
                    alert('Kunde inte spara: '+(data.error||'Okänt fel'));
                }
            } catch(e){
                alert('Kunde inte spara: '+e.message);
            } finally {
                btn.disabled = false;
            }
        }

        // Save as draft (from affär view)
        async function saveQuoteAsDraft(){
            const cs = currentCalcState;
            const c = pendingKalkylCustomer || {};
            const margin = parseInt(document.getElementById('affarMarginSlider').value)||0;
            const extrasTotal = affarExtraCosts.reduce((sum,ec)=>sum+(ec.amount||0),0);
            const baseBeforeMargin = cs.subtotal + extrasTotal;
            const marginAmount = Math.round(baseBeforeMargin * margin / 100);
            const totalBeforeDeduction = baseBeforeMargin + marginAmount;

            // Same deduction logic as updateAffarCalc
            const dt = cs.deductionType || 'green';
            const ownerMax = (cs.ownerCount || 1) * 50000;
            const totalLabor = cs.laborCost + Math.round(extrasTotal * SOL_LABOR_RATIO) + Math.round(marginAmount * SOL_LABOR_RATIO);
            const totalMaterial = totalBeforeDeduction - totalLabor;
            let totalDeduction = 0;
            if(dt === 'green') totalDeduction = Math.min(Math.round(totalBeforeDeduction * GREEN_TECH_RATE), ownerMax);
            else if(dt === 'rot') totalDeduction = Math.min(Math.round(totalLabor * ROT_RATE), ownerMax);
            else if(dt === 'both'){ totalDeduction = Math.min(Math.round(totalMaterial * GREEN_TECH_RATE) + Math.round(totalLabor * ROT_RATE), ownerMax); }
            const dealTotal = totalBeforeDeduction - totalDeduction;

            const payload = {
                customer_name: c.name || null,
                customer_address: c.address || null,
                customer_email: c.email || null,
                customer_phone: c.phone || null,
                customer_personnummer: c.personnummer || null,
                owner_count: cs.ownerCount || 1,
                panel_id: cs.panelId,
                panel_name: cs.panelName,
                panel_count: cs.panelCount,
                panel_watt: cs.panelWatt,
                battery_kwh: cs.batteryKwh || 0,
                battery_price: cs.batteryPrice || 0,
                charger_name: cs.chargerName || null,
                charger_price: cs.chargerPrice || 0,
                material_cost: cs.materialCost,
                labor_cost: cs.laborCost,
                subtotal: totalBeforeDeduction,
                green_tech_deduction: totalDeduction,
                total_price: dealTotal,
                extra_costs: affarExtraCosts.filter(ec => ec.name && ec.amount),
                margin_percent: margin,
                deal_total: dealTotal,
                images: affarImages,
                notes: document.getElementById('affarNotes').value || null,
                status: 'utkast',
                created_by: gStaffId || null,
                finance_years: SOL_FINANCE_YEARS,
                finance_rate: SOL_FINANCE_RATE,
                yearly_kwh: cs.yearlyKwh,
                roof_area: cs.roofArea,
                prospect_data: c.solarData || null
            };

            if(currentQuoteId) payload.id = currentQuoteId;

            try {
                const resp = await fetch('/api/quotes.php', {
                    method:'POST',
                    headers:{'Content-Type':'application/json'},
                    body: JSON.stringify(payload)
                });
                const data = await resp.json();
                if(data.success){
                    currentQuoteId = data.id || currentQuoteId;
                    const statusEl = document.getElementById('affarStatus');
                    statusEl.textContent = 'Utkast sparad ✓';
                    statusEl.style.background = '#dcfce7';
                    statusEl.style.color = '#166534';
                    setTimeout(()=>{ statusEl.textContent='Utkast'; statusEl.style.background='#fef3c7'; statusEl.style.color='#92400e'; }, 2000);
                    // Uppdatera prospektstatus till "kalkyl"
                    const pIdx = (pendingKalkylCustomer||{}).prospectIdx;
                    if(pIdx >= 0 && faltProspects[pIdx] && faltProspects[pIdx].status !== 'offert'){
                        faltProspects[pIdx].status = 'kalkyl';
                        faltProspects[pIdx].quoteId = currentQuoteId;
                        localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
                        renderFaltMarkers(); renderFaltList(); updateFaltStats(); renderLeadsTable();
                    }
                    loadQuotesList();
                } else {
                    alert('Kunde inte spara: ' + (data.error || 'Okänt fel'));
                }
            } catch(e){
                alert('Kunde inte spara: ' + e.message);
            }
        }

        async function createFinalQuote(){
            await saveQuoteAsDraft();
            if(!currentQuoteId) return;
            // Update status to offert
            try {
                await fetch('/api/quotes.php', {
                    method:'POST',
                    headers:{'Content-Type':'application/json'},
                    body: JSON.stringify({id: currentQuoteId, status: 'offert'})
                });
                const statusEl = document.getElementById('affarStatus');
                statusEl.textContent = 'Offert skapad!';
                statusEl.style.background = '#dcfce7';
                statusEl.style.color = '#166534';
                // Uppdatera prospektstatus till "offert"
                const pIdx = (pendingKalkylCustomer||{}).prospectIdx;
                if(pIdx >= 0 && faltProspects[pIdx]){
                    faltProspects[pIdx].status = 'offert';
                    faltProspects[pIdx].quoteId = currentQuoteId;
                    localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
                    renderFaltMarkers(); renderFaltList(); updateFaltStats(); renderLeadsTable();
                }
                loadQuotesList();
                alert('Offert #' + currentQuoteId + ' skapad!\n\nOffert-PDF generering kommer i nästa steg.');
            } catch(e){
                alert('Kunde inte skapa offert: ' + e.message);
            }
        }

        // Load quotes from DB into list
        async function loadQuotesList(){
            const body = document.getElementById('quotesListBody');
            if(!body) return;

            const status = document.getElementById('quotesFilterStatus')?.value || '';
            const search = document.getElementById('quotesSearch')?.value.trim() || '';
            let url = '/api/quotes.php?';
            if(status) url += 'status='+encodeURIComponent(status)+'&';
            if(search) url += 'search='+encodeURIComponent(search)+'&';

            try {
                const resp = await fetch(url);
                const data = await resp.json();
                if(!data.success || !data.quotes || data.quotes.length === 0){
                    body.innerHTML = '<tr><td colspan="9" style="padding:40px;text-align:center;color:#94a3b8;font-size:14px">Inga kalkyler hittade</td></tr>';
                    return;
                }

                const statusMap = {
                    utkast: {bg:'#fef3c7',color:'#92400e',label:'Utkast'},
                    skickad: {bg:'#e0f2fe',color:'#0369a1',label:'Skickad'},
                    offert: {bg:'#e0f2fe',color:'#0369a1',label:'Offert'},
                    'godkänd': {bg:'#dcfce7',color:'#166534',label:'Godkänd'},
                    'förlorad': {bg:'#fee2e2',color:'#991b1b',label:'Förlorad'}
                };

                body.innerHTML = data.quotes.map(q => {
                    const st = statusMap[q.status] || {bg:'#f1f5f9',color:'#64748b',label:q.status||'—'};
                    const date = q.updated_at ? q.updated_at.slice(0,10) : (q.created_at||'').slice(0,10);
                    const amount = q.deal_total ? parseInt(q.deal_total).toLocaleString('sv-SE')+' kr' : (q.total_price ? parseInt(q.total_price).toLocaleString('sv-SE')+' kr' : '—');
                    const product = q.panel_name ? q.panel_name + (q.panel_count ? ' × '+q.panel_count : '') : '—';
                    // Parse images JSON
                    let imgs = [];
                    try { if(q.images) imgs = typeof q.images === 'string' ? JSON.parse(q.images) : q.images; } catch(e){}
                    if(!Array.isArray(imgs)) imgs = [];
                    let imgHtml = '';
                    if(imgs.length > 0){
                        const thumbs = imgs.slice(0,3);
                        imgHtml = '<div style="display:flex;gap:4px;align-items:center">' + thumbs.map(function(im){
                            var src = typeof im === 'string' ? im : (im.url||'');
                            return '<img src="'+src+'" onclick="event.stopPropagation();openLightbox(this.src)" style="width:32px;height:32px;border-radius:4px;object-fit:cover;cursor:pointer;border:1px solid #e5e7eb" onerror="this.style.display=\'none\'">';
                        }).join('') + (imgs.length > 3 ? '<span style="font-size:10px;color:#94a3b8">+' + (imgs.length-3) + '</span>' : '') + '</div>';
                    } else {
                        imgHtml = '<span style="color:#cbd5e1;font-size:11px">—</span>';
                    }
                    return '<tr style="border-bottom:1px solid #f1f5f9;cursor:pointer" onclick="openQuoteFromList('+q.id+')" onmouseover="this.style.background=\'#fafbfc\'" onmouseout="this.style.background=\'\'">'
                        +'<td style="padding:10px 14px;font-size:13px;font-weight:600;color:#024550">#'+q.id+'</td>'
                        +'<td style="padding:10px 14px;font-size:13px"><div style="font-weight:600;color:#1a1a1a">'+(q.customer_name||'Ej angiven')+'</div><div style="font-size:11px;color:#94a3b8;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">'+(q.customer_address||'')+'</div></td>'
                        +'<td style="padding:10px 14px;font-size:12px;color:#64748b">'+product+'</td>'
                        +'<td style="padding:10px 14px;font-size:13px;font-weight:700;color:#1a1a1a;text-align:right">'+amount+'</td>'
                        +'<td style="padding:10px 14px">'+imgHtml+'</td>'
                        +'<td style="padding:10px 14px;font-size:12px;color:#64748b">'+(q.created_by_name||'—')+'</td>'
                        +'<td style="padding:10px 14px;font-size:12px;color:#94a3b8">'+date+'</td>'
                        +'<td style="padding:10px 14px"><span style="padding:3px 10px;border-radius:10px;font-size:11px;font-weight:600;background:'+st.bg+';color:'+st.color+'">'+st.label+'</span></td>'
                        +'<td style="padding:10px 14px"><button onclick="event.stopPropagation();deleteQuote('+q.id+')" style="background:none;border:none;cursor:pointer;color:#dc2626;font-size:16px" title="Ta bort">&times;</button></td>'
                        +'</tr>';
                }).join('');
            } catch(e){
                body.innerHTML = '<tr><td colspan="9" style="padding:40px;text-align:center;color:#ef4444;font-size:13px">Kunde inte ladda kalkyler: '+e.message+'</td></tr>';
            }
        }

        async function openQuoteFromList(id){
            try {
                const resp = await fetch('/api/quotes.php?id='+id);
                const data = await resp.json();
                if(!data.success || !data.quote) { alert('Kunde inte ladda kalkyl'); return; }
                const q = data.quote;
                currentQuoteId = q.id;

                // Bygg pendingKalkylCustomer
                pendingKalkylCustomer = {
                    prospectIdx: -1,
                    name: q.customer_name || '',
                    email: q.customer_email || '',
                    phone: q.customer_phone || '',
                    address: q.customer_address || '',
                    ownerType: q.owner_count == 2 ? '2' : (q.owner_count == 0 ? 'brf' : '1'),
                    maxDeduction: (q.owner_count||1) * 50000,
                    owner1: { name: q.customer_name || '', pnr: q.customer_personnummer || '' },
                    owner2: null,
                    product: 'Solceller',
                    solarData: q.prospect_data || {},
                    created: q.created_at
                };

                const savedImages = q.images || [];
                const isOffert = (q.status === 'offert' || q.status === 'skickad' || q.status === 'godkänd');

                // Navigera till konfigurator-sidan (viktigt om vi kommer från fältsälj etc)
                navigateTo('konfigurator');

                // Visa konfiguratorn
                showKalkylConfig();
                populateKalkylFromCustomer();

                // Ladda sparade bilder till kalkylImages
                kalkylImages = savedImages.map(img => ({
                    url: img.url || img,
                    type: img.type || 'photo',
                    selected: true,
                    created: img.created || new Date().toISOString()
                }));
                renderKalkylPhotos();

                // Ladda in kalkylinställningar
                setTimeout(() => {
                    const catSel = document.getElementById('categorySelect');
                    if(catSel){ catSel.value = 'solceller'; changeCategory(); }

                    if(q.panel_count){
                        const slider = document.getElementById('solPanelCount');
                        if(slider) slider.value = q.panel_count;
                    }
                    if(q.battery_kwh){
                        const bSlider = document.getElementById('solBatteryKwh');
                        if(bSlider) bSlider.value = q.battery_kwh;
                    }
                    updateSolarCalc();

                    // Bara öppna affär-vyn om det är en offert
                    if(isOffert){
                        setTimeout(() => {
                            const savedExtras = q.extra_costs || [];
                            const savedNotes = q.notes || '';
                            const savedMargin = q.margin_percent || 0;

                            document.getElementById('solarConfigView').style.display='none';
                            document.getElementById('affarView').style.display='block';

                            const banner = document.getElementById('affarCustomerBanner');
                            const c = pendingKalkylCustomer;
                            if(c && banner){
                                banner.innerHTML='<div style="background:linear-gradient(135deg,#ecfdf5,#f0f9ff);border:1px solid #bbf7d0;border-radius:12px;padding:14px 18px;display:flex;align-items:center;gap:16px;flex-wrap:wrap">'
                                    +'<div style="flex:1;min-width:200px"><div style="font-weight:700;font-size:15px;color:#1a1a1a">'+(c.name||'Ej angiven')+'</div><div style="font-size:12px;color:#64748b">'+c.address+'</div></div>'
                                    +(c.phone?'<div style="font-size:13px;color:#334155">'+c.phone+'</div>':'')
                                    +(c.email?'<div style="font-size:13px;color:#334155">'+c.email+'</div>':'')
                                    +'</div>';
                            }

                            const cs = currentCalcState;
                            const summary = document.getElementById('affarConfigSummary');
                            if(summary){
                                let rows = '<div style="display:flex;justify-content:space-between;padding:8px 12px;background:#f8fafc;border-radius:8px"><span style="font-size:13px;color:#64748b">Solpaneler</span><span style="font-size:13px;font-weight:600">'+cs.panelName+' × '+cs.panelCount+' ('+cs.kwp+' kWp)</span></div>';
                                if(cs.batteryKwh>0) rows += '<div style="display:flex;justify-content:space-between;padding:8px 12px;background:#f8fafc;border-radius:8px"><span style="font-size:13px;color:#64748b">Batteri</span><span style="font-size:13px;font-weight:600">'+cs.batteryKwh+' kWh</span></div>';
                                if(cs.chargerName) rows += '<div style="display:flex;justify-content:space-between;padding:8px 12px;background:#f8fafc;border-radius:8px"><span style="font-size:13px;color:#64748b">Laddare</span><span style="font-size:13px;font-weight:600">'+cs.chargerName+'</span></div>';
                                summary.innerHTML = rows;
                            }

                            affarExtraCosts = savedExtras;
                            affarImages = savedImages;
                            currentQuoteId = q.id;
                            const affarNotesEl = document.getElementById('affarNotes');
                            if(affarNotesEl) affarNotesEl.value = savedNotes;
                            const marginSlider = document.getElementById('affarMarginSlider');
                            if(marginSlider) marginSlider.value = savedMargin;

                            renderAffarExtras();
                            renderAffarImages();
                            updateAffarCalc();
                        }, 200);
                    }
                }, 100);
            } catch(e){
                alert('Kunde inte öppna kalkyl: '+e.message);
            }
        }

        async function deleteQuote(id){
            if(!confirm('Ta bort kalkyl #'+id+'?')) return;
            try {
                await fetch('/api/quotes.php?id='+id, {method:'DELETE'});
                loadQuotesList();
            } catch(e){ alert('Kunde inte ta bort: '+e.message); }
        }

        // Edit lead note modal
        function editLeadNote(idx){
            const p = faltProspects[idx];
            if(!p) return;
            const modal = document.createElement('div');
            modal.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:9999;display:flex;align-items:center;justify-content:center;padding:20px';
            modal.onclick = e => { if(e.target === modal) modal.remove(); };
            modal.innerHTML = '<div style="background:#fff;border-radius:16px;padding:28px;width:440px;max-width:95vw;box-shadow:0 20px 60px rgba(0,0,0,.2)">'
                +'<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">'
                +'<h3 style="font-size:18px;font-weight:700;margin:0">Anteckning</h3>'
                +'<button onclick="this.closest(\'div[style*=fixed]\').remove()" style="background:none;border:none;font-size:22px;cursor:pointer;color:#94a3b8">&times;</button>'
                +'</div>'
                +'<div style="font-size:13px;color:#64748b;margin-bottom:12px">'+p.addr+(p.city?', '+p.city:'')+'</div>'
                +'<textarea id="leadNoteText" rows="4" style="width:100%;padding:12px;border:1.5px solid #e5e7eb;border-radius:10px;font-size:14px;font-family:inherit;resize:vertical;box-sizing:border-box">'+(p.note||'')+'</textarea>'
                +'<div style="display:flex;gap:8px;margin-top:16px;justify-content:flex-end">'
                +'<button onclick="this.closest(\'div[style*=fixed]\').remove()" style="padding:10px 20px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;cursor:pointer;background:#fff;font-family:inherit">Avbryt</button>'
                +'<button onclick="saveLeadNote('+idx+')" style="padding:10px 20px;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;background:#024550;color:#fff;font-family:inherit">Spara</button>'
                +'</div></div>';
            document.body.appendChild(modal);
            setTimeout(()=>document.getElementById('leadNoteText')?.focus(),100);
        }

        function saveLeadNote(idx){
            const text = document.getElementById('leadNoteText')?.value || '';
            faltProspects[idx].note = text;
            document.querySelector('div[style*="fixed"][style*="9999"]')?.remove();
            renderLeadsTable();
        }

        function closeModal(){const m=document.getElementById('quoteModal');if(m)m.classList.remove('active');document.body.style.overflow=''}
        function submitQuote(e){if(e)e.preventDefault();alert('Tack! Vi återkommer.\n\n(DEMO)');closeModal()}

        /* === KUNDER MAP === */
        const customers=[
            {id:'K-1001',name:'Andersson Bygg AB',city:'Stockholm',email:'info@anderssonbygg.se',phone:'08-123 456',status:'order',lat:59.3293,lng:18.0686,amount:185000},
            {id:'K-1002',name:'Svensson Fastigheter',city:'Göteborg',email:'kontakt@svensson.se',phone:'031-789 012',status:'order',lat:57.7089,lng:11.9746,amount:92500},
            {id:'K-1003',name:'Johansson & Co',city:'Malmö',email:'order@johansson.se',phone:'040-345 678',status:'offert',lat:55.6050,lng:13.0038,amount:87200},
            {id:'K-1004',name:'Nilsson Renovering',city:'Lund',email:'info@nilssonren.se',phone:'046-901 234',status:'order',lat:55.7047,lng:13.1910,amount:67300},
            {id:'K-1005',name:'Karlsson Entreprenad',city:'Uppsala',email:'karl@entreprenad.se',phone:'070-567 890',status:'offert',lat:59.8586,lng:17.6389,amount:248000},
            {id:'K-1006',name:'Berg Fastigheter AB',city:'Linköping',email:'info@bergfast.se',phone:'013-456 789',status:'lead',lat:58.4108,lng:15.6214,amount:320000},
            {id:'K-1007',name:'Holm Bygg & Mur',city:'Västerås',email:'holm@byggmur.se',phone:'021-234 567',status:'order',lat:59.6099,lng:16.5448,amount:45800},
            {id:'K-1008',name:'Ekström Villor',city:'Örebro',email:'info@ekstromvillor.se',phone:'019-876 543',status:'lost',lat:59.2753,lng:15.2134,amount:156000},
            {id:'K-1009',name:'Lindgren Renovering',city:'Norrköping',email:'info@lindgren-ren.se',phone:'011-345 678',status:'offert',lat:58.5942,lng:16.1826,amount:53400},
            {id:'K-1010',name:'Pettersson & Söner',city:'Helsingborg',email:'ps@pettersson.se',phone:'042-567 890',status:'order',lat:56.0465,lng:12.6945,amount:78900},
            {id:'K-1011',name:'Åkerman Fastigheter',city:'Jönköping',email:'info@akerman.se',phone:'036-123 456',status:'lead',lat:57.7826,lng:14.1618,amount:195000},
            {id:'K-1012',name:'Sundström Bygg',city:'Umeå',email:'info@sundstrombygg.se',phone:'090-234 567',status:'lost',lat:63.8258,lng:20.2630,amount:89500},
            {id:'K-1013',name:'Larsson & Partners',city:'Södertälje',email:'info@larssonp.se',phone:'08-550 123',status:'order',lat:59.1955,lng:17.6253,amount:134200},
            {id:'K-1014',name:'Nordin Husrenovering',city:'Gävle',email:'info@nordinhus.se',phone:'026-345 678',status:'offert',lat:60.6749,lng:17.1413,amount:42500},
            {id:'K-1015',name:'Fransson Bygg AB',city:'Borås',email:'kontakt@franssonbygg.se',phone:'033-567 890',status:'lead',lat:57.7210,lng:12.9401,amount:68000},
            {id:'K-1016',name:'Wallin Fastigheter',city:'Karlstad',email:'info@wallinfast.se',phone:'054-123 456',status:'order',lat:59.3793,lng:13.5036,amount:112000},
            {id:'K-1017',name:'Hedström Entreprenad',city:'Växjö',email:'hedstrom@entre.se',phone:'0470-234 567',status:'lost',lat:56.8777,lng:14.8091,amount:73200},
            {id:'K-1018',name:'Berglund Renovering',city:'Halmstad',email:'info@berglund-ren.se',phone:'035-345 678',status:'offert',lat:56.6745,lng:12.8578,amount:96800},
            {id:'K-1019',name:'Olsson Bygg & Mål',city:'Trollhättan',email:'info@olssonbm.se',phone:'0520-456 789',status:'order',lat:58.2837,lng:12.2886,amount:58300},
            {id:'K-1020',name:'Dahlberg Hus AB',city:'Eskilstuna',email:'info@dahlberghus.se',phone:'016-567 890',status:'lead',lat:59.3666,lng:16.5077,amount:142000},
            {id:'K-1021',name:'Magnusson Tak & Fasad',city:'Luleå',email:'info@magtak.se',phone:'0920-123 456',status:'lost',lat:65.5848,lng:22.1547,amount:210000},
            {id:'K-1022',name:'Ericsson Villa',city:'Nyköping',email:'info@ericssonvilla.se',phone:'0155-234 567',status:'offert',lat:58.7530,lng:17.0086,amount:38700},
            {id:'K-1023',name:'Gustafsson Bygg',city:'Kalmar',email:'info@gustafssonbygg.se',phone:'0480-345 678',status:'order',lat:56.6634,lng:16.3566,amount:94500},
            {id:'K-1024',name:'Sjöberg & Co',city:'Sundsvall',email:'info@sjobergco.se',phone:'060-456 789',status:'lead',lat:62.3908,lng:17.3069,amount:175000},
            {id:'K-1025',name:'Bengtsson Montage',city:'Kristianstad',email:'info@benmontage.se',phone:'044-567 890',status:'order',lat:56.0294,lng:14.1567,amount:51200}
        ];

        const statusColors={order:'#16a34a',offert:'#eab308',lost:'#ef4444',lead:'#94a3b8'};
        const statusLabels={order:'Order',offert:'Offert',lost:'Ej order',lead:'Lead'};
        const statusBadgeClass={order:'green',offert:'yellow',lost:'gray',lead:'gray'};
        let activeFilters={order:true,offert:true,lost:true,lead:true};
        let customerMap=null,markerLayers={order:null,offert:null,lost:null,lead:null};

        function initCustomerMap(){
            if(customerMap)return;
            customerMap=L.map('customerMap',{scrollWheelZoom:true}).setView([59.3,16.0],5);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{attribution:'&copy; OpenStreetMap',maxZoom:18}).addTo(customerMap);
            Object.keys(statusColors).forEach(s=>{markerLayers[s]=L.layerGroup().addTo(customerMap)});
            customers.forEach(c=>{
                const icon=L.divIcon({className:'',html:'<div class="map-marker-'+c.status+'"></div>',iconSize:[14,14],iconAnchor:[7,7]});
                const popupHtml='<div style="font-family:Inter,sans-serif;min-width:190px;padding:2px">'
                    +'<strong style="font-size:13px;display:block;margin-bottom:2px">'+c.name+'</strong>'
                    +'<span style="font-size:12px;color:#64748b">'+c.city+'</span>'
                    +'<div style="margin-top:6px;display:flex;justify-content:space-between;align-items:center">'
                    +'<span style="display:inline-block;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:600;background:'+(c.status==='order'?'#dcfce7;color:#166534':c.status==='offert'?'#fef9c3;color:#854d0e':c.status==='lost'?'#fee2e2;color:#991b1b':'#f1f5f9;color:#64748b')+'">'+statusLabels[c.status]+'</span>'
                    +'<span style="font-size:13px;font-weight:700;color:#1a1a1a">'+fmtKr(c.amount)+'</span>'
                    +'</div>'
                    +'<div style="margin-top:6px;font-size:11px;color:#94a3b8">'+c.email+'<br>'+c.phone+'</div>'
                    +'</div>';
                const m=L.marker([c.lat,c.lng],{icon:icon}).bindPopup(popupHtml);
                markerLayers[c.status].addLayer(m);
            });
            updateCustomerStats();
            renderCustomerTable();
        }

        function toggleFilter(btn){
            const f=btn.dataset.filter;
            activeFilters[f]=!activeFilters[f];
            btn.classList.toggle('active',activeFilters[f]);
            if(customerMap){if(activeFilters[f]){customerMap.addLayer(markerLayers[f])}else{customerMap.removeLayer(markerLayers[f])}}
            renderCustomerTable();
        }

        function filterCustomers(){renderCustomerTable()}

        function renderCustomerTable(){
            const search=(document.getElementById('customerSearch').value||'').toLowerCase();
            const tbody=document.getElementById('customerTableBody');
            const filtered=customers.filter(c=>(search===''||c.name.toLowerCase().includes(search)||c.city.toLowerCase().includes(search)||c.id.toLowerCase().includes(search)||c.email.toLowerCase().includes(search)));
            tbody.innerHTML=filtered.map(c=>'<tr><td>'+c.id+'</td><td>'+c.name+'</td><td>'+c.city+'</td><td>'+c.email+'</td><td>'+c.phone+'</td><td><span class="status-badge '+(c.status==='order'?'green':c.status==='offert'?'yellow':c.status==='lost'?'blue':'gray')+'">'+statusLabels[c.status]+'</span></td></tr>').join('');
            document.getElementById('customerCount').textContent='('+filtered.length+' av '+customers.length+')';
        }

        function fmtKr(n){return n.toLocaleString('sv-SE')+' kr'}
        function updateCustomerStats(){
            const counts={order:0,offert:0,lost:0,lead:0};
            const sums={order:0,offert:0,lost:0,lead:0};
            customers.forEach(c=>{counts[c.status]++;sums[c.status]+=(c.amount||0)});
            const el=(id,v)=>{const e=document.getElementById(id);if(e)e.textContent=v};
            // Affärer page stats + filter counts
            el('statOrderA',counts.order);el('statOffertA',counts.offert);el('statLostA',counts.lost);el('statLeadA',counts.lead);
            el('sumOrderA',fmtKr(sums.order));el('sumOffertA',fmtKr(sums.offert));el('sumLostA',fmtKr(sums.lost));el('sumLeadA',fmtKr(sums.lead));
            el('countOrderA',counts.order);el('countOffertA',counts.offert);el('countLostA',counts.lost);el('countLeadA',counts.lead);
        }

        /* === KALENDER === */
        let calYear=2026,calMonth=1;
        const calDummyEvents={
            '2026-02-18':['Inmätning - Andersson','Offertpresentation - Svensson','Intern planering'],
            '2026-02-19':['Besiktning - Berg Fastigheter'],
            '2026-02-20':['Kundmöte - Karlsson','Produktträning Optima'],
            '2026-02-21':['Montering - Nilsson Renovering'],
            '2026-02-24':['Offertarbete'],
            '2026-02-25':['Kundbesök - Holm Bygg'],
            '2026-02-27':['Inmätning - Pettersson & Söner']
        };
        const monthNames=['Januari','Februari','Mars','April','Maj','Juni','Juli','Augusti','September','Oktober','November','December'];
        const dayNames=['Mån','Tis','Ons','Tor','Fre','Lör','Sön'];

        function renderCalendar(){
            const grid=document.getElementById('calGrid');
            if(!grid)return;
            document.getElementById('calMonthTitle').textContent=monthNames[calMonth]+' '+calYear;
            let html=dayNames.map(d=>'<div class="cal-day-header">'+d+'</div>').join('');
            const firstDay=new Date(calYear,calMonth,1).getDay();
            const daysInMonth=new Date(calYear,calMonth+1,0).getDate();
            const daysInPrev=new Date(calYear,calMonth,0).getDate();
            const startDay=firstDay===0?6:firstDay-1;
            for(let i=startDay-1;i>=0;i--){html+='<div class="cal-day other-month">'+(daysInPrev-i)+'</div>'}
            const today=new Date();
            for(let d=1;d<=daysInMonth;d++){
                const dateStr=calYear+'-'+String(calMonth+1).padStart(2,'0')+'-'+String(d).padStart(2,'0');
                const isToday=today.getDate()===d&&today.getMonth()===calMonth&&today.getFullYear()===calYear;
                const hasEvent=calDummyEvents[dateStr];
                html+='<div class="cal-day'+(isToday?' today':'')+(hasEvent?' has-event':'')+'">'+d+'</div>';
            }
            const totalCells=startDay+daysInMonth;
            const remaining=totalCells%7===0?0:7-(totalCells%7);
            for(let i=1;i<=remaining;i++){html+='<div class="cal-day other-month">'+i+'</div>'}
            grid.innerHTML=html;
        }
        function calPrev(){calMonth--;if(calMonth<0){calMonth=11;calYear--}renderCalendar()}
        function calNext(){calMonth++;if(calMonth>11){calMonth=0;calYear++}renderCalendar()}

        /* Init map when Affärer page shown */
        document.querySelectorAll('.nav-item').forEach(item=>{
            item.addEventListener('click',function(){
                if(this.dataset.page==='projekt'){
                    setTimeout(()=>{initCustomerMap();if(customerMap)customerMap.invalidateSize()},100);
                }
                if(this.dataset.page==='kunder'){
                    renderCustomerTable();
                }
                if(this.dataset.page==='faltsalj'){
                    setTimeout(()=>{initFaltMap();if(gMap)google.maps.event.trigger(gMap,'resize')},200);
                }
                if(this.dataset.page==='kalender'){
                    setTimeout(renderCalendar,50);
                }
            });
        });
        /* === EVA AI CHAT === */
        const EVA_KEY='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';
        const evaHistory=[];
        function ekoTab(btn,panelId){
            document.querySelectorAll('.eko-tab').forEach(t=>t.classList.remove('active'));
            btn.classList.add('active');
            document.querySelectorAll('.eko-panel').forEach(p=>p.classList.remove('active'));
            document.getElementById(panelId).classList.add('active');
        }

        const evaSystemPrompt=`Du är Eva Andersson, en proaktiv medarbetare på Solar Energy Group. Du jobbar med ekonomi och försäljning.
Du svarar alltid på svenska, kort och koncist. Du är vänlig, professionell och handlingskraftig.

VIKTIGT BETEENDE:
- Du säger ALDRIG att du inte kan göra något. Du är alltid lösningsorienterad.
- Om någon ber dig maila eller kontakta en kund - fråga ALLTID först: "Är det något mer du vill att jag ska inkludera i mailet?" innan du skickar. Vänta på svar.
- Om någon ber dig göra något praktiskt - bekräfta att du tar hand om det. "Fixat!", "Jag ordnar det direkt!", "Klart, du får en uppdatering när jag vet mer."
- Var som en duktig kollega som alltid tar tag i saker direkt.
- Du representerar företaget och kan agera å deras vägnar.

Du har tillgång till följande företagsdata:

KUNDER OCH STATUS:
${customers.map(c=>c.id+': '+c.name+' ('+c.city+') - Status: '+(c.status==='order'?'Order':c.status==='offert'?'Offert':c.status==='lost'?'Ej order':'Lead')+' - Belopp: '+c.amount.toLocaleString('sv-SE')+' kr').join('\n')}

SAMMANFATTNING KUNDER:
- Order: ${customers.filter(c=>c.status==='order').length} st, totalt ${customers.filter(c=>c.status==='order').reduce((s,c)=>s+c.amount,0).toLocaleString('sv-SE')} kr
- Offert: ${customers.filter(c=>c.status==='offert').length} st, totalt ${customers.filter(c=>c.status==='offert').reduce((s,c)=>s+c.amount,0).toLocaleString('sv-SE')} kr
- Ej order (förlorade): ${customers.filter(c=>c.status==='lost').length} st, totalt ${customers.filter(c=>c.status==='lost').reduce((s,c)=>s+c.amount,0).toLocaleString('sv-SE')} kr
- Leads: ${customers.filter(c=>c.status==='lead').length} st, totalt ${customers.filter(c=>c.status==='lead').reduce((s,c)=>s+c.amount,0).toLocaleString('sv-SE')} kr

PÅGÅENDE PROJEKT:
- PRJ-2024-001: Andersson Bygg AB - 12 fönster + 2 balkongdörrar - Montering 100% klar, Besiktning godkänd
- PRJ-2024-002: Svensson Fastigheter - 8 fönster villa - Montering 75%, väntar besiktning
- PRJ-2024-003: Johansson & Co - Kontorsfönster 24 st - Montering 30%, pågår
- PRJ-2024-004: Nilsson Renovering - 6 fönster + entredörr - Inmätning pågår, leverans packad, montering ej påbörjad
- PRJ-2024-005: Karlsson Entreprenad - Flerfamiljshus 48 fönster - Offert skickad, väntar svar
- PRJ-2024-006: Berg Fastigheter AB - BRF renovering 32 fönster - Utkast, ej skickad

ORDRAR:
- ORD-2024-001: Andersson Bygg, 24 500 kr, Levererad
- ORD-2024-002: Svensson Fastigheter, 48 200 kr, Under produktion
- ORD-2024-003: Johansson & Co, 12 800 kr, Väntar godkännande
- ORD-2024-004: Nilsson Renovering, 67 300 kr, Levererad
- ORD-2024-005: Karlsson Entreprenad, 35 900 kr, Under produktion

KALKYLER:
- KAL-2026-012: Andersson Bygg, Fönster, 185 400 kr - Godkänd
- KAL-2026-011: Svensson Fastigheter, Fönster, 92 500 kr - Skickad
- KAL-2026-010: Karlsson Entreprenad, Solceller, 248 000 kr - Utkast
- KAL-2026-009: Berg Fastigheter, Tak, 320 000 kr - Skickad
- KAL-2026-008: Nilsson Renovering, Dörrar, 67 300 kr - Godkänd

SÄLJARE:
- Erik Lundström: 8 affärer, 485 000 kr (bäst denna månad)
- Maria Andersson: 5 affärer, 312 000 kr
- Johan Bergman: 4 affärer, 248 000 kr
- Sofia Nilsson: 3 affärer, 187 000 kr

EKONOMI FEBRUARI 2026:
- Omsättning: 1 232 000 kr (mål: 1 500 000 kr, 82% uppnått)
- Antal stängda affärer: 20
- Genomsnittligt ordervärde: 61 600 kr
- Offert-till-order konvertering: 68%
- Leveransprecision: 94% (mål 97%)

Problem/Noteringar:
- Nilsson Renovering (PRJ-2024-004): Specialbeslag saknas, försenar montering med ca 1 vecka
- Karlsson Entreprenad (PRJ-2024-005): Stor offert 248 000 kr väntar svar sedan 2 veckor
- Leveransprecision under mål (94% vs 97%) pga materialbrist hos leverantör Optima
- 4 förlorade affärer totalt 528 700 kr - vanligaste orsak: pris (3 av 4)

Datum idag: 18 februari 2026.`;

        function getTimeStr(){const d=new Date();return d.getHours().toString().padStart(2,'0')+':'+d.getMinutes().toString().padStart(2,'0')}

        function addEvaMsg(text,isUser){
            const msgs=document.getElementById('evaMessages');
            const div=document.createElement('div');
            div.className='eva-msg '+(isUser?'user':'eva');
            let html=text.replace(/\*\*(.+?)\*\*/g,'<strong>$1</strong>').replace(/\n/g,'<br>');
            div.innerHTML=(isUser?'':'<img src="eva.png" alt="Eva" class="eva-msg-avatar">')
                +'<div><div class="eva-msg-bubble">'+html+'</div><div class="eva-msg-time">'+getTimeStr()+'</div></div>';
            msgs.appendChild(div);
            msgs.scrollTop=msgs.scrollHeight;
        }

        function showTyping(){
            const msgs=document.getElementById('evaMessages');
            const div=document.createElement('div');
            div.className='eva-msg eva';
            div.id='evaTyping';
            div.innerHTML='<img src="eva.png" alt="Eva" class="eva-msg-avatar"><div class="eva-typing"><span></span><span></span><span></span></div>';
            msgs.appendChild(div);
            msgs.scrollTop=msgs.scrollHeight;
        }
        function hideTyping(){const t=document.getElementById('evaTyping');if(t)t.remove()}

        async function evaSend(){
            const input=document.getElementById('evaInput');
            const text=input.value.trim();
            if(!text)return;
            input.value='';
            input.style.height='auto';
            document.getElementById('evaSuggestions').style.display='none';
            addEvaMsg(text,true);
            evaHistory.push({role:'user',content:text});
            document.getElementById('evaSendBtn').disabled=true;
            showTyping();
            try{
                const res=await fetch('https://api.openai.com/v1/chat/completions',{
                    method:'POST',
                    headers:{'Content-Type':'application/json','Authorization':'Bearer '+EVA_KEY},
                    body:JSON.stringify({model:'gpt-4o-mini',messages:[{role:'system',content:evaSystemPrompt},...evaHistory],temperature:0.7,max_tokens:800})
                });
                const data=await res.json();
                hideTyping();
                if(data.choices&&data.choices[0]){
                    const reply=data.choices[0].message.content;
                    evaHistory.push({role:'assistant',content:reply});
                    addEvaMsg(reply,false);
                }else{
                    addEvaMsg('Ursäkta, jag kunde inte svara just nu. Försök igen.',false);
                }
            }catch(e){
                hideTyping();
                addEvaMsg('Anslutningsfel. Kontrollera din internetanslutning.',false);
            }
            document.getElementById('evaSendBtn').disabled=false;
            document.getElementById('evaInput').focus();
        }

        function evaSuggest(btn){
            document.getElementById('evaInput').value=btn.textContent;
            evaSend();
        }

        /* === PRODUKTKATALOG === */
        let catalogProducts = [];

        async function loadCatalogFromDB() {
            try {
                const res = await fetch('/api/products.php');
                const data = await res.json();
                if(data.success && data.products) {
                    catalogProducts = data.products.map(p => ({
                        id: p.id,
                        name: p.name,
                        cat: p.cat,
                        catLabel: p.cat_label,
                        desc: p.description,
                        price: parseFloat(p.price),
                        stock: p.stock,
                        stockClass: p.stock_class,
                        img: p.img || '',
                        watt: p.watt ? parseInt(p.watt) : null,
                        kwhCapacity: p.kwh_capacity ? parseFloat(p.kwh_capacity) : null,
                        greenTechEligible: parseInt(p.green_tech_eligible) === 1
                    }));
                }
            } catch(e) { console.error('Kunde inte ladda produkter:', e); }
            renderCatalog(catalogProducts);
        }

        function filterCatalog(){
            const cat=document.getElementById('catalogCatSelect').value;
            const model=document.getElementById('catalogModelSelect').value;
            const modelSel=document.getElementById('catalogModelSelect');
            const filtered=cat?catalogProducts.filter(p=>p.cat===cat):catalogProducts;
            const models=[...new Set(filtered.map(p=>p.name))];
            modelSel.innerHTML='<option value="">Alla modeller</option>'+models.map(m=>'<option value="'+m+'">'+m+'</option>').join('');
            if(model)modelSel.value=model;
            let products=catalogProducts;
            if(cat)products=products.filter(p=>p.cat===cat);
            if(model&&modelSel.value)products=products.filter(p=>p.name===modelSel.value);
            renderCatalog(products);
        }

        function renderCatalog(products){
            const grid=document.getElementById('catalogGrid');
            if(!grid) return;
            document.getElementById('catalogCount').textContent=products.length+' produkter';
            const isAdmin = true; // TODO: check actual role
            grid.innerHTML=products.map(p=>{
                const imgHtml=p.img?'<img src="'+p.img+'" alt="'+p.name+'">':'<svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>';
                const editBtn = isAdmin ? '<button onclick="event.stopPropagation();editProduct(\''+p.id+'\')" style="position:absolute;top:8px;right:8px;background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:6px 8px;cursor:pointer;box-shadow:0 2px 6px rgba(0,0,0,.1);display:flex;align-items:center;gap:4px;font-size:11px;font-weight:600;color:#334155;font-family:inherit"><svg viewBox="0 0 24 24" style="width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>Redigera</button>' : '';
                const greenBadge = p.greenTechEligible ? '<span style="position:absolute;top:8px;left:8px;background:linear-gradient(135deg,#059669,#10b981);color:#fff;font-size:10px;font-weight:700;padding:4px 8px;border-radius:6px;letter-spacing:.3px;box-shadow:0 2px 6px rgba(16,185,129,.3)">GRÖNT TEKNIK-AVDRAG</span>' : '';
                return '<div class="catalog-card" style="position:relative"><div class="catalog-card-img">'+imgHtml+'</div>'+greenBadge+editBtn+'<div class="catalog-card-body"><div class="catalog-card-cat">'+p.catLabel+'</div><div class="catalog-card-name">'+p.name+'</div><div class="catalog-card-desc">'+p.desc+'</div><div class="catalog-card-footer"><div class="catalog-card-price">'+p.price.toLocaleString('sv-SE')+' kr</div><span class="catalog-card-badge status-badge '+p.stockClass+'">'+p.stock+'</span></div></div></div>';
            }).join('');
        }

        // === PRODUCT EDIT MODAL ===
        function editProduct(id) {
            const p = catalogProducts.find(x => x.id === id);
            if(!p) return;
            const cats = [{v:'fonster',l:'Fönster'},{v:'dorrar',l:'Dörrar'},{v:'solceller',l:'Solceller'},{v:'tak',l:'Tak'},{v:'tillbehor',l:'Tillbehör'}];
            const stocks = [{v:'I lager',c:'green'},{v:'Få kvar',c:'yellow'},{v:'Beställning',c:'blue'},{v:'Slut',c:'red'}];

            const modal = document.createElement('div');
            modal.id = 'productEditModal';
            modal.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:9999;display:flex;align-items:center;justify-content:center;padding:20px';
            modal.onclick = e => { if(e.target === modal) modal.remove(); };

            modal.innerHTML = '<div style="background:#fff;border-radius:16px;max-width:600px;width:100%;max-height:90vh;overflow-y:auto;box-shadow:0 25px 60px rgba(0,0,0,.3)">'
                +'<div style="padding:20px 24px;border-bottom:1px solid #f1f5f9;display:flex;justify-content:space-between;align-items:center">'
                +'<h2 style="font-size:18px;font-weight:700;color:#1a1a1a;margin:0">Redigera produkt</h2>'
                +'<button onclick="this.closest(\'#productEditModal\').remove()" style="background:none;border:none;cursor:pointer;padding:4px"><svg viewBox="0 0 24 24" style="width:20px;height:20px;stroke:#94a3b8;fill:none;stroke-width:2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>'
                +'</div>'
                +'<div style="padding:24px">'

                // Bild
                +'<div style="margin-bottom:20px">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b;display:block;margin-bottom:6px">PRODUKTBILD</label>'
                +'<div id="peImgPreview" style="width:100%;aspect-ratio:16/9;background:#f8f9fa;border-radius:10px;border:2px dashed #e5e7eb;display:flex;align-items:center;justify-content:center;overflow:hidden;cursor:pointer;margin-bottom:8px" onclick="document.getElementById(\'peFileInput\').click()">'
                +(p.img ? '<img src="'+p.img+'" style="width:100%;height:100%;object-fit:cover">' : '<div style="text-align:center;color:#94a3b8"><svg viewBox="0 0 24 24" style="width:40px;height:40px;stroke:#cbd5e1;fill:none;stroke-width:1.5;margin:0 auto 8px;display:block"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg><div style="font-size:13px">Klicka för att ladda upp bild</div></div>')
                +'</div>'
                +'<input type="file" id="peFileInput" accept="image/*" style="display:none" onchange="previewProductImage(this)">'
                +'<div id="peUploadStatus" style="font-size:11px;color:#94a3b8"></div>'
                +'</div>'

                // Fält
                +'<div style="display:grid;grid-template-columns:100px 1fr;gap:12px 16px;align-items:center">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">ID</label>'
                +'<input id="peId" value="'+p.id+'" readonly style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;background:#f8f9fa;color:#94a3b8;font-family:inherit">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">Namn</label>'
                +'<input id="peName" value="'+p.name.replace(/"/g,'&quot;')+'" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">Kategori</label>'
                +'<select id="peCat" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">'+cats.map(c=>'<option value="'+c.v+'"'+(c.v===p.cat?' selected':'')+'>'+c.l+'</option>').join('')+'</select>'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">Pris (kr)</label>'
                +'<input id="pePrice" type="number" value="'+p.price+'" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">Watt</label>'
                +'<input id="peWatt" type="number" value="'+(p.watt||'')+'" placeholder="Endast solpaneler" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">kWh</label>'
                +'<input id="peKwh" type="number" step="0.1" value="'+(p.kwhCapacity||'')+'" placeholder="Batteri kapacitet" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">Lagerstatus</label>'
                +'<select id="peStock" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">'+stocks.map(s=>'<option value="'+s.v+'" data-class="'+s.c+'"'+(s.v===p.stock?' selected':'')+'>'+s.v+'</option>').join('')+'</select>'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">Beskrivning</label>'
                +'<textarea id="peDesc" rows="3" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;resize:vertical">'+p.desc.replace(/</g,'&lt;')+'</textarea>'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">Grönt teknik</label>'
                +'<label style="display:flex;align-items:center;gap:8px;cursor:pointer"><input type="checkbox" id="peGreenTech" '+(p.greenTechEligible?'checked':'')+' style="width:18px;height:18px;accent-color:#059669"><span style="font-size:14px;color:#1a1a1a">Berättigad till grönt teknik-avdrag</span></label>'
                +'</div>'

                // Knappar
                +'<div style="display:flex;gap:10px;margin-top:20px">'
                +'<button onclick="saveProduct(\''+p.id+'\')" style="flex:1;padding:12px;background:#024550;color:#fff;border:none;border-radius:10px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit">Spara</button>'
                +'<button onclick="deleteProduct(\''+p.id+'\')" style="padding:12px 20px;background:#fee2e2;color:#dc2626;border:none;border-radius:10px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit">Ta bort</button>'
                +'<button onclick="this.closest(\'#productEditModal\').remove()" style="padding:12px 20px;background:#f1f5f9;color:#64748b;border:none;border-radius:10px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit">Avbryt</button>'
                +'</div>'
                +'</div></div>';

            document.body.appendChild(modal);
        }

        function previewProductImage(input) {
            if(!input.files || !input.files[0]) return;
            const file = input.files[0];
            const preview = document.getElementById('peImgPreview');
            const reader = new FileReader();
            reader.onload = e => {
                preview.innerHTML = '<img src="'+e.target.result+'" style="width:100%;height:100%;object-fit:cover">';
            };
            reader.readAsDataURL(file);
            document.getElementById('peUploadStatus').textContent = file.name + ' (' + (file.size/1024).toFixed(0) + ' KB) — sparas vid klick på Spara';
        }

        async function saveProduct(id) {
            const catSel = document.getElementById('peCat');
            const stockSel = document.getElementById('peStock');
            const catLabel = catSel.options[catSel.selectedIndex].text;
            const stockClass = stockSel.options[stockSel.selectedIndex].dataset.class;

            // Upload image first if selected
            const fileInput = document.getElementById('peFileInput');
            let imgPath = '';
            if(fileInput && fileInput.files && fileInput.files[0]) {
                const fd = new FormData();
                fd.append('id', id);
                fd.append('image', fileInput.files[0]);
                document.getElementById('peUploadStatus').textContent = 'Laddar upp bild...';
                try {
                    const upRes = await fetch('/api/products.php?upload=1', { method:'POST', body: fd });
                    const upData = await upRes.json();
                    if(upData.success) {
                        imgPath = upData.img;
                        document.getElementById('peUploadStatus').textContent = 'Bild uppladdad!';
                    } else {
                        document.getElementById('peUploadStatus').textContent = 'Fel: ' + (upData.error || 'okänt');
                        return;
                    }
                } catch(e) {
                    document.getElementById('peUploadStatus').textContent = 'Uppladdningsfel: ' + e.message;
                    return;
                }
            }

            const body = {
                id: id,
                name: document.getElementById('peName').value,
                cat: catSel.value,
                cat_label: catLabel,
                description: document.getElementById('peDesc').value,
                price: parseFloat(document.getElementById('pePrice').value) || 0,
                stock: stockSel.value,
                stock_class: stockClass,
                watt: parseInt(document.getElementById('peWatt').value) || null,
                kwh_capacity: parseFloat(document.getElementById('peKwh').value) || null,
                green_tech_eligible: document.getElementById('peGreenTech').checked ? 1 : 0
            };
            if(imgPath) body.img = imgPath;

            try {
                const res = await fetch('/api/products.php', {
                    method: 'POST',
                    headers: {'Content-Type':'application/json'},
                    body: JSON.stringify(body)
                });
                const data = await res.json();
                if(data.success) {
                    document.getElementById('productEditModal')?.remove();
                    await loadCatalogFromDB();
                    filterCatalog();
                } else {
                    alert('Fel: ' + (data.error || 'okänt'));
                }
            } catch(e) {
                alert('Fel: ' + e.message);
            }
        }

        async function deleteProduct(id) {
            if(!confirm('Ta bort produkt ' + id + '?')) return;
            try {
                const res = await fetch('/api/products.php?id=' + id, { method: 'DELETE' });
                const data = await res.json();
                if(data.success) {
                    document.getElementById('productEditModal')?.remove();
                    await loadCatalogFromDB();
                    filterCatalog();
                }
            } catch(e) { alert('Fel: ' + e.message); }
        }

        function showAddProductModal() {
            const cats = [{v:'fonster',l:'Fönster'},{v:'dorrar',l:'Dörrar'},{v:'solceller',l:'Solceller'},{v:'tak',l:'Tak'},{v:'tillbehor',l:'Tillbehör'}];
            const stocks = [{v:'I lager',c:'green'},{v:'Få kvar',c:'yellow'},{v:'Beställning',c:'blue'},{v:'Slut',c:'red'}];

            const modal = document.createElement('div');
            modal.id = 'productEditModal';
            modal.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:9999;display:flex;align-items:center;justify-content:center;padding:20px';
            modal.onclick = e => { if(e.target === modal) modal.remove(); };

            modal.innerHTML = '<div style="background:#fff;border-radius:16px;max-width:600px;width:100%;max-height:90vh;overflow-y:auto;box-shadow:0 25px 60px rgba(0,0,0,.3)">'
                +'<div style="padding:20px 24px;border-bottom:1px solid #f1f5f9"><h2 style="font-size:18px;font-weight:700;margin:0">Ny produkt</h2></div>'
                +'<div style="padding:24px">'
                +'<div id="peImgPreview" style="width:100%;aspect-ratio:16/9;background:#f8f9fa;border-radius:10px;border:2px dashed #e5e7eb;display:flex;align-items:center;justify-content:center;overflow:hidden;cursor:pointer;margin-bottom:8px" onclick="document.getElementById(\'peFileInput\').click()">'
                +'<div style="text-align:center;color:#94a3b8"><svg viewBox="0 0 24 24" style="width:40px;height:40px;stroke:#cbd5e1;fill:none;stroke-width:1.5;margin:0 auto 8px;display:block"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg><div style="font-size:13px">Klicka för att ladda upp bild</div></div>'
                +'</div>'
                +'<input type="file" id="peFileInput" accept="image/*" style="display:none" onchange="previewProductImage(this)">'
                +'<div id="peUploadStatus" style="font-size:11px;color:#94a3b8;margin-bottom:12px"></div>'
                +'<div style="display:grid;grid-template-columns:100px 1fr;gap:12px 16px;align-items:center">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">ID</label>'
                +'<input id="peId" placeholder="t.ex. SOL05" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">Namn</label>'
                +'<input id="peName" placeholder="Produktnamn" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">Kategori</label>'
                +'<select id="peCat" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">'+cats.map(c=>'<option value="'+c.v+'">'+c.l+'</option>').join('')+'</select>'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">Pris (kr)</label>'
                +'<input id="pePrice" type="number" placeholder="0" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">Watt</label>'
                +'<input id="peWatt" type="number" placeholder="Solpaneler" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">kWh</label>'
                +'<input id="peKwh" type="number" step="0.1" placeholder="Batteri" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">Lagerstatus</label>'
                +'<select id="peStock" style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit">'+stocks.map(s=>'<option value="'+s.v+'" data-class="'+s.c+'">'+s.v+'</option>').join('')+'</select>'
                +'<label style="font-size:12px;font-weight:600;color:#64748b">Beskrivning</label>'
                +'<textarea id="peDesc" rows="3" placeholder="Produktbeskrivning..." style="padding:10px 14px;border:1px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;resize:vertical"></textarea>'
                +'</div>'
                +'<div style="display:flex;gap:10px;margin-top:20px">'
                +'<button onclick="saveNewProduct()" style="flex:1;padding:12px;background:#024550;color:#fff;border:none;border-radius:10px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit">Skapa produkt</button>'
                +'<button onclick="this.closest(\'#productEditModal\').remove()" style="padding:12px 20px;background:#f1f5f9;color:#64748b;border:none;border-radius:10px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit">Avbryt</button>'
                +'</div></div></div>';

            document.body.appendChild(modal);
        }

        async function saveNewProduct() {
            const id = document.getElementById('peId').value.trim();
            if(!id) { alert('ID krävs'); return; }
            const name = document.getElementById('peName').value.trim();
            if(!name) { alert('Namn krävs'); return; }

            const catSel = document.getElementById('peCat');
            const stockSel = document.getElementById('peStock');

            // Create product first
            const body = {
                id: id,
                name: name,
                cat: catSel.value,
                cat_label: catSel.options[catSel.selectedIndex].text,
                description: document.getElementById('peDesc').value,
                price: parseFloat(document.getElementById('pePrice').value) || 0,
                stock: stockSel.value,
                stock_class: stockSel.options[stockSel.selectedIndex].dataset.class,
                watt: parseInt(document.getElementById('peWatt').value) || null,
                kwh_capacity: parseFloat(document.getElementById('peKwh').value) || null
            };

            try {
                const res = await fetch('/api/products.php', {
                    method: 'POST',
                    headers: {'Content-Type':'application/json'},
                    body: JSON.stringify(body)
                });
                const data = await res.json();
                if(!data.success) { alert('Fel: ' + (data.error||'')); return; }

                // Upload image if selected
                const fileInput = document.getElementById('peFileInput');
                if(fileInput && fileInput.files && fileInput.files[0]) {
                    const fd = new FormData();
                    fd.append('id', id);
                    fd.append('image', fileInput.files[0]);
                    await fetch('/api/products.php?upload=1', { method:'POST', body: fd });
                }

                document.getElementById('productEditModal')?.remove();
                await loadCatalogFromDB();
                filterCatalog();
            } catch(e) { alert('Fel: ' + e.message); }
        }

        // Init catalog from DB
        loadCatalogFromDB();

        /* === DASHBOARD CHARTS === */
        function initDashCharts(){
            const ctxM=document.getElementById('chartMonthly');
            const ctxY=document.getElementById('chartYearly');
            if(!ctxM||!ctxY)return;
            new Chart(ctxM,{
                type:'bar',
                data:{
                    labels:['V6','V7','V8','V9'],
                    datasets:[
                        {label:'Order',data:[185000,92500,248000,134200],backgroundColor:'#10b981',borderRadius:4},
                        {label:'Offerter',data:[87200,53400,96800,42500],backgroundColor:'#eab308',borderRadius:4},
                        {label:'Förlorade',data:[0,156000,0,73200],backgroundColor:'#ef4444',borderRadius:4}
                    ]
                },
                options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'bottom',labels:{usePointStyle:true,padding:12,font:{family:'Inter',size:11}}}},scales:{y:{beginAtZero:true,ticks:{callback:v=>v>=1000?(v/1000)+'k':''+v,font:{family:'Inter',size:11}},grid:{color:'#f1f5f9'}},x:{grid:{display:false},ticks:{font:{family:'Inter',size:11}}}}}
            });
            new Chart(ctxY,{
                type:'line',
                data:{
                    labels:['Jan','Feb','Mar','Apr','Maj','Jun','Jul','Aug','Sep','Okt','Nov','Dec'],
                    datasets:[
                        {label:'Försäljning',data:[420000,659700,null,null,null,null,null,null,null,null,null,null],borderColor:'#024550',backgroundColor:'rgba(2,69,80,.08)',fill:true,tension:.3,pointRadius:5,pointBackgroundColor:'#024550'},
                        {label:'Mål',data:[500000,500000,550000,550000,600000,650000,400000,450000,600000,650000,700000,750000],borderColor:'#e5e7eb',borderDash:[5,5],fill:false,tension:.3,pointRadius:0}
                    ]
                },
                options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'bottom',labels:{usePointStyle:true,padding:12,font:{family:'Inter',size:11}}}},scales:{y:{beginAtZero:true,ticks:{callback:v=>v>=1000?(v/1000)+'k':''+v,font:{family:'Inter',size:11}},grid:{color:'#f1f5f9'}},x:{grid:{display:false},ticks:{font:{family:'Inter',size:11}}}}}
            });
        }
        initDashCharts();

        /* === FÄLTSÄLJ === */
        /* === FÄLTSÄLJ - Google Maps + Solar API === */
        const GOOGLE_MAPS_KEY = 'AIzaSyBJPnfNCe6un1J7ck6co7zr2uvGrxhFYXY';
        const faltStatusColors={unvisited:'#94a3b8',interested:'#10b981',kalkyl:'#7c3aed',offert:'#2563eb',not_interested:'#ef4444',not_home:'#eab308',callback:'#3b82f6'};
        const faltStatusLabels={unvisited:'Ej besökt',interested:'Intresserad',kalkyl:'Kalkyl',offert:'Offert',not_interested:'Ej intresserad',not_home:'Ej hemma',callback:'Återbesök'};
        let gMap=null, gMarker=null, gInfoWindow=null, faltProspects=[], faltGMarkers=[];
        let faltActiveIdx = -1;
        let faltAutocomplete=null;

        function initFaltMap(){
            if(gMap) return;
            const el = document.getElementById('faltMap');
            if(!el) return;

            gMap = new google.maps.Map(el, {
                center:{lat:59.3293,lng:18.0686}, // Stockholm default
                zoom:14,
                mapTypeId:'hybrid',
                mapTypeControl:true,
                streetViewControl:true,
                fullscreenControl:true,
            });

            gInfoWindow = new google.maps.InfoWindow();

            // Places autocomplete
            const input = document.getElementById('faltAddressInput');
            if(input){
                faltAutocomplete = new google.maps.places.Autocomplete(input, {
                    componentRestrictions:{country:'se'},
                    fields:['formatted_address','geometry','name','address_components'],
                });
                faltAutocomplete.addListener('place_changed', function(){
                    const place = faltAutocomplete.getPlace();
                    if(!place.geometry) return;
                    const loc = place.geometry.location;
                    gMap.setCenter(loc);
                    gMap.setZoom(19);
                    placeMarkerAndSolar(loc.lat(), loc.lng(), place.formatted_address);
                    saveAddressHistory(place.formatted_address, loc.lat(), loc.lng());
                    hideAddressHistory();
                });
                // Filtrera historik medan man skriver
                input.addEventListener('input', function(){ showAddressHistory(); });
                // Hide dropdown when clicking outside
                document.addEventListener('click', function(e){
                    if(!document.getElementById('faltSearchWrap')?.contains(e.target)) hideAddressHistory();
                });
            }

            // Click on map
            gMap.addListener('click', function(e){
                reverseGeocodeAndSolar(e.latLng.lat(), e.latLng.lng());
            });

            // Auto-center on user's GPS position
            if(navigator.geolocation){
                navigator.geolocation.getCurrentPosition(function(pos){
                    const lat = pos.coords.latitude;
                    const lng = pos.coords.longitude;
                    gMap.setCenter({lat, lng});
                    gMap.setZoom(17);
                }, function(){}, {enableHighAccuracy:true, timeout:5000});
            }

            // Load saved prospects
            const saved = localStorage.getItem('faltProspects');
            if(saved){
                try { faltProspects = JSON.parse(saved); } catch(e) { faltProspects = []; }
            }
            renderFaltMarkers();
            renderFaltList();
            updateFaltStats();
            renderFaltKalkyler();
        }

        // === DRAW AREA TO ADD PROSPECTS ===
        let drawingManager = null;
        let drawnShape = null;

        function startDrawArea(){
            if(!gMap) return;
            const btn = document.getElementById('btnDrawArea');

            // If already drawing, cancel
            if(drawingManager){
                drawingManager.setDrawingMode(null);
                drawingManager.setMap(null);
                drawingManager = null;
                if(drawnShape){ drawnShape.setMap(null); drawnShape = null; }
                btn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="12 2 22 8.5 22 15.5 12 22 2 15.5 2 8.5"/></svg> Markera område';
                btn.style.background = '#024550';
                return;
            }

            btn.innerHTML = 'Klicka för att rita polygon... (dubbelklicka = klar)';
            btn.style.background = '#10b981';

            drawingManager = new google.maps.drawing.DrawingManager({
                drawingMode: google.maps.drawing.OverlayType.POLYGON,
                drawingControl: false,
                polygonOptions: {
                    fillColor: '#eab308',
                    fillOpacity: 0.2,
                    strokeColor: '#eab308',
                    strokeWeight: 2,
                    editable: false,
                    clickable: false,
                }
            });
            drawingManager.setMap(gMap);

            google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon){
                drawingManager.setDrawingMode(null);
                drawingManager.setMap(null);
                drawingManager = null;
                drawnShape = polygon;
                btn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="12 2 22 8.5 22 15.5 12 22 2 15.5 2 8.5"/></svg> Markera område';
                btn.style.background = '#024550';
                scanPolygonForAddresses(polygon);
            });
        }

        function pointInPolygon(lat, lng, polygon){
            return google.maps.geometry ? google.maps.geometry.poly.containsLocation(new google.maps.LatLng(lat, lng), polygon) : true;
        }

        async function scanPolygonForAddresses(polygon){
            const path = polygon.getPath();
            // Get bounding box of polygon
            let minLat=90, maxLat=-90, minLng=180, maxLng=-180;
            path.forEach(p => {
                if(p.lat()<minLat) minLat=p.lat();
                if(p.lat()>maxLat) maxLat=p.lat();
                if(p.lng()<minLng) minLng=p.lng();
                if(p.lng()>maxLng) maxLng=p.lng();
            });

            const geocoder = new google.maps.Geocoder();
            const latStep = 0.0003; // ~33m
            const lngStep = 0.0005; // ~33m
            const points = [];
            for(let lat = minLat; lat <= maxLat; lat += latStep){
                for(let lng = minLng; lng <= maxLng; lng += lngStep){
                    // Check if point is inside polygon
                    if(google.maps.geometry && !google.maps.geometry.poly.containsLocation(new google.maps.LatLng(lat, lng), polygon)) continue;
                    points.push({lat, lng});
                }
            }

            if(points.length > 300){
                alert('Området är för stort ('+points.length+' punkter). Rita ett mindre område eller zooma in mer.');
                if(drawnShape){ drawnShape.setMap(null); drawnShape = null; }
                return;
            }
            if(points.length === 0){
                alert('Området är för litet. Rita ett större område.');
                if(drawnShape){ drawnShape.setMap(null); drawnShape = null; }
                return;
            }

            // Show progress
            const btn = document.getElementById('btnDrawArea');
            btn.innerHTML = 'Skannar 0/'+points.length+'...';
            btn.style.background = '#eab308';
            btn.disabled = true;

            const foundAddresses = new Map(); // address -> {lat,lng}
            let done = 0;

            // Process in batches of 5 with delay
            for(let batch = 0; batch < points.length; batch += 5){
                const chunk = points.slice(batch, batch+5);
                const promises = chunk.map(pt =>
                    new Promise(resolve => {
                        geocoder.geocode({location: pt}, function(results, status){
                            if(status === 'OK' && results[0]){
                                const r = results[0];
                                // Only street addresses (not just postcode/city)
                                const hasStreetNumber = r.types.includes('street_address') || r.types.includes('premise') || r.types.includes('subpremise') || r.address_components.some(c=>c.types.includes('street_number'));
                                if(hasStreetNumber){
                                    const addr = r.formatted_address;
                                    if(!foundAddresses.has(addr)){
                                        foundAddresses.set(addr, {
                                            lat: r.geometry.location.lat(),
                                            lng: r.geometry.location.lng()
                                        });
                                    }
                                }
                            }
                            resolve();
                        });
                    })
                );
                await Promise.all(promises);
                done += chunk.length;
                btn.innerHTML = 'Skannar '+done+'/'+points.length+'...';

                // Small delay to avoid rate limits
                if(batch + 5 < points.length) await new Promise(r => setTimeout(r, 200));
            }

            // Remove shape
            if(drawnShape){ drawnShape.setMap(null); drawnShape = null; }

            btn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="12 2 22 8.5 22 15.5 12 22 2 15.5 2 8.5"/></svg> Markera område';
            btn.style.background = '#024550';
            btn.disabled = false;

            // Filter out already existing prospects
            const newAddresses = [];
            foundAddresses.forEach((coords, addr) => {
                const exists = faltProspects.some(p => Math.abs(p.lat-coords.lat)<0.0001 && Math.abs(p.lng-coords.lng)<0.0001);
                if(!exists) newAddresses.push({addr, ...coords});
            });

            if(newAddresses.length === 0){
                alert('Inga nya fastigheter hittades i området ('+foundAddresses.size+' redan i listan).');
                return;
            }

            if(!confirm('Hittade '+newAddresses.length+' fastigheter. Lägga till alla som prospekt?')) return;

            // Add all as prospects
            newAddresses.forEach(a => {
                const parts = a.addr.split(',');
                faltProspects.push({
                    id: Date.now() + Math.random()*1000|0,
                    addr: parts[0]?.trim() || a.addr,
                    city: parts.slice(1).join(',').trim() || '',
                    lat: a.lat, lng: a.lng,
                    status: 'unvisited', note: '',
                    created: new Date().toISOString().split('T')[0],
                    maxPanels:null, yearlyKwh:null, roofArea:null,
                    kundNamn:'', kundTel:'', kundEmail:'', product:'',
                    checkinTime:null,
                });
            });
            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
            renderFaltMarkers();
            renderFaltList();
            updateFaltStats();
        }

        // === ADDRESS HISTORY ===
        function getAddressHistory(){
            try { return JSON.parse(localStorage.getItem('faltAddrHistory') || '[]'); } catch(e){ return []; }
        }
        function saveAddressHistory(address, lat, lng){
            let hist = getAddressHistory();
            // Ta bort duplikat
            hist = hist.filter(h => h.address !== address);
            hist.unshift({ address, lat, lng, ts: Date.now() });
            if(hist.length > 15) hist = hist.slice(0, 15);
            localStorage.setItem('faltAddrHistory', JSON.stringify(hist));
        }
        function showAddressHistory(){
            const dd = document.getElementById('addressHistoryDropdown');
            if(!dd) return;
            const hist = getAddressHistory();
            const input = document.getElementById('faltAddressInput');
            const val = (input?.value || '').trim().toLowerCase();
            if(hist.length === 0 && !val){ dd.style.display='none'; return; }

            let items = hist;
            // Filtrera om man börjat skriva
            if(val.length >= 2){
                items = hist.filter(h => h.address.toLowerCase().includes(val));
            }
            if(items.length === 0){ dd.style.display='none'; return; }

            dd.innerHTML = '<div style="padding:6px 12px;font-size:10px;font-weight:600;color:#94a3b8;text-transform:uppercase;letter-spacing:.5px;border-bottom:1px solid #f1f5f9;display:flex;justify-content:space-between;align-items:center"><span>Senaste sökningar</span><button onclick="event.stopPropagation();clearAddressHistory()" style="background:none;border:none;font-size:10px;color:#94a3b8;cursor:pointer;font-family:inherit;padding:0">Rensa</button></div>'
                + items.map(h => {
                    const parts = h.address.split(',');
                    const street = parts[0]?.trim() || h.address;
                    const rest = parts.slice(1).join(',').trim();
                    const ago = timeAgo(h.ts);
                    return '<div onclick="selectAddressHistory(\''+h.address.replace(/'/g,"\\'")+'\','+h.lat+','+h.lng+')" style="padding:10px 12px;cursor:pointer;border-bottom:1px solid #f8f9fa;transition:background .1s;display:flex;align-items:center;gap:10px" onmouseover="this.style.background=\'#f8f9fa\'" onmouseout="this.style.background=\'#fff\'">'
                        +'<svg viewBox="0 0 24 24" style="width:16px;height:16px;fill:none;stroke:#94a3b8;stroke-width:2;flex-shrink:0"><circle cx="12" cy="10" r="3"/><path d="M12 21.7C17.3 17 20 13 20 10a8 8 0 1 0-16 0c0 3 2.7 7 8 11.7z"/></svg>'
                        +'<div style="flex:1;min-width:0"><div style="font-size:13px;font-weight:500;color:#1a1a1a;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">'+street+'</div>'
                        +(rest?'<div style="font-size:11px;color:#94a3b8;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">'+rest+'</div>':'')
                        +'</div>'
                        +'<span style="font-size:10px;color:#cbd5e1;flex-shrink:0">'+ago+'</span>'
                        +'</div>';
                }).join('');
            dd.style.display = 'block';
        }
        function hideAddressHistory(){
            const dd = document.getElementById('addressHistoryDropdown');
            if(dd) dd.style.display = 'none';
        }
        function selectAddressHistory(address, lat, lng){
            document.getElementById('faltAddressInput').value = address;
            hideAddressHistory();
            gMap.setCenter({lat, lng});
            gMap.setZoom(19);
            placeMarkerAndSolar(lat, lng, address);
            saveAddressHistory(address, lat, lng);
        }
        function clearAddressHistory(){
            localStorage.removeItem('faltAddrHistory');
            hideAddressHistory();
        }
        function timeAgo(ts){
            const diff = Date.now() - ts;
            const min = Math.floor(diff/60000);
            if(min < 1) return 'nu';
            if(min < 60) return min+' min';
            const hrs = Math.floor(min/60);
            if(hrs < 24) return hrs+' tim';
            const days = Math.floor(hrs/24);
            return days+' d';
        }

        function placeMarkerAndSolar(lat, lng, address){
            if(gMarker) gMarker.setMap(null);
            gMarker = new google.maps.Marker({
                position:{lat, lng},
                map:gMap,
                animation:google.maps.Animation.DROP,
                title:address
            });
            gMap.setCenter({lat, lng});

            // Fetch Solar API data
            fetchSolarData(lat, lng, address);
        }

        function reverseGeocodeAndSolar(lat, lng){
            const geocoder = new google.maps.Geocoder();
            geocoder.geocode({location:{lat, lng}}, function(results, status){
                const addr = (status === 'OK' && results[0]) ? results[0].formatted_address : lat.toFixed(5)+', '+lng.toFixed(5);
                document.getElementById('faltAddressInput').value = addr;
                gMap.setZoom(19);
                placeMarkerAndSolar(lat, lng, addr);
                saveAddressHistory(addr, lat, lng);
            });
        }

        function faltUseMyLocation(){
            if(!navigator.geolocation){ alert('Geolokalisering stöds inte i din webbläsare'); return; }
            navigator.geolocation.getCurrentPosition(function(pos){
                reverseGeocodeAndSolar(pos.coords.latitude, pos.coords.longitude);
            }, function(err){
                alert('Kunde inte hämta position: '+err.message);
            }, {enableHighAccuracy:true});
        }

        async function fetchSolarData(lat, lng, address){
            const panel = document.getElementById('solarDataPanel');
            panel.innerHTML = '<div style="text-align:center;padding:30px;color:#94a3b8"><div class="spinner" style="display:inline-block;width:24px;height:24px;border:3px solid #e5e7eb;border-top-color:#024550;border-radius:50%;animation:bgspin .6s linear infinite"></div><p style="margin-top:8px;font-size:13px">Hämtar soldata...</p></div>';

            try {
                const res = await fetch('https://solar.googleapis.com/v1/buildingInsights:findClosest?location.latitude='+lat+'&location.longitude='+lng+'&requiredQuality=HIGH&key='+GOOGLE_MAPS_KEY);

                if(!res.ok){
                    const err = await res.json().catch(()=>({}));
                    if(res.status === 404){
                        lastSolarData = null;
                        // Fallback: try PVGIS/estimation
                        await fetchPvgisFallback(lat, lng, address, panel);
                    } else {
                        panel.innerHTML = '<div style="padding:18px;color:#ef4444;font-size:13px">Fel: '+(err.error?.message || 'HTTP '+res.status)+'</div>';
                    }
                    return;
                }

                const data = await res.json();
                lastSolarData = data;
                panel.innerHTML = renderSolarResults(data, address, lat, lng);
                // Store solar kWh and auto-lookup resident
                const configs = data.solarPotential?.solarPanelConfigs || [];
                window._lastSolarKwh = configs.length ? Math.round(configs[configs.length-1].yearlyEnergyDcKwh||0) : 0;
                lookupHittaForPanel(address);
            } catch(e){
                panel.innerHTML = '<div style="padding:18px;color:#ef4444;font-size:13px">Nätverksfel: '+e.message+'</div>';
            }
        }

        async function fetchPvgisFallback(lat, lng, address, panel){
            panel.innerHTML = '<div style="text-align:center;padding:30px;color:#94a3b8"><div class="spinner" style="display:inline-block;width:24px;height:24px;border:3px solid #e5e7eb;border-top-color:#f59e0b;border-radius:50%;animation:bgspin .6s linear infinite"></div><p style="margin-top:8px;font-size:13px">Google Solar saknar data — beräknar uppskattning...</p></div>';
            try {
                const res = await fetch('/api/pvgis-proxy.php?lat='+lat+'&lon='+lng);
                if(res.ok){
                    const data = await res.json();
                    if(data.success){
                        panel.innerHTML = renderPvgisResults(data, address, lat, lng);
                        window._lastSolarKwh = data.yearly_kwh || 0;
                        lookupHittaForPanel(address);
                        return;
                    }
                }
            } catch(e){}
            // Total fallback
            panel.innerHTML = renderSolarNoData(address, lat, lng);
            lookupHittaForPanel(address);
        }

        function renderPvgisResults(data, address, lat, lng){
            const sys = data.system || {};
            const panels = sys.panels || 0;
            const kWh = data.yearly_kwh || 0;
            const source = data.source === 'PVGIS' ? 'PVGIS (EU)' : 'Uppskattning (SMHI-data)';
            const sourceColor = data.source === 'PVGIS' ? '#0284c7' : '#ca8a04';
            const note = data.note || '';

            // Monthly chart bars
            let monthlyHtml = '';
            if(data.monthly && data.monthly.length) {
                const maxM = Math.max(...data.monthly.map(m=>m.kWh));
                const months = ['Jan','Feb','Mar','Apr','Maj','Jun','Jul','Aug','Sep','Okt','Nov','Dec'];
                monthlyHtml = '<div style="margin-top:16px"><div style="font-size:12px;font-weight:700;color:#1a1a1a;margin-bottom:8px">Månadsproduktion (kWh)</div>'
                    +'<div style="display:flex;align-items:flex-end;gap:3px;height:80px">'
                    +data.monthly.map((m,i)=>{
                        const h = maxM > 0 ? Math.round((m.kWh/maxM)*70) : 0;
                        return '<div style="flex:1;display:flex;flex-direction:column;align-items:center">'
                            +'<div style="font-size:9px;color:#64748b;margin-bottom:2px">'+m.kWh+'</div>'
                            +'<div style="width:100%;height:'+h+'px;background:linear-gradient(180deg,#f59e0b,#eab308);border-radius:3px 3px 0 0"></div>'
                            +'<div style="font-size:9px;color:#94a3b8;margin-top:2px">'+months[i]+'</div>'
                            +'</div>';
                    }).join('')
                    +'</div></div>';
            }

            return '<div style="padding:18px">'
                +'<div style="font-weight:700;font-size:14px;margin-bottom:4px">'+address+'</div>'
                +'<div style="color:#94a3b8;font-size:11px;margin-bottom:8px">'+lat.toFixed(5)+', '+lng.toFixed(5)+'</div>'
                +'<div style="display:inline-block;padding:3px 10px;background:'+sourceColor+'15;color:'+sourceColor+';border-radius:6px;font-size:11px;font-weight:600;margin-bottom:14px">'+source+'</div>'
                +(note?'<div style="font-size:11px;color:#64748b;margin-bottom:12px">'+note+'</div>':'')

                // Key metrics (2 boxes)
                +'<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:16px">'
                +'<div style="background:#ecfdf5;padding:12px;border-radius:8px;text-align:center"><div style="font-size:10px;color:#10b981;font-weight:600;text-transform:uppercase">Uppsk. paneler</div><div style="font-size:22px;font-weight:700;color:#166534">'+panels+'</div><div style="font-size:10px;color:#64748b">'+sys.panel_watt+'W / st</div></div>'
                +'<div style="background:#eff6ff;padding:12px;border-radius:8px;text-align:center"><div style="font-size:10px;color:#3b82f6;font-weight:600;text-transform:uppercase">Produktion/år</div><div style="font-size:22px;font-weight:700;color:#1e40af">'+kWh.toLocaleString('sv-SE')+' <span style="font-size:12px">kWh</span></div></div>'
                +'</div>'

                // Monthly chart
                +monthlyHtml

                // Actions
                +'<div style="display:flex;gap:8px;margin-top:16px">'
                +'<button class="dummy-btn" style="flex:1;justify-content:center;font-size:12px" onclick="addAsProspect(\''+address.replace(/'/g,"\\'")+'\','+lat+','+lng+')">+ Prospekt</button>'
                +'<a href="'+hittaUrl(address)+'" target="_blank" class="dummy-btn secondary" style="flex:1;justify-content:center;font-size:12px;text-decoration:none">Hitta.se</a>'
                +'</div>'
                +'<div id="hittaResult" style="margin-top:10px;font-size:12px;color:#94a3b8">Söker boende...</div>'
                +'<div id="energyEstimate"></div>'
                +'</div>';
        }

        function renderSolarNoData(address, lat, lng){
            return '<div style="padding:18px">'
                +'<div style="font-weight:700;font-size:14px;margin-bottom:8px">'+address+'</div>'
                +'<div style="color:#94a3b8;font-size:12px;margin-bottom:12px">'+lat.toFixed(5)+', '+lng.toFixed(5)+'</div>'
                +'<div style="padding:16px;background:#fef9c3;border-radius:8px;font-size:13px;color:#854d0e">Ingen soldata tillgänglig för denna plats.</div>'
                +'<button class="dummy-btn" style="margin-top:12px;width:100%;justify-content:center" onclick="addAsProspect(\''+address.replace(/'/g,"\\'")+'\','+lat+','+lng+')">+ Lägg till som prospekt</button>'
                +'<div id="hittaResult" style="margin-top:10px"><button onclick="lookupHittaForPanel(\''+address.replace(/'/g,"\\'")+'\');this.disabled=true;this.textContent=\'Söker...\'" style="padding:6px 12px;border:1px solid #dbeafe;border-radius:6px;font-size:12px;cursor:pointer;background:#eff6ff;font-family:inherit;color:#3b82f6;width:100%">Vem bor här?</button></div>'
                +'<div id="energyEstimate"></div>'
                +'</div>';
        }

        function renderSolarResults(data, address, lat, lng){
            const si = data.solarPotential || {};
            const maxPanels = si.maxArrayPanelsCount || 0;
            const maxArea = si.maxArrayAreaMeters2 ? si.maxArrayAreaMeters2.toFixed(0) : '-';
            const maxSunHrs = si.maxSunshineHoursPerYear ? si.maxSunshineHoursPerYear.toFixed(0) : '-';
            const roofArea = si.wholeRoofStats?.areaMeters2 ? si.wholeRoofStats.areaMeters2.toFixed(0) : '-';

            // Best config
            const configs = si.solarPanelConfigs || [];
            const best = configs[configs.length - 1];
            const bestKwh = best ? (best.yearlyEnergyDcKwh||0).toFixed(0) : '-';
            const bestPanels = best ? best.panelsCount : maxPanels;

            // Roof segments
            let segmentsHtml = '';
            const segments = si.roofSegmentStats || [];
            const directions = {0:'N',45:'NE',90:'Ö',135:'SO',180:'S',225:'SV',270:'V',315:'NV',360:'N'};
            const segCount = segments.length;
            const segRows = segments.map((seg, i) => {
                const az = seg.azimuthDegrees || 0;
                let dir = 'N';
                for(const [deg, label] of Object.entries(directions)){
                    if(az >= (deg-22.5) && az < (Number(deg)+22.5)) dir = label;
                }
                const pitch = seg.pitchDegrees ? seg.pitchDegrees.toFixed(0) : '-';
                const area = seg.stats?.areaMeters2 ? seg.stats.areaMeters2.toFixed(0) : '-';
                const sun = seg.stats?.sunshineQuantiles?.[10] ? seg.stats.sunshineQuantiles[10].toFixed(0) : '-';
                return '<div style="display:flex;justify-content:space-between;padding:5px 0;border-bottom:1px solid #f1f5f9;font-size:12px">'
                    +'<span>Yta '+(i+1)+' ('+dir+')</span>'
                    +'<span>'+pitch+'° • '+area+' m² • '+sun+' h/år</span>'
                    +'</div>';
            });
            if(segCount > 0){
                if(segCount <= 3){
                    segmentsHtml = segRows.join('');
                } else {
                    // Visa 2 först, resten expanderbart
                    const rndId = 'seg_'+Date.now();
                    segmentsHtml = segRows.slice(0,2).join('')
                        +'<div id="'+rndId+'" style="display:none">'+segRows.slice(2).join('')+'</div>'
                        +'<button onclick="const el=document.getElementById(\''+rndId+'\');if(el.style.display===\'none\'){el.style.display=\'block\';this.textContent=\'Dölj\';}else{el.style.display=\'none\';this.textContent=\'Visa alla '+segCount+' ytor\';}" style="padding:4px 10px;background:none;border:1px solid #e5e7eb;border-radius:6px;font-size:11px;color:#3b82f6;cursor:pointer;font-family:inherit;margin-top:4px;font-weight:600">Visa alla '+segCount+' ytor</button>';
                }
            }

            return '<div style="padding:18px">'
                +'<div style="font-weight:700;font-size:14px;margin-bottom:4px">'+address+'</div>'
                +'<div style="color:#94a3b8;font-size:11px;margin-bottom:16px">'+lat.toFixed(5)+', '+lng.toFixed(5)+'</div>'

                // Key metrics
                +'<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:16px">'
                +'<div style="background:#ecfdf5;padding:12px;border-radius:8px;text-align:center"><div style="font-size:10px;color:#10b981;font-weight:600;text-transform:uppercase">Max paneler</div><div style="font-size:22px;font-weight:700;color:#166534">'+maxPanels+'</div></div>'
                +'<div style="background:#eff6ff;padding:12px;border-radius:8px;text-align:center"><div style="font-size:10px;color:#3b82f6;font-weight:600;text-transform:uppercase">Produktion/år</div><div style="font-size:22px;font-weight:700;color:#1e40af">'+Number(bestKwh).toLocaleString('sv-SE')+' <span style="font-size:12px">kWh</span></div></div>'
                +'<div style="background:#faf5ff;padding:12px;border-radius:8px;text-align:center"><div style="font-size:10px;color:#a855f7;font-weight:600;text-transform:uppercase">Takyta</div><div style="font-size:22px;font-weight:700;color:#6d28d9">'+roofArea+' <span style="font-size:12px">m²</span></div></div>'
                +'<div style="background:#fef9c3;padding:12px;border-radius:8px;text-align:center"><div style="font-size:10px;color:#ca8a04;font-weight:600;text-transform:uppercase">Soltimmar/år</div><div style="font-size:22px;font-weight:700;color:#854d0e">'+maxSunHrs+'</div></div>'
                +'</div>'

                // Roof segments
                +(segmentsHtml ? '<div style="margin-bottom:16px"><div style="font-size:12px;font-weight:700;color:#1a1a1a;margin-bottom:6px">Takytor <span style="font-weight:400;color:#64748b">('+segCount+' ytor — lutning • yta • sol)</span></div>'+segmentsHtml+'</div>' : '')

                // Actions
                +'<div style="display:flex;gap:8px">'
                +'<button class="dummy-btn" style="flex:1;justify-content:center;font-size:12px" onclick="addAsProspect(\''+address.replace(/'/g,"\\'")+'\','+lat+','+lng+')">+ Prospekt</button>'
                +'<a href="'+hittaUrl(address)+'" target="_blank" class="dummy-btn secondary" style="flex:1;justify-content:center;font-size:12px;text-decoration:none">Hitta.se</a>'
                +'</div>'
                +'<div id="hittaResult" style="margin-top:10px;font-size:12px;color:#94a3b8">Söker boende...</div>'
                +'<div id="energyEstimate"></div>'
                +'</div>';
        }

        function hittaUrl(addr){
            // Clean address for hitta.se: remove ", Sweden", postal codes, keep street + city
            let clean = addr.replace(/,?\s*Sweden$/i,'').replace(/,?\s*Sverige$/i,'');
            // Remove postal code (5 digits with optional space: "856 44" or "85644")
            clean = clean.replace(/,?\s*\d{3}\s?\d{2}\s*/g, ', ');
            // Clean up multiple commas/spaces
            clean = clean.replace(/,\s*,/g,',').replace(/,\s*$/,'').replace(/^\s*,/,'').trim();
            return 'https://www.hitta.se/s%C3%B6k?vad='+encodeURIComponent(clean);
        }

        let lastSolarData = null;
        let faltListFilter = 'all';
        let checkinIdx = null;
        let checkinStatus = null;

        function addAsProspect(address, lat, lng){
            if(faltProspects.some(p => Math.abs(p.lat-lat)<0.0001 && Math.abs(p.lng-lng)<0.0001)){
                alert('Denna adress finns redan i rutten');
                return;
            }
            const parts = address.split(',');
            const solar = lastSolarData || {};
            const si = solar.solarPotential || {};
            const idx = faltProspects.length;
            faltProspects.push({
                id: Date.now(),
                addr: parts[0]?.trim()||address,
                city: parts.slice(1).join(',').trim()||'',
                lat:lat, lng:lng,
                status: 'unvisited',
                note: '',
                created: new Date().toISOString().split('T')[0],
                // Solar
                maxPanels: si.maxArrayPanelsCount || null,
                yearlyKwh: si.solarPanelConfigs?.length ? Math.round(si.solarPanelConfigs[si.solarPanelConfigs.length-1].yearlyEnergyDcKwh||0) : null,
                roofArea: si.wholeRoofStats?.areaMeters2 ? Math.round(si.wholeRoofStats.areaMeters2) : null,
                solarScore: null,
                // Lead info
                kundNamn: '', kundTel: '', kundEmail: '', product: '',
                checkinTime: null,
                photos: [],
            });
            // Calculate solar score if we have data already
            if(si.maxArrayPanelsCount) {
                faltProspects[idx].solarScore = calcSolarScore(si);
            }
            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
            renderFaltMarkers();
            renderFaltList();
            updateFaltStats();
            // Auto-fetch solar data in background if not already available
            if(!si.maxArrayPanelsCount) {
                fetchSolarScoreForProspect(idx, lat, lng);
            }
        }

        function calcSolarScore(si) {
            // Score 1-5 based on yearly kWh potential
            const configs = si.solarPanelConfigs || [];
            const best = configs.length ? configs[configs.length-1] : null;
            const kWh = best ? (best.yearlyEnergyDcKwh || 0) : 0;
            const panels = si.maxArrayPanelsCount || 0;
            const sunHrs = si.maxSunshineHoursPerYear || 0;
            // kWh per panel efficiency
            const efficiency = panels > 0 ? kWh / panels : 0;
            // Score: <200kWh/panel=1, 200-300=2, 300-400=3, 400-500=4, 500+=5
            if(efficiency >= 500) return 5;
            if(efficiency >= 400) return 4;
            if(efficiency >= 300) return 3;
            if(efficiency >= 200) return 2;
            return 1;
        }

        // === HITTA.SE CACHE ===
        const hittaCache = {};
        const HITTA_CACHE_TTL = 10 * 60 * 1000; // 10 minuter

        function hittaCacheKey(address) {
            return address.trim().toLowerCase().replace(/\s+/g,' ');
        }

        function getHittaCache(address) {
            const key = hittaCacheKey(address);
            const entry = hittaCache[key];
            if(entry && (Date.now() - entry.ts) < HITTA_CACHE_TTL) return entry.data;
            return null;
        }

        function setHittaCache(address, data) {
            // Sortera boende äldst först (högst ålder överst)
            if(data && data.persons && data.persons.length > 1){
                data.persons.sort((a,b) => (parseInt(b.age)||0) - (parseInt(a.age)||0));
            }
            hittaCache[hittaCacheKey(address)] = { data: data, ts: Date.now() };
        }

        // === ENERGIBERÄKNING ===
        // Beräknar uppskattad årsförbrukning baserat på boyta
        // Svensk genomsnittsvilla: eluppvärmning ~130 kWh/m²/år, värmepump/fjärrvärme ~50 kWh/m²/år
        // Elpris: ~1.50 kr/kWh (snitt inkl nätavgift, skatt, elhandel)
        const ENERGY_ELECTRIC_HEAT = 130; // kWh/m²/år med direktverkande el
        const ENERGY_HEATPUMP = 50;       // kWh/m²/år med värmepump/fjärrvärme
        const ELECTRICITY_PRICE = 1.50;   // kr/kWh snitt Sverige
        const SOLAR_SELF_USE = 0.70;      // 70% egenanvändning (resten säljs billigare)
        const SOLAR_SELL_PRICE = 0.50;    // kr/kWh vid överskottsförsäljning

        function estimateEnergyConsumption(livingAreaStr) {
            // Parsa boyta från Hitta.se format, t.ex. "120 m²" eller "85m²"
            if(!livingAreaStr) return null;
            const m = livingAreaStr.match(/(\d+)/);
            if(!m) return null;
            const area = parseInt(m[1]);
            if(area < 20 || area > 1000) return null;

            const elHeat = Math.round(area * ENERGY_ELECTRIC_HEAT);
            const heatPump = Math.round(area * ENERGY_HEATPUMP);

            return {
                livingAreaM2: area,
                withElectricHeat: elHeat,
                withHeatPump: heatPump,
                // Kostnader per år
                costElHeat: Math.round(elHeat * ELECTRICITY_PRICE),
                costHeatPump: Math.round(heatPump * ELECTRICITY_PRICE)
            };
        }

        function buildEnergyEstimateHtml(energyEst, solarKwh) {
            if(!energyEst) return '';
            const area = energyEst.livingAreaM2;
            const consumption = energyEst.withElectricHeat;
            const consumptionHP = energyEst.withHeatPump;

            let html = '<div style="margin-top:16px;padding:14px;background:linear-gradient(135deg,#fef3c7,#fde68a);border-radius:10px;border:1px solid #f59e0b33">'
                +'<div style="font-size:11px;font-weight:700;color:#92400e;text-transform:uppercase;margin-bottom:8px">Energianalys ('+area+' m²)</div>';

            // Förbrukning
            html += '<div style="display:flex;justify-content:space-between;padding:4px 0;font-size:12px">'
                +'<span style="color:#78350f">Förbrukning (elvärme):</span>'
                +'<span style="font-weight:700;color:#92400e">'+consumption.toLocaleString('sv-SE')+' kWh/år</span></div>';
            html += '<div style="display:flex;justify-content:space-between;padding:4px 0;font-size:12px">'
                +'<span style="color:#78350f">Förbrukning (värmepump):</span>'
                +'<span style="font-weight:600;color:#a16207">'+consumptionHP.toLocaleString('sv-SE')+' kWh/år</span></div>';

            if(solarKwh && solarKwh > 0) {
                // Beräkna besparingar
                const coverageElHeat = Math.min(100, Math.round((solarKwh / consumption) * 100));
                const coverageHP = Math.min(100, Math.round((solarKwh / consumptionHP) * 100));

                // Ekonomisk besparing: egenanvändning sparar elpris, överskott säljs
                const selfUseKwh = Math.min(solarKwh * SOLAR_SELF_USE, consumption);
                const sellKwh = solarKwh - selfUseKwh;
                const yearlySaving = Math.round(selfUseKwh * ELECTRICITY_PRICE + sellKwh * SOLAR_SELL_PRICE);

                html += '<div style="border-top:1px solid #f59e0b44;margin:8px 0"></div>';

                // Solproduktion vs förbrukning
                html += '<div style="display:flex;justify-content:space-between;padding:4px 0;font-size:12px">'
                    +'<span style="color:#166534;font-weight:600">Solproduktion:</span>'
                    +'<span style="font-weight:700;color:#166534">'+solarKwh.toLocaleString('sv-SE')+' kWh/år</span></div>';

                // Coverage bar
                html += '<div style="margin:6px 0">'
                    +'<div style="display:flex;justify-content:space-between;font-size:11px;margin-bottom:3px">'
                    +'<span style="color:#78350f">Täcker (elvärme)</span>'
                    +'<span style="font-weight:700;color:'+(coverageElHeat >= 70 ? '#059669' : coverageElHeat >= 40 ? '#ca8a04' : '#dc2626')+'">'+coverageElHeat+'%</span></div>'
                    +'<div style="background:#fff8e1;border-radius:6px;height:8px;overflow:hidden">'
                    +'<div style="height:100%;border-radius:6px;background:'+(coverageElHeat >= 70 ? 'linear-gradient(90deg,#10b981,#059669)' : coverageElHeat >= 40 ? 'linear-gradient(90deg,#eab308,#ca8a04)' : 'linear-gradient(90deg,#f87171,#dc2626)')+';width:'+coverageElHeat+'%"></div>'
                    +'</div></div>';

                html += '<div style="margin:6px 0">'
                    +'<div style="display:flex;justify-content:space-between;font-size:11px;margin-bottom:3px">'
                    +'<span style="color:#78350f">Täcker (värmepump)</span>'
                    +'<span style="font-weight:700;color:'+(coverageHP >= 70 ? '#059669' : coverageHP >= 40 ? '#ca8a04' : '#dc2626')+'">'+coverageHP+'%</span></div>'
                    +'<div style="background:#fff8e1;border-radius:6px;height:8px;overflow:hidden">'
                    +'<div style="height:100%;border-radius:6px;background:'+(coverageHP >= 70 ? 'linear-gradient(90deg,#10b981,#059669)' : coverageHP >= 40 ? 'linear-gradient(90deg,#eab308,#ca8a04)' : 'linear-gradient(90deg,#f87171,#dc2626)')+';width:'+Math.min(100,coverageHP)+'%"></div>'
                    +'</div></div>';

                // Besparing i SEK
                html += '<div style="border-top:1px solid #f59e0b44;margin:8px 0"></div>'
                    +'<div style="display:flex;justify-content:space-between;padding:4px 0;font-size:13px">'
                    +'<span style="color:#166534;font-weight:700">Besparing/år:</span>'
                    +'<span style="font-weight:800;color:#059669;font-size:15px">'+yearlySaving.toLocaleString('sv-SE')+' kr</span></div>'
                    +'<div style="font-size:10px;color:#92400e;opacity:0.7">Baserat på '+ELECTRICITY_PRICE.toFixed(2)+' kr/kWh, 70% egenanvändning</div>';
            }

            html += '</div>';
            return html;
        }

        function solarScoreLabel(score) {
            if(!score) return '';
            const labels = {1:'Låg',2:'OK',3:'Bra',4:'Mycket bra',5:'Utmärkt'};
            const colors = {1:'#ef4444',2:'#eab308',3:'#22c55e',4:'#10b981',5:'#059669'};
            const suns = '☀️'.repeat(Math.min(score, 5));
            return '<span style="color:'+colors[score]+';font-weight:600" title="Solpotential: '+labels[score]+'">'+suns+' '+labels[score]+'</span>';
        }

        let solarFetchQueue = [];
        let solarFetching = false;

        async function fetchSolarScoreForProspect(idx, lat, lng) {
            solarFetchQueue.push({idx, lat, lng});
            if(solarFetching) return;
            solarFetching = true;
            while(solarFetchQueue.length > 0) {
                const job = solarFetchQueue.shift();
                try {
                    const res = await fetch('https://solar.googleapis.com/v1/buildingInsights:findClosest?location.latitude='+job.lat+'&location.longitude='+job.lng+'&requiredQuality=HIGH&key='+GOOGLE_MAPS_KEY);
                    if(res.ok) {
                        const data = await res.json();
                        const si = data.solarPotential || {};
                        if(faltProspects[job.idx]) {
                            faltProspects[job.idx].maxPanels = si.maxArrayPanelsCount || null;
                            const configs = si.solarPanelConfigs || [];
                            faltProspects[job.idx].yearlyKwh = configs.length ? Math.round(configs[configs.length-1].yearlyEnergyDcKwh||0) : null;
                            faltProspects[job.idx].roofArea = si.wholeRoofStats?.areaMeters2 ? Math.round(si.wholeRoofStats.areaMeters2) : null;
                            faltProspects[job.idx].solarScore = calcSolarScore(si);
                            faltProspects[job.idx].solarSource = 'google';
                            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
                            renderFaltMarkers();
                            renderFaltList();
                        }
                    } else if(res.status === 404 && faltProspects[job.idx]) {
                        // Google Solar has no data — try PVGIS/estimation fallback
                        try {
                            const fbRes = await fetch('/api/pvgis-proxy.php?lat='+job.lat+'&lon='+job.lng);
                            if(fbRes.ok) {
                                const fbData = await fbRes.json();
                                if(fbData.success) {
                                    faltProspects[job.idx].maxPanels = fbData.system?.panels || null;
                                    faltProspects[job.idx].yearlyKwh = fbData.yearly_kwh || null;
                                    faltProspects[job.idx].solarScore = fbData.solar_score || null;
                                    faltProspects[job.idx].solarSource = fbData.source || 'estimate';
                                    localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
                                    renderFaltMarkers();
                                    renderFaltList();
                                }
                            }
                        } catch(fe) {}
                    }
                } catch(e) {}
                // Rate limit: wait 200ms between requests
                if(solarFetchQueue.length > 0) await new Promise(r => setTimeout(r, 200));
            }
            solarFetching = false;
        }

        function renderFaltMarkers(){
            faltGMarkers.forEach(m=>m.setMap(null));
            faltGMarkers=[];
            if(!gMap) return;
            faltProspects.forEach((p,i)=>{
                const color=faltStatusColors[p.status];
                const pinLabel = String(i+1);
                const pinFontSize = pinLabel.length > 2 ? 11 : 14;
                // Solar score — gul sol
                const score = p.solarScore;
                const sunYellow = 'rgb(251,191,36)';
                const sunAmber = 'rgb(245,158,11)';
                const sunBrown = 'rgb(113,63,18)';
                const scoreBadge = score ? '<g transform="translate(30,8)">'
                    +'<line x1="0" y1="-10" x2="0" y2="-7" stroke="'+sunAmber+'" stroke-width="1.5" stroke-linecap="round"/>'
                    +'<line x1="0" y1="7" x2="0" y2="10" stroke="'+sunAmber+'" stroke-width="1.5" stroke-linecap="round"/>'
                    +'<line x1="-10" y1="0" x2="-7" y2="0" stroke="'+sunAmber+'" stroke-width="1.5" stroke-linecap="round"/>'
                    +'<line x1="7" y1="0" x2="10" y2="0" stroke="'+sunAmber+'" stroke-width="1.5" stroke-linecap="round"/>'
                    +'<line x1="-7" y1="-7" x2="-5" y2="-5" stroke="'+sunAmber+'" stroke-width="1.5" stroke-linecap="round"/>'
                    +'<line x1="5" y1="-5" x2="7" y2="-7" stroke="'+sunAmber+'" stroke-width="1.5" stroke-linecap="round"/>'
                    +'<line x1="-7" y1="7" x2="-5" y2="5" stroke="'+sunAmber+'" stroke-width="1.5" stroke-linecap="round"/>'
                    +'<line x1="5" y1="5" x2="7" y2="7" stroke="'+sunAmber+'" stroke-width="1.5" stroke-linecap="round"/>'
                    +'<circle r="6" fill="'+sunYellow+'" stroke="white" stroke-width="1.5"/>'
                    +'<text y="4" text-anchor="middle" fill="'+sunBrown+'" font-family="sans-serif" font-size="9" font-weight="800">'+score+'</text>'
                    +'</g>' : '';
                const kwhLabel = p.yearlyKwh ? '<text x="18" y="36" text-anchor="middle" fill="'+color+'" font-family="sans-serif" font-size="7" font-weight="700">'+(p.yearlyKwh>=1000?(p.yearlyKwh/1000).toFixed(0)+'k':p.yearlyKwh)+'kWh</text>' : '';
                const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="'+(score?46:36)+'" height="'+(p.yearlyKwh?48:44)+'" viewBox="0 0 '+(score?46:36)+' '+(p.yearlyKwh?48:44)+'">'
                    +'<path d="M18 0C8 0 0 8 0 18c0 13 18 26 18 26s18-13 18-26C36 8 28 0 18 0z" fill="'+color+'" stroke="white" stroke-width="2"/>'
                    +'<text x="18" y="22" text-anchor="middle" fill="white" font-family="Inter,sans-serif" font-size="'+pinFontSize+'" font-weight="700">'+pinLabel+'</text>'
                    +scoreBadge+kwhLabel
                    +'</svg>';
                const marker = new google.maps.Marker({
                    position:{lat:p.lat,lng:p.lng},
                    map:gMap,
                    icon:{
                        url:'data:image/svg+xml;charset=UTF-8,'+encodeURIComponent(svg),
                        scaledSize:new google.maps.Size(score?46:36, p.yearlyKwh?48:44),
                        anchor:new google.maps.Point(18, p.yearlyKwh?48:44),
                    },
                    title:pinLabel+' '+p.addr,
                });
                marker.addListener('click', function(){
                    faltActiveIdx = i;
                    renderFaltList();
                    setTimeout(() => {
                        const activeEl = document.querySelector('.falt-item-active');
                        if(activeEl) activeEl.scrollIntoView({block:'nearest',behavior:'smooth'});
                    }, 50);
                    let solarInfo = '';
                    if(p.maxPanels || p.solarScore) {
                        solarInfo = '<div style="display:flex;gap:6px;margin:6px 0;font-size:10px;flex-wrap:wrap;align-items:center">';
                        if(p.solarScore) solarInfo += '<span style="background:#f0fdf4;padding:3px 8px;border-radius:6px;font-size:11px">' + solarScoreLabel(p.solarScore) + '</span>';
                        if(p.maxPanels) solarInfo += '<span style="background:#ecfdf5;padding:2px 6px;border-radius:4px;color:#166534">'+p.maxPanels+' paneler</span>';
                        if(p.yearlyKwh) solarInfo += '<span style="background:#eff6ff;padding:2px 6px;border-radius:4px;color:#1e40af">'+p.yearlyKwh.toLocaleString('sv-SE')+' kWh/år</span>';
                        if(p.roofArea) solarInfo += '<span style="background:#faf5ff;padding:2px 6px;border-radius:4px;color:#6d28d9">'+p.roofArea+' m²</span>';
                        solarInfo += '</div>';
                    }
                    let leadInfo = '';
                    if(p.kundNamn) leadInfo = '<div style="margin:6px 0;padding:8px;background:#f0fdf4;border-radius:6px;font-size:12px">'
                        +'<strong>'+p.kundNamn+'</strong>'+(p.kundTel?' • '+p.kundTel:'')
                        +(p.product?' • <span style="color:#10b981">'+p.product+'</span>':'')
                        +'</div>';
                    const isUnvisited = p.status === 'unvisited';
                    const html='<div style="font-family:Inter,sans-serif;min-width:260px">'
                        +'<div style="display:flex;justify-content:space-between;align-items:start">'
                        +'<div><strong style="font-size:13px">'+p.addr+'</strong><br><span style="font-size:12px;color:#64748b">'+p.city+'</span></div>'
                        +'<span style="padding:2px 8px;border-radius:8px;font-size:11px;font-weight:600;background:'+color+'20;color:'+color+';white-space:nowrap">'+faltStatusLabels[p.status]+'</span>'
                        +'</div>'
                        +solarInfo+leadInfo
                        +'<div id="popupHitta_'+i+'" style="font-size:12px;color:#94a3b8;margin:4px 0">Söker boende...</div>'
                        +(p.note?'<div style="font-size:12px;color:#64748b;font-style:italic;margin:4px 0">'+p.note+'</div>':'')
                        +'<div style="display:flex;gap:6px;margin-top:8px">'
                        +(isUnvisited
                            ? '<button onclick="openCheckin('+i+')" style="flex:1;padding:10px;background:#024550;color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit">Checka in</button>'
                            : '<button onclick="openCheckin('+i+')" style="flex:1;padding:8px;background:#f1f5f9;color:#334155;border:1px solid #e5e7eb;border-radius:8px;font-size:12px;cursor:pointer;font-family:inherit">Uppdatera</button>')
                        +'</div></div>';
                    gInfoWindow.setContent(html);
                    gInfoWindow.open(gMap, marker);
                    // Fetch resident name
                    lookupHittaForPopup(p.addr + (p.city ? ', '+p.city : ''), i);
                });
                faltGMarkers.push(marker);
            });
        }

        function setFaltStatus(id,status){
            faltProspects[id].status=status;
            if(!faltProspects[id].checkinTime) faltProspects[id].checkinTime = new Date().toISOString();
            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
            renderFaltMarkers();
            renderFaltList();
            updateFaltStats();
            gInfoWindow.close();
        }

        function saveProspectNote(id, note){
            faltProspects[id].note = note;
            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
            renderFaltList();
        }

        // === CHECK-IN MODAL ===
        function openCheckin(idx){
            checkinIdx = idx;
            checkinStatus = null;
            const p = faltProspects[idx];
            document.getElementById('checkinTitle').textContent = 'Incheckning — Hus #'+(idx+1);
            document.getElementById('checkinAddr').innerHTML = p.addr + (p.city?', '+p.city:'') + '<span id="ciHittaStatus" style="margin-left:8px;font-size:11px;color:#94a3b8"></span>';
            document.getElementById('checkinStep0').style.display = 'block';
            document.getElementById('checkinStep1').style.display = 'block';
            document.getElementById('checkinStep2').style.display = 'none';
            document.getElementById('checkinStep2b').style.display = 'none';
            if(document.getElementById('checkinStep2c')) document.getElementById('checkinStep2c').style.display = 'none';
            // Pre-fill if revisiting
            document.getElementById('ciName').value = p.kundNamn || '';
            document.getElementById('ciPhone').value = p.kundTel || '';
            document.getElementById('ciEmail').value = p.kundEmail || '';
            document.getElementById('ciProduct').value = p.product || '';
            document.getElementById('ciNote').value = p.note || '';
            document.getElementById('ciNoteSimple').value = p.note || '';
            document.getElementById('checkinModal').style.display = 'flex';
            gInfoWindow.close();

            // Auto-lookup name from Hitta.se
            if(!p.kundNamn){
                lookupHitta(p.addr + (p.city ? ', '+p.city : ''), idx);
            }
        }

        async function lookupHittaForPopup(address, idx){
            try {
                let data = getHittaCache(address);
                if(!data) {
                    const res = await fetch('/api/hitta-lookup.php?address='+encodeURIComponent(address));
                    data = await res.json();
                    setHittaCache(address, data);
                }
                const el = document.getElementById('popupHitta_'+idx);
                if(!el) return;
                if(data.persons && data.persons.length > 0){
                    let livingAreaStr = null;
                    // Hämta fastighetsinfo från första personen (gäller hela fastigheten)
                    const propDetails = [];
                    const fp = data.persons[0];
                    if(fp.livingArea) { propDetails.push(fp.livingArea); livingAreaStr = fp.livingArea; }
                    if(fp.household) propDetails.push(fp.household);
                    el.innerHTML = '<div style="padding:6px 8px;background:#f0fdf4;border-radius:6px;border:1px solid #dcfce7">'
                        +(propDetails.length ? '<div style="font-size:11px;color:#64748b;margin-bottom:4px;padding-bottom:4px;border-bottom:1px solid #dcfce7">'+propDetails.join(' · ')+'</div>' : '')
                        +'<div style="font-size:10px;font-weight:600;color:#10b981;margin-bottom:2px">BOENDE</div>'
                        + data.persons.map(n => {
                            let info = '<div style="font-size:13px;font-weight:600;color:#166534">'+n.name+'</div>';
                            let details = [];
                            if(n.age) details.push(n.age + ' år');
                            if(details.length) info += '<div style="font-size:11px;color:#64748b;margin-top:1px">'+details.join(' · ')+'</div>';
                            if(n.phone && n.phone.length) info += '<div style="font-size:11px;color:#0284c7;margin-top:1px">'+n.phone.join(', ')+'</div>';
                            return info;
                        }).join('<div style="border-top:1px solid #dcfce7;margin:4px 0"></div>')
                        +'</div>';
                    // Visa kort energiuppskattning i popup om vi har boyta + soldata
                    if(livingAreaStr && faltProspects[idx]) {
                        const p = faltProspects[idx];
                        const energyEst = estimateEnergyConsumption(livingAreaStr);
                        if(energyEst && p.yearlyKwh) {
                            const coverage = Math.min(100, Math.round((p.yearlyKwh / energyEst.withElectricHeat) * 100));
                            const selfUse = Math.min(p.yearlyKwh * SOLAR_SELF_USE, energyEst.withElectricHeat);
                            const sell = p.yearlyKwh - selfUse;
                            const saving = Math.round(selfUse * ELECTRICITY_PRICE + sell * SOLAR_SELL_PRICE);
                            el.innerHTML += '<div style="margin-top:4px;padding:5px 8px;background:#fef9c3;border-radius:6px;border:1px solid #fde68a;font-size:11px">'
                                +'<span style="color:#92400e;font-weight:600">Energi:</span> '
                                +'<span style="color:#78350f">'+energyEst.withElectricHeat.toLocaleString('sv-SE')+' kWh/år</span>'
                                +' · <span style="color:#166534;font-weight:600">Sol täcker '+coverage+'%</span>'
                                +' · <span style="color:#059669;font-weight:700">Spar '+saving.toLocaleString('sv-SE')+' kr/år</span>'
                                +'</div>';
                        } else if(energyEst) {
                            el.innerHTML += '<div style="margin-top:4px;padding:5px 8px;background:#fef9c3;border-radius:6px;border:1px solid #fde68a;font-size:11px">'
                                +'<span style="color:#92400e;font-weight:600">Uppsk. förbrukning:</span> '
                                +'<span style="color:#78350f">'+energyEst.withElectricHeat.toLocaleString('sv-SE')+' kWh/år (elvärme)</span>'
                                +'</div>';
                        }
                    }
                } else {
                    el.textContent = 'Inga boende hittade';
                }
            } catch(e){
                const el = document.getElementById('popupHitta_'+idx);
                if(el) el.textContent = '';
            }
        }

        async function lookupHittaForPanel(address){
            try {
                let data = getHittaCache(address);
                if(!data) {
                    const res = await fetch('/api/hitta-lookup.php?address='+encodeURIComponent(address));
                    data = await res.json();
                    setHittaCache(address, data);
                }
                const el = document.getElementById('hittaResult');
                if(!el) return;
                let livingAreaStr = null;
                if(data.persons && data.persons.length > 0){
                    // Fastighetsinfo (boyta, hushållstyp) — gäller hela fastigheten
                    const fp0 = data.persons[0];
                    const propInfo = [];
                    if(fp0.livingArea) { propInfo.push(fp0.livingArea); livingAreaStr = fp0.livingArea; }
                    if(fp0.household) propInfo.push(fp0.household);
                    el.innerHTML = (propInfo.length ? '<div style="font-size:11px;color:#64748b;margin-bottom:6px;padding:4px 8px;background:#f8fafc;border-radius:6px;border:1px solid #e5e7eb">'+propInfo.join(' · ')+'</div>' : '')
                        +'<div style="font-size:12px;font-weight:600;color:#1a1a1a;margin-bottom:4px">Boende:</div>'
                        + data.persons.map(p => {
                            let html = '<div style="font-size:13px;color:#334155;padding:2px 0;font-weight:600">'+p.name+'</div>';
                            let details = [];
                            if(p.age) details.push(p.age + ' år');
                            if(details.length) html += '<div style="font-size:11px;color:#64748b;padding:0 0 4px">'+details.join(' · ')+'</div>';
                            if(p.phone && p.phone.length) html += '<div style="font-size:11px;color:#0284c7;padding:0 0 4px">'+p.phone.join(', ')+'</div>';
                            return html;
                        }).join('');
                } else {
                    el.textContent = 'Inga boende hittade på Hitta.se';
                }
                // Visa energianalys om vi har boyta
                const energyEl = document.getElementById('energyEstimate');
                if(energyEl && livingAreaStr) {
                    const energyEst = estimateEnergyConsumption(livingAreaStr);
                    if(energyEst) {
                        energyEl.innerHTML = buildEnergyEstimateHtml(energyEst, window._lastSolarKwh || 0);
                    }
                }
            } catch(e){
                const el = document.getElementById('hittaResult');
                if(el) el.textContent = '';
            }
        }

        async function lookupHitta(address, idx){
            const status = document.getElementById('ciHittaStatus');
            if(status) status.textContent = 'Söker på Hitta.se...';
            try {
                let data = getHittaCache(address);
                if(!data) {
                    const res = await fetch('/api/hitta-lookup.php?address='+encodeURIComponent(address));
                    data = await res.json();
                    setHittaCache(address, data);
                }
                if(data.persons && data.persons.length > 0){
                    const names = data.persons.map(p=>p.name);
                    if(status) status.innerHTML = '<span style="color:#10b981">Hittade '+names.length+' person'+(names.length>1?'er':'')+'</span>';
                    // Show name picker
                    const nameField = document.getElementById('ciName');
                    if(!nameField.value){
                        if(names.length === 1){
                            nameField.value = names[0];
                            faltProspects[idx].hittaNames = names;
                        } else {
                            // Multiple - show picker
                            nameField.value = names[0];
                            faltProspects[idx].hittaNames = names;
                        }
                    }
                    // Show property info + name buttons
                    if(status && data.persons.length > 0){
                        const fp0 = data.persons[0];
                        const propInfo = [];
                        if(fp0.livingArea) propInfo.push(fp0.livingArea);
                        if(fp0.household) propInfo.push(fp0.household);
                        status.innerHTML = (propInfo.length ? '<div style="font-size:11px;color:#64748b;margin-top:4px;padding:4px 8px;background:#f8fafc;border-radius:6px;border:1px solid #e5e7eb">'+propInfo.join(' · ')+'</div>' : '')
                            +'<div style="margin-top:6px;display:flex;flex-direction:column;gap:4px">'
                            + data.persons.map(p => {
                                const ageStr = p.age ? '<span style="font-size:10px;color:#64748b;margin-left:6px">'+p.age+' år</span>' : '';
                                return '<button onclick="document.getElementById(\'ciName\').value=\''+p.name.replace(/'/g,"\\'")+'\';this.style.background=\'#dcfce7\'" style="padding:5px 10px;border:1px solid #e5e7eb;border-radius:6px;font-size:12px;cursor:pointer;background:#fff;font-family:inherit;color:#1a1a1a;text-align:left">'+p.name+ageStr+'</button>';
                            }).join('')
                            + '</div>';
                    }
                } else {
                    if(status) status.textContent = 'Inga namn hittade';
                }
            } catch(e){
                if(status) status.textContent = '';
            }
        }

        function closeCheckin(){
            document.getElementById('checkinModal').style.display = 'none';
        }

        function checkinResult(status){
            checkinStatus = status;
            document.getElementById('checkinStep0').style.display = 'none';
            document.getElementById('checkinStep1').style.display = 'none';
            document.getElementById('checkinStep2').style.display = 'none';
            document.getElementById('checkinStep2b').style.display = 'none';
            document.getElementById('checkinStep2c').style.display = 'none';
            if(status === 'interested'){
                document.getElementById('checkinStep2').style.display = 'block';
                document.getElementById('ciName').focus();
            } else if(status === 'callback'){
                document.getElementById('checkinStep2c').style.display = 'block';
                // Set default date to tomorrow
                const tomorrow = new Date(Date.now() + 86400000);
                document.getElementById('ciCallbackDate').value = tomorrow.toISOString().slice(0, 10);
            } else {
                document.getElementById('checkinStep2b').style.display = 'block';
            }
        }

        async function checkinDirectToKalkyl(){
            const p = faltProspects[checkinIdx];
            p.status = 'interested';
            p.product = 'Solceller';
            p.checkinTime = new Date().toISOString();

            // Fetch Hitta data if not already cached
            const address = p.addr + (p.city ? ', '+p.city : '');
            try {
                let data = getHittaCache(address);
                if(!data){
                    const res = await fetch('/api/hitta-lookup.php?address='+encodeURIComponent(address));
                    data = await res.json();
                    setHittaCache(address, data);
                }
                if(data.persons && data.persons.length > 0){
                    p.hittaNames = data.persons.map(pp=>pp.name);
                    p.hittaPersons = data.persons;
                    if(!p.kundNamn) p.kundNamn = data.persons[0].name || '';
                }
            } catch(e){}

            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
            closeCheckin();
            renderFaltMarkers();
            renderFaltList();
            updateFaltStats();
            renderLeadsTable();

            // Gå direkt till konfiguratorn (utan kundinformation-modal)
            pendingKalkylCustomer = {
                prospectIdx: checkinIdx,
                name: p.kundNamn || '',
                email: p.kundEmail || '',
                phone: p.kundTel || '',
                address: address,
                ownerType: '1',
                maxDeduction: 50000,
                owner1: { name: p.kundNamn || '', pnr: '' },
                owner2: null,
                product: 'Solceller',
                solarData: {
                    yearlyKwh: p.yearlyKwh || null,
                    maxPanels: p.maxPanels || null,
                    roofArea: p.roofArea || null,
                    solarScore: p.solarScore || null
                },
                created: new Date().toISOString()
            };

            // Navigera direkt till konfiguratorvyn
            document.querySelectorAll('.nav-item').forEach(n=>n.classList.remove('active'));
            document.querySelectorAll('.page-content').forEach(p=>{p.classList.remove('active');p.style.display='';});
            const kalkylPage = document.getElementById('page-konfigurator');
            if(kalkylPage) kalkylPage.classList.add('active');
            const navItem = document.querySelector('[data-page="konfigurator"]');
            if(navItem) navItem.classList.add('active');
            showKalkylConfig();
            populateKalkylFromCustomer();
        }

        function saveCheckinLead(){
            const p = faltProspects[checkinIdx];
            p.status = 'interested';
            p.kundNamn = document.getElementById('ciName').value.trim();
            p.kundTel = document.getElementById('ciPhone').value.trim();
            p.kundEmail = document.getElementById('ciEmail').value.trim();
            p.product = document.getElementById('ciProduct').value;
            p.note = document.getElementById('ciNote').value.trim();
            p.checkinTime = new Date().toISOString();
            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
            closeCheckin();
            renderFaltMarkers();
            renderFaltList();
            updateFaltStats();
            renderLeadsTable();
            // Auto-advance: go to next unvisited
            goToNextUnvisited(checkinIdx);
        }

        function saveCheckinSimple(){
            const p = faltProspects[checkinIdx];
            p.status = checkinStatus;
            p.note = document.getElementById('ciNoteSimple').value.trim();
            p.checkinTime = new Date().toISOString();
            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
            closeCheckin();
            renderFaltMarkers();
            renderFaltList();
            updateFaltStats();
            renderLeadsTable();
            goToNextUnvisited(checkinIdx);
        }

        async function saveCheckinCallback(){
            const p = faltProspects[checkinIdx];
            const date = document.getElementById('ciCallbackDate').value;
            const time = document.getElementById('ciCallbackTime').value || '10:00';
            const note = document.getElementById('ciCallbackNote').value.trim();

            if(!date){ alert('Välj ett datum för återbesöket'); return; }

            p.status = 'callback';
            p.note = note;
            p.callbackDate = date;
            p.callbackTime = time;
            p.checkinTime = new Date().toISOString();
            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));

            // Create Google Calendar event if logged in
            if(gAccessToken){
                const startTime = date + 'T' + time + ':00';
                const endHour = parseInt(time.split(':')[0]) + 1;
                const endTime = date + 'T' + String(endHour).padStart(2,'0') + ':' + time.split(':')[1] + ':00';
                const addr = p.addr + (p.city ? ', ' + p.city : '');
                await createCalendarEvent(
                    'Återbesök: ' + addr,
                    (p.kundNamn ? 'Kund: ' + p.kundNamn + '\n' : '') + (note ? 'Notering: ' + note : ''),
                    addr,
                    startTime, endTime
                );
            } else {
                // Fallback: open Google Calendar URL
                const startDt = date.replace(/-/g,'') + 'T' + time.replace(':','') + '00';
                const endH = parseInt(time.split(':')[0]) + 1;
                const endDt = date.replace(/-/g,'') + 'T' + String(endH).padStart(2,'0') + time.slice(2).replace(':','') + '00';
                const addr = p.addr + (p.city ? ', ' + p.city : '');
                const gcUrl = 'https://calendar.google.com/calendar/event?action=TEMPLATE'
                    + '&text=' + encodeURIComponent('Återbesök: ' + addr)
                    + '&dates=' + startDt + '/' + endDt
                    + '&location=' + encodeURIComponent(addr)
                    + '&details=' + encodeURIComponent(note || 'Planerat återbesök');
                window.open(gcUrl, '_blank');
            }

            closeCheckin();
            renderFaltMarkers();
            renderFaltList();
            updateFaltStats();
            renderLeadsTable();
            goToNextUnvisited(checkinIdx);
        }

        function goToNextUnvisited(afterIdx){
            // Find next unvisited prospect after current
            for(let j = afterIdx+1; j < faltProspects.length; j++){
                if(faltProspects[j].status === 'unvisited'){
                    focusProspect(j);
                    return;
                }
            }
            // Wrap around
            for(let j = 0; j < afterIdx; j++){
                if(faltProspects[j].status === 'unvisited'){
                    focusProspect(j);
                    return;
                }
            }
        }

        function updateFaltStats(){
            const total=faltProspects.length;
            const visited=faltProspects.filter(p=>p.status!=='unvisited').length;
            const interested=faltProspects.filter(p=>p.status==='interested'||p.status==='kalkyl'||p.status==='offert').length;
            const notInt=faltProspects.filter(p=>p.status==='not_interested').length;
            const notHome=faltProspects.filter(p=>p.status==='not_home').length;
            document.getElementById('faltTotal').textContent=total;
            document.getElementById('faltVisited').textContent=visited;
            document.getElementById('faltVisitedPct').textContent=total?Math.round(visited/total*100)+'%':'0%';
            document.getElementById('faltInterested').textContent=interested;
            document.getElementById('faltNotInt').textContent=notInt;
            document.getElementById('faltNotHome').textContent=notHome;
        }

        function renderFaltList(){
            const list=document.getElementById('faltList');
            if(!list) return;

            // Update filter button styles
            ['All','Plan','Lead'].forEach(f=>{
                const btn=document.getElementById('flt'+f);
                if(!btn) return;
                const active = (f==='All'&&faltListFilter==='all')||(f==='Plan'&&faltListFilter==='unvisited')||(f==='Lead'&&faltListFilter==='interested');
                btn.style.background=active?'#024550':'#fff';
                btn.style.color=active?'#fff':'#64748b';
            });

            if(faltProspects.length===0){
                list.innerHTML='<div style="padding:20px;text-align:center;color:#94a3b8;font-size:13px">Klicka på hus på kartan och tryck "+ Lägg till" för att bygga din rutt.</div>';
                document.getElementById('faltListCount').textContent='(0)';
                return;
            }

            let filtered = faltProspects;
            if(faltListFilter==='unvisited') filtered = faltProspects.filter(p=>p.status==='unvisited');
            else if(faltListFilter==='interested') filtered = faltProspects.filter(p=>p.status==='interested'||p.status==='kalkyl'||p.status==='offert');

            list.innerHTML=filtered.map((p,fi)=>{
                const color=faltStatusColors[p.status];
                const idx=faltProspects.findIndex(x=>x.id===p.id);
                const routeNum = fi+1;
                const isActive = idx === faltActiveIdx;
                const photoCount = (p.photos||[]).length;
                let extra = '';
                if(p.kundNamn) extra = '<div style="font-size:11px;color:#10b981;font-weight:600;margin-top:1px">'+p.kundNamn+(p.product?' • '+p.product:'')+'</div>';
                if(p.solarScore) extra += '<div style="font-size:10px;margin-top:1px">'+solarScoreLabel(p.solarScore)+' <span style="color:#64748b">'+(p.yearlyKwh?p.yearlyKwh.toLocaleString('sv-SE')+' kWh/år':'')+'</span></div>';
                else if(p.maxPanels) extra += '<div style="font-size:10px;color:#64748b;margin-top:1px">'+p.maxPanels+' paneler • '+(p.yearlyKwh?p.yearlyKwh.toLocaleString('sv-SE'):'-')+' kWh</div>';
                if(p.callbackDate) extra += '<div style="font-size:10px;color:#3b82f6;margin-top:1px">Återbesök: '+p.callbackDate+' '+(p.callbackTime||'')+'</div>';
                // Photo thumbnails
                let thumbsHtml = '';
                if(photoCount > 0){
                    thumbsHtml = '<div style="display:flex;gap:3px;margin-top:3px;overflow:hidden">'
                        + (p.photos||[]).slice(0,3).map((ph,pi) =>
                            '<img src="'+ph.thumb+'" onclick="event.stopPropagation();viewProspectPhotos('+idx+')" style="width:28px;height:28px;border-radius:4px;object-fit:cover;cursor:pointer;border:1px solid #e5e7eb">'
                        ).join('')
                        + (photoCount>3?'<div style="width:28px;height:28px;border-radius:4px;background:#f1f5f9;display:flex;align-items:center;justify-content:center;font-size:9px;color:#64748b;font-weight:600;cursor:pointer" onclick="event.stopPropagation();viewProspectPhotos('+idx+')">+'+( photoCount-3)+'</div>':'')
                        + '</div>';
                }
                return '<div class="falt-item'+(isActive?' falt-item-active':'')+'" data-idx="'+idx+'" draggable="true" ondragstart="faltDragStart(event,'+idx+')" ondragover="faltDragOver(event)" ondrop="faltDrop(event,'+idx+')" ondragend="faltDragEnd(event)" style="gap:6px;flex-wrap:wrap;cursor:grab'+(isActive?';background:#f0f9ff;border-left:3px solid #024550':'')+'" onclick="focusProspect('+idx+')">'
                    +'<div style="display:flex;flex-direction:column;align-items:center;gap:2px;flex-shrink:0;cursor:grab" title="Dra för att ändra ordning">'
                    +'<svg viewBox="0 0 24 24" style="width:12px;height:12px;fill:#cbd5e1;stroke:none"><circle cx="8" cy="4" r="2"/><circle cx="16" cy="4" r="2"/><circle cx="8" cy="12" r="2"/><circle cx="16" cy="12" r="2"/><circle cx="8" cy="20" r="2"/><circle cx="16" cy="20" r="2"/></svg>'
                    +'<div style="width:22px;height:22px;border-radius:50%;background:'+color+';color:#fff;font-size:10px;font-weight:700;display:flex;align-items:center;justify-content:center">'+routeNum+'</div>'
                    +'</div>'
                    +'<div class="falt-item-info" style="flex:1;min-width:0">'
                    +'<div class="falt-item-addr" style="font-size:12px">'+p.addr+'</div>'
                    +extra
                    +(p.note?'<div style="font-size:10px;color:#94a3b8;font-style:italic;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">'+p.note+'</div>':'')
                    +thumbsHtml
                    +'</div>'
                    +'<div style="display:flex;flex-direction:column;align-items:flex-end;gap:4px;flex-shrink:0">'
                    +'<div style="display:flex;gap:3px">'
                    +'<button onclick="event.stopPropagation();captureProspectPhoto('+idx+')" style="background:#f0f9ff;border:1px solid #bfdbfe;border-radius:6px;cursor:pointer;padding:3px 6px;display:flex;align-items:center;gap:3px;font-size:10px;font-weight:600;color:#1e40af;font-family:inherit" title="Ta bild / ladda upp"><svg viewBox="0 0 24 24" style="width:13px;height:13px;fill:none;stroke:currentColor;stroke-width:2"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>Bild</button>'
                    +'<button onclick="event.stopPropagation();openStreetView('+idx+')" style="background:#f5f3ff;border:1px solid #ddd6fe;border-radius:6px;cursor:pointer;padding:3px 6px;display:flex;align-items:center;gap:3px;font-size:10px;font-weight:600;color:#6d28d9;font-family:inherit" title="Street View"><svg viewBox="0 0 24 24" style="width:13px;height:13px;fill:none;stroke:currentColor;stroke-width:2"><circle cx="12" cy="5" r="3"/><path d="M12 8v4"/><path d="M8 20l4-8 4 8"/></svg>SV</button>'
                    +(photoCount?'<button onclick="event.stopPropagation();viewProspectPhotos('+idx+')" style="background:#ecfdf5;border:1px solid #bbf7d0;border-radius:6px;cursor:pointer;padding:3px 6px;display:flex;align-items:center;gap:2px;font-size:10px;font-weight:600;color:#166534;font-family:inherit"><svg viewBox="0 0 24 24" style="width:12px;height:12px;fill:none;stroke:currentColor;stroke-width:2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>'+photoCount+'</button>':'')
                    +'</div>'
                    +'<div style="display:flex;align-items:center;gap:4px">'
                    +'<div style="padding:1px 6px;border-radius:5px;font-size:9px;font-weight:600;background:'+color+'15;color:'+color+';white-space:nowrap">'+faltStatusLabels[p.status]+'</div>'
                    +'<button onclick="event.stopPropagation();removeProspect('+idx+')" style="background:none;border:none;cursor:pointer;color:#cbd5e1;font-size:13px;padding:0;line-height:1" title="Ta bort">&times;</button>'
                    +'</div>'
                    +'</div></div>';
            }).join('');
            document.getElementById('faltListCount').textContent='('+faltProspects.length+')';
        }

        // Drag & drop för ruttordning
        let faltDragIdx = null;
        function faltDragStart(e, idx){
            faltDragIdx = idx;
            e.dataTransfer.effectAllowed = 'move';
            e.target.closest('.falt-item').style.opacity = '0.4';
        }
        function faltDragOver(e){
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';
            const item = e.target.closest('.falt-item');
            if(item) item.style.borderTop = '2px solid #024550';
        }
        function faltDrop(e, targetIdx){
            e.preventDefault();
            const item = e.target.closest('.falt-item');
            if(item) item.style.borderTop = '';
            if(faltDragIdx === null || faltDragIdx === targetIdx) return;
            const moved = faltProspects.splice(faltDragIdx, 1)[0];
            faltProspects.splice(targetIdx > faltDragIdx ? targetIdx - 1 : targetIdx, 0, moved);
            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
            faltDragIdx = null;
            renderFaltList();
            renderFaltMarkers();
            renderLeadsTable();
        }
        function faltDragEnd(e){
            faltDragIdx = null;
            document.querySelectorAll('.falt-item').forEach(el => {
                el.style.opacity = '';
                el.style.borderTop = '';
            });
        }

        function focusProspect(idx){
            const p = faltProspects[idx];
            if(!p || !gMap) return;
            faltActiveIdx = idx;
            gMap.setCenter({lat:p.lat, lng:p.lng});
            gMap.setZoom(19);
            if(faltGMarkers[idx]) google.maps.event.trigger(faltGMarkers[idx], 'click');
            renderFaltList();
            // Scrolla till aktivt prospekt i listan
            setTimeout(() => {
                const activeEl = document.querySelector('.falt-item-active');
                if(activeEl) activeEl.scrollIntoView({block:'nearest',behavior:'smooth'});
            }, 50);
        }

        function removeProspect(idx){
            faltProspects.splice(idx, 1);
            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
            renderFaltMarkers();
            renderFaltList();
            updateFaltStats();
        }

        // === PROSPECT PHOTOS ===
        function captureProspectPhoto(idx){
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'image/*';
            input.capture = 'environment'; // Bakre kameran på mobil
            input.multiple = true;
            input.onchange = async (e) => {
                const files = Array.from(e.target.files);
                if(!files.length) return;
                const p = faltProspects[idx];
                if(!p.photos) p.photos = [];
                for(const file of files){
                    try {
                        const dataUrl = await readFileAsDataUrl(file);
                        const thumb = await resizeImage(dataUrl, 200);
                        // Ladda upp original till servern
                        let fullUrl = dataUrl;
                        try {
                            const upResp = await fetch('/api/upload-photo.php', {
                                method:'POST', headers:{'Content-Type':'application/json'},
                                body: JSON.stringify({ image: dataUrl, name: file.name })
                            });
                            const upData = await upResp.json();
                            if(upData.success && upData.url) fullUrl = upData.url;
                        } catch(ue){ console.warn('Upload failed, keeping base64:', ue); }
                        p.photos.push({
                            full: fullUrl,
                            thumb: thumb,
                            name: file.name,
                            date: new Date().toISOString(),
                            type: 'camera'
                        });
                    } catch(err){ console.error('Photo error:', err); }
                }
                localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
                renderFaltList();
            };
            input.click();
        }

        function readFileAsDataUrl(file){
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => resolve(reader.result);
                reader.onerror = reject;
                reader.readAsDataURL(file);
            });
        }

        function resizeImage(dataUrl, maxSize){
            return new Promise((resolve) => {
                const img = new Image();
                img.onload = () => {
                    const canvas = document.createElement('canvas');
                    const scale = Math.min(maxSize/img.width, maxSize/img.height, 1);
                    canvas.width = img.width * scale;
                    canvas.height = img.height * scale;
                    canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
                    resolve(canvas.toDataURL('image/jpeg', 0.7));
                };
                img.src = dataUrl;
            });
        }

        let svPanorama = null;
        let svProspectIdx = null;
        let svPhotoCount = 0;
        let svRouteMode = false;

        function startStreetViewRoute(){
            if(faltProspects.length === 0){ alert('Lägg till prospekt först'); return; }
            svRouteMode = true;
            openStreetView(0);
        }

        function openStreetView(idx){
            const p = faltProspects[idx];
            if(!p.photos) p.photos = [];
            svProspectIdx = idx;
            svPhotoCount = 0;

            // Skapa modal med inbäddad Street View
            let modal = document.getElementById('svModal');
            if(modal) modal.remove();
            modal = document.createElement('div');
            modal.id = 'svModal';
            modal.style.cssText = 'position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,.9);display:flex;flex-direction:column';

            // Rutt-navigation
            const total = faltProspects.length;
            const num = idx + 1;
            let routeNav = '';
            if(svRouteMode || total > 1){
                routeNav = '<div style="display:flex;align-items:center;gap:6px">'
                    +'<button id="svPrevProspect" onclick="svGoProspect(-1)" style="width:32px;height:32px;background:rgba(255,255,255,.1);border:none;color:#fff;border-radius:6px;font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center'+(idx===0?';opacity:.3;pointer-events:none':'')+'">&#8249;</button>'
                    +'<span style="color:#fff;font-size:13px;font-weight:700;min-width:40px;text-align:center">'+num+'/'+total+'</span>'
                    +'<button id="svNextProspect" onclick="svGoProspect(1)" style="width:32px;height:32px;background:rgba(255,255,255,.1);border:none;color:#fff;border-radius:6px;font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center'+(idx>=total-1?';opacity:.3;pointer-events:none':'')+'">&#8250;</button>'
                    +'</div>';
            }

            modal.innerHTML = '<div style="display:flex;align-items:center;justify-content:space-between;padding:10px 16px;background:#1e293b;flex-shrink:0;gap:8px;flex-wrap:wrap">'
                +'<div style="display:flex;align-items:center;gap:10px;min-width:0;flex:1">'
                +routeNav
                +'<div style="min-width:0;flex:1"><div style="color:#fff;font-size:14px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">'+p.addr+'</div>'
                +'<div style="color:#94a3b8;font-size:11px">'+(p.kundNamn||'')+(p.photos.length?' — '+p.photos.length+' bilder':'')+'</div>'
                +'<div id="svLookingAt" style="display:none;margin-top:4px"></div>'
                +'</div>'
                +'</div>'
                +'<div style="display:flex;align-items:center;gap:6px">'
                +'<button onclick="svRemoveCurrentProspect()" style="padding:8px 14px;background:rgba(239,68,68,.2);color:#fca5a5;border:1px solid rgba(239,68,68,.3);border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;display:flex;align-items:center;gap:5px"><svg viewBox="0 0 24 24" style="width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>Ta bort</button>'
                +'<span id="svCaptureCount" style="color:#94a3b8;font-size:12px"></span>'
                +'<button id="svCaptureBtn" onclick="captureStreetViewImage()" style="padding:8px 16px;background:#3b82f6;color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;font-family:inherit;display:flex;align-items:center;gap:6px;transition:all .15s"><svg viewBox="0 0 24 24" style="width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:2"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>Ta bild</button>'
                +'<button onclick="closeStreetViewModal()" style="background:rgba(255,255,255,.1);border:none;color:#fff;width:36px;height:36px;border-radius:8px;font-size:20px;cursor:pointer;display:flex;align-items:center;justify-content:center">&times;</button>'
                +'</div></div>'
                +'<div id="svPanoContainer" style="flex:1;position:relative"></div>'
                +'<div id="svThumbs" style="display:flex;gap:6px;padding:10px 16px;background:#1e293b;overflow-x:auto;flex-shrink:0;min-height:56px;align-items:center"></div>';

            document.body.appendChild(modal);

            // Initiera Street View Panorama
            const panoEl = document.getElementById('svPanoContainer');
            svPanorama = new google.maps.StreetViewPanorama(panoEl, {
                position: {lat: p.lat, lng: p.lng},
                pov: {heading: 0, pitch: 10},
                zoom: 1,
                addressControl: false,
                fullscreenControl: false,
                motionTracking: false,
                motionTrackingControl: false,
                linksControl: true,
                panControl: true,
                zoomControl: true,
                enableCloseButton: false
            });

            // Lyssna på position-ändringar (navigering i SV)
            let svGeoTimer = null;
            svPanorama.addListener('position_changed', function(){
                clearTimeout(svGeoTimer);
                svGeoTimer = setTimeout(() => {
                    const pos = svPanorama.getPosition();
                    if(!pos) return;
                    const pPos = faltProspects[svProspectIdx];
                    const dist = Math.sqrt(Math.pow(pos.lat()-pPos.lat,2)+Math.pow(pos.lng()-pPos.lng,2)) * 111000;
                    // Om vi rört oss >30m från prospektet, reverse geocode
                    if(dist > 30){
                        svReverseGeocode(pos.lat(), pos.lng());
                    } else {
                        const el = document.getElementById('svLookingAt');
                        if(el) el.style.display = 'none';
                    }
                }, 800);
            });

            // Kolla om Street View finns
            const svService = new google.maps.StreetViewService();
            svService.getPanorama({location: {lat: p.lat, lng: p.lng}, radius: 100}, function(data, status){
                if(status !== 'OK'){
                    panoEl.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#94a3b8;font-size:16px">Ingen Street View — <button onclick="svGoProspect(1)" style="margin-left:8px;padding:6px 14px;background:#3b82f6;color:#fff;border:none;border-radius:8px;cursor:pointer;font-family:inherit;font-size:14px">Nästa</button></div>';
                    document.getElementById('svCaptureBtn').disabled = true;
                    document.getElementById('svCaptureBtn').style.opacity = '0.4';
                }
            });

            updateSvThumbs();
        }

        async function captureStreetViewImage(){
            if(!svPanorama || svProspectIdx === null) return;
            const btn = document.getElementById('svCaptureBtn');
            const origHtml = btn.innerHTML;
            btn.innerHTML = '<svg viewBox="0 0 24 24" style="width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:2;animation:spin 1s linear infinite"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg> Sparar...';
            btn.disabled = true;

            try {
                const pov = svPanorama.getPov();
                const pos = svPanorama.getPosition();
                const heading = Math.round(pov.heading * 10) / 10;
                const pitch = Math.round(pov.pitch * 10) / 10;

                // Hämta bild via Static Street View API (pålitligt)
                const fov = Math.round(180 / Math.pow(2, svPanorama.getZoom()));
                const panoId = svPanorama.getPano();
                let svUrl = 'https://maps.googleapis.com/maps/api/streetview?size=640x360';
                if(panoId) svUrl += '&pano='+encodeURIComponent(panoId);
                else svUrl += '&location='+pos.lat()+','+pos.lng();
                svUrl += '&heading='+heading+'&pitch='+pitch+'&fov='+fov+'&key='+GOOGLE_MAPS_KEY;

                // Ladda bilden via img-element (undviker CORS-problem med fetch)
                const dataUrl = await new Promise((resolve, reject) => {
                    const img = new Image();
                    img.crossOrigin = 'anonymous';
                    img.onload = function(){
                        const cv = document.createElement('canvas');
                        cv.width = this.naturalWidth;
                        cv.height = this.naturalHeight;
                        cv.getContext('2d').drawImage(this, 0, 0);
                        try { resolve(cv.toDataURL('image/png')); }
                        catch(e){ resolve(cv.toDataURL('image/jpeg', 0.95)); }
                    };
                    img.onerror = () => {
                        // Sista fallback: direkt fetch
                        fetch(svUrl).then(r => r.blob()).then(b => {
                            if(b.size < 5000) reject(new Error('Ingen bild'));
                            else {
                                const reader = new FileReader();
                                reader.onload = () => resolve(reader.result);
                                reader.onerror = reject;
                                reader.readAsDataURL(b);
                            }
                        }).catch(reject);
                    };
                    img.src = svUrl;
                });

                const thumb = await resizeImage(dataUrl, 200);
                // Ladda upp original till servern — spara URL istället för megabyte base64 i localStorage
                let fullUrl = dataUrl;
                try {
                    const upResp = await fetch('/api/upload-photo.php', {
                        method:'POST', headers:{'Content-Type':'application/json'},
                        body: JSON.stringify({ image: dataUrl, name: 'sv_h'+Math.round(heading)+'_p'+Math.round(pitch) })
                    });
                    const upData = await upResp.json();
                    if(upData.success && upData.url) fullUrl = upData.url;
                } catch(ue){ console.warn('Upload failed, keeping base64:', ue); }

                const p = faltProspects[svProspectIdx];
                p.photos.push({
                    full: fullUrl,
                    thumb: thumb,
                    name: 'sv_h'+Math.round(heading)+'_p'+Math.round(pitch)+'.jpg',
                    date: new Date().toISOString(),
                    type: 'streetview',
                    heading: heading,
                    pitch: pitch
                });
                svPhotoCount++;
                localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
                renderFaltList();
                updateSvThumbs();

                // Flash-effekt
                const flash = document.createElement('div');
                flash.style.cssText = 'position:absolute;inset:0;background:#fff;z-index:10;opacity:0.8;transition:opacity .3s';
                document.getElementById('svPanoContainer').appendChild(flash);
                setTimeout(()=>flash.style.opacity='0', 50);
                setTimeout(()=>flash.remove(), 400);

            } catch(e){
                console.error('SV capture error:', e);
            } finally {
                btn.innerHTML = '<svg viewBox="0 0 24 24" style="width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:2"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg> Ta bild';
                btn.disabled = false;
            }
        }

        function updateSvThumbs(){
            const container = document.getElementById('svThumbs');
            if(!container || svProspectIdx === null) return;
            const p = faltProspects[svProspectIdx];
            const photos = (p.photos||[]).filter(ph => ph.type === 'streetview');
            const countEl = document.getElementById('svCaptureCount');
            if(countEl) countEl.textContent = photos.length > 0 ? photos.length + ' bilder tagna' : '';
            if(photos.length === 0){
                container.innerHTML = '<span style="color:#64748b;font-size:12px">Rotera vyn och klicka "Ta bild" för att spara</span>';
                return;
            }
            container.innerHTML = photos.map((ph,i) => {
                const allIdx = (p.photos||[]).indexOf(ph);
                return '<div style="position:relative;flex-shrink:0">'
                    +'<img src="'+ph.thumb+'" style="width:50px;height:38px;border-radius:6px;object-fit:cover;border:2px solid #334155;cursor:pointer" onclick="event.stopPropagation();viewProspectPhotos('+svProspectIdx+')">'
                    +'<button onclick="event.stopPropagation();deleteProspectPhoto('+svProspectIdx+','+allIdx+');updateSvThumbs()" style="position:absolute;top:-4px;right:-4px;width:16px;height:16px;background:#ef4444;color:#fff;border:none;border-radius:50%;font-size:10px;cursor:pointer;display:flex;align-items:center;justify-content:center;line-height:1">&times;</button>'
                    +'</div>';
            }).join('');
        }

        function svGoProspect(dir){
            const newIdx = svProspectIdx + dir;
            if(newIdx < 0 || newIdx >= faltProspects.length) return;
            openStreetView(newIdx);
        }

        let svSpottedAddr = null;
        let svSpottedLat = null;
        let svSpottedLng = null;

        function svReverseGeocode(lat, lng){
            const geocoder = new google.maps.Geocoder();
            geocoder.geocode({location:{lat,lng}}, function(results, status){
                const el = document.getElementById('svLookingAt');
                if(!el) return;
                if(status === 'OK' && results[0]){
                    const addr = results[0].formatted_address.replace(/, Sverige$/, '').replace(/, Sweden$/, '');
                    // Kolla om denna adress redan finns som prospekt
                    const existIdx = faltProspects.findIndex(pp => {
                        if(!pp.addr) return false;
                        // Kolla adress-match eller nära koordinater (<25m)
                        const addrMatch = addr.toLowerCase().includes(pp.addr.split(',')[0].toLowerCase());
                        const coordDist = Math.sqrt(Math.pow(lat-pp.lat,2)+Math.pow(lng-pp.lng,2)) * 111000;
                        return addrMatch || coordDist < 25;
                    });
                    const exists = existIdx >= 0;
                    const existNum = exists ? existIdx + 1 : 0;
                    svSpottedAddr = addr;
                    svSpottedLat = lat;
                    svSpottedLng = lng;
                    el.style.display = 'flex';
                    el.style.cssText = 'display:flex;align-items:center;gap:8px;margin-top:4px;flex-wrap:wrap';
                    el.innerHTML = '<span style="color:#fbbf24;font-size:12px;font-weight:600">('+addr+')</span>'
                        +(exists
                            ? '<span style="padding:2px 8px;background:rgba(16,185,129,.15);border:1px solid rgba(16,185,129,.3);border-radius:6px;color:#10b981;font-size:11px;font-weight:600">Finns i rutt (#'+existNum+')</span>'
                            : '<button onclick="svAddSpottedProspect()" style="padding:3px 10px;background:#10b981;color:#fff;border:none;border-radius:6px;font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;display:flex;align-items:center;gap:4px"><svg viewBox="0 0 24 24" style="width:12px;height:12px;fill:none;stroke:currentColor;stroke-width:2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>Lägg till</button>');
                } else {
                    el.style.display = 'none';
                }
            });
        }

        function svAddSpottedProspect(){
            if(!svSpottedAddr) return;
            // Extrahera gatuadress och stad
            const parts = svSpottedAddr.split(',').map(s=>s.trim());
            const addr = parts[0] || svSpottedAddr;
            const city = parts[1] || '';
            const newP = {
                id: Date.now(),
                addr: addr,
                city: city,
                lat: svSpottedLat,
                lng: svSpottedLng,
                status: 'unvisited',
                created: new Date().toISOString(),
                photos: []
            };
            faltProspects.push(newP);
            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
            renderFaltMarkers();
            renderFaltList();
            updateFaltStats();
            // Visa bekräftelse
            const el = document.getElementById('svLookingAt');
            if(el) el.innerHTML = '<span style="color:#10b981;font-size:12px;font-weight:600">Tillagd som prospekt #'+faltProspects.length+'</span>';
            svSpottedAddr = null;
        }

        function svRemoveCurrentProspect(){
            if(svProspectIdx === null) return;
            const p = faltProspects[svProspectIdx];
            if(!p) return;
            faltProspects.splice(svProspectIdx, 1);
            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
            renderFaltMarkers();
            renderFaltList();
            updateFaltStats();
            renderLeadsTable();
            // Gå till nästa prospekt eller stäng
            if(faltProspects.length === 0){
                closeStreetViewModal();
                return;
            }
            const nextIdx = svProspectIdx >= faltProspects.length ? faltProspects.length - 1 : svProspectIdx;
            openStreetView(nextIdx);
        }

        function closeStreetViewModal(){
            const modal = document.getElementById('svModal');
            if(modal) modal.remove();
            svPanorama = null;
            svProspectIdx = null;
            svRouteMode = false;
        }

        function blobToDataUrl(blob){
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => resolve(reader.result);
                reader.onerror = reject;
                reader.readAsDataURL(blob);
            });
        }

        function viewProspectPhotos(idx){
            const p = faltProspects[idx];
            if(!p.photos || p.photos.length === 0) return;
            const modal = document.createElement('div');
            modal.id = 'photoViewerModal';
            modal.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.9);z-index:9999;display:flex;flex-direction:column';
            modal.onclick = e => { if(e.target === modal) modal.remove(); };

            let currentPhoto = 0;
            const render = () => {
                const ph = p.photos[currentPhoto];
                modal.innerHTML =
                    // Topbar
                    '<div style="display:flex;align-items:center;justify-content:space-between;padding:12px 20px;flex-shrink:0">'
                    +'<button onclick="document.getElementById(\'photoViewerModal\').remove()" style="padding:8px 16px;background:rgba(255,255,255,.1);color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;display:flex;align-items:center;gap:6px"><svg viewBox="0 0 24 24" style="width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:2"><path d="M19 12H5"/><path d="M12 19l-7-7 7-7"/></svg> Tillbaka</button>'
                    +'<span style="color:#fff;font-size:13px;font-weight:600">'+(currentPhoto+1)+' / '+p.photos.length
                    +(ph.type==='streetview'?' — Street View':' — Foto')+'</span>'
                    +'<button onclick="event.stopPropagation();deleteProspectPhoto('+idx+','+currentPhoto+')" style="padding:8px 16px;background:rgba(220,38,38,.8);color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit">Ta bort</button>'
                    +'</div>'
                    // Bild
                    +'<div style="flex:1;display:flex;align-items:center;justify-content:center;padding:0 20px;position:relative;min-height:0">'
                    +(p.photos.length>1?'<button onclick="event.stopPropagation()" id="pvPrev" style="position:absolute;left:10px;top:50%;transform:translateY(-50%);width:44px;height:44px;background:rgba(255,255,255,.15);color:#fff;border:none;border-radius:50%;font-size:20px;cursor:pointer;z-index:2;display:flex;align-items:center;justify-content:center">&larr;</button>':'')
                    +'<img src="'+ph.full+'" style="max-width:100%;max-height:100%;border-radius:8px;object-fit:contain">'
                    +(p.photos.length>1?'<button onclick="event.stopPropagation()" id="pvNext" style="position:absolute;right:10px;top:50%;transform:translateY(-50%);width:44px;height:44px;background:rgba(255,255,255,.15);color:#fff;border:none;border-radius:50%;font-size:20px;cursor:pointer;z-index:2;display:flex;align-items:center;justify-content:center">&rarr;</button>':'')
                    +'</div>'
                    // Info + thumbnails
                    +'<div style="padding:10px 20px;flex-shrink:0;display:flex;align-items:center;gap:12px;overflow-x:auto">'
                    + p.photos.map((thumb,ti) =>
                        '<img src="'+thumb.thumb+'" onclick="event.stopPropagation()" data-ti="'+ti+'" style="width:48px;height:36px;border-radius:6px;object-fit:cover;cursor:pointer;border:2px solid '+(ti===currentPhoto?'#3b82f6':'rgba(255,255,255,.2)')+';flex-shrink:0">'
                    ).join('')
                    +'</div>';
                // Nav events
                if(p.photos.length>1){
                    const prev = modal.querySelector('#pvPrev');
                    const next = modal.querySelector('#pvNext');
                    if(prev) prev.onclick = (e) => { e.stopPropagation(); currentPhoto = (currentPhoto-1+p.photos.length)%p.photos.length; render(); };
                    if(next) next.onclick = (e) => { e.stopPropagation(); currentPhoto = (currentPhoto+1)%p.photos.length; render(); };
                }
                // Thumbnail click
                modal.querySelectorAll('img[data-ti]').forEach(img => {
                    img.onclick = (e) => { e.stopPropagation(); currentPhoto = parseInt(img.dataset.ti); render(); };
                });
            };
            render();
            document.body.appendChild(modal);
            // Keyboard nav
            const keyHandler = (e) => {
                if(!document.getElementById('photoViewerModal')) { document.removeEventListener('keydown', keyHandler); return; }
                if(e.key==='ArrowLeft'){ currentPhoto = (currentPhoto-1+p.photos.length)%p.photos.length; render(); }
                else if(e.key==='ArrowRight'){ currentPhoto = (currentPhoto+1)%p.photos.length; render(); }
                else if(e.key==='Escape'){ document.getElementById('photoViewerModal')?.remove(); document.removeEventListener('keydown', keyHandler); }
            };
            document.addEventListener('keydown', keyHandler);
        }

        function deleteProspectPhoto(idx, photoIdx){
            faltProspects[idx].photos.splice(photoIdx, 1);
            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
            // Close viewer and re-render
            const modals = document.querySelectorAll('div[style*="position:fixed"][style*="z-index:9999"]');
            modals.forEach(m => { if(m.id !== 'svHelper') m.remove(); });
            renderFaltList();
            if(faltProspects[idx].photos.length > 0) viewProspectPhotos(idx);
        }

        function clearAllProspects(){
            if(!confirm('Rensa alla '+faltProspects.length+' prospekt?')) return;
            faltProspects = [];
            currentRouteId = null;
            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
            renderFaltMarkers();
            renderFaltList();
            updateFaltStats();
            renderLeadsTable();
            updateRouteInfoBar();
        }

        // === ROUTE MANAGEMENT ===
        let currentRouteId = null;
        let staffList = [];

        async function loadStaffList(){
            if(staffList.length) return staffList;
            try {
                const res = await fetch('/api/staff.php');
                const data = await res.json();
                if(data.success) staffList = data.staff || [];
            } catch(e){}
            return staffList;
        }

        function updateRouteInfoBar(){
            const bar = document.getElementById('currentRouteInfo');
            if(!bar) return;
            if(currentRouteId){
                bar.style.display = 'block';
                bar.innerHTML = '<strong>Aktiv rutt #'+currentRouteId+'</strong> — Ändringar sparas automatiskt';
            } else {
                bar.style.display = 'none';
            }
        }

        async function showSaveRouteModal(){
            if(faltProspects.length === 0){
                alert('Lägg till prospekt i rutten först');
                return;
            }
            await loadStaffList();
            const currentStaff = staffList.find(s => s.email === (localStorage.getItem('userEmail')||''));
            const currentId = currentStaff ? currentStaff.id : 43; // default admin

            const modal = document.createElement('div');
            modal.id = 'routeSaveModal';
            modal.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:9999;display:flex;align-items:center;justify-content:center;padding:20px';
            modal.onclick = e => { if(e.target === modal) modal.remove(); };

            modal.innerHTML = '<div style="background:#fff;border-radius:16px;max-width:500px;width:100%;box-shadow:0 25px 60px rgba(0,0,0,.3)">'
                +'<div style="padding:20px 24px;border-bottom:1px solid #f1f5f9;display:flex;justify-content:space-between;align-items:center">'
                +'<h2 style="font-size:18px;font-weight:700;color:#1a1a1a;margin:0">'+(currentRouteId?'Uppdatera rutt':'Spara rutt')+'</h2>'
                +'<button onclick="this.closest(\'#routeSaveModal\').remove()" style="background:none;border:none;cursor:pointer;padding:4px"><svg viewBox="0 0 24 24" style="width:20px;height:20px;stroke:#94a3b8;fill:none;stroke-width:2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>'
                +'</div>'
                +'<div style="padding:24px">'
                +'<div style="margin-bottom:16px">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b;display:block;margin-bottom:6px">RUTTNAMN</label>'
                +'<input id="routeName" value="Rutt '+new Date().toLocaleDateString('sv-SE')+'" style="width:100%;padding:10px 14px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;box-sizing:border-box">'
                +'</div>'
                +'<div style="margin-bottom:16px">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b;display:block;margin-bottom:6px">DATUM</label>'
                +'<input id="routeDate" type="date" value="'+new Date().toISOString().split('T')[0]+'" style="width:100%;padding:10px 14px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;box-sizing:border-box">'
                +'</div>'
                +'<div style="margin-bottom:16px">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b;display:block;margin-bottom:6px">TILLDELA TILL</label>'
                +'<select id="routeAssignee" style="width:100%;padding:10px 14px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;box-sizing:border-box">'
                +'<option value="">Mig själv</option>'
                +staffList.filter(s=>s.active!==0).map(s => '<option value="'+s.id+'"'+(s.id==currentId?' selected':'')+'>'+s.name+'</option>').join('')
                +'</select>'
                +'</div>'
                +'<div style="margin-bottom:20px">'
                +'<label style="font-size:12px;font-weight:600;color:#64748b;display:block;margin-bottom:6px">ANTECKNINGAR</label>'
                +'<textarea id="routeNotes" rows="2" placeholder="T.ex. fokusområde, mål..." style="width:100%;padding:10px 14px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;resize:vertical;box-sizing:border-box"></textarea>'
                +'</div>'
                +'<div style="background:#f8fafc;border-radius:10px;padding:14px;margin-bottom:20px">'
                +'<div style="font-size:12px;color:#64748b;margin-bottom:4px">Rutten innehåller</div>'
                +'<div style="font-size:20px;font-weight:700;color:#1a1a1a">'+faltProspects.length+' prospekt</div>'
                +'<div style="font-size:12px;color:#64748b">'+faltProspects.filter(p=>p.status==='interested').length+' leads, '+faltProspects.filter(p=>p.status==='unvisited').length+' obesökta</div>'
                +'</div>'
                +'<button onclick="saveRoute()" style="width:100%;padding:14px;background:#024550;color:#fff;border:none;border-radius:10px;font-size:15px;font-weight:700;cursor:pointer;font-family:inherit">'+(currentRouteId?'Uppdatera rutt':'Spara rutt')+'</button>'
                +'</div></div>';

            document.body.appendChild(modal);
        }

        async function saveRoute(){
            const name = document.getElementById('routeName').value.trim();
            const date = document.getElementById('routeDate').value;
            const assignee = document.getElementById('routeAssignee').value;
            const notes = document.getElementById('routeNotes').value.trim();
            const currentStaff = staffList.find(s => s.email === (localStorage.getItem('userEmail')||''));
            const myId = currentStaff ? currentStaff.id : 43;

            const body = {
                name: name || 'Rutt ' + date,
                created_by: myId,
                assigned_to: assignee ? parseInt(assignee) : myId,
                status: 'active',
                prospects: faltProspects,
                notes: notes || null,
                route_date: date
            };
            if(currentRouteId) body.id = currentRouteId;

            try {
                const res = await fetch('/api/routes.php', {
                    method: 'POST',
                    headers: {'Content-Type':'application/json'},
                    body: JSON.stringify(body)
                });
                const data = await res.json();
                if(data.success){
                    currentRouteId = data.id || currentRouteId;
                    document.getElementById('routeSaveModal')?.remove();
                    updateRouteInfoBar();
                    const assigneeName = assignee ? (staffList.find(s=>s.id==assignee)?.name||'') : 'dig';
                    alert('Rutt sparad! '+(assignee && assignee != myId ? 'Tilldelad till '+assigneeName+'.' : ''));
                } else {
                    alert('Fel: '+(data.error||'okänt'));
                }
            } catch(e){
                alert('Fel: '+e.message);
            }
        }

        async function showLoadRouteModal(){
            const modal = document.createElement('div');
            modal.id = 'routeLoadModal';
            modal.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:9999;display:flex;align-items:center;justify-content:center;padding:20px';
            modal.onclick = e => { if(e.target === modal) modal.remove(); };

            modal.innerHTML = '<div style="background:#fff;border-radius:16px;max-width:600px;width:100%;max-height:85vh;display:flex;flex-direction:column;box-shadow:0 25px 60px rgba(0,0,0,.3)">'
                +'<div style="padding:20px 24px;border-bottom:1px solid #f1f5f9;display:flex;justify-content:space-between;align-items:center;flex-shrink:0">'
                +'<h2 style="font-size:18px;font-weight:700;color:#1a1a1a;margin:0">Sparade rutter</h2>'
                +'<button onclick="this.closest(\'#routeLoadModal\').remove()" style="background:none;border:none;cursor:pointer;padding:4px"><svg viewBox="0 0 24 24" style="width:20px;height:20px;stroke:#94a3b8;fill:none;stroke-width:2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>'
                +'</div>'
                +'<div id="routeListContent" style="padding:24px;overflow-y:auto;flex:1">'
                +'<div style="text-align:center;padding:20px;color:#94a3b8"><div class="spinner" style="display:inline-block;width:24px;height:24px;border:3px solid #e5e7eb;border-top-color:#024550;border-radius:50%;animation:bgspin .6s linear infinite"></div><p style="margin-top:8px;font-size:13px">Laddar rutter...</p></div>'
                +'</div></div>';

            document.body.appendChild(modal);

            // Fetch routes
            try {
                const res = await fetch('/api/routes.php');
                const data = await res.json();
                const container = document.getElementById('routeListContent');
                if(!data.success || !data.routes || data.routes.length === 0){
                    container.innerHTML = '<div style="text-align:center;padding:30px;color:#94a3b8"><svg viewBox="0 0 24 24" style="width:40px;height:40px;stroke:currentColor;fill:none;stroke-width:1.5;margin-bottom:8px"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg><p style="font-size:14px;font-weight:600">Inga sparade rutter</p><p style="font-size:12px">Spara din nuvarande rutt med knappen "Spara rutt"</p></div>';
                    return;
                }

                const statusColors = {draft:'#94a3b8',active:'#10b981',completed:'#3b82f6',archived:'#64748b'};
                const statusLabels = {draft:'Utkast',active:'Aktiv',completed:'Avklarad',archived:'Arkiverad'};

                container.innerHTML = data.routes.map(r => {
                    const count = r.prospect_count || 0;
                    const col = statusColors[r.status]||'#94a3b8';
                    return '<div style="border:1px solid #e5e7eb;border-radius:12px;padding:16px;margin-bottom:10px;cursor:pointer;transition:all .15s" onmouseover="this.style.borderColor=\'#3b82f6\';this.style.background=\'#f0f9ff\'" onmouseout="this.style.borderColor=\'#e5e7eb\';this.style.background=\'#fff\'">'
                        +'<div style="display:flex;justify-content:space-between;align-items:start;margin-bottom:8px">'
                        +'<div>'
                        +'<div style="font-weight:700;font-size:15px;color:#1a1a1a">'+r.name+'</div>'
                        +'<div style="font-size:12px;color:#64748b;margin-top:2px">'+(r.route_date||r.created_at?.split(' ')[0]||'')+'</div>'
                        +'</div>'
                        +'<span style="background:'+col+'20;color:'+col+';font-size:10px;font-weight:700;padding:3px 8px;border-radius:6px;text-transform:uppercase">'+(statusLabels[r.status]||r.status)+'</span>'
                        +'</div>'
                        +'<div style="display:flex;gap:16px;font-size:12px;color:#64748b;margin-bottom:10px">'
                        +'<span>'+count+' prospekt</span>'
                        +(r.assigned_to_name ? '<span>Tilldelad: <strong>'+r.assigned_to_name+'</strong></span>' : '')
                        +(r.created_by_name ? '<span>Skapad av: '+r.created_by_name+'</span>' : '')
                        +'</div>'
                        +(r.notes ? '<div style="font-size:12px;color:#64748b;margin-bottom:10px;font-style:italic">'+r.notes+'</div>' : '')
                        +'<div style="display:flex;gap:8px">'
                        +'<button onclick="loadRoute('+r.id+')" style="flex:1;padding:8px;background:#024550;color:#fff;border:none;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit">Ladda rutt</button>'
                        +'<button onclick="deleteRoute('+r.id+')" style="padding:8px 12px;background:#fee2e2;color:#dc2626;border:none;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit">Ta bort</button>'
                        +'</div>'
                        +'</div>';
                }).join('');
            } catch(e){
                document.getElementById('routeListContent').innerHTML = '<div style="padding:20px;color:#ef4444;text-align:center">Fel: '+e.message+'</div>';
            }
        }

        async function loadRoute(id){
            try {
                const res = await fetch('/api/routes.php?id='+id);
                const data = await res.json();
                if(!data.success || !data.route){
                    alert('Kunde inte ladda rutt');
                    return;
                }
                const route = data.route;
                faltProspects = route.prospects || [];
                currentRouteId = route.id;
                localStorage.setItem('faltProspects', JSON.stringify(faltProspects));

                document.getElementById('routeLoadModal')?.remove();

                renderFaltMarkers();
                renderFaltList();
                updateFaltStats();
                renderLeadsTable();
                updateRouteInfoBar();

                // Zoom to fit all prospects
                if(gMap && faltProspects.length > 0){
                    const bounds = new google.maps.LatLngBounds();
                    faltProspects.forEach(p => bounds.extend({lat:p.lat,lng:p.lng}));
                    gMap.fitBounds(bounds, 50);
                }
            } catch(e){
                alert('Fel: '+e.message);
            }
        }

        async function deleteRoute(id){
            if(!confirm('Ta bort denna sparade rutt?')) return;
            try {
                const res = await fetch('/api/routes.php?id='+id, {method:'DELETE'});
                const data = await res.json();
                if(data.success){
                    if(currentRouteId === id) { currentRouteId = null; updateRouteInfoBar(); }
                    document.getElementById('routeLoadModal')?.remove();
                    showLoadRouteModal(); // refresh list
                }
            } catch(e){ alert('Fel: '+e.message); }
        }

        /* === LEADS TABLE === */
        function renderLeadsTable(){
            const body=document.getElementById('faltKalkylBody');
            if(!body)return;
            const leads = faltProspects.filter(p=>p.status!=='unvisited');
            if(leads.length===0){
                body.innerHTML='<tr><td colspan="6" style="text-align:center;padding:30px;color:#94a3b8">Inga besök registrerade ännu. Checka in vid ett hus för att skapa leads.</td></tr>';
                document.getElementById('fkCount').textContent='(0)';
                return;
            }
            body.innerHTML=leads.map(p=>{
                const color=faltStatusColors[p.status];
                const idx = faltProspects.indexOf(p);
                const time = p.checkinTime ? new Date(p.checkinTime).toLocaleString('sv-SE',{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'}) : p.created;
                const noteIcon = p.note ? '<button onclick="editLeadNote('+idx+')" title="'+((p.note||'').replace(/"/g,'&quot;'))+'" style="background:none;border:none;cursor:pointer;padding:2px"><svg viewBox="0 0 24 24" style="width:14px;height:14px;fill:none;stroke:#3b82f6;stroke-width:2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></button>' : '<button onclick="editLeadNote('+idx+')" style="background:none;border:none;cursor:pointer;padding:2px;opacity:.3"><svg viewBox="0 0 24 24" style="width:14px;height:14px;fill:none;stroke:#94a3b8;stroke-width:2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></button>';
                const actionBtn = p.status==='interested' ? '<button class="fk-action" onclick="createKalkylFromLead('+idx+')">Kalkyl</button>'
                    : (p.status==='kalkyl'||p.status==='offert') && p.quoteId ? '<button class="fk-action" onclick="openQuoteFromList('+p.quoteId+')">Öppna</button>' : '';
                return '<tr>'
                    +'<td><span style="display:inline-block;width:7px;height:7px;border-radius:50%;background:'+color+';margin-right:4px"></span><span class="fk-badge" style="background:'+color+'15;color:'+color+';font-size:10px;padding:2px 7px">'+faltStatusLabels[p.status]+'</span></td>'
                    +'<td class="addr-cell" title="'+p.addr+(p.city?', '+p.city:'')+'">'+p.addr+'</td>'
                    +'<td>'+(p.kundNamn||'-')+'</td>'
                    +'<td>'+(p.kundTel||'-')+'</td>'
                    +'<td style="font-size:11px;color:#64748b">'+time+'</td>'
                    +'<td style="white-space:nowrap">'+actionBtn+noteIcon+'</td>'
                    +'</tr>';
            }).join('');
            document.getElementById('fkCount').textContent='('+leads.length+' st)';
        }

        function createKalkylFromLead(idx){
            const p = faltProspects[idx];
            const addr = p.addr + (p.city ? ', ' + p.city : '');

            const modal = document.createElement('div');
            modal.id = 'kalkylStep1Modal';
            modal.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:9999;display:flex;align-items:center;justify-content:center;padding:20px';
            modal.onclick = e => { if(e.target === modal) modal.remove(); };

            // Build Hitta.se persons section
            const hPersons = p.hittaPersons || [];
            let hittaHtml = '';
            if(hPersons.length > 0){
                const fp0 = hPersons[0];
                const propInfo = [];
                if(fp0.livingArea) propInfo.push(fp0.livingArea);
                if(fp0.household) propInfo.push(fp0.household);
                hittaHtml = '<div style="margin-bottom:18px;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:12px;padding:14px 16px">'
                    +(propInfo.length ? '<div style="font-size:11px;color:#64748b;margin-bottom:8px;padding:6px 10px;background:#fff;border-radius:6px;border:1px solid #e5e7eb">'+propInfo.join(' · ')+'</div>' : '')
                    +'<div style="font-size:11px;font-weight:700;color:#059669;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px">Boende (Hitta.se)</div>'
                    +'<div style="display:flex;flex-direction:column;gap:6px">'
                    + hPersons.map(hp => {
                        const ageStr = hp.age ? ' <span style="font-size:11px;color:#64748b;font-weight:400">'+hp.age+' år</span>' : '';
                        return '<button onclick="document.getElementById(\'ks1Name\').value=\''+hp.name.replace(/'/g,"\\'")+'\';document.getElementById(\'ks1OwnerName1\').value=\''+hp.name.replace(/'/g,"\\'")+'\';this.style.background=\'#dcfce7\'" style="padding:8px 12px;border:1px solid #e5e7eb;border-radius:8px;font-size:13px;cursor:pointer;background:#fff;font-family:inherit;color:#1a1a1a;text-align:left;font-weight:600;transition:background .15s"><span>'+hp.name+'</span>'+ageStr+'</button>';
                    }).join('')
                    +'</div></div>';
            }

            modal.innerHTML = '<div style="background:#fff;border-radius:16px;max-width:520px;width:100%;max-height:90vh;overflow-y:auto;box-shadow:0 25px 60px rgba(0,0,0,.3)">'
                +'<div style="padding:28px 32px">'
                +'<h2 style="font-size:22px;font-weight:800;color:#1a1a1a;margin:0 0 20px">Kundinformation</h2>'
                + hittaHtml

                // Namn
                +'<div style="margin-bottom:16px">'
                +'<label style="font-size:13px;font-weight:600;color:#334155;display:block;margin-bottom:6px">Namn <span style="color:#dc2626">*</span></label>'
                +'<input id="ks1Name" type="text" value="'+(p.kundNamn||'').replace(/"/g,'&quot;')+'" placeholder="Förnamn Efternamn" style="width:100%;padding:12px 16px;border:1.5px solid #e5e7eb;border-radius:10px;font-size:15px;font-family:inherit;box-sizing:border-box">'
                +'</div>'

                // E-post
                +'<div style="margin-bottom:16px">'
                +'<label style="font-size:13px;font-weight:600;color:#334155;display:block;margin-bottom:6px">E-post <span style="color:#dc2626">*</span></label>'
                +'<input id="ks1Email" type="email" value="'+(p.kundEmail||'').replace(/"/g,'&quot;')+'" placeholder="kund@email.se" style="width:100%;padding:12px 16px;border:1.5px solid #e5e7eb;border-radius:10px;font-size:15px;font-family:inherit;box-sizing:border-box">'
                +'</div>'

                // Telefon
                +'<div style="margin-bottom:16px">'
                +'<label style="font-size:13px;font-weight:600;color:#334155;display:block;margin-bottom:6px">Telefon</label>'
                +'<input id="ks1Phone" type="tel" value="'+(p.kundTel||'').replace(/"/g,'&quot;')+'" placeholder="070-123 45 67" style="width:100%;padding:12px 16px;border:1.5px solid #e5e7eb;border-radius:10px;font-size:15px;font-family:inherit;box-sizing:border-box">'
                +'</div>'

                // Adress
                +'<div style="margin-bottom:16px">'
                +'<label style="font-size:13px;font-weight:600;color:#334155;display:block;margin-bottom:6px">Adress</label>'
                +'<input id="ks1Addr" type="text" value="'+addr.replace(/"/g,'&quot;')+'" placeholder="Gatuadress, Stad" style="width:100%;padding:12px 16px;border:1.5px solid #e5e7eb;border-radius:10px;font-size:15px;font-family:inherit;box-sizing:border-box">'
                +'</div>'

                // Fastighetsägare
                +'<div style="margin-bottom:6px">'
                +'<label style="font-size:13px;font-weight:600;color:#334155;display:block;margin-bottom:6px">Fastighetsägare</label>'
                +'<select id="ks1OwnerType" onchange="updateKs1MaxDeduction()" style="width:100%;padding:12px 16px;border:1.5px solid #e5e7eb;border-radius:10px;font-size:15px;font-family:inherit;box-sizing:border-box;background:#fff">'
                +'<option value="1">1 privatperson</option>'
                +'<option value="2">2 privatpersoner</option>'
                +'<option value="brf">Företag/BRF</option>'
                +'</select>'
                +'</div>'
                +'<div id="ks1MaxDeduction" style="font-size:12px;color:#64748b;margin-bottom:20px">Max Grön teknik-avdrag: 50 000 kr</div>'

                // Personuppgifter för skattereduktion
                +'<div id="ks1OwnersBox" style="background:#f8f9fa;border:1px solid #e5e7eb;border-radius:12px;padding:20px;margin-bottom:16px">'
                +'<h3 style="font-size:15px;font-weight:700;margin:0 0 16px">Personuppgifter för skattereduktion</h3>'
                +'<div id="ks1Owner1">'
                +'<div style="font-size:12px;font-weight:600;color:#64748b;margin-bottom:8px">Ägare</div>'
                +'<input id="ks1OwnerName1" type="text" value="'+(p.kundNamn||'').replace(/"/g,'&quot;')+'" placeholder="Namn" style="width:100%;padding:10px 14px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;box-sizing:border-box;margin-bottom:8px">'
                +'<input id="ks1OwnerPnr1" type="text" placeholder="Personnummer (ÅÅÅÅMMDDXXXX)" style="width:100%;padding:10px 14px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;box-sizing:border-box">'
                +'</div>'
                +'<div id="ks1Owner2" style="display:none;margin-top:14px;padding-top:14px;border-top:1px solid #e5e7eb">'
                +'<div style="font-size:12px;font-weight:600;color:#64748b;margin-bottom:8px">Ägare 2</div>'
                +'<input id="ks1OwnerName2" type="text" placeholder="Namn" style="width:100%;padding:10px 14px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;box-sizing:border-box;margin-bottom:8px">'
                +'<input id="ks1OwnerPnr2" type="text" placeholder="Personnummer (ÅÅÅÅMMDDXXXX)" style="width:100%;padding:10px 14px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:inherit;box-sizing:border-box">'
                +'</div>'
                +'</div>'

                // Checkbox: begränsad skattereduktion
                +'<label style="display:flex;gap:10px;align-items:flex-start;margin-bottom:24px;cursor:pointer">'
                +'<input type="checkbox" id="ks1LimitedDeduction" style="margin-top:3px;width:18px;height:18px;accent-color:#166534">'
                +'<div><div style="font-size:13px;font-weight:600;color:#1a1a1a">Kunden har mindre än 50 000 kr i skattereduktion totalt</div>'
                +'<div style="font-size:12px;color:#64748b;margin-top:2px">Markera om kunden redan utnyttjat sin skattereduktion eller har begränsat utrymme</div></div>'
                +'</label>'

                // Nästa-knapp
                +'<button onclick="submitKalkylStep1('+idx+')" style="width:100%;padding:14px;background:#166534;color:#fff;border:none;border-radius:12px;font-size:16px;font-weight:700;cursor:pointer;font-family:inherit;transition:background .15s" onmouseover="this.style.background=\'#14532d\'" onmouseout="this.style.background=\'#166534\'">Nästa: Skapa kalkyl</button>'

                +'</div></div>';

            document.body.appendChild(modal);
        }

        function updateKs1MaxDeduction(){
            const type = document.getElementById('ks1OwnerType').value;
            const el = document.getElementById('ks1MaxDeduction');
            const owner2 = document.getElementById('ks1Owner2');
            if(type === '2'){
                el.textContent = 'Max Grön teknik-avdrag: 100 000 kr (50 000 kr per person)';
                owner2.style.display = '';
            } else if(type === 'brf'){
                el.textContent = 'Företag/BRF: Inget grönt teknik-avdrag';
                owner2.style.display = 'none';
            } else {
                el.textContent = 'Max Grön teknik-avdrag: 50 000 kr';
                owner2.style.display = 'none';
            }
        }

        // Spara kundinfo och gå till kalkyl steg 2
        let pendingKalkylCustomer = null;
        let kalkylImages = []; // {url, type, selected:bool, created}

        function submitKalkylStep1(idx){
            const name = document.getElementById('ks1Name').value.trim();
            const email = document.getElementById('ks1Email').value.trim();
            if(!name){ alert('Namn krävs'); return; }
            if(!email){ alert('E-post krävs'); return; }

            const ownerType = document.getElementById('ks1OwnerType').value;
            let maxDeduction = 50000;
            if(ownerType === '2') maxDeduction = 100000;
            if(ownerType === 'brf') maxDeduction = 0;

            if(document.getElementById('ks1LimitedDeduction').checked){
                const custom = prompt('Ange kvarvarande skattereduktion (kr):', maxDeduction);
                if(custom !== null) maxDeduction = parseInt(custom) || 0;
            }

            pendingKalkylCustomer = {
                prospectIdx: idx,
                name: name,
                email: email,
                phone: document.getElementById('ks1Phone').value.trim(),
                address: document.getElementById('ks1Addr').value.trim(),
                ownerType: ownerType,
                maxDeduction: maxDeduction,
                owner1: {
                    name: document.getElementById('ks1OwnerName1').value.trim(),
                    pnr: document.getElementById('ks1OwnerPnr1').value.trim()
                },
                owner2: ownerType === '2' ? {
                    name: document.getElementById('ks1OwnerName2')?.value.trim() || '',
                    pnr: document.getElementById('ks1OwnerPnr2')?.value.trim() || ''
                } : null,
                product: faltProspects[idx]?.product || '',
                solarData: {
                    yearlyKwh: faltProspects[idx]?.yearlyKwh || null,
                    maxPanels: faltProspects[idx]?.maxPanels || null,
                    roofArea: faltProspects[idx]?.roofArea || null,
                    solarScore: faltProspects[idx]?.solarScore || null
                },
                created: new Date().toISOString()
            };

            // Uppdatera prospect
            const p = faltProspects[idx];
            p.kundNamn = name;
            p.kundEmail = email;
            p.kundTel = document.getElementById('ks1Phone').value.trim();
            p.kalkylStatus = 'started';
            localStorage.setItem('faltProspects', JSON.stringify(faltProspects));

            // Stäng modal
            document.getElementById('kalkylStep1Modal')?.remove();

            // Navigera till Ny Kalkyl-sidan
            document.querySelectorAll('.nav-item').forEach(n=>n.classList.remove('active'));
            document.querySelectorAll('.page-content').forEach(p=>{p.classList.remove('active');p.style.display='';});
            const kalkylPage = document.getElementById('page-konfigurator');
            if(kalkylPage) kalkylPage.classList.add('active');
            const navItem = document.querySelector('[data-page="konfigurator"]');
            if(navItem) navItem.classList.add('active');

            // Visa konfiguratorvyn med kundinfo
            showKalkylConfig();
            populateKalkylFromCustomer();
        }

        function populateKalkylFromCustomer(){
            if(!pendingKalkylCustomer) return;
            const c = pendingKalkylCustomer;
            const p = faltProspects[c.prospectIdx];

            const banner = document.getElementById('kalkylCustomerBanner');
            if(!banner) return;

            const sd = c.solarData || {};
            const hasSolar = sd.yearlyKwh || sd.maxPanels;

            // Hitta.se boende-knappar
            const hPersons = (p && p.hittaPersons) || [];
            let hittaHtml = '';
            if(hPersons.length > 0){
                const fp0 = hPersons[0];
                const propInfo = [];
                if(fp0.livingArea) propInfo.push(fp0.livingArea);
                if(fp0.household) propInfo.push(fp0.household);
                hittaHtml = '<div style="margin-bottom:12px">'
                    +(propInfo.length ? '<div style="font-size:11px;color:#64748b;margin-bottom:6px;padding:4px 8px;background:#f8fafc;border-radius:6px;border:1px solid #e5e7eb">'+propInfo.join(' · ')+'</div>' : '')
                    +'<div style="font-size:10px;font-weight:700;color:#059669;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px">Boende — klicka för att fylla i</div>'
                    +'<div style="display:flex;flex-wrap:wrap;gap:4px">'
                    + hPersons.map(hp => {
                        const ageStr = hp.age ? ' · '+hp.age+' år' : '';
                        return '<button onclick="fillKalkylCustomerName(\''+hp.name.replace(/'/g,"\\'")+'\')" style="padding:5px 10px;border:1px solid #bbf7d0;border-radius:6px;font-size:12px;cursor:pointer;background:#f0fdf4;font-family:inherit;color:#166534;font-weight:600;transition:background .15s" onmouseover="this.style.background=\'#dcfce7\'" onmouseout="this.style.background=\'#f0fdf4\'">'+hp.name+'<span style="font-weight:400;color:#64748b;font-size:11px">'+ageStr+'</span></button>';
                    }).join('')
                    +'</div></div>';
            }

            banner.style.cssText = 'background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:18px 20px;margin-bottom:20px';
            banner.innerHTML = '<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;cursor:pointer" onclick="toggleKalkylCustomerEdit()">'
                +'<div style="display:flex;align-items:center;gap:8px">'
                +'<svg viewBox="0 0 24 24" style="width:18px;height:18px;fill:none;stroke:#024550;stroke-width:2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>'
                +'<span style="font-size:14px;font-weight:700;color:#1a1a1a">Kundinformation</span>'
                +'<span id="kcNamePreview" style="font-size:13px;color:#64748b;font-weight:400;margin-left:8px">'+(c.name||'Ej ifylld')+'</span>'
                +'</div>'
                +'<svg id="kcChevron" viewBox="0 0 24 24" style="width:18px;height:18px;fill:none;stroke:#94a3b8;stroke-width:2;transition:transform .2s"><polyline points="6 9 12 15 18 9"/></svg>'
                +'</div>'
                +'<div id="kcEditSection" style="display:none">'
                + hittaHtml
                +'<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px">'
                +'<div><label style="font-size:11px;font-weight:600;color:#64748b;display:block;margin-bottom:3px">Namn</label>'
                +'<input id="kcName" type="text" value="'+(c.name||'').replace(/"/g,'&quot;')+'" placeholder="Förnamn Efternamn" onchange="syncKalkylCustomer()" style="width:100%;padding:8px 10px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;box-sizing:border-box"></div>'
                +'<div><label style="font-size:11px;font-weight:600;color:#64748b;display:block;margin-bottom:3px">Telefon</label>'
                +'<input id="kcPhone" type="tel" value="'+(c.phone||'').replace(/"/g,'&quot;')+'" placeholder="070-123 45 67" onchange="syncKalkylCustomer()" style="width:100%;padding:8px 10px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;box-sizing:border-box"></div>'
                +'</div>'
                +'<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px">'
                +'<div><label style="font-size:11px;font-weight:600;color:#64748b;display:block;margin-bottom:3px">E-post</label>'
                +'<input id="kcEmail" type="email" value="'+(c.email||'').replace(/"/g,'&quot;')+'" placeholder="kund@email.se" onchange="syncKalkylCustomer()" style="width:100%;padding:8px 10px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;box-sizing:border-box"></div>'
                +'<div><label style="font-size:11px;font-weight:600;color:#64748b;display:block;margin-bottom:3px">Adress</label>'
                +'<input id="kcAddr" type="text" value="'+(c.address||'').replace(/"/g,'&quot;')+'" onchange="syncKalkylCustomer()" style="width:100%;padding:8px 10px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;box-sizing:border-box"></div>'
                +'</div>'
                +'<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin-bottom:10px">'
                +'<div><label style="font-size:11px;font-weight:600;color:#64748b;display:block;margin-bottom:3px">Ägare</label>'
                +'<select id="kcOwnerType" onchange="updateKcOwner();syncKalkylCustomer()" style="width:100%;padding:8px 10px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;box-sizing:border-box;background:#fff">'
                +'<option value="1"'+(c.ownerType==='1'?' selected':'')+'>1 privatperson</option>'
                +'<option value="2"'+(c.ownerType==='2'?' selected':'')+'>2 privatpersoner</option>'
                +'<option value="brf"'+(c.ownerType==='brf'?' selected':'')+'>Företag/BRF</option>'
                +'</select></div>'
                +'<div><label style="font-size:11px;font-weight:600;color:#64748b;display:block;margin-bottom:3px">Personnr ägare 1</label>'
                +'<input id="kcPnr1" type="text" value="'+((c.owner1&&c.owner1.pnr)||'').replace(/"/g,'&quot;')+'" placeholder="ÅÅÅÅMMDDXXXX" onchange="syncKalkylCustomer()" style="width:100%;padding:8px 10px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;box-sizing:border-box"></div>'
                +'<div id="kcOwner2Box" style="'+(c.ownerType==='2'?'':'display:none')+'"><label style="font-size:11px;font-weight:600;color:#64748b;display:block;margin-bottom:3px">Personnr ägare 2</label>'
                +'<input id="kcPnr2" type="text" value="'+((c.owner2&&c.owner2.pnr)||'').replace(/"/g,'&quot;')+'" placeholder="ÅÅÅÅMMDDXXXX" onchange="syncKalkylCustomer()" style="width:100%;padding:8px 10px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:13px;font-family:inherit;box-sizing:border-box"></div>'
                +'</div>'
                // Solar data
                +(hasSolar ? '<div style="margin-top:8px;padding:10px 12px;background:#f0f9ff;border:1px solid #bfdbfe;border-radius:8px;display:flex;align-items:center;gap:10px;flex-wrap:wrap">'
                    +'<label style="display:flex;align-items:center;gap:6px;cursor:pointer;flex-shrink:0"><input type="checkbox" id="useSolarData" checked onchange="applySolarDataToCalc()" style="width:16px;height:16px;accent-color:#2563eb"><span style="font-size:12px;font-weight:600;color:#1e40af">Soldata från FältSälj</span></label>'
                    +'<div style="display:flex;gap:12px;font-size:11px;color:#334155">'
                    +(sd.yearlyKwh ? '<span><strong>'+sd.yearlyKwh.toLocaleString('sv-SE')+'</strong> kWh/år</span>' : '')
                    +(sd.maxPanels ? '<span>Max <strong>'+sd.maxPanels+'</strong> paneler</span>' : '')
                    +(sd.roofArea ? '<span><strong>'+sd.roofArea+'</strong> m² tak</span>' : '')
                    +(sd.solarScore ? '<span>Score: <strong>'+sd.solarScore+'</strong>/5</span>' : '')
                    +'</div></div>' : '')
                +'</div>';

            // Förvälj solceller
            const catSel = document.getElementById('categorySelect');
            if(catSel){
                catSel.value = 'solceller';
                changeCategory();
            }

            // Applicera soldata
            if(hasSolar) setTimeout(applySolarDataToCalc, 100);

            // Initiera prospektbilder
            initKalkylPhotos();
        }

        function toggleKalkylCustomerEdit(){
            const sec = document.getElementById('kcEditSection');
            const chev = document.getElementById('kcChevron');
            if(!sec) return;
            if(sec.style.display === 'none'){
                sec.style.display = 'block';
                if(chev) chev.style.transform = 'rotate(180deg)';
            } else {
                sec.style.display = 'none';
                if(chev) chev.style.transform = '';
            }
        }

        function fillKalkylCustomerName(name){
            const el = document.getElementById('kcName');
            if(el) el.value = name;
            // Uppdatera preview
            const prev = document.getElementById('kcNamePreview');
            if(prev) prev.textContent = name;
            syncKalkylCustomer();
        }

        function updateKcOwner(){
            const type = document.getElementById('kcOwnerType')?.value;
            const box = document.getElementById('kcOwner2Box');
            if(box) box.style.display = type === '2' ? '' : 'none';
        }

        function syncKalkylCustomer(){
            if(!pendingKalkylCustomer) return;
            const c = pendingKalkylCustomer;
            c.name = document.getElementById('kcName')?.value.trim() || '';
            c.phone = document.getElementById('kcPhone')?.value.trim() || '';
            c.email = document.getElementById('kcEmail')?.value.trim() || '';
            c.address = document.getElementById('kcAddr')?.value.trim() || '';
            c.ownerType = document.getElementById('kcOwnerType')?.value || '1';
            let maxD = 50000;
            if(c.ownerType === '2') maxD = 100000;
            if(c.ownerType === 'brf') maxD = 0;
            c.maxDeduction = maxD;
            c.owner1 = { name: c.name, pnr: document.getElementById('kcPnr1')?.value.trim() || '' };
            c.owner2 = c.ownerType === '2' ? { name: '', pnr: document.getElementById('kcPnr2')?.value.trim() || '' } : null;

            // Uppdatera preview
            const prev = document.getElementById('kcNamePreview');
            if(prev) prev.textContent = c.name || 'Ej ifylld';

            // Uppdatera prospect
            const p = faltProspects[c.prospectIdx];
            if(p){
                p.kundNamn = c.name;
                p.kundTel = c.phone;
                p.kundEmail = c.email;
                localStorage.setItem('faltProspects', JSON.stringify(faltProspects));
            }

            // Uppdatera kalkyl owner count
            updateSolarCalc();
        }

        // === KALKYL PHOTOS (inbäddad bildgenerering) ===
        let kpExpanded = false;
        let kpUploadedImage = null; // base64 original för bildgenerering
        let kpSelectedProduct = null;
        let kpSelectedSub = null;
        let kpSelectedCount = null;
        let kpLastResultUrl = null;
        let kpProspectOriginals = []; // original full-quality bilder
        let kpActiveProspectIdx = -1; // vilken prospektbild som är vald som bas

        function initKalkylPhotos(){
            kalkylImages = [];
            kpExpanded = false;
            kpUploadedImage = null;
            kpSelectedProduct = null;
            kpSelectedSub = null;
            kpSelectedCount = null;
            kpLastResultUrl = null;
            kpProspectOriginals = [];
            kpActiveProspectIdx = -1;
            const sec = document.getElementById('kalkylPhotosSection');
            if(!sec) return;

            // Ladda prospektbilder från fältsälj — ALLTID originalkvalitet
            const c = pendingKalkylCustomer;
            if(c && c.prospectIdx !== undefined){
                const p = faltProspects[c.prospectIdx];
                if(p && p.photos && p.photos.length > 0){
                    kpProspectOriginals = p.photos.map(ph => ({
                        full: ph.full || ph.url || ph.dataUrl,
                        thumb: ph.thumb || ph.full || ph.url || ph.dataUrl,
                        type: ph.type || 'photo',
                        created: ph.date || ph.created || new Date().toISOString()
                    })).filter(ph => ph.full);
                }
            }

            sec.style.display = 'block';
            renderKpProspectPhotos();
            initKpOptions();
            renderKalkylPhotos();
        }

        function renderKpProspectPhotos(){
            const container = document.getElementById('kpProspectPhotos');
            if(!container) return;
            if(kpProspectOriginals.length === 0){
                container.innerHTML = '<div style="padding:10px;text-align:center;color:#94a3b8;font-size:12px;border:1px dashed #e5e7eb;border-radius:8px;margin-bottom:8px">Inga prospektbilder. Ladda upp eller ta ett foto.</div>';
                return;
            }
            container.innerHTML = '<div style="margin-bottom:10px">'
                +'<label style="display:block;font-size:12px;font-weight:600;color:#059669;margin-bottom:6px">Prospektbilder — klicka för att använda som bas</label>'
                +'<div style="display:flex;gap:8px;flex-wrap:wrap">'
                + kpProspectOriginals.map((ph, i) => {
                    const isActive = (i === kpActiveProspectIdx);
                    return '<div onclick="useProspectPhotoAsBase('+i+')" style="width:80px;height:60px;border-radius:8px;overflow:hidden;border:2px solid '+(isActive?'#059669':'#e5e7eb')+';cursor:pointer;position:relative;transition:border-color .15s" id="kpPPhoto_'+i+'" onmouseover="this.style.borderColor=\'#059669\'" onmouseout="this.style.borderColor=this.dataset.active===\'1\'?\'#059669\':\'#e5e7eb\'" data-active="'+(isActive?'1':'0')+'">'
                    +'<img src="'+ph.thumb+'" style="width:100%;height:100%;object-fit:cover">'
                    +'</div>';
                }).join('')
                +'</div></div>';
        }

        async function useProspectPhotoAsBase(idx){
            const photo = kpProspectOriginals[idx];
            if(!photo) return;

            kpActiveProspectIdx = idx;

            const prev = document.getElementById('kpBgPreview');
            const prevImg = document.getElementById('kpBgPreviewImg');
            if(prevImg) prevImg.src = photo.full;
            if(prev) prev.style.display = 'block';

            // Markera aktiv
            document.querySelectorAll('[id^="kpPPhoto_"]').forEach(d => { d.style.borderColor='#e5e7eb'; d.dataset.active='0'; });
            const el = document.getElementById('kpPPhoto_'+idx);
            if(el){ el.style.borderColor = '#059669'; el.dataset.active = '1'; }

            // Om URL (inte base64) → hämta som base64 för API:t
            if(photo.full && !photo.full.startsWith('data:')){
                try {
                    const resp = await fetch(photo.full);
                    const blob = await resp.blob();
                    kpUploadedImage = await blobToDataUrl(blob);
                } catch(e){
                    console.error('Kunde inte hämta original:', e);
                    kpUploadedImage = photo.full;
                }
            } else {
                kpUploadedImage = photo.full;
            }
        }

        function handleKpBgUpload(input){
            const file = input.files?.[0];
            if(!file) return;
            const reader = new FileReader();
            reader.onload = function(e){
                kpUploadedImage = e.target.result;
                kpActiveProspectIdx = -1;
                document.getElementById('kpBgPreviewImg').src = kpUploadedImage;
                document.getElementById('kpBgPreview').style.display = 'block';
                document.querySelectorAll('[id^="kpPPhoto_"]').forEach(d => { d.style.borderColor='#e5e7eb'; d.dataset.active='0'; });
            };
            reader.readAsDataURL(file);
        }

        function clearKpBgUpload(){
            kpUploadedImage = null;
            kpActiveProspectIdx = -1;
            document.getElementById('kpBgPreview').style.display = 'none';
            document.getElementById('kpBgFileInput').value = '';
            document.getElementById('kpBgCameraInput').value = '';
            document.querySelectorAll('[id^="kpPPhoto_"]').forEach(d => { d.style.borderColor='#e5e7eb'; d.dataset.active='0'; });
        }

        function initKpOptions(){
            const grid = document.getElementById('kpOptionGrid');
            if(!grid) return;
            grid.innerHTML = Object.entries(bgProducts).map(([key, p]) =>
                '<div onclick="selectKpProduct(\''+key+'\')" id="kpOpt_'+key+'" style="padding:10px;border:2px solid #e5e7eb;border-radius:8px;cursor:pointer;text-align:center;transition:all .15s;background:#fafbfc">'
                +'<div style="font-size:18px;margin-bottom:2px">'+p.icon+'</div>'
                +'<div style="font-size:11px;font-weight:600;color:#1a1a1a">'+p.label+'</div>'
                +'</div>'
            ).join('');
        }

        function selectKpProduct(key){
            kpSelectedProduct = key;
            kpSelectedSub = null;
            kpSelectedCount = null;
            const p = bgProducts[key];
            document.getElementById('kpProjectType').value = p.label;
            document.getElementById('kpPrompt').value = p.prompt;

            document.querySelectorAll('#kpOptionGrid > div').forEach(d => { d.style.borderColor='#e5e7eb'; d.style.background='#fafbfc'; });
            const sel = document.getElementById('kpOpt_'+key);
            if(sel){ sel.style.borderColor='#024550'; sel.style.background='#f0fdfa'; }

            const panel = document.getElementById('kpDetailsPanel');
            const subGrid = document.getElementById('kpSubOptions');
            if(p.subs && p.subs.length){
                panel.style.display = 'block';
                subGrid.innerHTML = p.subs.map((s, i) =>
                    '<div onclick="selectKpSub('+i+')" id="kpSub_'+i+'" style="padding:8px;border:2px solid #e5e7eb;border-radius:8px;cursor:pointer;text-align:center;transition:all .15s;background:#fafbfc">'
                    +'<div style="font-size:11px;font-weight:600;color:#1a1a1a">'+s.label+'</div>'
                    +'</div>'
                ).join('');
            } else {
                panel.style.display = 'none';
            }

            const countPanel = document.getElementById('kpCountPanel');
            if(p.hasCount && p.countOptions){
                countPanel.style.display = 'block';
                document.getElementById('kpCountLabel').textContent = p.countLabel || 'Antal';
                document.getElementById('kpCountOptions').innerHTML = p.countOptions.map(n =>
                    '<div onclick="selectKpCount('+n+')" id="kpCount_'+n+'" style="padding:6px 10px;border:2px solid #e5e7eb;border-radius:8px;cursor:pointer;text-align:center;transition:all .15s;background:#fafbfc;min-width:36px">'
                    +'<div style="font-size:12px;font-weight:600;color:#1a1a1a">'+n+'</div>'
                    +'</div>'
                ).join('');
                // Auto-select panel count from kalkyl if solceller
                if(key === 'solceller' && currentCalcState.panelCount){
                    setTimeout(() => selectKpCount(currentCalcState.panelCount), 50);
                }
            } else {
                countPanel.style.display = 'none';
            }
        }

        function selectKpSub(idx){
            kpSelectedSub = idx;
            updateKpPrompt();
            document.querySelectorAll('#kpSubOptions > div').forEach(d => { d.style.borderColor='#e5e7eb'; d.style.background='#fafbfc'; });
            const sel = document.getElementById('kpSub_'+idx);
            if(sel){ sel.style.borderColor='#024550'; sel.style.background='#f0fdfa'; }
        }

        function selectKpCount(n){
            kpSelectedCount = n;
            updateKpPrompt();
            document.querySelectorAll('#kpCountOptions > div').forEach(d => { d.style.borderColor='#e5e7eb'; d.style.background='#fafbfc'; });
            const sel = document.getElementById('kpCount_'+n);
            if(sel){ sel.style.borderColor='#024550'; sel.style.background='#f0fdfa'; }
        }

        function updateKpPrompt(){
            const p = bgProducts[kpSelectedProduct];
            if(!p) return;
            let prompt = p.prompt;
            if(kpSelectedSub !== null && p.subs[kpSelectedSub]){
                prompt += ' ' + p.subs[kpSelectedSub].extra;
            }
            if(kpSelectedCount && p.hasCount){
                const rows = kpSelectedCount <= 8 ? 2 : kpSelectedCount <= 18 ? 2 : 3;
                const cols = Math.ceil(kpSelectedCount / rows);
                prompt += ' CRITICAL: Place EXACTLY '+kpSelectedCount+' solar panels on the roof — arranged as '+rows+' rows x '+cols+' columns. There must be precisely '+kpSelectedCount+' panels total, not more and not less.';
            }
            document.getElementById('kpPrompt').value = prompt;
        }

        async function generateKpImage(){
            const prompt = document.getElementById('kpPrompt').value.trim();
            const projectType = document.getElementById('kpProjectType').value;
            const extra = document.getElementById('kpExtraPrompt')?.value?.trim() || '';
            if(!kpUploadedImage){ alert('Välj en prospektbild eller ladda upp ett foto av huset först'); return; }
            if(!prompt || !projectType){ alert('Välj en produkttyp först'); return; }

            const fullPrompt = kpUploadedImage
                ? prompt + (extra ? '. ' + extra : '')
                : prompt + (extra ? '. Additional details: ' + extra : '') + '. Show the ENTIRE house from street level, wide angle, full building visible. Photorealistic, professional photography, Scandinavian architecture.';

            const btn = document.getElementById('kpGenerateBtn');
            btn.disabled = true;
            btn.textContent = 'Genererar...';

            document.getElementById('kpPlaceholder').style.display = 'none';
            document.getElementById('kpResult').style.display = 'none';
            document.getElementById('kpLoading').style.display = 'flex';

            try {
                const provider = document.getElementById('kpProvider').value;
                const res = await fetch('/api/generate.php', {
                    method:'POST',
                    headers:{'Content-Type':'application/json'},
                    body: JSON.stringify({
                        prompt: fullPrompt,
                        projectType: projectType,
                        baseImage: kpUploadedImage,
                        provider: provider
                    })
                });
                const data = await res.json();
                if(data.error) throw new Error(data.error);

                document.getElementById('kpLoading').style.display = 'none';
                document.getElementById('kpResult').style.display = 'block';
                kpLastResultUrl = data.base64 || data.imageUrl;
                document.getElementById('kpResultImg').src = kpLastResultUrl;

            } catch(err){
                document.getElementById('kpLoading').style.display = 'none';
                document.getElementById('kpPlaceholder').style.display = 'flex';
                alert('Fel: '+err.message);
            } finally {
                btn.disabled = false;
                btn.textContent = 'Generera bild';
            }
        }

        function saveKpResultToGallery(){
            if(!kpLastResultUrl) return;
            // Spara före-bild om den inte redan finns
            if(kpUploadedImage && !kalkylImages.find(i => i.url === kpUploadedImage)){
                kalkylImages.push({ url: kpUploadedImage, type: 'before', selected: false, created: new Date().toISOString() });
            }
            // Spara efter-bild
            kalkylImages.push({ url: kpLastResultUrl, type: 'after', selected: true, created: new Date().toISOString() });
            renderKalkylPhotos();
            // Reset result
            document.getElementById('kpResult').style.display = 'none';
            document.getElementById('kpPlaceholder').style.display = 'flex';
            kpLastResultUrl = null;
        }

        function downloadKpResult(){
            if(!kpLastResultUrl) return;
            const a = document.createElement('a');
            a.href = kpLastResultUrl;
            a.download = 'prospekt-'+Date.now()+'.png';
            a.click();
        }

        function resetKpResult(){
            document.getElementById('kpResult').style.display = 'none';
            document.getElementById('kpPlaceholder').style.display = 'flex';
            kpLastResultUrl = null;
        }

        function toggleKalkylPhotos(){
            kpExpanded = !kpExpanded;
            const exp = document.getElementById('kpExpanded');
            const thumbs = document.getElementById('kpThumbsCollapsed');
            const chev = document.getElementById('kpChevron');
            if(kpExpanded){
                if(exp) exp.style.display = 'block';
                if(thumbs) thumbs.style.display = 'none';
                if(chev) chev.style.transform = 'rotate(180deg)';
            } else {
                if(exp) exp.style.display = 'none';
                if(thumbs) thumbs.style.display = 'flex';
                if(chev) chev.style.transform = '';
            }
            renderKalkylPhotos();
        }

        function renderKalkylPhotos(){
            // Säkerställ att prospektbilder alltid visas
            renderKpProspectPhotos();

            const count = document.getElementById('kpCount');
            const thumbs = document.getElementById('kpThumbsCollapsed');
            const gallery = document.getElementById('kpGallery');
            const empty = document.getElementById('kpEmpty');
            const selected = kalkylImages.filter(i => i.selected);

            const totalPhotos = kpProspectOriginals.length + kalkylImages.length;
            if(count) count.textContent = totalPhotos > 0 ? '('+totalPhotos+' bilder'+(selected.length>0?', '+selected.length+' valda':'')+')' : '';

            // Collapsed thumbnails — visa ALLA bilder (grön ram = vald)
            if(thumbs){
                // Visa prospektoriginal + kalkylbilder
                const allThumbs = [];
                kpProspectOriginals.forEach(ph => {
                    if(!kalkylImages.find(ki => ki.url === ph.full)){
                        allThumbs.push({url: ph.thumb, selected: false, source: 'prospect'});
                    }
                });
                kalkylImages.forEach(img => allThumbs.push({url: img.url, selected: img.selected, source: 'kalkyl'}));

                if(allThumbs.length > 0){
                    thumbs.innerHTML = allThumbs.map(t =>
                        '<div style="width:56px;height:56px;border-radius:8px;overflow:hidden;border:2px solid '+(t.selected?'#059669':'#d1d5db')+';flex-shrink:0;opacity:'+(t.selected?'1':'.7')+'">'
                        +'<img src="'+t.url+'" style="width:100%;height:100%;object-fit:cover">'
                        +'</div>'
                    ).join('')
                    + (selected.length > 0 ? '<span style="font-size:11px;color:#059669;font-weight:600;margin-left:4px">'+selected.length+' valda</span>' : '');
                    thumbs.style.display = kpExpanded ? 'none' : 'flex';
                } else {
                    thumbs.innerHTML = '<span style="font-size:12px;color:#94a3b8">Inga bilder — expandera för att lägga till</span>';
                    thumbs.style.display = kpExpanded ? 'none' : 'flex';
                }
            }

            // Gallery (expanded, inside kpGallery)
            if(gallery){
                const typeLabels = {before:'Före',after:'Efter',photo:'Foto',generated:'Genererad'};
                const typeBg = {before:'#fef3c7',after:'#dcfce7',photo:'#e0f2fe',generated:'#f3e8ff'};
                const typeColor = {before:'#92400e',after:'#166534',photo:'#0369a1',generated:'#7c3aed'};
                if(kalkylImages.length > 0){
                    if(empty) empty.style.display = 'none';
                    gallery.innerHTML = kalkylImages.map((img, i) => {
                        const lbl = typeLabels[img.type]||'Bild';
                        const bg = typeBg[img.type]||'#f1f5f9';
                        const clr = typeColor[img.type]||'#64748b';
                        return '<div style="position:relative;border-radius:8px;overflow:hidden;border:2px solid '+(img.selected?'#059669':'#e5e7eb')+'">'
                        +'<img src="'+img.url+'" style="width:100%;aspect-ratio:4/3;object-fit:cover;cursor:pointer" onclick="openLightbox(kalkylImages['+i+'].url)">'
                        +'<div style="position:absolute;top:4px;left:4px;display:flex;gap:3px">'
                        +'<button onclick="event.stopPropagation();toggleKalkylPhotoSelect('+i+')" style="width:22px;height:22px;background:'+(img.selected?'#059669':'rgba(0,0,0,.5)')+';color:#fff;border:none;border-radius:50%;cursor:pointer;font-size:11px;display:flex;align-items:center;justify-content:center">'+(img.selected?'&#10003;':'')+'</button>'
                        +'<span style="padding:2px 6px;border-radius:4px;font-size:9px;font-weight:700;background:'+bg+';color:'+clr+'">'+lbl+'</span>'
                        +'</div>'
                        +'<div style="position:absolute;top:4px;right:4px;display:flex;gap:3px">'
                        +'<button onclick="event.stopPropagation();downloadKalkylPhoto('+i+')" style="width:22px;height:22px;background:rgba(0,0,0,.5);color:#fff;border:none;border-radius:50%;cursor:pointer;font-size:10px;display:flex;align-items:center;justify-content:center" title="Ladda ner"><svg viewBox="0 0 24 24" style="width:11px;height:11px;fill:none;stroke:currentColor;stroke-width:2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg></button>'
                        +'<button onclick="event.stopPropagation();removeKalkylPhoto('+i+')" style="width:22px;height:22px;background:rgba(239,68,68,.8);color:#fff;border:none;border-radius:50%;cursor:pointer;font-size:12px;display:flex;align-items:center;justify-content:center">&times;</button>'
                        +'</div>'
                        +'</div>';
                    }).join('');
                } else {
                    gallery.innerHTML = '';
                    if(empty) empty.style.display = 'block';
                }
            }
        }

        function toggleKalkylPhotoSelect(idx){
            if(kalkylImages[idx]) kalkylImages[idx].selected = !kalkylImages[idx].selected;
            renderKalkylPhotos();
        }

        function removeKalkylPhoto(idx){
            kalkylImages.splice(idx, 1);
            renderKalkylPhotos();
        }

        function downloadKalkylPhoto(idx){
            const img = kalkylImages[idx];
            if(!img) return;
            const a = document.createElement('a');
            a.href = img.url;
            a.download = 'prospekt_'+(idx+1)+'.png';
            a.target = '_blank';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }

        function applySolarDataToCalc(){
            if(!pendingKalkylCustomer) return;
            const sd = pendingKalkylCustomer.solarData || {};
            const use = document.getElementById('useSolarData')?.checked;
            if(use && sd.maxPanels){
                const slider = document.getElementById('solPanelCount');
                if(slider){
                    // Clamp to slider range
                    let count = Math.min(80, Math.max(8, sd.maxPanels));
                    // Round to nearest even
                    count = Math.round(count / 2) * 2;
                    slider.value = count;
                }
            }
            updateSolarCalc();
        }

        // Alias for backward compat
        function renderFaltKalkyler(){ renderLeadsTable(); }

        /* === LOGIN === */
        const loginQuotes=[
            '"Chase the vision, not the money; the money will end up following you." — Tony Hsieh',
            '"If you are not taking care of your customer, your competitor will." — Bob Hooey',
            '"Success is not final, failure is not fatal: it is the courage to continue that counts." — Winston Churchill',
            '"The best way to predict the future is to create it." — Peter Drucker',
            '"Don\'t find customers for your products, find products for your customers." — Seth Godin',
            '"Every sale has five basic obstacles: no need, no money, no hurry, no desire, no trust." — Zig Ziglar',
            '"Quality is remembered long after the price is forgotten." — Gucci',
            '"Your most unhappy customers are your greatest source of learning." — Bill Gates',
            '"Stop selling. Start helping." — Zig Ziglar',
            '"Make a customer, not a sale." — Katherine Barchetti'
        ];

        function setLoginGreeting(){
            const h=new Date().getHours();
            let g;
            if(h>=23||h<5) g='Borde du inte sova nu?';
            else if(h<12) g='God morgon';
            else if(h<17) g='God eftermiddag';
            else g='God kväll';
            const big=document.getElementById('loginGreetingBig');
            if(big)big.textContent=g;
            const q=document.getElementById('loginQuote');
            if(q)q.textContent=loginQuotes[Math.floor(Math.random()*loginQuotes.length)];
        }
        setLoginGreeting();

        let gUserRole = '';

        async function doLogin(e){
            e.preventDefault();
            var email=document.getElementById('loginEmail').value.trim();
            var pass=document.getElementById('loginPassword').value;
            const errEl = document.getElementById('loginError');
            const pendEl = document.getElementById('loginPending');
            if(errEl) errEl.style.display='none';
            if(pendEl) pendEl.style.display='none';

            if(!email || !pass){
                if(errEl){ errEl.textContent='Ange e-post och lösenord'; errEl.style.display='block'; }
                return;
            }

            try {
                const res = await fetch('/api/auth.php?action=login', {
                    method:'POST', headers:{'Content-Type':'application/json'},
                    body: JSON.stringify({email:email, password:pass})
                });
                const data = await res.json();

                if(data.error){
                    if(data.pending){
                        if(pendEl){ pendEl.textContent=data.error; pendEl.style.display='block'; }
                    } else {
                        if(errEl){ errEl.textContent=data.error; errEl.style.display='block'; }
                    }
                    return;
                }

                if(data.success && data.user){
                    gStaffId = data.user.id;
                    gUserEmail = data.user.email;
                    gUserName = data.user.name;
                    gUserRole = data.user.role || '';
                    gUserAvatar = data.user.avatar_url || '';
                    gMailSignature = data.user.mail_signature || '';
                    sessionStorage.setItem('gStaffId', gStaffId);
                    sessionStorage.setItem('gUserEmail', gUserEmail);
                    sessionStorage.setItem('gUserName', gUserName);
                    sessionStorage.setItem('gUserRole', gUserRole);
                    sessionStorage.setItem('gUserAvatar', gUserAvatar);
                    localStorage.setItem('mailSignature', gMailSignature);
                    enterApp(gUserEmail, gUserAvatar);
                }
            } catch(err){
                if(errEl){ errEl.textContent='Anslutningsfel: '+err.message; errEl.style.display='block'; }
            }
        }

        function enterApp(email, avatar) {
            document.getElementById('loginScreen').classList.add('hidden');
            document.getElementById('appSidebar').style.display='';
            document.getElementById('appMain').style.display='';
            var userInfo=document.querySelector('.sidebar-user-info strong');
            if(userInfo&&email) userInfo.textContent=email;
            var userSpan=document.querySelector('.sidebar-user-info span');
            if(userSpan) userSpan.textContent = (typeof gUserName !== 'undefined' && gUserName) ? gUserName : 'Inloggad som';
            if(avatar) {
                var avatarEl = document.querySelector('.sidebar-user');
                if(avatarEl && !document.getElementById('sidebarAvatar')) {
                    avatarEl.insertAdjacentHTML('afterbegin', '<img id="sidebarAvatar" src="'+avatar+'" style="width:36px;height:36px;border-radius:50%;object-fit:cover;margin-right:8px">');
                }
            }
            if(typeof updateAuthUI === 'function') updateAuthUI();
            // Restore role from sessionStorage if not set (Google login)
            if(!gUserRole) gUserRole = sessionStorage.getItem('gUserRole') || '';
            updateAdminVisibility();
            checkPendingUsers();
            applyNavPermissions();
        }

        async function googleLoginFromScreen() {
            const clientId = await initGoogleAuth();
            if (!clientId) {
                alert('Google Client ID inte konfigurerat. Kontakta admin.');
                return;
            }
            const client = google.accounts.oauth2.initCodeClient({
                client_id: clientId,
                scope: LOGIN_SCOPES,
                ux_mode: 'popup',
                redirect_uri: window.location.origin,
                callback: async (response) => {
                    if (response.error) { alert('Google login misslyckades: ' + response.error); return; }
                    try {
                        const res = await fetch('/api/google-token.php', {
                            method: 'POST',
                            headers: {'Content-Type': 'application/json'},
                            body: JSON.stringify({
                                action: 'exchange',
                                code: response.code,
                                redirectUri: window.location.origin
                            })
                        });
                        const data = await res.json();
                        if (data.error) { const errEl = document.getElementById("loginError"); const pendEl = document.getElementById("loginPending"); if(errEl) errEl.style.display="none"; if(pendEl) pendEl.style.display="none"; if(data.pending) { if(pendEl){ pendEl.textContent=data.error; pendEl.style.display="block"; } } else { if(errEl){ errEl.textContent=data.error; errEl.style.display="block"; } } return; }
                        gAccessToken = data.accessToken;
                        gTokenExpiry = Date.now() + (data.expiresIn * 1000);
                        gStaffId = data.user.id;
                        gUserEmail = data.user.email;
                        gUserName = data.user.name;
                        gUserAvatar = data.user.avatar_url || '';
                        gUserRole = data.user.role || '';
                        gMailSignature = data.user.mail_signature || '';
                        sessionStorage.setItem('gAccessToken', gAccessToken);
                        sessionStorage.setItem('gTokenExpiry', gTokenExpiry);
                        sessionStorage.setItem('gStaffId', gStaffId);
                        sessionStorage.setItem('gUserEmail', gUserEmail);
                        sessionStorage.setItem('gUserName', gUserName);
                        sessionStorage.setItem('gUserAvatar', gUserAvatar);
                        sessionStorage.setItem('gUserRole', gUserRole);
                        localStorage.setItem('mailSignature', gMailSignature);
                        enterApp(gUserEmail, gUserAvatar);
                    } catch(e) { alert('Anslutningsfel: ' + e.message); }
                }
            });
            client.requestCode();
        }

        // Logout
        document.querySelector('.sidebar-logout')?.addEventListener('click',function(){
            sessionStorage.clear();
            gUserRole = '';
            gStaffId = '';
            gUserEmail = '';
            gUserName = '';
            document.getElementById('loginScreen').classList.remove('hidden');
            document.getElementById('appSidebar').style.display='none';
            document.getElementById('appMain').style.display='none';
            document.getElementById('loginEmail').value='';
            document.getElementById('loginPassword').value='';
            const errEl = document.getElementById('loginError');
            const pendEl = document.getElementById('loginPending');
            if(errEl) errEl.style.display='none';
            if(pendEl) pendEl.style.display='none';
            hideRegisterForm();
            setLoginGreeting();
        });

        // Registrering
        function showRegisterForm(){
            document.getElementById('registerForm').style.display='block';
        }
        function hideRegisterForm(){
            document.getElementById('registerForm').style.display='none';
            document.getElementById('regError').style.display='none';
            document.getElementById('regSuccess').style.display='none';
        }
        async function doRegister(){
            const name = document.getElementById('regName').value.trim();
            const email = document.getElementById('regEmail').value.trim();
            const password = document.getElementById('regPassword').value;
            const errEl = document.getElementById('regError');
            const sucEl = document.getElementById('regSuccess');
            errEl.style.display='none';
            sucEl.style.display='none';

            if(!name || !email || !password){
                errEl.textContent='Fyll i alla fält'; errEl.style.display='block'; return;
            }
            if(password.length < 4){
                errEl.textContent='Lösenordet måste vara minst 4 tecken'; errEl.style.display='block'; return;
            }

            try {
                const res = await fetch('/api/auth.php?action=register', {
                    method:'POST', headers:{'Content-Type':'application/json'},
                    body: JSON.stringify({name, email, password})
                });
                const data = await res.json();
                if(data.error){
                    errEl.textContent=data.error; errEl.style.display='block';
                } else {
                    sucEl.textContent = data.message || 'Konto skapat! Väntar på godkännande från admin.';
                    sucEl.style.display='block';
                    document.getElementById('regName').value='';
                    document.getElementById('regEmail').value='';
                    document.getElementById('regPassword').value='';
                }
            } catch(err){
                errEl.textContent='Anslutningsfel: '+err.message; errEl.style.display='block';
            }
        }

        // Visa/dölj admin-meny baserat på roll
        function updateAdminVisibility(){
            const navAdmin = document.getElementById('navAdmin');
            if(navAdmin){
                navAdmin.style.display = (gUserRole === 'systemadmin' || gUserRole === 'admin' || gUserRole === 'saljchef') ? '' : 'none';
            }
        }

        // Admin-sida
        function switchAdminTab(tab){
            document.querySelectorAll('[data-admin-tab]').forEach(t => {
                const isActive = t.dataset.adminTab === tab;
                t.style.borderBottomColor = isActive ? '#024550' : 'transparent';
                t.style.color = isActive ? '#024550' : '#64748b';
            });
            document.getElementById('adminUsersPanel').style.display = tab==='users' ? '' : 'none';
            document.getElementById('adminPendingPanel').style.display = tab==='pending' ? '' : 'none';
            document.getElementById('adminPermissionsPanel').style.display = tab==='permissions' ? '' : 'none';
            if(tab==='users') loadAdminUsers();
            if(tab==='pending') loadAdminPending();
            if(tab==='permissions') loadPermissions();
        }

        const PAGE_LABELS = {oversikt:'Dashboard',faltsalj:'FältSälj',kunder:'Kunder',projektering:'Projektering',projekt:'Affärer',konfigurator:'Kalkyler',produkter:'Produktkatalog',ekonomi:'Ekonomi',bildgen:'Bildgenerering',personal:'Personal',kalender:'Kalender',inkorg:'Inkorg',dagrapport:'Dagrapport',minlon:'Min Lön',settings:'Inställningar'};
        const PAGE_KEYS = Object.keys(PAGE_LABELS);
        const PERM_ROLES = ['admin','saljchef','saljare','installator','projektledare','ekonomi'];
        let permData = {};
        let permSelectedRole = 'saljare';

        let menuOrder = [];

        async function loadPermissions(){
            try {
                const res = await fetch('/api/permissions.php');
                permData = await res.json();
                renderPermRoleTabs();
                renderPermMatrix();
                await loadMenuOrder();
            } catch(e){ console.error('loadPermissions error', e); }
        }

        async function loadMenuOrder(){
            try {
                const res = await fetch('/api/permissions.php?action=order&t='+Date.now());
                menuOrder = await res.json();
                renderMenuOrder();
            } catch(e){ console.error('loadMenuOrder error', e); }
        }

        function renderMenuOrder(){
            const container = document.getElementById('menuOrderList');
            if(!container) return;
            container.innerHTML = menuOrder.map((key, i) => {
                const label = PAGE_LABELS[key] || key;
                return `<div draggable="true" data-page-key="${key}" style="padding:8px 12px;background:#fff;border:1px solid #e5e7eb;border-radius:8px;font-size:13px;color:#1a1a1a;cursor:grab;display:flex;align-items:center;gap:8px;user-select:none;transition:box-shadow .15s" onmousedown="this.style.cursor='grabbing'" onmouseup="this.style.cursor='grab'"><svg viewBox="0 0 24 24" style="width:14px;height:14px;stroke:#94a3b8;fill:none;stroke-width:2;flex-shrink:0"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>${label}</div>`;
            }).join('');
            // Add drag events
            const items = container.querySelectorAll('[draggable]');
            items.forEach(item => {
                item.addEventListener('dragstart', e => {
                    e.dataTransfer.setData('text/plain', item.dataset.pageKey);
                    item.style.opacity = '0.4';
                });
                item.addEventListener('dragend', e => { item.style.opacity = '1'; });
                item.addEventListener('dragover', e => {
                    e.preventDefault();
                    item.style.boxShadow = '0 -2px 0 #024550';
                });
                item.addEventListener('dragleave', e => { item.style.boxShadow = ''; });
                item.addEventListener('drop', async e => {
                    e.preventDefault();
                    item.style.boxShadow = '';
                    const draggedKey = e.dataTransfer.getData('text/plain');
                    const targetKey = item.dataset.pageKey;
                    if(draggedKey === targetKey) return;
                    const oldIdx = menuOrder.indexOf(draggedKey);
                    const newIdx = menuOrder.indexOf(targetKey);
                    menuOrder.splice(oldIdx, 1);
                    menuOrder.splice(newIdx, 0, draggedKey);
                    renderMenuOrder();
                    await saveMenuOrder();
                    applyNavOrder();
                });
            });
        }

        async function saveMenuOrder(){
            try {
                await fetch('/api/permissions.php?action=order', {
                    method:'POST', headers:{'Content-Type':'application/json'},
                    body: JSON.stringify({ order: menuOrder })
                });
            } catch(e){ console.error('saveMenuOrder error', e); }
        }

        function applyNavOrder(){
            const nav = document.querySelector('.sidebar-nav');
            if(!nav) return;
            const items = Array.from(nav.querySelectorAll('.nav-item[data-page]'));
            const adminItem = items.find(el => el.dataset.page === 'admin');
            items.sort((a, b) => {
                const ai = menuOrder.indexOf(a.dataset.page);
                const bi = menuOrder.indexOf(b.dataset.page);
                return (ai === -1 ? 999 : ai) - (bi === -1 ? 999 : bi);
            });
            items.forEach(item => nav.appendChild(item));
            if(adminItem) nav.appendChild(adminItem);
        }

        function renderPermRoleTabs(){
            const container = document.getElementById('permRoleTabs');
            container.innerHTML = PERM_ROLES.map(r => {
                const active = r === permSelectedRole;
                return `<button onclick="selectPermRole('${r}')" style="padding:8px 16px;border-radius:8px;font-size:13px;font-weight:${active?'600':'500'};cursor:pointer;font-family:inherit;border:1.5px solid ${active?'#024550':'#e5e7eb'};background:${active?'#024550':'#fff'};color:${active?'#fff':'#334155'};transition:all .15s">${ROLE_LABELS[r]}</button>`;
            }).join('');
        }

        function selectPermRole(role){
            permSelectedRole = role;
            renderPermRoleTabs();
            renderPermMatrix();
        }

        function renderPermMatrix(){
            const container = document.getElementById('permMatrixContainer');
            const rolePerms = permData[permSelectedRole] || {};
            let html = '<div style="display:grid;grid-template-columns:1fr auto;gap:0;border:1px solid #e5e7eb;border-radius:10px;overflow:hidden">';
            html += '<div style="padding:10px 16px;background:#f8fafc;font-weight:600;font-size:13px;color:#64748b;border-bottom:1px solid #e5e7eb">Menyval</div>';
            html += '<div style="padding:10px 16px;background:#f8fafc;font-weight:600;font-size:13px;color:#64748b;border-bottom:1px solid #e5e7eb;text-align:center">Synlig</div>';
            PAGE_KEYS.forEach((key, i) => {
                const visible = rolePerms[key] !== undefined ? rolePerms[key] : 1;
                const bg = i % 2 === 0 ? '#fff' : '#fafbfc';
                const border = i < PAGE_KEYS.length - 1 ? 'border-bottom:1px solid #f1f5f9;' : '';
                html += `<div style="padding:10px 16px;font-size:14px;color:#1a1a1a;${border}background:${bg};display:flex;align-items:center;gap:10px">${PAGE_LABELS[key]}</div>`;
                html += `<div style="padding:10px 16px;text-align:center;${border}background:${bg}">`;
                html += `<label style="position:relative;display:inline-block;width:44px;height:24px;cursor:pointer">`;
                html += `<input type="checkbox" ${visible?'checked':''} onchange="togglePerm('${key}',this.checked)" style="opacity:0;width:0;height:0">`;
                html += `<span style="position:absolute;inset:0;background:${visible?'#10b981':'#e5e7eb'};border-radius:24px;transition:all .2s"></span>`;
                html += `<span style="position:absolute;left:${visible?'22px':'2px'};top:2px;width:20px;height:20px;background:#fff;border-radius:50%;transition:all .2s;box-shadow:0 1px 3px rgba(0,0,0,.15)"></span>`;
                html += '</label></div>';
            });
            html += '</div>';
            container.innerHTML = html;
        }

        async function togglePerm(pageKey, visible){
            if(!permData[permSelectedRole]) permData[permSelectedRole] = {};
            permData[permSelectedRole][pageKey] = visible ? 1 : 0;
            renderPermMatrix();
            try {
                await fetch('/api/permissions.php', {
                    method:'POST', headers:{'Content-Type':'application/json'},
                    body: JSON.stringify({ role: permSelectedRole, permissions: { [pageKey]: visible ? 1 : 0 } })
                });
            } catch(e){ console.error('togglePerm error', e); }
            if(permSelectedRole === gUserRole) applyNavPermissions();
        }

        async function applyNavPermissions(){
            try {
                const res = await fetch('/api/permissions.php?role=' + encodeURIComponent(gUserRole || 'saljare') + '&t=' + Date.now());
                const data = await res.json();
                const perms = data.permissions || data;
                const order = data.order || [];
                if(gUserRole !== 'systemadmin') {
                    document.querySelectorAll('.nav-item[data-page]').forEach(el => {
                        const page = el.dataset.page;
                        if(page === 'admin') return;
                        if(perms[page] !== undefined) {
                            el.style.display = perms[page] ? '' : 'none';
                        }
                    });
                }
                if(order.length > 0) {
                    menuOrder = order;
                    applyNavOrder();
                }
            } catch(e){ console.error('applyNavPermissions error', e); }
        }

        const ROLE_LABELS = {systemadmin:'Systemadmin', admin:'Admin', saljchef:'Säljchef', saljare:'Säljare', installator:'Installatör', projektledare:'Projektledare', ekonomi:'Ekonomi', pending:'Väntande'};
        const ROLE_OPTIONS = ['admin','saljchef','saljare','installator','projektledare','ekonomi'];

        let allAdminUsers = [];
        async function loadAdminUsers(){
            try {
                const res = await fetch('/api/staff.php?active=0&t='+Date.now());
                const users = await res.json();
                allAdminUsers = users.filter(u => u.approved == 1 && u.role !== 'systemadmin');
                filterAdminUsers();
            } catch(err){
                console.error('loadAdminUsers error:', err);
            }
        }

        function filterAdminUsers(){
            const search = (document.getElementById('adminUserSearch')?.value || '').toLowerCase();
            const roleFilter = document.getElementById('adminUserRoleFilter')?.value || '';
            let filtered = allAdminUsers;
            if(search) filtered = filtered.filter(u => (u.name||'').toLowerCase().includes(search) || (u.email||'').toLowerCase().includes(search));
            if(roleFilter) filtered = filtered.filter(u => u.role === roleFilter);
            const tbody = document.getElementById('adminUsersBody');
            document.getElementById('adminUserCount').textContent = filtered.length + ' av ' + allAdminUsers.length + ' användare';
            tbody.innerHTML = filtered.map(u => {
                    const roleOpts = ROLE_OPTIONS.map(r => '<option value="'+r+'"'+(u.role===r?' selected':'')+'>'+ROLE_LABELS[r]+'</option>').join('');
                    const lastLogin = u.last_login ? new Date(u.last_login).toLocaleDateString('sv-SE') : '—';
                    return '<tr style="border-bottom:1px solid #f1f5f9">'
                        +'<td style="padding:10px 12px;font-weight:500">'+escHtml(u.name)+'</td>'
                        +'<td style="padding:10px 12px;color:#64748b">'+escHtml(u.email)+'</td>'
                        +'<td style="padding:10px 12px"><select onchange="changeUserRole('+u.id+',this.value)" style="padding:4px 8px;border:1px solid #e5e7eb;border-radius:6px;font-size:12px;font-family:inherit;background:#fff;cursor:pointer">'+roleOpts+'</select></td>'
                        +'<td style="padding:10px 12px;color:#64748b;font-size:12px">'+(u.phone||'—')+'</td>'
                        +'<td style="padding:10px 12px;text-align:center"><button onclick="toggleUserActive('+u.id+','+(u.active?0:1)+')" style="width:36px;height:20px;border-radius:10px;border:none;cursor:pointer;background:'+(u.active==1?'#059669':'#cbd5e1')+';position:relative;transition:background .2s"><span style="position:absolute;top:2px;'+(u.active==1?'right:2px':'left:2px')+';width:16px;height:16px;background:#fff;border-radius:50%;transition:all .2s"></span></button></td>'
                        +'<td style="padding:10px 12px;color:#94a3b8;font-size:12px">'+lastLogin+'</td>'
                        +'<td style="padding:10px 12px;text-align:center"><button onclick="deleteUser('+u.id+',\''+escHtml(u.name)+'\')" style="background:none;border:none;cursor:pointer;color:#ef4444;font-size:14px" title="Ta bort">&times;</button></td>'
                        +'</tr>';
                }).join('');
        }

        async function loadAdminPending(){
            try {
                const res = await fetch('/api/staff.php?approved=0&t='+Date.now());
                const pending = await res.json();
                const listEl = document.getElementById('adminPendingList');
                const emptyEl = document.getElementById('adminPendingEmpty');
                const countEl = document.getElementById('adminPendingCount');
                const badgeEl = document.getElementById('adminPendingBadge');

                if(pending.length === 0){
                    emptyEl.style.display='block';
                    listEl.style.display='none';
                    if(countEl) countEl.style.display='none';
                    if(badgeEl) badgeEl.style.display='none';
                    return;
                }

                emptyEl.style.display='none';
                listEl.style.display='flex';
                if(countEl){ countEl.textContent=pending.length; countEl.style.display='inline'; }
                if(badgeEl){ badgeEl.textContent=pending.length; badgeEl.style.display='inline'; }

                listEl.innerHTML = pending.map(u => {
                    const created = u.created_at ? new Date(u.created_at).toLocaleDateString('sv-SE') : '—';
                    const roleOpts = ROLE_OPTIONS.map(r => '<option value="'+r+'"'+(r==='saljare'?' selected':'')+'>'+ROLE_LABELS[r]+'</option>').join('');
                    return '<div style="background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:16px;display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap">'
                        +'<div style="flex:1;min-width:200px">'
                        +'<div style="font-weight:600;font-size:15px;color:#1e293b">'+escHtml(u.name)+'</div>'
                        +'<div style="font-size:13px;color:#64748b;margin-top:2px">'+escHtml(u.email)+'</div>'
                        +'<div style="font-size:11px;color:#94a3b8;margin-top:4px">Registrerad: '+created+'</div>'
                        +'</div>'
                        +'<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">'
                        +'<select id="pendingRole_'+u.id+'" style="padding:6px 10px;border:1px solid #e5e7eb;border-radius:8px;font-size:12px;font-family:inherit;background:#fff">'+roleOpts+'</select>'
                        +'<button onclick="approveUser('+u.id+')" style="padding:6px 16px;background:#059669;color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit">Godkänn</button>'
                        +'<button onclick="rejectUser('+u.id+',\''+escHtml(u.name)+'\')" style="padding:6px 16px;background:#ef4444;color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit">Neka</button>'
                        +'</div></div>';
                }).join('');
            } catch(err){
                console.error('loadAdminPending error:', err);
            }
        }

        async function approveUser(id){
            const roleSelect = document.getElementById('pendingRole_'+id);
            const role = roleSelect ? roleSelect.value : 'saljare';
            try {
                await fetch('/api/staff.php?id='+id, {
                    method:'PUT', headers:{'Content-Type':'application/json'},
                    body: JSON.stringify({approved:1, role:role, active:1})
                });
                // Skicka välkomstmail
                try {
                    const userRes = await fetch('/api/staff.php?id='+id);
                    const user = await userRes.json();
                    if(user && user.email){
                        await fetch('/api/mail.php', {
                            method:'POST', headers:{'Content-Type':'application/json'},
                            body: JSON.stringify({
                                to: user.email,
                                subject: 'Välkommen till SolarGroup!',
                                body: '<h2>Välkommen '+escHtml(user.name)+'!</h2><p>Ditt konto har godkänts. Du kan nu logga in på <a href="https://prodconfig.wenesthosting.com">Solar Sales Suite</a>.</p><p>Din roll: <strong>'+ROLE_LABELS[role]+'</strong></p><br><p>Med vänliga hälsningar,<br>SolarGroup Admin</p>'
                            })
                        });
                    }
                } catch(mailErr){ console.warn('Welcome mail failed:', mailErr); }
                loadAdminPending();
                loadAdminUsers();
            } catch(err){ alert('Fel: '+err.message); }
        }

        async function rejectUser(id, name){
            if(!confirm('Neka och ta bort '+name+'?')) return;
            try {
                await fetch('/api/staff.php?id='+id, { method:'DELETE' });
                loadAdminPending();
            } catch(err){ alert('Fel: '+err.message); }
        }

        async function changeUserRole(id, role){
            try {
                await fetch('/api/staff.php?id='+id, {
                    method:'PUT', headers:{'Content-Type':'application/json'},
                    body: JSON.stringify({role:role})
                });
            } catch(err){ alert('Fel: '+err.message); }
        }

        async function toggleUserActive(id, active){
            try {
                await fetch('/api/staff.php?id='+id, {
                    method:'PUT', headers:{'Content-Type':'application/json'},
                    body: JSON.stringify({active:active})
                });
                loadAdminUsers();
            } catch(err){ alert('Fel: '+err.message); }
        }

        async function deleteUser(id, name){
            if(!confirm('Ta bort '+name+'? Detta kan inte ångras.')) return;
            try {
                await fetch('/api/staff.php?id='+id, { method:'DELETE' });
                loadAdminUsers();
            } catch(err){ alert('Fel: '+err.message); }
        }

        function escHtml(s){ return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }

        // Ladda admin-data när sidan visas
        function initAdminPage(){
            loadAdminUsers();
            loadAdminPending();
        }

        // Kolla väntande vid start (för badge)
        async function checkPendingUsers(){
            if(gUserRole !== 'systemadmin' && gUserRole !== 'admin' && gUserRole !== 'saljchef') return;
            try {
                const res = await fetch('/api/staff.php?approved=0&t='+Date.now());
                const pending = await res.json();
                const badge = document.getElementById('adminPendingBadge');
                if(badge){
                    if(pending.length > 0){
                        badge.textContent = pending.length;
                        badge.style.display = 'inline';
                    } else {
                        badge.style.display = 'none';
                    }
                }
            } catch(e){}
        }

        /* === BILDGENERERING === */
        let bgUploadedImage = null;
        let bgGeneratedImages = JSON.parse(localStorage.getItem('bgGallery') || '[]');

        function handleBgUpload(input) {
            const file = input.files?.[0];
            if (!file) return;
            const reader = new FileReader();
            reader.onload = function(e) {
                const img = new Image();
                img.onload = function() {
                    const canvas = document.createElement('canvas');
                    canvas.width = img.width;
                    canvas.height = img.height;
                    canvas.getContext('2d').drawImage(img, 0, 0);
                    bgUploadedImage = canvas.toDataURL('image/jpeg', 0.85);
                    document.getElementById('bgPreviewImg').src = bgUploadedImage;
                    document.getElementById('bgPreview').style.display = 'block';
                };
                img.src = e.target.result;
            };
            reader.readAsDataURL(file);
        }

        function clearBgUpload() {
            bgUploadedImage = null;
            document.getElementById('bgPreview').style.display = 'none';
            document.getElementById('bgFileInput').value = '';
            document.getElementById('bgCameraInput').value = '';
        }

        // === Bildgenerering — produktval med inbyggda prompts ===
        const bgProducts = {
            solceller: {
                label: 'Solceller', icon: '☀️',
                hasCount: true, countLabel: 'Antal paneler', countOptions: [6,8,10,12,14,16,18,20,24,28,32,36,40],
                prompt: 'Install solar panels on the roof of this house. Professional installation, realistic mounting system visible.',
                subs: [
                    {label:'Svarta paneler', extra:'All-black premium solar panels with black frames and black backsheet'},
                    {label:'Blå paneler', extra:'Traditional blue polycrystalline solar panels with silver frames'},
                    {label:'Integrerade (BIPV)', extra:'Building-integrated photovoltaic roof tiles that replace traditional roofing material, seamless look'},
                ]
            },
            takbyte: {
                label: 'Takbyte', icon: '🏠',
                prompt: 'Replace the roof on this house with new roofing material. Show the complete house with the new roof installed. Wide angle view showing the entire building.',
                subs: [
                    {label:'Betongpannor röda', extra:'Red concrete roof tiles, traditional Scandinavian style'},
                    {label:'Betongpannor svarta', extra:'Black/dark grey concrete roof tiles, modern Scandinavian look'},
                    {label:'Plåttak svart', extra:'Standing seam black metal roof, sleek modern appearance'},
                    {label:'Tegelpannor', extra:'Classic clay/terracotta roof tiles, warm orange-red tones'},
                ]
            },
            fonster: {
                label: 'Fönster', icon: '🪟',
                prompt: 'Replace the windows on this house with new modern energy-efficient windows. Show the entire house with new windows installed.',
                subs: [
                    {label:'Vita träfönster', extra:'White wooden windows with traditional Swedish style, double-pane'},
                    {label:'Svarta aluminium', extra:'Black aluminum frame windows, large glass surfaces, modern minimalist'},
                    {label:'Spröjsade', extra:'Windows with glazing bars (spröjs), classic Scandinavian cottage style'},
                ]
            },
            fasad: {
                label: 'Fasadrenovering', icon: '🏗️',
                prompt: 'Renovate the facade of this house. Show the complete building with the new facade finish.',
                subs: [
                    {label:'Vit puts', extra:'Clean white stucco/plaster facade, modern Scandinavian minimalism'},
                    {label:'Gul träpanel', extra:'Traditional Swedish yellow painted wooden siding (Falu-style)'},
                    {label:'Grå träpanel', extra:'Modern grey-stained wooden cladding, contemporary Nordic style'},
                    {label:'Röd Falu', extra:'Classic Falu red (Falu rödfärg) painted wooden facade, iconic Swedish look'},
                ]
            },
            laddbox: {
                label: 'Laddbox', icon: '⚡',
                prompt: 'Add an EV charger/wallbox to this house. Show the charging station mounted on the wall near the driveway or garage.',
                subs: [
                    {label:'Zaptec Go', extra:'Sleek white Zaptec Go wallbox charger mounted on wall'},
                    {label:'Garo Entity', extra:'Garo Entity Pro wallbox, dark grey, wall-mounted'},
                    {label:'Easee Home', extra:'Compact Easee Home charger in white, minimalist design'},
                ]
            },
            batteri: {
                label: 'Batteri', icon: '🔋',
                prompt: 'Add a home battery energy storage system to this house. Show the battery unit installed on an interior or exterior wall.',
                subs: [
                    {label:'Huawei LUNA', extra:'Huawei LUNA 2000 battery stack, white modular units'},
                    {label:'SolarEdge Home', extra:'SolarEdge Home Battery, compact dark grey unit'},
                    {label:'Tesla Powerwall', extra:'Tesla Powerwall, sleek white wall-mounted unit'},
                ]
            },
            varmepump: {
                label: 'Värmepump', icon: '🌡️',
                prompt: 'Add an air source heat pump to this house. Show the outdoor unit installed on the side of the building.',
                subs: [
                    {label:'Panasonic', extra:'Panasonic Aquarea outdoor unit, white, professional installation'},
                    {label:'Mitsubishi', extra:'Mitsubishi Ecodan outdoor heat pump unit'},
                    {label:'Nibe', extra:'Nibe air-to-water heat pump outdoor unit, Swedish brand'},
                ]
            },
            kombination: {
                label: 'Kombination', icon: '🏡',
                prompt: 'Complete renovation of this house showing multiple improvements installed together.',
                subs: [
                    {label:'Sol + Tak', extra:'New roof with solar panels installed on top, complete makeover'},
                    {label:'Sol + Batteri + Laddbox', extra:'Solar panels on roof, battery storage and EV charger on wall'},
                    {label:'Helrenovering', extra:'New roof, new windows, new facade, solar panels - complete transformation'},
                ]
            },
        };
        let bgSelectedProduct = null;
        let bgSelectedSub = null;
        let bgSelectedCount = null;

        function initBgOptions() {
            const grid = document.getElementById('bgOptionGrid');
            if(!grid) return;
            grid.innerHTML = Object.entries(bgProducts).map(([key, p]) =>
                '<div onclick="selectBgProduct(\''+key+'\')" id="bgOpt_'+key+'" style="padding:14px;border:2px solid #e5e7eb;border-radius:10px;cursor:pointer;text-align:center;transition:all .15s;background:#fafbfc">'
                +'<div style="font-size:24px;margin-bottom:4px">'+p.icon+'</div>'
                +'<div style="font-size:13px;font-weight:600;color:#1a1a1a">'+p.label+'</div>'
                +'</div>'
            ).join('');
        }

        function selectBgProduct(key) {
            bgSelectedProduct = key;
            bgSelectedSub = null;
            bgSelectedCount = null;
            const p = bgProducts[key];
            document.getElementById('bgProjectType').value = p.label;
            document.getElementById('bgPrompt').value = p.prompt;

            // Highlight selected
            document.querySelectorAll('#bgOptionGrid > div').forEach(d => {
                d.style.borderColor = '#e5e7eb'; d.style.background = '#fafbfc';
            });
            const sel = document.getElementById('bgOpt_'+key);
            if(sel){ sel.style.borderColor = '#024550'; sel.style.background = '#f0fdfa'; }

            // Show sub-options
            const panel = document.getElementById('bgDetailsPanel');
            const subGrid = document.getElementById('bgSubOptions');
            if(p.subs && p.subs.length) {
                panel.style.display = 'block';
                subGrid.innerHTML = p.subs.map((s, i) =>
                    '<div onclick="selectBgSub('+i+')" id="bgSub_'+i+'" style="padding:10px;border:2px solid #e5e7eb;border-radius:8px;cursor:pointer;text-align:center;transition:all .15s;background:#fafbfc">'
                    +'<div style="font-size:12px;font-weight:600;color:#1a1a1a">'+s.label+'</div>'
                    +'</div>'
                ).join('');
            } else {
                panel.style.display = 'none';
            }

            // Show count selector if product has it
            const countPanel = document.getElementById('bgCountPanel');
            if(p.hasCount && p.countOptions) {
                countPanel.style.display = 'block';
                document.getElementById('bgCountLabel').textContent = p.countLabel || 'Antal';
                document.getElementById('bgCountOptions').innerHTML = p.countOptions.map(n =>
                    '<div onclick="selectBgCount('+n+')" id="bgCount_'+n+'" style="padding:8px 14px;border:2px solid #e5e7eb;border-radius:8px;cursor:pointer;text-align:center;transition:all .15s;background:#fafbfc;min-width:44px">'
                    +'<div style="font-size:13px;font-weight:600;color:#1a1a1a">'+n+'</div>'
                    +'</div>'
                ).join('');
            } else {
                countPanel.style.display = 'none';
            }
        }

        function selectBgSub(idx) {
            bgSelectedSub = idx;
            const p = bgProducts[bgSelectedProduct];
            const sub = p.subs[idx];
            updateBgPrompt();

            document.querySelectorAll('#bgSubOptions > div').forEach(d => {
                d.style.borderColor = '#e5e7eb'; d.style.background = '#fafbfc';
            });
            const sel = document.getElementById('bgSub_'+idx);
            if(sel){ sel.style.borderColor = '#024550'; sel.style.background = '#f0fdfa'; }
        }

        function selectBgCount(n) {
            bgSelectedCount = n;
            updateBgPrompt();

            document.querySelectorAll('#bgCountOptions > div').forEach(d => {
                d.style.borderColor = '#e5e7eb'; d.style.background = '#fafbfc';
            });
            const sel = document.getElementById('bgCount_'+n);
            if(sel){ sel.style.borderColor = '#024550'; sel.style.background = '#f0fdfa'; }
        }

        function updateBgPrompt() {
            const p = bgProducts[bgSelectedProduct];
            if(!p) return;
            let prompt = p.prompt;
            if(bgSelectedSub !== null && p.subs[bgSelectedSub]) {
                prompt += ' ' + p.subs[bgSelectedSub].extra;
            }
            if(bgSelectedCount && p.hasCount) {
                const rows = bgSelectedCount <= 8 ? 2 : bgSelectedCount <= 18 ? 2 : 3;
                const cols = Math.ceil(bgSelectedCount / rows);
                prompt += ' CRITICAL: Place EXACTLY ' + bgSelectedCount + ' solar panels on the roof — arranged as ' + rows + ' rows x ' + cols + ' columns. There must be precisely ' + bgSelectedCount + ' panels total, not more and not less.';
            }
            document.getElementById('bgPrompt').value = prompt;
        }

        // Init options on page load
        setTimeout(initBgOptions, 100);

        async function generateBgImage() {
            const prompt = document.getElementById('bgPrompt').value.trim();
            const projectType = document.getElementById('bgProjectType').value;
            const extra = document.getElementById('bgExtraPrompt')?.value?.trim() || '';
            if (!prompt || !projectType) { alert('Välj en produkttyp först'); return; }

            const fullPrompt = bgUploadedImage
                ? prompt + (extra ? '. ' + extra : '')
                : prompt + (extra ? '. Additional details: ' + extra : '') + '. Show the ENTIRE house from street level, wide angle, full building visible. Photorealistic, professional photography, Scandinavian architecture.';

            const btn = document.getElementById('bgGenerateBtn');
            btn.disabled = true;
            btn.textContent = 'Genererar...';
            document.getElementById('bgPlaceholder').style.display = 'none';
            document.getElementById('bgResult').style.display = 'none';
            document.getElementById('bgLoading').style.display = 'flex';

            try {
                const provider = document.getElementById('bgProvider').value;
                const res = await fetch('/api/generate.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        prompt: fullPrompt,
                        projectType: projectType,
                        baseImage: bgUploadedImage,
                        provider: provider
                    })
                });
                const data = await res.json();
                if (data.error) throw new Error(data.error);

                document.getElementById('bgLoading').style.display = 'none';
                document.getElementById('bgResult').style.display = 'block';
                document.getElementById('bgResultImg').src = data.base64 || data.imageUrl;

                bgGeneratedImages.unshift({
                    url: data.imageUrl,
                    base64: data.base64,
                    prompt: projectType + (bgSelectedSub !== null ? ' - ' + bgProducts[bgSelectedProduct].subs[bgSelectedSub].label : ''),
                    type: projectType,
                    date: new Date().toISOString().split('T')[0]
                });
                if (bgGeneratedImages.length > 20) bgGeneratedImages = bgGeneratedImages.slice(0, 20);
                try { localStorage.setItem('bgGallery', JSON.stringify(bgGeneratedImages)); } catch(e) {}
                renderBgGallery();

            } catch (err) {
                document.getElementById('bgLoading').style.display = 'none';
                document.getElementById('bgPlaceholder').style.display = 'flex';
                alert('Fel: ' + err.message);
            } finally {
                btn.disabled = false;
                btn.textContent = 'Generera bild';
            }
        }

        function downloadBgImage() {
            const img = document.getElementById('bgResultImg');
            if (!img.src) return;
            const a = document.createElement('a');
            a.href = img.src;
            a.download = 'visualization-' + Date.now() + '.png';
            a.click();
        }

        function resetBgResult() {
            document.getElementById('bgResult').style.display = 'none';
            document.getElementById('bgPlaceholder').style.display = 'flex';
        }

        function renderBgGallery() {
            const grid = document.getElementById('bgGalleryGrid');
            const container = document.getElementById('bgGallery');
            if (!bgGeneratedImages.length) { container.style.display = 'none'; return; }
            container.style.display = 'block';
            grid.innerHTML = bgGeneratedImages.map((img, i) =>
                '<div style="position:relative;cursor:pointer" onclick="document.getElementById(\'bgResult\').style.display=\'block\';document.getElementById(\'bgPlaceholder\').style.display=\'none\';document.getElementById(\'bgLoading\').style.display=\'none\';document.getElementById(\'bgResultImg\').src=\'' + (img.base64 || img.url) + '\'">' +
                '<img src="' + (img.base64 || img.url) + '" style="width:100%;aspect-ratio:4/3;object-fit:cover;border-radius:8px;border:1px solid #e5e7eb">' +
                '<div style="position:absolute;bottom:0;left:0;right:0;background:linear-gradient(transparent,rgba(0,0,0,.7));color:#fff;padding:6px 8px;border-radius:0 0 8px 8px;font-size:10px">' + img.type + ' • ' + img.date + '</div>' +
                '</div>'
            ).join('');
        }
        renderBgGallery();

        // === SETTINGS TABS ===
        function switchSettingsTab(tab) {
            document.querySelectorAll('.settings-tab').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.settings-panel').forEach(p => p.classList.remove('active'));
            document.querySelector('[data-settings-tab="' + tab + '"]').classList.add('active');
            document.getElementById('settings-' + tab).classList.add('active');
            if (tab === 'google') loadGoogleSettings();
            if (tab === 'ai') loadAiSettings();
            if (tab === 'monday') loadMondaySettings();
        }

        // === GOOGLE SETTINGS ===
        async function loadGoogleSettings() {
            const uriEl = document.getElementById('googleRedirectUri');
            if (uriEl) uriEl.textContent = window.location.origin;
            try {
                const res = await fetch('/api/settings.php?keys=google_client_id,google_client_secret,google_maps_key');
                const data = await res.json();
                if (data.settings) {
                    document.getElementById('settGoogleClientId').value = data.settings.google_client_id || '';
                    document.getElementById('settGoogleClientSecret').value = data.settings.google_client_secret_set ? '••••••••' : '';
                    if (data.settings.google_client_secret_set) {
                        document.getElementById('settGoogleSecretStatus').textContent = 'Konfigurerad';
                    }
                    document.getElementById('settGoogleMapsKey').value = data.settings.google_maps_key || '';
                }
            } catch(e) {}
        }

        async function saveGoogleSettings() {
            const settings = {};
            const clientId = document.getElementById('settGoogleClientId').value.trim();
            const secret = document.getElementById('settGoogleClientSecret').value.trim();
            const mapsKey = document.getElementById('settGoogleMapsKey').value.trim();
            if (clientId) settings.google_client_id = clientId;
            if (secret && !secret.startsWith('••')) settings.google_client_secret = secret;
            if (mapsKey) settings.google_maps_key = mapsKey;
            try {
                const res = await fetch('/api/settings.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({settings})
                });
                const data = await res.json();
                const msg = document.getElementById('googleSettingsMsg');
                if (data.success) {
                    msg.innerHTML = '<span style="color:#10b981;font-weight:600">Sparat!</span>';
                    setTimeout(() => msg.textContent = '', 3000);
                } else {
                    msg.innerHTML = '<span style="color:#ef4444">' + (data.error || 'Fel') + '</span>';
                }
            } catch(e) {
                document.getElementById('googleSettingsMsg').innerHTML = '<span style="color:#ef4444">Nätverksfel</span>';
            }
        }

        // === GOOGLE OAUTH + GMAIL + CALENDAR ===
        let gAccessToken = sessionStorage.getItem('gAccessToken') || '';
        let gTokenExpiry = parseInt(sessionStorage.getItem('gTokenExpiry') || '0');
        let gStaffId = parseInt(sessionStorage.getItem('gStaffId') || '0');
        let gUserEmail = sessionStorage.getItem('gUserEmail') || '';
        let gUserName = sessionStorage.getItem('gUserName') || '';
        let gUserAvatar = sessionStorage.getItem('gUserAvatar') || '';
        let gMailSignature = localStorage.getItem('mailSignature') || '';

        const GOOGLE_SCOPES = 'openid email profile https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/gmail.send https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.readonly';
        const LOGIN_SCOPES = 'openid email profile';

        async function initGoogleAuth() {
            // Load GIS library if not present
            if (!window.google?.accounts?.oauth2) {
                const script = document.createElement('script');
                script.src = 'https://accounts.google.com/gsi/client';
                script.async = true;
                document.head.appendChild(script);
                await new Promise(r => script.onload = r);
            }
            // Get client ID from settings
            try {
                const res = await fetch('/api/settings.php?keys=google_client_id');
                const data = await res.json();
                return data.settings?.google_client_id || '';
            } catch(e) { return ''; }
        }

        async function googleLogin() {
            const clientId = await initGoogleAuth();
            if (!clientId) {
                alert('Google Client ID inte konfigurerat. Gå till Inställningar → Google API.');
                return;
            }
            const client = google.accounts.oauth2.initCodeClient({
                client_id: clientId,
                scope: GOOGLE_SCOPES,
                ux_mode: 'popup',
                redirect_uri: window.location.origin,
                callback: async (response) => {
                    if (response.error) { alert('Google login misslyckades: ' + response.error); return; }
                    try {
                        const res = await fetch('/api/google-token.php', {
                            method: 'POST',
                            headers: {'Content-Type': 'application/json'},
                            body: JSON.stringify({
                                action: 'exchange',
                                code: response.code,
                                redirectUri: window.location.origin
                            })
                        });
                        const data = await res.json();
                        if (data.error) { const errEl = document.getElementById("loginError"); const pendEl = document.getElementById("loginPending"); if(errEl) errEl.style.display="none"; if(pendEl) pendEl.style.display="none"; if(data.pending) { if(pendEl){ pendEl.textContent=data.error; pendEl.style.display="block"; } } else { if(errEl){ errEl.textContent=data.error; errEl.style.display="block"; } } return; }
                        gAccessToken = data.accessToken;
                        gTokenExpiry = Date.now() + (data.expiresIn * 1000);
                        gStaffId = data.user.id;
                        gUserEmail = data.user.email;
                        gUserName = data.user.name;
                        gUserAvatar = data.user.avatar_url || '';
                        gUserRole = data.user.role || '';
                        gMailSignature = data.user.mail_signature || '';
                        sessionStorage.setItem('gAccessToken', gAccessToken);
                        sessionStorage.setItem('gTokenExpiry', gTokenExpiry);
                        sessionStorage.setItem('gStaffId', gStaffId);
                        sessionStorage.setItem('gUserEmail', gUserEmail);
                        sessionStorage.setItem('gUserName', gUserName);
                        sessionStorage.setItem('gUserAvatar', gUserAvatar);
                        sessionStorage.setItem('gUserRole', gUserRole);
                        localStorage.setItem('mailSignature', gMailSignature);
                        updateAuthUI();
                        // Auto-load mail and calendar
                        if (document.getElementById('page-inkorg').classList.contains('active')) loadGmailInbox();
                        if (document.getElementById('page-kalender').classList.contains('active')) loadCalendarEvents();
                    } catch(e) { alert('Anslutningsfel: ' + e.message); }
                }
            });
            client.requestCode();
        }

        async function ensureToken() {
            if (!gAccessToken) return false;
            if (Date.now() > gTokenExpiry - 60000) {
                // Token expired or about to expire, refresh
                try {
                    const res = await fetch('/api/google-token.php', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({ action: 'refresh', staffId: gStaffId })
                    });
                    const data = await res.json();
                    if (data.accessToken) {
                        gAccessToken = data.accessToken;
                        gTokenExpiry = Date.now() + (data.expiresIn * 1000);
                        sessionStorage.setItem('gAccessToken', gAccessToken);
                        sessionStorage.setItem('gTokenExpiry', gTokenExpiry);
                        return true;
                    }
                } catch(e) {}
                return false;
            }
            return true;
        }

        function updateAuthUI() {
            const loginRequired = !gAccessToken;
            // Mail page
            const mailLogin = document.getElementById('mailLogin');
            const mailClient = document.getElementById('mailClient');
            if (loginRequired) {
                if (mailLogin) { mailLogin.style.display = 'block'; mailLogin.innerHTML = '<div style="text-align:center;padding:40px"><p style="font-size:16px;color:#334155;margin-bottom:16px">Logga in med Google för att ansluta din e-post och kalender</p><button onclick="googleLogin()" style="padding:12px 28px;background:#024550;color:#fff;border:none;border-radius:10px;font-size:15px;font-weight:600;cursor:pointer;font-family:inherit">Logga in med Google</button></div>'; }
                if (mailClient) mailClient.style.display = 'none';
            } else {
                if (mailLogin) mailLogin.style.display = 'none';
                if (mailClient) mailClient.style.display = 'block';
            }
            // Calendar page
            const calSetup = document.getElementById('calSetup');
            if (calSetup) {
                if (loginRequired) {
                    calSetup.innerHTML = '<div style="text-align:center;padding:20px"><p style="font-size:16px;color:#334155;margin-bottom:16px">Logga in med Google för att visa din kalender</p><button onclick="googleLogin()" style="padding:12px 28px;background:#024550;color:#fff;border:none;border-radius:10px;font-size:15px;font-weight:600;cursor:pointer;font-family:inherit">Logga in med Google</button></div>';
                } else {
                    calSetup.innerHTML = '<div style="display:flex;align-items:center;gap:12px"><div style="width:36px;height:36px;border-radius:50%;background:#f0fdf4;display:flex;align-items:center;justify-content:center"><span style="color:#10b981;font-size:18px">&#10003;</span></div><div><strong style="font-size:14px">' + gUserName + '</strong><br><span style="font-size:12px;color:#64748b">' + gUserEmail + '</span></div></div>';
                }
            }
        }

        // === GMAIL CLIENT ===
        let gmailLabel = 'INBOX';
        let gmailNextPage = null;
        let gmailCurrentId = null;

        async function loadGmailInbox(pageToken) {
            if (!await ensureToken()) { updateAuthUI(); return; }
            const list = document.getElementById('mailList');
            const loading = document.getElementById('mailListLoading');
            if (loading) loading.style.display = 'block';

            const search = document.getElementById('mailSearch')?.value || '';
            const params = { action: 'list', accessToken: gAccessToken, label: gmailLabel, maxResults: 25 };
            if (search) params.q = search;
            if (pageToken) params.pageToken = pageToken;

            try {
                const res = await fetch('/api/gmail-proxy.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(params)
                });
                const data = await res.json();
                if (data.error === 'TOKEN_EXPIRED') { gAccessToken = ''; updateAuthUI(); return; }
                if (data.error) throw new Error(data.error);

                gmailNextPage = data.nextPageToken;
                const count = document.getElementById('mailCount');
                if (count) count.textContent = (data.resultSizeEstimate || 0) + ' meddelanden';

                if (list) {
                    list.innerHTML = data.messages.map(m => {
                        const fromName = m.from.replace(/<.*>/, '').trim() || m.from;
                        const isActive = m.id === gmailCurrentId;
                        return '<div onclick="readGmail(\'' + m.id + '\')" style="padding:12px 16px;border-bottom:1px solid #f1f5f9;cursor:pointer;background:' + (isActive ? '#eff6ff' : (m.unread ? '#fefce8' : '#fff')) + ';transition:background .15s' + '">'
                            + '<div style="display:flex;justify-content:space-between;align-items:start">'
                            + '<strong style="font-size:13px;font-weight:' + (m.unread ? '700' : '500') + ';color:#1a1a1a;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:220px">' + escHtml(fromName) + '</strong>'
                            + '<span style="font-size:11px;color:#94a3b8;white-space:nowrap;margin-left:8px">' + formatMailDate(m.timestamp) + '</span>'
                            + '</div>'
                            + '<div style="font-size:13px;color:#334155;font-weight:' + (m.unread ? '600' : '400') + ';overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-top:2px">' + escHtml(m.subject) + '</div>'
                            + '<div style="font-size:12px;color:#94a3b8;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-top:2px">' + escHtml(m.snippet) + '</div>'
                            + '</div>';
                    }).join('');
                }

                // Pagination
                const pag = document.getElementById('mailPagination');
                if (pag) {
                    pag.innerHTML = gmailNextPage
                        ? '<button onclick="loadGmailInbox(\'' + gmailNextPage + '\')" style="padding:6px 16px;background:#f1f5f9;border:1px solid #e5e7eb;border-radius:6px;font-size:12px;cursor:pointer;font-family:inherit">Visa fler</button>'
                        : '';
                }
            } catch(e) {
                if (list) list.innerHTML = '<div style="padding:20px;text-align:center;color:#ef4444;font-size:13px">' + e.message + '</div>';
            }
            if (loading) loading.style.display = 'none';
        }

        async function readGmail(id) {
            if (!await ensureToken()) return;
            gmailCurrentId = id;
            // Highlight in list
            loadGmailInbox();

            const content = document.getElementById('mailReaderContent');
            const empty = document.getElementById('mailReaderEmpty');
            if (empty) empty.style.display = 'none';
            if (content) { content.style.display = 'block'; content.innerHTML = '<div style="text-align:center;padding:40px;color:#94a3b8">Laddar...</div>'; }

            try {
                const res = await fetch('/api/gmail-proxy.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ action: 'read', accessToken: gAccessToken, id })
                });
                const data = await res.json();
                if (data.error) throw new Error(data.error);

                const fromName = data.from.replace(/<.*>/, '').trim();
                const fromEmail = (data.from.match(/<(.+)>/) || ['', data.from])[1];
                const dateStr = new Date(data.timestamp * 1000).toLocaleString('sv-SE');

                content.innerHTML = '<div style="margin-bottom:20px">'
                    + '<h2 style="font-size:18px;font-weight:700;color:#1a1a1a;margin-bottom:12px">' + escHtml(data.subject) + '</h2>'
                    + '<div style="display:flex;justify-content:space-between;align-items:start;flex-wrap:wrap;gap:8px">'
                    + '<div><strong style="font-size:14px">' + escHtml(fromName) + '</strong><br><span style="font-size:12px;color:#64748b">' + escHtml(fromEmail) + '</span>'
                    + (data.cc ? '<br><span style="font-size:12px;color:#94a3b8">Cc: ' + escHtml(data.cc) + '</span>' : '') + '</div>'
                    + '<span style="font-size:12px;color:#94a3b8">' + dateStr + '</span>'
                    + '</div>'
                    + '<div style="display:flex;gap:6px;margin-top:12px">'
                    + '<button onclick="mailReply(\'' + id + '\')" style="padding:6px 14px;background:#024550;color:#fff;border:none;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit">Svara</button>'
                    + '<button onclick="mailForward(\'' + id + '\')" style="padding:6px 14px;background:#f1f5f9;color:#334155;border:1px solid #e5e7eb;border-radius:6px;font-size:12px;cursor:pointer;font-family:inherit">Vidarebefordra</button>'
                    + '<button onclick="mailTrash(\'' + id + '\')" style="padding:6px 14px;background:#fef2f2;color:#991b1b;border:1px solid #fecaca;border-radius:6px;font-size:12px;cursor:pointer;font-family:inherit">Radera</button>'
                    + '</div>'
                    + '</div>'
                    + (data.attachments.length ? '<div style="padding:8px 12px;background:#f8fafc;border-radius:8px;margin-bottom:12px;border:1px solid #e5e7eb"><span style="font-size:12px;font-weight:600;color:#334155">Bilagor: </span>' + data.attachments.map(a => '<span style="font-size:12px;color:#3b82f6">' + escHtml(a.filename) + ' (' + formatSize(a.size) + ')</span>').join(', ') + '</div>' : '')
                    + '<div style="border-top:1px solid #e5e7eb;padding-top:16px">'
                    + '<iframe id="mailBodyFrame" srcdoc="" style="width:100%;min-height:400px;border:none" sandbox="allow-same-origin"></iframe>'
                    + '</div>';

                // Set iframe content
                const iframe = document.getElementById('mailBodyFrame');
                if (iframe) {
                    const bodyContent = data.bodyHtml || ('<pre style="white-space:pre-wrap;font-family:sans-serif">' + escHtml(data.bodyText) + '</pre>');
                    iframe.srcdoc = '<html><head><style>body{font-family:sans-serif;font-size:14px;color:#1a1a1a;margin:0;padding:0;line-height:1.5}img{max-width:100%}a{color:#0284c7}</style></head><body>' + bodyContent + '</body></html>';
                }

                // Store for reply
                window._lastMailData = data;
            } catch(e) {
                content.innerHTML = '<div style="padding:20px;color:#ef4444">' + e.message + '</div>';
            }
        }

        function mailCompose() {
            document.getElementById('composeTitle').textContent = 'Nytt meddelande';
            document.getElementById('composeTo').value = '';
            document.getElementById('composeCc').value = '';
            document.getElementById('composeSubject').value = '';
            document.getElementById('composeBody').value = '';
            document.getElementById('composeReplyUid').value = '0';
            document.getElementById('composeReplyFolder').value = '';
            document.getElementById('composeReplyTo').value = '';
            document.getElementById('composeSignature').value = gMailSignature || '--\nMed vänliga hälsningar\n' + gUserName + '\nSolargroup';
            document.getElementById('mailComposeModal').style.display = 'flex';
        }

        function mailReply(id) {
            const d = window._lastMailData;
            if (!d) return;
            document.getElementById('composeTitle').textContent = 'Svara';
            document.getElementById('composeTo').value = d.replyTo || d.from;
            document.getElementById('composeCc').value = '';
            document.getElementById('composeSubject').value = (d.subject.startsWith('Re:') ? '' : 'Re: ') + d.subject;
            document.getElementById('composeBody').value = '\n\n--- Ursprungligt meddelande ---\nFrån: ' + d.from + '\nDatum: ' + new Date(d.timestamp*1000).toLocaleString('sv-SE') + '\n\n' + (d.bodyText || '');
            document.getElementById('composeReplyUid').value = id;
            document.getElementById('composeReplyTo').value = d.messageId || '';
            document.getElementById('composeSignature').value = gMailSignature || '--\nMed vänliga hälsningar\n' + gUserName;
            document.getElementById('mailComposeModal').style.display = 'flex';
        }

        function mailForward(id) {
            const d = window._lastMailData;
            if (!d) return;
            document.getElementById('composeTitle').textContent = 'Vidarebefordra';
            document.getElementById('composeTo').value = '';
            document.getElementById('composeCc').value = '';
            document.getElementById('composeSubject').value = 'Fwd: ' + d.subject;
            document.getElementById('composeBody').value = '\n\n--- Vidarebefordrat meddelande ---\nFrån: ' + d.from + '\nTill: ' + d.to + '\nDatum: ' + new Date(d.timestamp*1000).toLocaleString('sv-SE') + '\nÄmne: ' + d.subject + '\n\n' + (d.bodyText || '');
            document.getElementById('composeReplyUid').value = '0';
            document.getElementById('composeReplyTo').value = '';
            document.getElementById('composeSignature').value = gMailSignature || '--\nMed vänliga hälsningar\n' + gUserName;
            document.getElementById('mailComposeModal').style.display = 'flex';
        }

        async function mailSend() {
            if (!await ensureToken()) return;
            const btn = document.getElementById('composeSendBtn');
            btn.textContent = 'Skickar...'; btn.disabled = true;
            try {
                const sig = document.getElementById('composeSignature').value.trim();
                // Save signature for next time
                if (sig !== gMailSignature) {
                    gMailSignature = sig;
                    localStorage.setItem('mailSignature', sig);
                    fetch('/api/gmail-proxy.php', {
                        method: 'POST', headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({ action: 'signature', staffId: gStaffId, signature: sig })
                    });
                }
                const replyTo = document.getElementById('composeReplyTo').value;
                const res = await fetch('/api/gmail-proxy.php', {
                    method: 'POST', headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        action: 'send', accessToken: gAccessToken,
                        to: document.getElementById('composeTo').value,
                        cc: document.getElementById('composeCc').value,
                        subject: document.getElementById('composeSubject').value,
                        body: document.getElementById('composeBody').value,
                        signature: sig,
                        inReplyTo: replyTo,
                        references: replyTo,
                        threadId: replyTo ? (window._lastMailData?.threadId || '') : '',
                    })
                });
                const data = await res.json();
                if (data.error) throw new Error(data.error);
                mailCloseCompose();
                loadGmailInbox();
            } catch(e) {
                alert('Kunde inte skicka: ' + e.message);
            }
            btn.textContent = 'Skicka'; btn.disabled = false;
        }

        async function mailTrash(id) {
            if (!await ensureToken()) return;
            try {
                await fetch('/api/gmail-proxy.php', {
                    method: 'POST', headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ action: 'trash', accessToken: gAccessToken, id })
                });
                gmailCurrentId = null;
                document.getElementById('mailReaderContent').style.display = 'none';
                document.getElementById('mailReaderEmpty').style.display = 'flex';
                loadGmailInbox();
            } catch(e) { alert(e.message); }
        }

        function mailCloseCompose() { document.getElementById('mailComposeModal').style.display = 'none'; }

        function mailRefresh() { loadGmailInbox(); }

        function mailSwitchFolder() {
            gmailLabel = document.getElementById('mailFolderSelect').value;
            gmailCurrentId = null;
            document.getElementById('mailReaderContent').style.display = 'none';
            document.getElementById('mailReaderEmpty').style.display = 'flex';
            loadGmailInbox();
        }

        async function loadGmailLabels() {
            if (!await ensureToken()) return;
            try {
                const res = await fetch('/api/gmail-proxy.php', {
                    method: 'POST', headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ action: 'labels', accessToken: gAccessToken })
                });
                const data = await res.json();
                const select = document.getElementById('mailFolderSelect');
                if (select && data.labels) {
                    const labelNames = { INBOX: 'Inkorg', SENT: 'Skickat', DRAFTS: 'Utkast', TRASH: 'Papperskorg', SPAM: 'Skräppost', STARRED: 'Stjärnmärkt', IMPORTANT: 'Viktigt' };
                    const show = data.labels.filter(l => ['INBOX','SENT','DRAFTS','TRASH','SPAM','STARRED','IMPORTANT'].includes(l.id) || l.type === 'user');
                    select.innerHTML = show.map(l => '<option value="' + l.id + '"' + (l.id === gmailLabel ? ' selected' : '') + '>' + (labelNames[l.id] || l.name) + '</option>').join('');
                }
            } catch(e) {}
        }

        function mailDisconnect() {
            gAccessToken = '';
            sessionStorage.removeItem('gAccessToken');
            sessionStorage.removeItem('gTokenExpiry');
            updateAuthUI();
        }

        // === CALENDAR CLIENT ===
        let calEvents = [];

        async function loadCalendarEvents() {
            if (!await ensureToken()) { updateAuthUI(); return; }
            const listEl = document.getElementById('calEventsList') || document.getElementById('callbackList');
            try {
                const res = await fetch('/api/calendar-proxy.php', {
                    method: 'POST', headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        action: 'list', accessToken: gAccessToken,
                        timeMin: new Date().toISOString(),
                        timeMax: new Date(Date.now() + 30*86400000).toISOString(),
                        maxResults: 50
                    })
                });
                const data = await res.json();
                if (data.error === 'TOKEN_EXPIRED') { gAccessToken = ''; updateAuthUI(); return; }
                calEvents = data.events || [];
                renderCalendarEvents();
            } catch(e) {}
        }

        function renderCalendarEvents() {
            const embed = document.getElementById('calEmbed');
            const listEl = document.getElementById('calEventsList');

            // Show event list
            if (listEl) {
                if (calEvents.length === 0) {
                    listEl.innerHTML = '<div style="padding:16px;background:#f8fafc;border-radius:10px;color:#94a3b8;text-align:center;font-size:13px">Inga kommande händelser</div>';
                } else {
                    const eventColors = ['#16a34a','#3b82f6','#eab308','#a855f7','#ef4444','#06b6d4'];
                    listEl.innerHTML = calEvents.slice(0, 20).map((ev, i) => {
                        const start = ev.allDay ? ev.start : new Date(ev.start).toLocaleString('sv-SE', {weekday:'short', month:'short', day:'numeric', hour:'2-digit', minute:'2-digit'});
                        const color = eventColors[i % eventColors.length];
                        return '<div style="display:flex;align-items:center;gap:12px;padding:10px 12px;background:#fff;border-radius:8px;border:1px solid #f1f5f9">'
                            + '<div style="width:8px;height:8px;border-radius:50%;background:' + color + ';flex-shrink:0"></div>'
                            + '<div style="flex:1;min-width:0">'
                            + '<div style="font-size:13px;font-weight:600;color:#1a1a1a;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + escHtml(ev.summary) + '</div>'
                            + '<div style="font-size:12px;color:#64748b">' + start + (ev.location ? ' · ' + escHtml(ev.location) : '') + '</div>'
                            + '</div>'
                            + '<a href="' + (ev.htmlLink || '#') + '" target="_blank" style="font-size:11px;color:#3b82f6;text-decoration:none;white-space:nowrap">Öppna</a>'
                            + '</div>';
                    }).join('');
                }
            }

            // Also render in the calendar embed area
            if (embed) {
                embed.style.display = 'block';
                const calendarHtml = buildCalendarView();
                embed.innerHTML = calendarHtml;
            }
        }

        function buildCalendarView() {
            const now = new Date();
            const year = now.getFullYear();
            const month = now.getMonth();
            const firstDay = new Date(year, month, 1).getDay();
            const daysInMonth = new Date(year, month + 1, 0).getDate();
            const monthNames = ['Januari','Februari','Mars','April','Maj','Juni','Juli','Augusti','September','Oktober','November','December'];
            const dayNames = ['Mån','Tis','Ons','Tor','Fre','Lör','Sön'];
            const startDay = (firstDay + 6) % 7;

            let html = '<div style="padding:16px">';
            html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px"><h3 style="font-size:18px;font-weight:700">' + monthNames[month] + ' ' + year + '</h3></div>';
            html += '<div style="display:grid;grid-template-columns:repeat(7,1fr);gap:1px;background:#e5e7eb;border:1px solid #e5e7eb;border-radius:8px;overflow:hidden">';
            dayNames.forEach(d => { html += '<div style="padding:8px 4px;text-align:center;font-size:11px;font-weight:600;color:#64748b;background:#f8fafc">' + d + '</div>'; });

            for (let i = 0; i < startDay; i++) html += '<div style="padding:8px;background:#fafafa;min-height:60px"></div>';

            for (let day = 1; day <= daysInMonth; day++) {
                const dateStr = year + '-' + String(month+1).padStart(2,'0') + '-' + String(day).padStart(2,'0');
                const isToday = day === now.getDate();
                const dayEvents = calEvents.filter(e => (e.start || '').startsWith(dateStr));
                html += '<div style="padding:4px 6px;background:' + (isToday ? '#eff6ff' : '#fff') + ';min-height:60px;vertical-align:top">';
                html += '<div style="font-size:12px;font-weight:' + (isToday ? '700' : '500') + ';color:' + (isToday ? '#024550' : '#334155') + ';margin-bottom:2px">' + day + '</div>';
                dayEvents.slice(0, 2).forEach(e => {
                    html += '<div style="font-size:10px;padding:1px 4px;background:#dcfce7;border-radius:3px;margin-bottom:1px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#166534" title="' + escHtml(e.summary) + '">' + escHtml(e.summary) + '</div>';
                });
                if (dayEvents.length > 2) html += '<div style="font-size:10px;color:#94a3b8">+' + (dayEvents.length - 2) + ' till</div>';
                html += '</div>';
            }
            html += '</div></div>';
            return html;
        }

        async function createCalendarEvent(summary, description, location, startTime, endTime) {
            if (!await ensureToken()) return null;
            try {
                const res = await fetch('/api/calendar-proxy.php', {
                    method: 'POST', headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        action: 'create', accessToken: gAccessToken,
                        summary, description, location, startTime, endTime
                    })
                });
                const data = await res.json();
                if (data.success) { loadCalendarEvents(); return data.event; }
                throw new Error(data.error);
            } catch(e) { alert('Kunde inte skapa event: ' + e.message); return null; }
        }

        // === HELPERS ===
        function escHtml(s) { const d = document.createElement('div'); d.textContent = s || ''; return d.innerHTML; }
        function formatMailDate(ts) {
            if (!ts) return '';
            const d = new Date(ts * 1000);
            const now = new Date();
            if (d.toDateString() === now.toDateString()) return d.toLocaleTimeString('sv-SE', {hour:'2-digit', minute:'2-digit'});
            if (d.getFullYear() === now.getFullYear()) return d.toLocaleDateString('sv-SE', {day:'numeric', month:'short'});
            return d.toLocaleDateString('sv-SE');
        }
        function formatSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            if (bytes < 1048576) return (bytes/1024).toFixed(0) + ' KB';
            return (bytes/1048576).toFixed(1) + ' MB';
        }

        // Auto-load on page navigation
        // Mail/calendar hooks injected into existing navigateTo override below

        // Init on load
        updateAuthUI();

        // === PERSONAL ===
        const STAFF_API = '/api/staff.php';
        const roleLabels = {admin:'Admin',saljare:'Säljare',installator:'Installatör',projektledare:'Projektledare',ekonomi:'Ekonomi'};
        const roleColors = {admin:'purple',saljare:'green',installator:'blue',projektledare:'yellow',ekonomi:'gray'};

        async function loadStaff() {
            const role = document.getElementById('staffRoleFilter')?.value || '';
            let url = STAFF_API;
            if (role) url += '?role=' + role;
            try {
                const res = await fetch(url);
                const staff = await res.json();
                const tbody = document.getElementById('staffTableBody');
                const count = document.getElementById('staffCount');
                if (!Array.isArray(staff) || staff.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="8" style="text-align:center;padding:40px;color:#94a3b8">Ingen personal tillagd ännu</td></tr>';
                    if (count) count.textContent = '0 personer';
                    return;
                }
                if (count) count.textContent = staff.length + ' person' + (staff.length !== 1 ? 'er' : '');
                tbody.innerHTML = staff.map(s => {
                    const avatar = s.avatar_url
                        ? '<img src="' + s.avatar_url + '" style="width:36px;height:36px;border-radius:50%;object-fit:cover">'
                        : '<div style="width:36px;height:36px;border-radius:50%;background:#f1f5f9;display:flex;align-items:center;justify-content:center;font-weight:700;color:#64748b;font-size:14px">' + (s.name ? s.name.charAt(0).toUpperCase() : '?') + '</div>';
                    const google = s.google_id
                        ? '<span style="color:#10b981;font-size:12px">&#10003; Kopplad</span>'
                        : '<span style="color:#94a3b8;font-size:12px">Ej kopplad</span>';
                    const status = s.active == 1
                        ? '<span class="status-badge green">Aktiv</span>'
                        : '<span class="status-badge gray">Inaktiv</span>';
                    return '<tr>' +
                        '<td>' + avatar + '</td>' +
                        '<td><strong>' + (s.name || '') + '</strong>' + (s.title ? '<br><span style="font-size:11px;color:#94a3b8">' + s.title + '</span>' : '') + '</td>' +
                        '<td>' + (s.email || '') + '</td>' +
                        '<td><span class="status-badge ' + (roleColors[s.role] || 'gray') + '">' + (roleLabels[s.role] || s.role) + '</span></td>' +
                        '<td>' + (s.phone || '-') + '</td>' +
                        '<td>' + google + '</td>' +
                        '<td>' + status + '</td>' +
                        '<td><button onclick="editStaff(' + s.id + ')" style="background:none;border:none;cursor:pointer;color:#3b82f6;font-size:12px;padding:4px 8px" title="Redigera">&#9998;</button>' +
                        '<button onclick="toggleStaffActive(' + s.id + ',' + s.active + ')" style="background:none;border:none;cursor:pointer;color:' + (s.active == 1 ? '#ef4444' : '#10b981') + ';font-size:12px;padding:4px 8px" title="' + (s.active == 1 ? 'Inaktivera' : 'Aktivera') + '">' + (s.active == 1 ? '&#10007;' : '&#10003;') + '</button></td>' +
                        '</tr>';
                }).join('');
            } catch (e) {
                document.getElementById('staffTableBody').innerHTML = '<tr><td colspan="8" style="text-align:center;padding:40px;color:#ef4444">Fel: ' + e.message + '</td></tr>';
            }
        }

        function showStaffModal(staffData) {
            const modal = document.getElementById('staffModal');
            document.getElementById('staffModalTitle').textContent = staffData ? 'Redigera personal' : 'Lägg till personal';
            document.getElementById('staffEditId').value = staffData ? staffData.id : '';
            document.getElementById('staffName').value = staffData ? staffData.name : '';
            document.getElementById('staffEmail').value = staffData ? staffData.email : '';
            document.getElementById('staffRole').value = staffData ? staffData.role : 'saljare';
            document.getElementById('staffPhone').value = staffData ? (staffData.phone || '') : '';
            document.getElementById('staffTitle').value = staffData ? (staffData.title || '') : '';
            document.getElementById('staffModalError').style.display = 'none';
            modal.style.display = 'flex';
        }

        function closeStaffModal() {
            document.getElementById('staffModal').style.display = 'none';
        }

        async function saveStaff() {
            const id = document.getElementById('staffEditId').value;
            const data = {
                name: document.getElementById('staffName').value.trim(),
                email: document.getElementById('staffEmail').value.trim(),
                role: document.getElementById('staffRole').value,
                phone: document.getElementById('staffPhone').value.trim() || null,
                title: document.getElementById('staffTitle').value.trim() || null,
            };
            if (!data.name || !data.email) {
                const err = document.getElementById('staffModalError');
                err.textContent = 'Namn och e-post krävs';
                err.style.display = 'block';
                return;
            }
            try {
                const url = id ? STAFF_API + '?id=' + id : STAFF_API;
                const res = await fetch(url, {
                    method: id ? 'PUT' : 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(data),
                });
                const result = await res.json();
                if (!res.ok) {
                    const err = document.getElementById('staffModalError');
                    err.textContent = result.error || 'Något gick fel';
                    err.style.display = 'block';
                    return;
                }
                closeStaffModal();
                loadStaff();
            } catch (e) {
                const err = document.getElementById('staffModalError');
                err.textContent = e.message;
                err.style.display = 'block';
            }
        }

        async function editStaff(id) {
            try {
                const res = await fetch(STAFF_API + '?id=' + id);
                const staff = await res.json();
                showStaffModal(staff);
            } catch (e) {
                alert('Kunde inte ladda: ' + e.message);
            }
        }

        async function toggleStaffActive(id, currentActive) {
            try {
                await fetch(STAFF_API + '?id=' + id, {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({active: currentActive == 1 ? 0 : 1}),
                });
                loadStaff();
            } catch (e) {
                alert('Fel: ' + e.message);
            }
        }

        // Load staff when navigating to Personal page
        const origNavigate = window.navigateTo;
        if (typeof origNavigate === 'function') {
            window.navigateTo = function(page) {
                origNavigate(page);
                if (page === 'personal') loadStaff();
                if (page === 'inkorg' && gAccessToken) { loadGmailLabels(); loadGmailInbox(); }
                if (page === 'kalender' && gAccessToken) { loadCalendarEvents(); }
            };
        }
        document.querySelectorAll('[data-page="personal"]').forEach(el => {
            el.addEventListener('click', () => setTimeout(loadStaff, 100));
        });
    
        // Monday.com settings
        async function loadMondaySettings(){
            try {
                const res = await fetch('/api/settings.php?keys=monday_api_token');
                const data = await res.json();
                const token = data.settings?.monday_api_token || '';
                const input = document.getElementById('settMondayToken');
                if(input && token) input.value = token;
                if(token) loadMondayBoards();
            } catch(e){}
        }

        async function testMondayConnection(){
            const statusEl = document.getElementById('mondayConnectionStatus');
            statusEl.innerHTML = '<span style="color:#64748b">Testar...</span>';
            try {
                const res = await fetch('/api/monday.php?action=test');
                const data = await res.json();
                if(data.success){
                    statusEl.innerHTML = '<span style="color:#059669">Ansluten som <strong>'+data.user.name+'</strong> ('+data.user.email+')</span>';
                    loadMondayBoards();
                } else {
                    statusEl.innerHTML = '<span style="color:#ef4444">'+( data.error||'Anslutning misslyckades')+'</span>';
                }
            } catch(e){
                statusEl.innerHTML = '<span style="color:#ef4444">Fel: '+e.message+'</span>';
            }
        }

        async function saveMondaySettings(){
            const token = document.getElementById('settMondayToken').value;
            try {
                await fetch('/api/settings.php', {
                    method:'POST', headers:{'Content-Type':'application/json'},
                    body: JSON.stringify({monday_api_token: token})
                });
                testMondayConnection();
            } catch(e){ alert('Kunde inte spara: '+e.message); }
        }

        async function loadMondayBoards(){
            const section = document.getElementById('mondayBoardsSection');
            const list = document.getElementById('mondayBoardsList');
            try {
                const res = await fetch('/api/monday.php?action=boards');
                const boards = await res.json();
                if(boards.length === 0){ section.style.display='none'; return; }
                section.style.display='';
                list.innerHTML = boards.filter(b => b.state === 'active').map(b => {
                    const kind = b.board_kind === 'private' ? ' (privat)' : '';
                    return '<div style="padding:10px 14px;background:#fff;border:1px solid #e5e7eb;border-radius:8px;display:flex;justify-content:space-between;align-items:center">'
                        +'<div><span style="font-size:14px;font-weight:500;color:#1a1a1a">'+b.name+'</span>'
                        +'<span style="font-size:11px;color:#94a3b8;margin-left:8px">'+b.items_count+' items'+kind+'</span></div>'
                        +'<button onclick="viewMondayBoard('+b.id+')" style="padding:4px 12px;background:#f1f5f9;border:1px solid #e5e7eb;border-radius:6px;font-size:12px;cursor:pointer;font-family:inherit;color:#334155">Visa</button>'
                        +'</div>';
                }).join('');
            } catch(e){ console.error('loadMondayBoards error', e); }
        }

        async function viewMondayBoard(boardId){
            try {
                const res = await fetch('/api/monday.php?action=board&id='+boardId);
                const board = await res.json();
                if(!board) return;
                let html = '<h3 style="margin:24px 0 8px">'+board.name+'</h3>';
                html += '<p style="font-size:12px;color:#94a3b8;margin-bottom:12px">'+board.columns.length+' kolumner, '+board.groups.length+' grupper</p>';
                html += '<div style="margin-bottom:16px"><strong style="font-size:13px">Grupper:</strong> <span style="font-size:13px;color:#64748b">'+board.groups.map(g=>g.title).join(', ')+'</span></div>';
                html += '<table style="width:100%;border-collapse:collapse;font-size:12px;margin-bottom:16px"><thead><tr style="background:#f8fafc"><th style="text-align:left;padding:6px 10px;border-bottom:1px solid #e5e7eb">Kolumn</th><th style="text-align:left;padding:6px 10px;border-bottom:1px solid #e5e7eb">Typ</th></tr></thead><tbody>';
                board.columns.forEach(c => {
                    html += '<tr><td style="padding:4px 10px;border-bottom:1px solid #f1f5f9">'+c.title+'</td><td style="padding:4px 10px;border-bottom:1px solid #f1f5f9;color:#64748b">'+c.type+'</td></tr>';
                });
                html += '</tbody></table>';
                if(board.items_page && board.items_page.items && board.items_page.items.length > 0){
                    html += '<strong style="font-size:13px">Senaste items ('+board.items_page.items.length+'):</strong>';
                    html += '<div style="display:flex;flex-direction:column;gap:4px;margin-top:8px">';
                    board.items_page.items.slice(0,10).forEach(item => {
                        html += '<div style="padding:6px 10px;background:#fafbfc;border-radius:6px;font-size:12px;color:#1a1a1a">'+item.name+'</div>';
                    });
                    if(board.items_page.items.length > 10) html += '<div style="font-size:11px;color:#94a3b8;padding:4px 10px">...och '+(board.items_page.items.length-10)+' till</div>';
                    html += '</div>';
                }
                document.getElementById('mondayBoardsList').insertAdjacentHTML('beforeend', html);
            } catch(e){ alert('Kunde inte ladda board: '+e.message); }
        }


        // AI Settings
        async function loadAiSettings(){
            try {
                const res = await fetch('/api/settings.php?keys=openai_api_key,openai_model,gemini_api_key,gemini_model,default_ai_provider');
                const data = await res.json();
                const s = data.settings || {};
                if(s.openai_api_key) document.getElementById('settOpenaiKey').value = s.openai_api_key;
                if(s.openai_model) document.getElementById('settOpenaiModel').value = s.openai_model;
                if(s.gemini_api_key) document.getElementById('settGeminiKey').value = s.gemini_api_key;
                if(s.gemini_model) document.getElementById('settGeminiModel').value = s.gemini_model;
                if(s.default_ai_provider) document.getElementById('settDefaultProvider').value = s.default_ai_provider;
            } catch(e){ console.error('loadAiSettings', e); }
        }

        async function saveAiSettings(){
            const settings = {
                openai_api_key: document.getElementById('settOpenaiKey').value,
                openai_model: document.getElementById('settOpenaiModel').value,
                gemini_api_key: document.getElementById('settGeminiKey').value,
                gemini_model: document.getElementById('settGeminiModel').value,
                default_ai_provider: document.getElementById('settDefaultProvider').value,
            };
            try {
                await fetch('/api/settings.php', {
                    method:'POST', headers:{'Content-Type':'application/json'},
                    body: JSON.stringify(settings)
                });
                document.getElementById('openaiTestStatus').innerHTML = '<span style="color:#059669">Sparad</span>';
                document.getElementById('geminiTestStatus').innerHTML = '<span style="color:#059669">Sparad</span>';
                setTimeout(() => {
                    document.getElementById('openaiTestStatus').innerHTML = '';
                    document.getElementById('geminiTestStatus').innerHTML = '';
                }, 2000);
            } catch(e){ alert('Fel: '+e.message); }
        }

</script>

    <!-- Mobil bottom navigation -->
    <nav class="mobile-nav" id="mobileNav">
        <a data-page="dashboard" class="active"><svg viewBox="0 0 24 24"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>Hem</a>
        <a data-page="faltsalj"><svg viewBox="0 0 24 24"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>Fält</a>
        <a data-page="bildgenerering"><svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>Bild</a>
        <a data-page="kunder"><svg viewBox="0 0 24 24"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/></svg>Kunder</a>
        <a data-page="installningar"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>Inst.</a>
    </nav>
    <!-- Lightbox för bildförhandsgranskning -->
    <div id="imgLightbox" onclick="if(event.target===this)closeLightbox()" style="display:none;position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,.85);display:none;align-items:center;justify-content:center;cursor:zoom-out">
        <img id="imgLightboxImg" style="max-width:90vw;max-height:90vh;border-radius:12px;box-shadow:0 20px 60px rgba(0,0,0,.5)">
        <button onclick="closeLightbox()" style="position:absolute;top:20px;right:20px;background:rgba(255,255,255,.2);color:#fff;border:none;border-radius:50%;width:40px;height:40px;font-size:20px;cursor:pointer;display:flex;align-items:center;justify-content:center">&times;</button>
    </div>
</body>
</html>