const API_URL = '/api';

const api = {
    // ── BOARD ──────────────────────────────────────────────────────────────
    async getBoard()                    { return (await fetch(`${API_URL}/board`)).json(); },
    async getBoardHistory(from, to)     { return (await fetch(`${API_URL}/board/history?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`)).json(); },
    async updateVfp(divId, vfp)         { await fetch(`${API_URL}/divisions/${divId}/vfp`,  { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify({vfp}) }); },
    async updateInfo(divId, info)       { await fetch(`${API_URL}/divisions/${divId}/info`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify({info}) }); },

    // ── ITEMS & TODOS ──────────────────────────────────────────────────────
    async addItem(divId, title, workDate=null) { return (await fetch(`${API_URL}/items`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({division_id:divId,title,work_date:workDate}) })).json(); },
    async updateItemTitle(id, title)    { await fetch(`${API_URL}/items/${id}/title`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify({title}) }); },
    async updateItemMeta(id, payload)   { return (await fetch(`${API_URL}/items/${id}/meta`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async moveItem(id, divId, moveDate=null) { await fetch(`${API_URL}/items/${id}/move`,  { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify({division_id:divId, move_date:moveDate}) }); },
    async deleteItem(id)                { await fetch(`${API_URL}/items/${id}`, { method:'DELETE' }); },
    async addTodo(itemId, text, workDate=null) { return (await fetch(`${API_URL}/items/${itemId}/todos`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({text,work_date:workDate}) })).json(); },
    async toggleTodo(id, done)          { await fetch(`${API_URL}/todos/${id}/toggle`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify({done}) }); },
    async updateTodoMeta(id, payload)   { return (await fetch(`${API_URL}/todos/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async deleteTodo(id)                { await fetch(`${API_URL}/todos/${id}`, { method:'DELETE' }); },

    // ── SETTINGS ───────────────────────────────────────────────────────────
    async getPublicConfig()             { return (await fetch(`${API_URL}/public-config`)).json(); },
    async savePublicConfig(config)      { return (await fetch(`${API_URL}/public-config`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(config) })).json(); },
    async getSettings()                 { return (await fetch(`${API_URL}/settings`)).json(); },
    async saveSettings(s)               { await fetch(`${API_URL}/settings`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(s) }); },
    async getLocalRuntimeStatus()       {
        const response = await fetch(`${API_URL}/local-runtime/status`);
        const data = await response.json().catch(() => ({}));
        if (!response.ok) throw new Error(data.error || 'Local runtime status failed');
        return data;
    },
    async installLocalRuntime()         {
        const response = await fetch(`${API_URL}/local-runtime/install`, { method:'POST' });
        const data = await response.json().catch(() => ({}));
        if (!response.ok) throw new Error(data.error || 'Local runtime install failed');
        return data;
    },
    async pullLocalRuntimeModel(modelSlug) {
        const response = await fetch(`${API_URL}/local-runtime/pull`, {
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body:JSON.stringify({ model_slug: modelSlug })
        });
        const data = await response.json().catch(() => ({}));
        if (!response.ok) throw new Error(data.error || 'Local runtime model download failed');
        return data;
    },
    async resetWorkspace()              { return (await fetch(`${API_URL}/system/reset`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({ confirmation:'RESET' }) })).json(); },

    // ── SERVICES CATALOG ───────────────────────────────────────────────────
    async getServices()                 { return (await fetch(`${API_URL}/services`)).json(); },
    async addService(s)                 { return (await fetch(`${API_URL}/services`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(s) })).json(); },
    async updateService(id, s)          { await fetch(`${API_URL}/services/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(s) }); },
    async deleteService(id)             { await fetch(`${API_URL}/services/${id}`, { method:'DELETE' }); },
    async getExecutiveOrders(targetDivisionId=null) {
        const url = targetDivisionId ? `${API_URL}/executive-orders?target_division_id=${targetDivisionId}` : `${API_URL}/executive-orders`;
        return (await fetch(url)).json();
    },
    async addExecutiveOrder(payload)    { return (await fetch(`${API_URL}/executive-orders`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateExecutiveOrder(id, payload) { await fetch(`${API_URL}/executive-orders/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deleteExecutiveOrder(id)      { await fetch(`${API_URL}/executive-orders/${id}`, { method:'DELETE' }); },
    async getPolicies(divId)            { return (await fetch(`${API_URL}/policies/${divId}`)).json(); },
    async addPolicy(payload)            { return (await fetch(`${API_URL}/policies`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updatePolicy(id, payload)     { await fetch(`${API_URL}/policies/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deletePolicy(id)              { await fetch(`${API_URL}/policies/${id}`, { method:'DELETE' }); },
    async getMeetings(divId)            { return (await fetch(`${API_URL}/meetings/${divId}`)).json(); },
    async addMeeting(payload)           { return (await fetch(`${API_URL}/meetings`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateMeeting(id, payload)    { await fetch(`${API_URL}/meetings/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deleteMeeting(id)             { await fetch(`${API_URL}/meetings/${id}`, { method:'DELETE' }); },
    async getRisks(divId)               { return (await fetch(`${API_URL}/risks/${divId}`)).json(); },
    async addRisk(payload)              { return (await fetch(`${API_URL}/risks`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateRisk(id, payload)       { await fetch(`${API_URL}/risks/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deleteRisk(id)                { await fetch(`${API_URL}/risks/${id}`, { method:'DELETE' }); },
    async getCommunicationTemplates(divId) { return (await fetch(`${API_URL}/communication-templates/${divId}`)).json(); },
    async addCommunicationTemplate(payload) { return (await fetch(`${API_URL}/communication-templates`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateCommunicationTemplate(id, payload) { await fetch(`${API_URL}/communication-templates/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deleteCommunicationTemplate(id) { await fetch(`${API_URL}/communication-templates/${id}`, { method:'DELETE' }); },
    async getCampaignBriefs(divId)      { return (await fetch(`${API_URL}/campaign-briefs/${divId}`)).json(); },
    async addCampaignBrief(payload)     { return (await fetch(`${API_URL}/campaign-briefs`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateCampaignBrief(id, payload) { await fetch(`${API_URL}/campaign-briefs/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deleteCampaignBrief(id)       { await fetch(`${API_URL}/campaign-briefs/${id}`, { method:'DELETE' }); },
    async getTreasuryCases(divId)       { return (await fetch(`${API_URL}/treasury-cases/${divId}`)).json(); },
    async addTreasuryCase(payload)      { return (await fetch(`${API_URL}/treasury-cases`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateTreasuryCase(id, payload) { await fetch(`${API_URL}/treasury-cases/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deleteTreasuryCase(id)        { await fetch(`${API_URL}/treasury-cases/${id}`, { method:'DELETE' }); },
    async getInvoiceProfile()           { return (await fetch(`${API_URL}/invoice-profile`)).json(); },
    async saveInvoiceProfile(payload)   { await fetch(`${API_URL}/invoice-profile`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async uploadInvoiceLogo(dataUrl)    { return (await fetch(`${API_URL}/invoice-logo`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({ data_url: dataUrl }) })).json(); },
    async getInvoices(divId)            { return (await fetch(`${API_URL}/invoices/${divId}`)).json(); },
    async addInvoice(payload)           { return (await fetch(`${API_URL}/invoices`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateInvoice(id, payload)    { await fetch(`${API_URL}/invoices/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deleteInvoice(id)             { await fetch(`${API_URL}/invoices/${id}`, { method:'DELETE' }); },
    async getProductionAssets(divId)    { return (await fetch(`${API_URL}/production-assets/${divId}`)).json(); },
    async addProductionAsset(payload)   { return (await fetch(`${API_URL}/production-assets`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateProductionAsset(id, payload) { await fetch(`${API_URL}/production-assets/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deleteProductionAsset(id)     { await fetch(`${API_URL}/production-assets/${id}`, { method:'DELETE' }); },
    async getStagingRuns(divId)         { return (await fetch(`${API_URL}/staging-runs/${divId}`)).json(); },
    async addStagingRun(payload)        { return (await fetch(`${API_URL}/staging-runs`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateStagingRun(id, payload) { await fetch(`${API_URL}/staging-runs/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deleteStagingRun(id)          { await fetch(`${API_URL}/staging-runs/${id}`, { method:'DELETE' }); },
    async getScopeControls(divId)       { return (await fetch(`${API_URL}/scope-controls/${divId}`)).json(); },
    async addScopeControl(payload)      { return (await fetch(`${API_URL}/scope-controls`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateScopeControl(id, payload) { await fetch(`${API_URL}/scope-controls/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deleteScopeControl(id)        { await fetch(`${API_URL}/scope-controls/${id}`, { method:'DELETE' }); },
    async getQaChecks(divId)            { return (await fetch(`${API_URL}/qa-checks/${divId}`)).json(); },
    async addQaCheck(payload)           { return (await fetch(`${API_URL}/qa-checks`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateQaCheck(id, payload)    { await fetch(`${API_URL}/qa-checks/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deleteQaCheck(id)             { await fetch(`${API_URL}/qa-checks/${id}`, { method:'DELETE' }); },
    async getReleaseGates(divId)        { return (await fetch(`${API_URL}/release-gates/${divId}`)).json(); },
    async addReleaseGate(payload)       { return (await fetch(`${API_URL}/release-gates`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateReleaseGate(id, payload){ await fetch(`${API_URL}/release-gates/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deleteReleaseGate(id)         { await fetch(`${API_URL}/release-gates/${id}`, { method:'DELETE' }); },
    async getSuccessLoops(divId)        { return (await fetch(`${API_URL}/success-loops/${divId}`)).json(); },
    async addSuccessLoop(payload)       { return (await fetch(`${API_URL}/success-loops`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateSuccessLoop(id, payload){ await fetch(`${API_URL}/success-loops/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deleteSuccessLoop(id)         { await fetch(`${API_URL}/success-loops/${id}`, { method:'DELETE' }); },

    // ── ONBOARDING ─────────────────────────────────────────────────────────
    async completeOnboarding(payload)   { return (await fetch(`${API_URL}/onboarding/complete`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },

    // ── DAILY BRIEFING ─────────────────────────────────────────────────────
    async getDailyBriefing(force=false) { return (await fetch(`${API_URL}/daily-briefing`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({force}) })).json(); },

    // ── METRICS ────────────────────────────────────────────────────────────
    async getMetrics(divId)             { return (await fetch(`${API_URL}/metrics/${divId}`)).json(); },
    async saveMetric(payload)           { await fetch(`${API_URL}/metrics`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async collectMetrics(date=null)     { return (await fetch(`${API_URL}/metrics/collect`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({ date }) })).json(); },
    async interpretMetrics(divId)       { return (await fetch(`${API_URL}/metrics/interpret`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({division_id:divId}) })).json(); },

    // ── BATTLE PLANS ───────────────────────────────────────────────────────
    async getBattlePlans(divId)         { return (await fetch(`${API_URL}/battle_plans/${divId}`)).json(); },
    async addBattlePlan(payload)        { return (await fetch(`${API_URL}/battle_plans`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async generateAIBattlePlan(divId,period) { return (await fetch(`${API_URL}/battle_plans/ai-generate`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({division_id:divId,target_period:period}) })).json(); },
    async guidedBattlePlan(divId,period,answers) { return (await fetch(`${API_URL}/ai/guided-battle-plan`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({division_id:divId,period,answers}) })).json(); },
    async toggleBattlePlan(id, done)    { await fetch(`${API_URL}/battle_plans/${id}/toggle`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify({done}) }); },
    async deleteBattlePlan(id)          { await fetch(`${API_URL}/battle_plans/${id}`, { method:'DELETE' }); },

    // ── TRAININGS ──────────────────────────────────────────────────────────
    async getTrainings(divId)           { return (await fetch(`${API_URL}/trainings/${divId}`)).json(); },
    async addTraining(payload)          { return (await fetch(`${API_URL}/trainings`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async deleteTraining(id)            { await fetch(`${API_URL}/trainings/${id}`, { method:'DELETE' }); },

    // ── AI ENGINE ──────────────────────────────────────────────────────────
    async generateAiTasks(itemId)       { return (await fetch(`${API_URL}/items/${itemId}/ai-tasks`, { method:'POST' })).json(); },
    async guidedGenerateTasks(itemId, answers) { return (await fetch(`${API_URL}/ai/guided-tasks`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({item_id:itemId,answers}) })).json(); },
    async chat(messages, divisionId, conversationId=null)    {
        const response = await fetch(`${API_URL}/ai/chat`, {
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body:JSON.stringify({messages,division_id:divisionId,conversation_id:conversationId})
        });
        const data = await response.json().catch(() => ({}));
        if (!response.ok) throw new Error(data.error || 'AI chat failed');
        return data;
    },
    async getAIConversations(divId)     { return (await fetch(`${API_URL}/ai/conversations/${divId}`)).json(); },
    async getAIConversation(id)         { return (await fetch(`${API_URL}/ai/conversations/thread/${id}`)).json(); },
    async createAIConversation(divisionId, title='New conversation') { return (await fetch(`${API_URL}/ai/conversations`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({division_id:divisionId,title}) })).json(); },
    async deleteAIConversation(id)      { await fetch(`${API_URL}/ai/conversations/${id}`, { method:'DELETE' }); },
    async translateTexts(texts, targetLanguage) { return (await fetch(`${API_URL}/i18n/translate`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({texts,target_language:targetLanguage}) })).json(); },

    // ── AGENTS ─────────────────────────────────────────────────────────────
    async getAgents(divisionId)         { return (await fetch(`${API_URL}/agents?division_id=${divisionId}`)).json(); },
    async getAgentRuns(divisionId)      { return (await fetch(`${API_URL}/agent-runs?division_id=${divisionId}`)).json(); },
    async generateAgent(payload)        { return (await fetch(`${API_URL}/agents/generate`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateAgent(id, payload)      { return (await fetch(`${API_URL}/agents/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async deleteAgent(id, requestedByDivisionId) { return (await fetch(`${API_URL}/agents/${id}?requested_by_division_id=${requestedByDivisionId}`, { method:'DELETE' })).json(); },
    async runAgent(id, divisionId)      { return (await fetch(`${API_URL}/agents/${id}/run`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({ division_id: divisionId }) })).json(); },
    async runAgents(divisionId)         { return (await fetch(`${API_URL}/agents/run`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({ division_id: divisionId }) })).json(); },

    // ── CLIENT PORTAL ──────────────────────────────────────────────────────
    async getClientPortal(magicLink)    { return (await fetch(`${API_URL}/client/portal/${magicLink}`)).json(); },

    // ── SKILLS ─────────────────────────────────────────────────────────────
    async getSkills(divId)              { return (await fetch(`${API_URL}/skills/${divId}`)).json(); },
    async getAllSkills()                 { return (await fetch(`${API_URL}/skills`)).json(); },
    async addSkill(payload)             { return (await fetch(`${API_URL}/skills`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) })).json(); },
    async updateSkill(id, payload)      { await fetch(`${API_URL}/skills/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) }); },
    async deleteSkill(id)               { await fetch(`${API_URL}/skills/${id}`, { method:'DELETE' }); },
    async aiEditSkill(id, instruction)  { return (await fetch(`${API_URL}/skills/${id}/ai-edit`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({instruction}) })).json(); },
    async backfillSkills()              { return (await fetch(`${API_URL}/skills/backfill`, { method:'POST' })).json(); },

    // ── MEMORY ─────────────────────────────────────────────────────────────
    async getMemory()                   { return (await fetch(`${API_URL}/memory`)).json(); },
    async deleteMemory(id)              { await fetch(`${API_URL}/memory/${id}`, { method:'DELETE' }); },
    async searchMemory(query, divId)    { return (await fetch(`${API_URL}/memory/search`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({query,division_id:divId,top_k:10}) })).json(); },
    async backfillMemory()              { return (await fetch(`${API_URL}/memory/backfill`, { method:'POST' })).json(); }
};
