#!/usr/bin/env python3
"""
PHT Sales CRM Board
Port: 18793
Product: Atmos Ethylene Monitoring
"""

import json
import os
from http.server import HTTPServer, SimpleHTTPRequestHandler
from urllib.parse import parse_qs, urlparse
import datetime

DATA_FILE = '/Users/max/.openclaw/workspace/postharvest/crm-data.json'

class PHT_CRM_Handler(SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/' or self.path == '/index.html':
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(self.get_html().encode())
        elif self.path == '/api/leads':
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            with open(DATA_FILE, 'r') as f:
                self.wfile.write(f.read().encode())
        else:
            super().do_GET()
    
    def do_POST(self):
        if self.path == '/api/leads':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            new_data = json.loads(post_data.decode())
            
            with open(DATA_FILE, 'w') as f:
                json.dump(new_data, f, indent=2)
            
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({"status": "success"}).encode())
    
    def get_html(self):
        return '''<!DOCTYPE html>
<html>
<head>
    <title>PHT Sales CRM</title>
    <meta charset="UTF-8">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            background: linear-gradient(135deg, #0f2027 0%, #203a43 50%, #2c5364 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .header {
            background: rgba(255,255,255,0.05);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            border: 1px solid rgba(255,255,255,0.1);
        }
        .header h1 {
            color: #4ade80;
            font-size: 36px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .header p {
            color: rgba(255,255,255,0.7);
            font-size: 16px;
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        .stat-card {
            background: rgba(255,255,255,0.05);
            padding: 15px;
            border-radius: 12px;
            border: 1px solid rgba(255,255,255,0.1);
        }
        .stat-card .value {
            color: #4ade80;
            font-size: 28px;
            font-weight: bold;
        }
        .stat-card .label {
            color: rgba(255,255,255,0.6);
            font-size: 14px;
            margin-top: 5px;
        }
        .pipeline {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }
        .stage {
            background: rgba(255,255,255,0.05);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 20px;
            border: 1px solid rgba(255,255,255,0.1);
        }
        .stage-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .stage-title {
            color: #fff;
            font-size: 18px;
            font-weight: 600;
        }
        .stage-count {
            background: rgba(74, 222, 128, 0.2);
            color: #4ade80;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
        }
        .lead-card {
            background: rgba(255,255,255,0.08);
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 12px;
            cursor: pointer;
            transition: all 0.2s;
            border: 1px solid rgba(255,255,255,0.1);
        }
        .lead-card:hover {
            background: rgba(255,255,255,0.12);
            transform: translateY(-2px);
        }
        .lead-company {
            color: #fff;
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 5px;
        }
        .lead-contact {
            color: rgba(255,255,255,0.7);
            font-size: 14px;
            margin-bottom: 8px;
        }
        .lead-meta {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 10px;
        }
        .lead-tag {
            background: rgba(74, 222, 128, 0.15);
            color: #4ade80;
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 12px;
        }
        .lead-value {
            background: rgba(251, 191, 36, 0.15);
            color: #fbbf24;
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 12px;
            font-weight: 600;
        }
        .lead-units {
            color: rgba(255,255,255,0.6);
            font-size: 12px;
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }
        .modal-content {
            background: #1f2937;
            border-radius: 20px;
            padding: 30px;
            max-width: 600px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            border: 1px solid rgba(255,255,255,0.1);
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .modal-title {
            color: #4ade80;
            font-size: 24px;
            font-weight: 600;
        }
        .close-btn {
            background: rgba(255,255,255,0.1);
            border: none;
            color: #fff;
            font-size: 24px;
            cursor: pointer;
            padding: 5px 12px;
            border-radius: 8px;
        }
        .detail-section {
            margin-bottom: 20px;
        }
        .detail-label {
            color: rgba(255,255,255,0.6);
            font-size: 12px;
            margin-bottom: 5px;
        }
        .detail-value {
            color: #fff;
            font-size: 16px;
        }
        .notes-section {
            background: rgba(255,255,255,0.05);
            padding: 15px;
            border-radius: 10px;
            margin-top: 15px;
        }
        .activity-list {
            margin-top: 10px;
        }
        .activity-item {
            background: rgba(255,255,255,0.05);
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 8px;
            border-left: 3px solid #4ade80;
        }
        .activity-date {
            color: #4ade80;
            font-size: 12px;
            font-weight: 600;
        }
        .activity-note {
            color: rgba(255,255,255,0.8);
            font-size: 14px;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🍏 PHT Sales CRM</h1>
        <p>Atmos Ethylene Monitoring Pipeline</p>
        <div class="stats" id="stats"></div>
    </div>
    
    <div class="pipeline" id="pipeline"></div>
    
    <div class="modal" id="modal">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-title" id="modal-company"></div>
                <button class="close-btn" onclick="closeModal()">×</button>
            </div>
            <div id="modal-details"></div>
        </div>
    </div>

    <script>
        const stages = [
            { id: 'New Lead', color: '#60a5fa' },
            { id: 'Contacted', color: '#fbbf24' },
            { id: 'Demo Scheduled', color: '#a78bfa' },
            { id: 'Pilot', color: '#f472b6' },
            { id: 'Proposal Made', color: '#fb923c' },
            { id: 'Won', color: '#4ade80' },
            { id: 'Lost', color: '#ef4444' }
        ];

        let allLeads = [];

        async function loadData() {
            const res = await fetch('/api/leads');
            const data = await res.json();
            allLeads = data.leads;
            renderPipeline();
            renderStats();
        }

        function renderStats() {
            const totalLeads = allLeads.length;
            const totalValue = allLeads.reduce((sum, l) => sum + (l.dealValue || 0), 0);
            const totalUnits = allLeads.reduce((sum, l) => sum + (l.estimatedUnits || 0), 0);
            const contacted = allLeads.filter(l => l.stage !== 'New Lead').length;
            
            const stats = `
                <div class="stat-card">
                    <div class="value">${totalLeads}</div>
                    <div class="label">Total Leads</div>
                </div>
                <div class="stat-card">
                    <div class="value">$${(totalValue/1000).toFixed(0)}K</div>
                    <div class="label">Pipeline Value</div>
                </div>
                <div class="stat-card">
                    <div class="value">${totalUnits}</div>
                    <div class="label">Est. Units</div>
                </div>
                <div class="stat-card">
                    <div class="value">${contacted}</div>
                    <div class="label">Engaged</div>
                </div>
            `;
            document.getElementById('stats').innerHTML = stats;
        }

        function renderPipeline() {
            const pipeline = document.getElementById('pipeline');
            pipeline.innerHTML = '';
            
            stages.forEach(stage => {
                const stageLeads = allLeads.filter(l => l.stage === stage.id);
                
                const stageDiv = document.createElement('div');
                stageDiv.className = 'stage';
                stageDiv.innerHTML = `
                    <div class="stage-header">
                        <div class="stage-title">${stage.id}</div>
                        <div class="stage-count">${stageLeads.length}</div>
                    </div>
                    ${stageLeads.map(lead => `
                        <div class="lead-card" onclick="showLeadDetails('${lead.id}')">
                            <div class="lead-company">${lead.company}</div>
                            <div class="lead-contact">${lead.contactName}</div>
                            <div class="lead-meta">
                                ${lead.region ? `<span class="lead-tag">${lead.region}</span>` : ''}
                                ${lead.fruitTypes ? lead.fruitTypes.map(f => `<span class="lead-tag">${f}</span>`).join('') : ''}
                                ${lead.dealValue ? `<span class="lead-value">$${(lead.dealValue/1000).toFixed(0)}K</span>` : ''}
                                ${lead.estimatedUnits ? `<span class="lead-units">${lead.estimatedUnits} units</span>` : ''}
                            </div>
                        </div>
                    `).join('')}
                `;
                pipeline.appendChild(stageDiv);
            });
        }

        function showLeadDetails(leadId) {
            const lead = allLeads.find(l => l.id === leadId);
            if (!lead) return;
            
            document.getElementById('modal-company').textContent = lead.company;
            
            const details = `
                <div class="detail-section">
                    <div class="detail-label">Contact</div>
                    <div class="detail-value">${lead.contactName}</div>
                </div>
                <div class="detail-section">
                    <div class="detail-label">Email</div>
                    <div class="detail-value">${lead.email}</div>
                </div>
                ${lead.phone ? `
                    <div class="detail-section">
                        <div class="detail-label">Phone</div>
                        <div class="detail-value">${lead.phone}</div>
                    </div>
                ` : ''}
                ${lead.linkedin ? `
                    <div class="detail-section">
                        <div class="detail-label">LinkedIn</div>
                        <div class="detail-value"><a href="${lead.linkedin}" target="_blank" style="color: #4ade80;">${lead.linkedin}</a></div>
                    </div>
                ` : ''}
                <div class="detail-section">
                    <div class="detail-label">Deal Value</div>
                    <div class="detail-value">$${lead.dealValue?.toLocaleString() || '0'}</div>
                </div>
                <div class="detail-section">
                    <div class="detail-label">Estimated Units</div>
                    <div class="detail-value">${lead.estimatedUnits || 'TBD'}</div>
                </div>
                ${lead.notes ? `
                    <div class="notes-section">
                        <div class="detail-label">Notes</div>
                        <div class="detail-value">${lead.notes}</div>
                    </div>
                ` : ''}
                ${lead.activities && lead.activities.length > 0 ? `
                    <div class="detail-section">
                        <div class="detail-label">Activity History</div>
                        <div class="activity-list">
                            ${lead.activities.map(a => `
                                <div class="activity-item">
                                    <div class="activity-date">${a.date} - ${a.type}</div>
                                    <div class="activity-note">${a.note}</div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                ` : ''}
            `;
            
            document.getElementById('modal-details').innerHTML = details;
            document.getElementById('modal').style.display = 'flex';
        }

        function closeModal() {
            document.getElementById('modal').style.display = 'none';
        }

        // Close modal on outside click
        document.getElementById('modal').addEventListener('click', (e) => {
            if (e.target.id === 'modal') closeModal();
        });

        // Load data on page load
        loadData();
        
        // Refresh every 30 seconds
        setInterval(loadData, 30000);
    </script>
</body>
</html>'''

def run(port=18794):
    server_address = ('', port)
    httpd = HTTPServer(server_address, PHT_CRM_Handler)
    print(f'🍏 PHT Sales CRM running on http://localhost:{port}')
    httpd.serve_forever()

if __name__ == '__main__':
    run()
