-- contacts.lua - Contacts management functionality
-- Handles contact list, search, details, and actions

local contacts_doc = nil
local contacts_data = {}
local filtered_contacts = {}
local search_query = ""
local selected_contact = nil

-- Avatar colors for contacts
local avatar_colors = {
    "#E91E63", "#9C27B0", "#673AB7", "#3F51B5", "#2196F3",
    "#03A9F4", "#00BCD4", "#009688", "#4CAF50", "#8BC34A",
    "#CDDC39", "#FFC107", "#FF9800", "#FF5722", "#795548"
}

-- Get color for contact based on name
local function getAvatarColor(name)
    local sum = 0
    for i = 1, #name do
        sum = sum + string.byte(name, i)
    end
    return avatar_colors[(sum % #avatar_colors) + 1]
end

-- Initialize contacts data
local function initContactsData()
    contacts_data = {
        {id = "1", name = "Alice Johnson", phone = "+1 555-0101", email = "alice@email.com", company = "Tech Corp"},
        {id = "2", name = "Andrew Smith", phone = "+1 555-0102", email = "andrew@email.com", company = "Design Studio"},
        {id = "3", name = "Bob Williams", phone = "+1 555-0201", email = "bob@email.com", company = ""},
        {id = "4", name = "Carol Davis", phone = "+1 555-0301", email = "carol.d@email.com", company = "Marketing Inc"},
        {id = "5", name = "Chris Miller", phone = "+1 555-0302", email = "", company = ""},
        {id = "6", name = "David Brown", phone = "+1 555-0401", email = "david.b@email.com", company = "Finance LLC"},
        {id = "7", name = "Emma Wilson", phone = "+1 555-0501", email = "emma@email.com", company = "Creative Agency"},
        {id = "8", name = "Frank Garcia", phone = "+1 555-0601", email = "", company = ""},
        {id = "9", name = "Grace Lee", phone = "+1 555-0701", email = "grace.lee@email.com", company = "Healthcare Plus"},
        {id = "10", name = "Henry Taylor", phone = "+1 555-0801", email = "henry@email.com", company = ""},
        {id = "11", name = "Isabella Martinez", phone = "+1 555-0901", email = "isabella@email.com", company = "Education Center"},
        {id = "12", name = "John Doe", phone = "+1 555-1234", email = "john.doe@email.com", company = "Software Inc"},
        {id = "13", name = "Kate Thompson", phone = "+1 555-1101", email = "", company = "Legal Partners"},
        {id = "14", name = "Liam Anderson", phone = "+1 555-1201", email = "liam.a@email.com", company = ""},
        {id = "15", name = "Mary Taylor", phone = "+1 555-0601", email = "mary@email.com", company = "Consulting Group"},
        {id = "16", name = "Michael Lee", phone = "+1 555-0602", email = "michael.l@email.com", company = ""},
        {id = "17", name = "Noah White", phone = "+1 555-1401", email = "noah@email.com", company = "Real Estate Co"},
        {id = "18", name = "Olivia Harris", phone = "+1 555-1501", email = "", company = ""},
        {id = "19", name = "Peter Clark", phone = "+1 555-1601", email = "peter.c@email.com", company = "Manufacturing Ltd"},
        {id = "20", name = "Sarah Anderson", phone = "+1 555-0701", email = "sarah@email.com", company = "Media Group"},
    }

    -- Sort by name
    table.sort(contacts_data, function(a, b)
        return a.name:lower() < b.name:lower()
    end)

    filtered_contacts = contacts_data
end

-- Initialize contacts
function initContacts(doc)
    print("[Contacts] Initializing...")
    contacts_doc = doc
    initContactsData()
    renderContacts()
end

-- Render contacts list grouped by first letter
function renderContacts()
    if not contacts_doc then return end

    local container = contacts_doc:GetElementById("contacts-list")
    if not container then return end

    local html = ""
    local current_letter = ""

    for _, contact in ipairs(filtered_contacts) do
        local first_letter = contact.name:sub(1, 1):upper()

        -- Add letter header if new letter
        if first_letter ~= current_letter then
            current_letter = first_letter
            html = html .. [[
                <div class="contact-letter">]] .. first_letter .. [[</div>
            ]]
        end

        -- Get avatar color and initial
        local color = getAvatarColor(contact.name)
        local initial = contact.name:sub(1, 1):upper()

        html = html .. [[
            <div class="contact-item" onclick="selectContact(']] .. contact.id .. [[')">
                <div class="contact-avatar" style="background-color: ]] .. color .. [[;">]] .. initial .. [[</div>
                <div class="contact-info">
                    <div class="contact-name">]] .. contact.name .. [[</div>
                    <div class="contact-phone">]] .. contact.phone .. [[</div>
                </div>
                <div class="contact-call-btn" onclick="callContact(']] .. contact.id .. [['); event.stopPropagation();">
                    <img src="../../icons/phone.tga"/>
                </div>
            </div>
        ]]
    end

    if #filtered_contacts == 0 then
        html = [[
            <div style="text-align: center; padding: 40px; color: #888888;">
                <div style="font-size: 18px;">No contacts found</div>
            </div>
        ]]
    end

    container.inner_rml = html
end

-- Search contacts
function searchContacts(query)
    print("[Contacts] Searching: " .. query)
    search_query = query:lower()

    if search_query == "" then
        filtered_contacts = contacts_data
    else
        filtered_contacts = {}
        for _, contact in ipairs(contacts_data) do
            if contact.name:lower():find(search_query, 1, true) or
               contact.phone:find(search_query, 1, true) or
               (contact.email and contact.email:lower():find(search_query, 1, true)) then
                table.insert(filtered_contacts, contact)
            end
        end
    end

    renderContacts()
end

-- Handle search input
function onSearchInput(element)
    local query = element.value or ""
    searchContacts(query)
end

-- Select a contact to view details
function selectContact(contact_id)
    print("[Contacts] Selected contact: " .. contact_id)

    -- Find contact by ID
    for _, contact in ipairs(contacts_data) do
        if contact.id == contact_id then
            selected_contact = contact
            break
        end
    end

    if selected_contact then
        showContactDetail()
    end
end

-- Show contact detail view
function showContactDetail()
    if not selected_contact or not contacts_doc then return end

    -- Store contact info for detail screen
    if mosis and mosis.state then
        mosis.state.set("selected_contact", selected_contact)
    end

    -- Navigate to detail screen
    if navigateTo then
        navigateTo("contact_detail")
    else
        -- Show inline detail
        showContactDetailInline()
    end
end

-- Show contact detail inline (if navigation not available)
function showContactDetailInline()
    if not contacts_doc then return end

    local detail = contacts_doc:GetElementById("contact-detail")
    local list = contacts_doc:GetElementById("contacts-list-container")

    if detail and list then
        list.style.display = "none"
        detail.style.display = "flex"
        renderContactDetail()
    end
end

-- Render contact detail
function renderContactDetail()
    if not selected_contact or not contacts_doc then return end

    local color = getAvatarColor(selected_contact.name)
    local initial = selected_contact.name:sub(1, 1):upper()

    local detail_avatar = contacts_doc:GetElementById("detail-avatar")
    local detail_name = contacts_doc:GetElementById("detail-name")
    local detail_info = contacts_doc:GetElementById("detail-info")

    if detail_avatar then
        detail_avatar.style["background-color"] = color
        detail_avatar.inner_rml = initial
    end

    if detail_name then
        detail_name.inner_rml = selected_contact.name
    end

    if detail_info then
        local html = ""

        -- Phone
        html = html .. [[
            <div class="detail-row" onclick="callContact(']] .. selected_contact.id .. [[')">
                <div class="detail-icon"><img src="../../icons/phone.tga" style="width: 24px; height: 24px;"/></div>
                <div class="detail-content">
                    <div class="detail-label">Phone</div>
                    <div class="detail-value">]] .. selected_contact.phone .. [[</div>
                </div>
                <div class="detail-action"><img src="../../icons/call_small.tga" style="width: 24px; height: 24px;"/></div>
            </div>
        ]]

        -- Email
        if selected_contact.email and selected_contact.email ~= "" then
            html = html .. [[
                <div class="detail-row">
                    <div class="detail-icon"><img src="../../icons/email.tga" style="width: 24px; height: 24px;"/></div>
                    <div class="detail-content">
                        <div class="detail-label">Email</div>
                        <div class="detail-value">]] .. selected_contact.email .. [[</div>
                    </div>
                </div>
            ]]
        end

        -- Company
        if selected_contact.company and selected_contact.company ~= "" then
            html = html .. [[
                <div class="detail-row">
                    <div class="detail-icon"><img src="../../icons/work.tga" style="width: 24px; height: 24px;"/></div>
                    <div class="detail-content">
                        <div class="detail-label">Company</div>
                        <div class="detail-value">]] .. selected_contact.company .. [[</div>
                    </div>
                </div>
            ]]
        end

        detail_info.inner_rml = html
    end
end

-- Hide contact detail
function hideContactDetail()
    if not contacts_doc then return end

    local detail = contacts_doc:GetElementById("contact-detail")
    local list = contacts_doc:GetElementById("contacts-list-container")

    if detail and list then
        detail.style.display = "none"
        list.style.display = "flex"
    end

    selected_contact = nil
end

-- Call a contact
function callContact(contact_id)
    print("[Contacts] Calling contact: " .. contact_id)

    local contact = nil
    for _, c in ipairs(contacts_data) do
        if c.id == contact_id then
            contact = c
            break
        end
    end

    if contact then
        -- Store call info
        if mosis and mosis.state then
            mosis.state.set("current_call", {
                number = contact.phone,
                name = contact.name
            })
        end

        -- Navigate to calling screen
        if navigateTo then
            navigateTo("calling")
        else
            if showToast then
                showToast("Calling " .. contact.name)
            end
        end
    end
end

-- Message a contact
function messageContact(contact_id)
    print("[Contacts] Messaging contact: " .. contact_id)

    local contact = nil
    for _, c in ipairs(contacts_data) do
        if c.id == contact_id then
            contact = c
            break
        end
    end

    if contact then
        if mosis and mosis.state then
            mosis.state.set("chat_contact", {
                name = contact.name,
                phone = contact.phone
            })
        end

        if navigateTo then
            navigateTo("chat")
        else
            if showToast then
                showToast("Message " .. contact.name)
            end
        end
    end
end

-- Add new contact
function addContact()
    print("[Contacts] Add new contact")
    if navigateTo then
        navigateTo("add_contact")
    else
        if showToast then
            showToast("Add contact")
        end
    end
end

-- Edit contact
function editContact(contact_id)
    print("[Contacts] Edit contact: " .. contact_id)
    if showToast then
        showToast("Edit contact")
    end
end

-- Delete contact
function deleteContact(contact_id)
    print("[Contacts] Delete contact: " .. contact_id)

    -- Find and remove contact
    for i, c in ipairs(contacts_data) do
        if c.id == contact_id then
            table.remove(contacts_data, i)
            break
        end
    end

    -- Re-filter and render
    searchContacts(search_query)
    hideContactDetail()

    if showToast then
        showToast("Contact deleted")
    end
end
