<?php
// ── Load shared platform bootstrap (session, env, etc.) ──────────────────────
if (!defined('SAVIT_ROOT')) {
    define('SAVIT_ROOT', dirname(__DIR__));
    require_once SAVIT_ROOT . '/Common/bootstrap.php';
}

// ── Load non-sensitive industry/benchmark data from config.json ───────────────
$config_file = __DIR__ . '/config.json';
$config_json = file_exists($config_file) ? (json_decode(file_get_contents($config_file), true) ?? []) : [];

// ── Build config: API credentials come from .env ONLY (never from config.json) -
$config = [
    'defaults' => [
        'industry'      => $config_json['defaults']['industry']    ?? 'ecommerce',
        'budget'        => (int)($_ENV['PPC_DEFAULT_BUDGET']        ?? $config_json['defaults']['budget']        ?? 100000),
        'duration'      => (int)($_ENV['PPC_DEFAULT_DURATION']      ?? $config_json['defaults']['duration']      ?? 30),
        'aov'           => (int)($_ENV['PPC_DEFAULT_AOV']           ?? $config_json['defaults']['aov']           ?? 1500),
        'currency'      => $_ENV['PPC_DEFAULT_CURRENCY_SYMBOL']     ?? $config_json['defaults']['currency']      ?? '\u20b9',
        'currency_code' => $_ENV['PPC_DEFAULT_CURRENCY']            ?? $config_json['defaults']['currency_code'] ?? 'INR',
        'calc_mode'     => $config_json['defaults']['calc_mode']    ?? 'topdown',
    ],
    'lead_category_cpls' => $config_json['lead_category_cpls'] ?? [],
    'industries'         => $config_json['industries']         ?? [],
    'api' => [
        'google_ads' => [
            'enabled'         => filter_var($_ENV['PPC_GOOGLE_ADS_ENABLED']    ?? false, FILTER_VALIDATE_BOOL),
            'customer_id'     => $_ENV['PPC_GOOGLE_ADS_CUSTOMER_ID']     ?? '',
            'developer_token' => $_ENV['PPC_GOOGLE_ADS_DEVELOPER_TOKEN'] ?? '',
            'client_id'       => $_ENV['PPC_GOOGLE_ADS_CLIENT_ID']       ?? $_ENV['GOOGLE_CLIENT_ID']     ?? '',
            'client_secret'   => $_ENV['PPC_GOOGLE_ADS_CLIENT_SECRET']   ?? $_ENV['GOOGLE_CLIENT_SECRET'] ?? '',
            'refresh_token'   => $_ENV['PPC_GOOGLE_ADS_REFRESH_TOKEN']   ?? '',
            'location_id'     => $_ENV['PPC_GOOGLE_ADS_LOCATION_ID']     ?? '2356',
            'language_id'     => $_ENV['PPC_GOOGLE_ADS_LANGUAGE_ID']     ?? '1000',
        ],
        'dataforseo' => [
            'enabled'  => filter_var($_ENV['PPC_DATAFORSEO_ENABLED'] ?? false, FILTER_VALIDATE_BOOL),
            'login'    => $_ENV['PPC_DATAFORSEO_LOGIN']    ?? '',
            'password' => $_ENV['PPC_DATAFORSEO_PASSWORD'] ?? '',
        ],
        'meta' => [
            'enabled'       => filter_var($_ENV['PPC_META_ENABLED'] ?? false, FILTER_VALIDATE_BOOL),
            'access_token'  => $_ENV['PPC_META_ACCESS_TOKEN']  ?? '',
            'graph_version' => $_ENV['PPC_META_GRAPH_VERSION'] ?? 'v17.0',
        ],
        'openai' => [
            'enabled' => !empty($_ENV['OPENAI_API_KEY']),
            'api_key' => $_ENV['OPENAI_API_KEY'] ?? '',
        ],
    ],
];

if (isset($_GET['action'])) {
    header('Content-Type: application/json');
    match($_GET['action']) {
        'fetch_keywords'  => print(json_encode(fetchKeywords(
            trim($_POST['website'] ?? ''),
            trim($_POST['industry'] ?? 'ecommerce'),
            $config,
            trim($_POST['competitors'] ?? '')
        ))),
        'fetch_audience'  => print(json_encode(fetchAudienceTargets(trim($_POST['platform'] ?? 'all'), trim($_POST['website'] ?? ''), trim($_POST['industry'] ?? 'ecommerce'), $config))),
        'refine_audience' => print(json_encode(refineAudienceWithAI($_POST, $config))),
        'save_plan'       => print(json_encode(savePlan($_POST['plan_data'] ?? ''))),
        'get_config'      => print(json_encode([
            // Expose only non-sensitive config to browser
            'defaults'           => $config['defaults'],
            'lead_category_cpls' => $config['lead_category_cpls'],
            'api_status' => [
                'google_ads' => $config['api']['google_ads']['enabled'],
                'dataforseo' => $config['api']['dataforseo']['enabled'],
                'meta'       => $config['api']['meta']['enabled'],
                'openai'     => $config['api']['openai']['enabled'],
            ],
        ])),
        default => print(json_encode(['error' => 'unknown action']))
    };
    exit;
}

function fetchKeywords(string $website, string $industry, array $config, string $competitorsRaw = ''): array {
    $d = $config['api']['dataforseo'] ?? [];
    if (!empty($d['enabled']) && !empty($d['login'])) {
        $r = fetchCommercialKeywordsFromDataForSEO($website, $industry, $d, $config, $competitorsRaw);
        if ($r) return ['source' => 'DataForSEO Paid + SERP', 'keywords' => $r];

        // Fallback to simpler keyword ideas if paid+serp flow yields nothing.
        $fallback = fetchFromDataForSEO($website, $d);
        if ($fallback) return ['source' => 'DataForSEO (Ideas Fallback)', 'keywords' => $fallback];
    }
    $g = $config['api']['google_ads'] ?? [];
    if (!empty($g['enabled']) && !empty($g['developer_token'])) {
        $r = fetchFromGoogleAds($website, $industry, $g, $config);
        if ($r) return ['source' => 'Google Ads API', 'keywords' => $r];
    }
    $seeds = $config['industries'][$industry]['seed_keywords'] ?? [];
    $cpc   = $config['industries'][$industry]['cpc']['google'] ?? 30;
    $mock  = [];
    $volumes = [90500,74000,49500,40500,33100,27100,22200,18100,14800,12100];
    $comps   = ['High','High','Medium','Medium','High','Medium','High','Low','Medium','Low'];
    foreach ($seeds as $i => $kw) {
        $mock[] = ['keyword'=>$kw,'cpc'=>round($cpc*(0.7+($i*0.08)),2),'volume'=>$volumes[$i]??5000,'competition'=>$comps[$i]??'Medium'];
    }
    return ['source' => 'Seed (no API)', 'keywords' => $mock];
}
function fetchAudienceTargets(string $platform, string $website, string $industry, array $config): array {
    $response = ['source' => 'Seed (no API)', 'audience' => ['google' => [], 'meta' => []]];
    $sources = [];
    if (in_array($platform, ['all', 'google'], true)) {
        $g = $config['api']['google_ads'] ?? [];
        if (!empty($g['enabled']) && !empty($g['developer_token']) && !empty($g['customer_id'])) {
            $aud = fetchAudienceFromGoogleAds($website, $industry, $g, $config);
            if ($aud) { $response['audience']['google'] = $aud; $sources[] = 'Google Ads'; }
        }
    }
    if (in_array($platform, ['all', 'meta'], true)) {
        $m = $config['api']['meta'] ?? [];
        if (!empty($m['enabled']) && !empty($m['access_token'])) {
            $industryName = $config['industries'][$industry]['name'] ?? '';
            $aud = fetchAudienceFromMeta($industry, $m);
            if ($aud) { $response['audience']['meta'] = $aud; $sources[] = 'Meta Marketing API'; }
        }
    }
    if (!empty($sources)) {
        $response['source'] = implode(' + ', $sources);
    }
    return $response;
}
function fetchAudienceFromGoogleAds(string $website, string $industry, array $cfg, array $config): array|false {
    $keywords = fetchFromGoogleAds($website, $industry, $cfg, $config);
    if (!$keywords) return false;
    $texts = array_values(array_filter(array_column($keywords, 'keyword')));
    return [
        'custom' => implode(', ', array_slice($texts, 0, 6)),
        'in_market' => $config['industries'][$industry]['audience']['google']['in_market'] ?? '',
        'affinity' => $config['industries'][$industry]['audience']['google']['affinity'] ?? '',
        'remarketing' => $website ? 'Website visitors last 30 days, Cart abandoners, Existing customers' : ''
    ];
}
function fetchAudienceFromMeta(string $query, array $cfg): array|false {
    $token = trim($cfg['access_token'] ?? '');
    if (!$token) return false;
    $version = trim($cfg['graph_version'] ?? 'v17.0');
    // Use a more targeted query based on industry
    $industryQueries = [
        'apparel_fashion' => 'fashion apparel clothing online shopping brands',
        'automotive' => 'cars automotive vehicles auto dealers new cars',
        'aviation' => 'flights airlines travel booking cheap flights',
        'beauty_personal_care' => 'beauty skincare cosmetics makeup hair care',
        'consumer_electronics' => 'electronics gadgets smartphones laptops technology',
        'ecommerce' => 'online shopping retail e-commerce deals',
        'finance' => 'finance banking loans credit cards investments',
        'healthcare' => 'health medical wellness fitness doctors',
        'real_estate' => 'real estate property homes apartments buying selling',
        'travel' => 'travel tourism vacation hotels booking deals'
    ];
    $searchQuery = $industryQueries[$query] ?? $query;
    $result = [];
    $classes = ['interests' => 'interests', 'behaviour' => 'behaviors', 'demographics' => 'demographics'];
    foreach ($classes as $field => $class) {
        $items = fetchMetaTargetingCategories($searchQuery, $class, $version, $token);
        if ($items) {
            $result[$field] = implode(', ', array_slice($items, 0, 6));
        }
    }
    return $result ?: false;
}
function fetchMetaTargetingCategories(string $query, string $class, string $version, string $token): array {
    $url = 'https://graph.facebook.com/' . $version . '/search?type=adTargetingCategory&class=' . urlencode($class) . '&q=' . urlencode($query) . '&limit=8&access_token=' . urlencode($token);
    $ch = curl_init($url);
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_SSL_VERIFYPEER=>false]);
    $raw = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
    if ($code !== 200) return [];
    $data = json_decode($raw, true) ?? [];
    $out = [];
    foreach ($data['data'] ?? [] as $item) {
        if (!empty($item['name'])) {
            $out[] = $item['name'];
            if (count($out) >= 6) break;
        }
    }
    return $out;
}
function sortKeywordsByCompetition(array &$keywords): void {
    $compMap = ['High' => 3, 'Medium' => 2, 'Low' => 1];
    usort($keywords, fn($a,$b) => ($compMap[$b['competition']] ?? 0) <=> ($compMap[$a['competition']] ?? 0));
}

function normalizeDomain(string $input): string {
    $input = trim($input);
    if ($input === '') return '';
    if (!preg_match('#^https?://#i', $input)) {
        $input = 'https://' . $input;
    }
    $host = parse_url($input, PHP_URL_HOST) ?: '';
    $host = strtolower(trim($host));
    return preg_replace('/^www\./i', '', $host);
}

function parseCompetitorDomains(string $raw, string $website): array {
    $domains = [];
    $siteDomain = normalizeDomain($website);
    if ($siteDomain !== '') $domains[] = $siteDomain;

    if ($raw !== '') {
        foreach (preg_split('/[\s,;\n]+/', $raw) as $candidate) {
            $d = normalizeDomain($candidate);
            if ($d !== '') $domains[] = $d;
        }
    }

    $domains = array_values(array_unique($domains));
    return array_slice($domains, 0, 3);
}

function inferIntent(string $keyword): string {
    $kw = strtolower($keyword);
    $transactional = ['buy', 'price', 'cost', 'near me', 'quote', 'book', 'hire', 'service', 'agency', 'company', 'dealer'];
    $commercial    = ['best', 'top', 'review', 'vs', 'comparison', 'compare'];
    $informational = ['what is', 'how to', 'meaning', 'guide', 'tutorial', 'examples'];

    foreach ($transactional as $term) if (str_contains($kw, $term)) return 'Transactional';
    foreach ($commercial as $term)    if (str_contains($kw, $term)) return 'Commercial';
    foreach ($informational as $term) if (str_contains($kw, $term)) return 'Informational';
    return 'Commercial';
}

function calculateCommercialScore(array $row, array $serpSignals): int {
    $intent = strtolower((string)($row['intent'] ?? ''));
    $intentScore = match ($intent) {
        'transactional' => 35,
        'commercial'    => 27,
        'navigational'  => 15,
        'informational' => 8,
        default         => 18,
    };

    $comp = strtolower((string)($row['competition'] ?? ''));
    $competitionScore = match ($comp) {
        'high'   => 20,
        'medium' => 13,
        'low'    => 7,
        default  => 8,
    };

    $cpc = (float)($row['cpc'] ?? 0);
    $cpcScore = min(10, (int)round($cpc / 6));

    $volume = (int)($row['volume'] ?? 0);
    $volumeScore = min(10, (int)round(log(max(1, $volume), 10) * 2));

    $serpScore = (int)($serpSignals['commercial_score'] ?? 0);

    return $intentScore + $competitionScore + $cpcScore + $volumeScore + $serpScore;
}

function postDataForSeo(string $url, array $payload, array $cfg): ?array {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode([$payload]),
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_CONNECTTIMEOUT => 8,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Basic ' . base64_encode("{$cfg['login']}:{$cfg['password']}"),
            'Content-Type: application/json',
        ],
    ]);
    $raw = curl_exec($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($code !== 200 || !$raw) return null;
    $data = json_decode($raw, true);
    return is_array($data) ? $data : null;
}

function extractKeywordItemsFromDataForSeo(array $data): array {
    $items = [];
    foreach (($data['tasks'] ?? []) as $task) {
        foreach (($task['result'] ?? []) as $result) {
            foreach (($result['items'] ?? []) as $item) {
                $keyword = $item['keyword'] ?? ($item['keyword_data']['keyword'] ?? '');
                if (!$keyword) continue;

                $ki = $item['keyword_info'] ?? ($item['keyword_data']['keyword_info'] ?? []);
                $intentInfo = $item['search_intent_info'] ?? ($item['keyword_data']['search_intent_info'] ?? []);
                $items[] = [
                    'keyword' => $keyword,
                    'cpc' => round((float)($ki['cpc'] ?? 0), 2),
                    'volume' => (int)($ki['search_volume'] ?? 0),
                    'competition' => ucfirst(strtolower((string)($ki['competition_level'] ?? 'Unknown'))),
                    'intent' => ucfirst(strtolower((string)($intentInfo['main_intent'] ?? ''))),
                ];
            }
        }
    }
    return $items;
}

function fetchPaidKeywordsForDomainDataForSeo(string $domain, array $cfg, int $limit = 50): array {
    // Try paid-focused endpoint first.
    $urlPaid = 'https://api.dataforseo.com/v3/dataforseo_labs/google/paid_keywords/live';
    $payloadPaid = [
        'target' => $domain,
        'location_code' => 2356,
        'language_code' => 'en',
        'limit' => $limit,
    ];
    $data = postDataForSeo($urlPaid, $payloadPaid, $cfg);
    $items = $data ? extractKeywordItemsFromDataForSeo($data) : [];
    if (!empty($items)) return $items;

    // Fallback: ranked keywords endpoint, then infer by commercial scoring.
    $urlRanked = 'https://api.dataforseo.com/v3/dataforseo_labs/google/ranked_keywords/live';
    $payloadRanked = [
        'target' => $domain,
        'location_code' => 2356,
        'language_code' => 'en',
        'limit' => $limit,
    ];
    $dataRanked = postDataForSeo($urlRanked, $payloadRanked, $cfg);
    return $dataRanked ? extractKeywordItemsFromDataForSeo($dataRanked) : [];
}

function fetchSerpCommercialSignalsDataForSeo(string $keyword, array $cfg): array {
    $url = 'https://api.dataforseo.com/v3/serp/google/organic/live/advanced';
    $payload = [
        'keyword' => $keyword,
        'location_code' => 2356,
        'language_code' => 'en',
        'depth' => 10,
    ];
    $data = postDataForSeo($url, $payload, $cfg);
    if (!$data) {
        return ['commercial_score' => 0, 'ads' => 0, 'shopping' => false, 'map' => false, 'lead_style' => false];
    }

    $ads = 0;
    $shopping = false;
    $map = false;
    $leadStyle = false;
    foreach (($data['tasks'] ?? []) as $task) {
        foreach (($task['result'] ?? []) as $result) {
            foreach (($result['items'] ?? []) as $item) {
                $type = strtolower((string)($item['type'] ?? ''));
                if (str_contains($type, 'paid')) $ads++;
                if (str_contains($type, 'shopping')) $shopping = true;
                if (str_contains($type, 'local_pack') || str_contains($type, 'map')) $map = true;

                $title = strtolower((string)($item['title'] ?? ''));
                $urlFound = strtolower((string)($item['url'] ?? ''));
                if (
                    str_contains($title, 'quote') || str_contains($title, 'book') || str_contains($title, 'pricing') ||
                    str_contains($urlFound, '/contact') || str_contains($urlFound, '/book') || str_contains($urlFound, '/quote')
                ) {
                    $leadStyle = true;
                }
            }
        }
    }

    $score = 0;
    $score += $ads >= 3 ? 12 : ($ads >= 1 ? 8 : 0);
    if ($shopping) $score += 6;
    if ($map) $score += 5;
    if ($leadStyle) $score += 4;

    return ['commercial_score' => $score, 'ads' => $ads, 'shopping' => $shopping, 'map' => $map, 'lead_style' => $leadStyle];
}

function fetchCommercialKeywordsFromDataForSEO(string $website, string $industry, array $cfg, array $config, string $competitorsRaw = ''): array|false {
    $domains = parseCompetitorDomains($competitorsRaw, $website);
    if (empty($domains)) return false;

    $pool = [];
    foreach ($domains as $domain) {
        $rows = fetchPaidKeywordsForDomainDataForSeo($domain, $cfg, 20);
        foreach ($rows as $row) {
            $key = strtolower(trim((string)($row['keyword'] ?? '')));
            if ($key === '') continue;
            if (!isset($pool[$key])) {
                $pool[$key] = $row;
                $pool[$key]['source_domain'] = $domain;
            } else {
                // Keep stronger CPC/volume if duplicate appears across domains.
                if ((float)($row['cpc'] ?? 0) > (float)($pool[$key]['cpc'] ?? 0)) $pool[$key]['cpc'] = $row['cpc'];
                if ((int)($row['volume'] ?? 0) > (int)($pool[$key]['volume'] ?? 0)) $pool[$key]['volume'] = $row['volume'];
            }
        }
    }

    if (empty($pool)) return false;

    $keywords = array_values($pool);
    usort($keywords, fn($a, $b) => ((float)($b['cpc'] ?? 0) <=> (float)($a['cpc'] ?? 0)) ?: ((int)($b['volume'] ?? 0) <=> (int)($a['volume'] ?? 0)));

    // Run SERP signal mining on top candidates to keep API usage controlled.
    $topForSignals = array_slice($keywords, 0, 10);
    $scored = [];
    foreach ($topForSignals as $row) {
        $row['intent'] = $row['intent'] ?: inferIntent((string)($row['keyword'] ?? ''));
        $signals = fetchSerpCommercialSignalsDataForSeo((string)$row['keyword'], $cfg);
        $row['serp_ads'] = (int)$signals['ads'];
        $row['serp_has_shopping'] = (bool)$signals['shopping'];
        $row['serp_has_map_pack'] = (bool)$signals['map'];
        $row['serp_lead_style'] = (bool)$signals['lead_style'];
        $row['commercial_score'] = calculateCommercialScore($row, $signals);
        $scored[] = $row;
    }

    // Backfill any remaining rows without SERP scan.
    foreach (array_slice($keywords, 30) as $row) {
        $row['intent'] = $row['intent'] ?: inferIntent((string)($row['keyword'] ?? ''));
        $row['serp_ads'] = 0;
        $row['serp_has_shopping'] = false;
        $row['serp_has_map_pack'] = false;
        $row['serp_lead_style'] = false;
        $row['commercial_score'] = calculateCommercialScore($row, ['commercial_score' => 0]);
        $scored[] = $row;
    }

    usort($scored, fn($a, $b) => ((int)($b['commercial_score'] ?? 0) <=> (int)($a['commercial_score'] ?? 0)) ?: ((float)($b['cpc'] ?? 0) <=> (float)($a['cpc'] ?? 0)));
    return array_slice($scored, 0, 10);
}
function fetchFromGoogleAds(string $website, string $industry, array $cfg, array $config): array|false {
    $token = refreshGoogleToken($cfg);
    if (!$token) return false;
    $ind = $config['industries'][$industry] ?? [];
    $seeds = $ind['seed_keywords'] ?? [$website];
    $payload = json_encode(['keywordSeed'=>['keywords'=>$seeds],'language'=>'languageConstants/'.($cfg['language_id']??'1000'),'geoTargetConstants'=>['geoTargetConstants/'.($cfg['location_id']??'2356')],'keywordPlanNetwork'=>'GOOGLE_SEARCH_AND_PARTNERS']);
    $ch = curl_init("https://googleads.googleapis.com/v14/customers/{$cfg['customer_id']}:generateKeywordIdeas");
    curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>$payload,CURLOPT_SSL_VERIFYPEER=>false,CURLOPT_HTTPHEADER=>["Authorization: Bearer $token","developer-token: {$cfg['developer_token']}",'Content-Type: application/json']]);
    $raw = curl_exec($ch); $code = curl_getinfo($ch,CURLINFO_HTTP_CODE); curl_close($ch);
    if ($code !== 200) return false;
    $data = json_decode($raw,true)??[];
    $out = [];
    foreach ($data['results']??[] as $item) {
        $m = $item['keywordIdeaMetrics']??[];
        $out[] = ['keyword'=>$item['text']??'','cpc'=>round(($m['averageCpcMicros']??0)/1000000,2),'volume'=>(int)($m['avgMonthlySearches']??0),'competition'=>ucfirst(strtolower($m['competition']??'UNKNOWN'))];
    }
    usort($out,fn($a,$b)=>$b['volume']<=>$a['volume']);
    return array_slice($out,0,10);
}
function refreshGoogleToken(array $cfg): string|false {
    $ch = curl_init('https://oauth2.googleapis.com/token');
    curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query(['client_id'=>$cfg['client_id'],'client_secret'=>$cfg['client_secret'],'refresh_token'=>$cfg['refresh_token'],'grant_type'=>'refresh_token']),CURLOPT_SSL_VERIFYPEER=>false]);
    $r = json_decode(curl_exec($ch),true)??[]; curl_close($ch);
    return $r['access_token']??false;
}
function fetchFromDataForSEO(string $website, array $cfg): array|false {
    $domain = parse_url($website,PHP_URL_HOST)?:$website;
    // Using keywords_for_domain to get keywords the site actually ranks for
    $payload = json_encode([['keywords'=>[$domain],'location_code'=>2356,'language_code'=>'en','limit'=>20]]);
    $ch = curl_init('https://api.dataforseo.com/v3/dataforseo_labs/google/keyword_ideas/live');
    curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>$payload,CURLOPT_SSL_VERIFYPEER=>false,CURLOPT_HTTPHEADER=>['Authorization: Basic '.base64_encode("{$cfg['login']}:{$cfg['password']}"),'Content-Type: application/json']]);
    $res = curl_exec($ch); $code = curl_getinfo($ch,CURLINFO_HTTP_CODE); curl_close($ch);
    
    // DEBUG: Log the response to a file we can check
    file_put_contents(__DIR__ . '/api_debug.log', "URL: " . $domain . "\nCode: " . $code . "\nResponse: " . $res . "\n\n", FILE_APPEND);

    $data = json_decode($res,true)??[];
    if (empty($data['tasks'][0]['result'])) return false;
    $out = [];
    foreach ($data['tasks'][0]['result'] as $item) {
        foreach ($item['items']??[] as $kw) {
            $ki = $kw['keyword_info']??[];
            $out[] = [
                'keyword' => $kw['keyword'] ?? '',
                'cpc'     => round((float)($ki['cpc'] ?? 0), 2),
                'volume'  => (int)($ki['search_volume'] ?? 0),
                'competition' => ucfirst(strtolower($ki['competition_level'] ?? 'Unknown')),
                'intent'  => ucfirst(strtolower((string)($kw['search_intent_info']['main_intent'] ?? inferIntent((string)($kw['keyword'] ?? '')))))
            ];
        }
    }
    usort($out,fn($a,$b)=>$b['volume']<=>$a['volume']);
    return array_slice($out,0,10);
}
function savePlan(string $json): array {
    $data = json_decode($json,true);
    if (!$data) return ['success'=>false,'error'=>'Invalid JSON'];
    $dir = __DIR__.'/saved_plans';
    if (!is_dir($dir)) mkdir($dir,0755,true);
    $file = $dir.'/plan_'.date('Ymd_His').'.json';
    file_put_contents($file,json_encode($data,JSON_PRETTY_PRINT));
    return ['success'=>true,'filename'=>basename($file)];
}
function refineAudienceWithAI(array $post, array $config): array {
    $o = $config['api']['openai'] ?? [];
    if (empty($o['enabled']) || empty($o['api_key'])) return ['error' => 'OpenAI not configured'];
    $industry = $post['industry'] ?? 'ecommerce';
    $goals = $post['goals'] ?? '';
    $current = $post['current_audience'] ?? '';
    $prompt = "Based on the industry: $industry, client goals: $goals, and current Meta audience targeting: $current, suggest improved interests, behaviors, and demographics for better business audience selection. Provide in JSON format: {\"interests\": \"comma separated\", \"behaviors\": \"comma separated\", \"demographics\": \"comma separated\"}";
    $payload = json_encode(['model' => 'gpt-3.5-turbo', 'messages' => [['role' => 'user', 'content' => $prompt]], 'max_tokens' => 300]);
    $ch = curl_init('https://api.openai.com/v1/chat/completions');
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_HTTPHEADER => ["Authorization: Bearer {$o['api_key']}", 'Content-Type: application/json']]);
    $res = curl_exec($ch); curl_close($ch);
    $data = json_decode($res, true) ?? [];
    $content = $data['choices'][0]['message']['content'] ?? '';
    $suggestions = json_decode($content, true) ?? ['error' => 'Failed to parse AI response'];
    return $suggestions;
}

$industries  = $config['industries'] ?? [];
$defaults    = $config['defaults']   ?? [];
$currency    = $defaults['currency'] ?? '₹';
$config_json = json_encode($config, JSON_HEX_TAG | JSON_HEX_APOS);
$grouped = [];
foreach ($industries as $key => $ind) { $grouped[$ind['group']??'Other'][$key] = $ind['name']; }
ksort($grouped);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>PPC Engine — Savit</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Inter',system-ui,sans-serif;font-size:13px;background:#f0f2f5;color:#1e293b}
input,select,textarea,button{font-family:inherit}

/* SIDEBAR */
.app-shell{display:flex;min-height:100vh}
.sidebar{width:210px;min-height:100vh;background:#0f172a;display:flex;flex-direction:column;flex-shrink:0;position:sticky;top:0;height:100vh;overflow-y:auto}
.sidebar-brand{padding:18px 16px 12px;border-bottom:1px solid #1e293b}
.sidebar-brand .logo-text{font-size:14px;font-weight:800;color:#fff;letter-spacing:-.3px}
.sidebar-brand .logo-sub{font-size:10px;color:#64748b;letter-spacing:.5px;text-transform:uppercase;margin-top:2px}
.sidebar-section{padding:12px 10px 4px;font-size:10px;font-weight:700;color:#475569;text-transform:uppercase;letter-spacing:.8px}
.sidebar-nav a{display:flex;align-items:center;gap:9px;padding:8px 12px;margin:1px 6px;border-radius:6px;color:#94a3b8;text-decoration:none;font-size:12px;font-weight:500;transition:all .15s}
.sidebar-nav a:hover{background:#1e293b;color:#e2e8f0}
.sidebar-nav a.active{background:#2563eb;color:#fff}
.sidebar-nav a .bi{font-size:13px;width:15px;text-align:center}
.sidebar-nav a .soon{font-size:9px;padding:1px 5px;background:#1e293b;color:#475569;border-radius:8px;margin-left:auto}
.sidebar-footer{margin-top:auto;padding:10px 12px;border-top:1px solid #1e293b}
.sidebar-footer small{color:#475569;font-size:10px}

/* TOPBAR */
.main-wrap{flex:1;display:flex;flex-direction:column;min-width:0}
.topbar{background:#fff;border-bottom:1px solid #e2e8f0;padding:0 20px;height:48px;display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;z-index:200}
.topbar-title{font-weight:800;font-size:14px;color:#0f172a;display:flex;align-items:center;gap:7px}
.topbar-title .bi{color:#2563eb;font-size:16px}
.topbar-actions{display:flex;gap:6px;align-items:center}
.btn-tb{height:30px;padding:0 11px;font-size:11px;font-weight:600;border-radius:6px;border:none;cursor:pointer;display:inline-flex;align-items:center;gap:4px;transition:all .15s}
.btn-tb-outline{background:#fff;border:1px solid #e2e8f0;color:#475569}
.btn-tb-outline:hover{background:#f8fafc;border-color:#cbd5e1}
.btn-tb-primary{background:#2563eb;color:#fff}.btn-tb-primary:hover{background:#1d4ed8}
.btn-tb-green{background:#16a34a;color:#fff}.btn-tb-green:hover{background:#15803d}
.btn-tb-red{background:#dc2626;color:#fff}.btn-tb-red:hover{background:#b91c1c}
.api-status{font-size:11px;padding:3px 9px;border-radius:6px;font-weight:600}
.api-ok{background:#dcfce7;color:#166534}.api-off{background:#f1f5f9;color:#64748b}

/* TAB NAV BAR */
.tab-nav-bar{background:#fff;border-bottom:2px solid #e2e8f0;padding:0 20px;display:flex;gap:2px;position:sticky;top:48px;z-index:150;overflow-x:auto}
.tab-btn{border:none;background:transparent;padding:12px 16px;font-size:12px;font-weight:600;color:#64748b;cursor:pointer;border-bottom:2px solid transparent;margin-bottom:-2px;white-space:nowrap;display:flex;align-items:center;gap:6px;transition:all .15s}
.tab-btn:hover{color:#1e293b;background:#f8fafc}
.tab-btn.active{color:#2563eb;border-bottom-color:#2563eb;background:transparent}
.tab-btn .bi{font-size:13px}

/* PAGE CONTENT */
.page-content{padding:18px 20px;flex:1}
.tab-pane{display:none}.tab-pane.active{display:block}

/* SECTION CARDS */
.pcard{background:#fff;border:1px solid #e2e8f0;border-radius:10px;margin-bottom:14px}
.pcard-head{padding:11px 16px;border-bottom:1px solid #f1f5f9;display:flex;align-items:center;gap:8px;font-weight:700;font-size:13px;color:#0f172a}
.pcard-head .ph-icon{width:24px;height:24px;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;font-size:12px;color:#fff;flex-shrink:0}
.ph-icon.blue{background:#2563eb}.ph-icon.purple{background:#7c3aed}.ph-icon.teal{background:#0891b2}
.ph-icon.green{background:#16a34a}.ph-icon.amber{background:#d97706}.ph-icon.red{background:#dc2626}.ph-icon.slate{background:#475569}
.pcard-body{padding:14px 16px}

/* COMPACT GOAL CHIPS */
.goal-chips{display:flex;gap:8px;flex-wrap:wrap}
.goal-chip{display:inline-flex;align-items:center;gap:6px;padding:7px 14px;border:2px solid #e2e8f0;border-radius:20px;cursor:pointer;font-size:12px;font-weight:600;color:#475569;background:#fff;user-select:none;transition:all .15s;position:relative}
.goal-chip:hover{border-color:#93c5fd;color:#2563eb;background:#f0f7ff}
.goal-chip.selected{border-color:#2563eb;background:#eff6ff;color:#2563eb}
.goal-chip.selected.awareness{border-color:#7c3aed;background:#f5f3ff;color:#7c3aed}
.goal-chip.selected.consideration{border-color:#0891b2;background:#ecfeff;color:#0891b2}
.goal-chip.selected.conversion{border-color:#16a34a;background:#f0fdf4;color:#16a34a}
.chip-icon{font-size:14px}
.chip-check{font-size:11px;margin-left:2px}

/* COMPACT PLATFORM CHIPS */
.platform-chips{display:flex;gap:8px;flex-wrap:wrap}
.platform-chip{display:inline-flex;align-items:center;gap:8px;padding:7px 16px;border:2px solid #e2e8f0;border-radius:20px;cursor:pointer;font-size:12px;font-weight:600;color:#475569;background:#fff;user-select:none;transition:all .15s}
.platform-chip:hover{border-color:#93c5fd;background:#f0f7ff}
.platform-chip.selected.google{border-color:#4285f4;background:#f0f4ff;color:#4285f4}
.platform-chip.selected.meta{border-color:#1877f2;background:#f0f4ff;color:#1877f2}
.plat-mini-logo{width:22px;height:22px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;font-size:11px;font-weight:800;color:#fff;flex-shrink:0}
.plat-mini-logo.google{background:linear-gradient(135deg,#4285f4,#34a853)}
.plat-mini-logo.meta{background:linear-gradient(135deg,#1877f2,#42a5f5)}

/* DURATION PILLS */
.dur-pills{display:flex;background:#f1f5f9;border-radius:8px;padding:3px;gap:2px}
.dur-pill{flex:1;border:none;background:transparent;padding:6px 10px;border-radius:6px;font-size:12px;font-weight:600;color:#64748b;cursor:pointer;transition:all .15s;white-space:nowrap}
.dur-pill.active{background:#fff;color:#2563eb;box-shadow:0 1px 3px rgba(0,0,0,.1)}

/* CALC MODE */
.calc-mode-pill{display:flex;background:#f1f5f9;border-radius:8px;padding:3px;gap:2px}
.calc-mode-pill button{flex:1;border:none;background:transparent;padding:6px 12px;border-radius:6px;font-size:12px;font-weight:600;color:#64748b;cursor:pointer;transition:all .15s}
.calc-mode-pill button.active{background:#fff;color:#2563eb;box-shadow:0 1px 3px rgba(0,0,0,.1)}
.goalfirst-panel{background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:12px;margin-top:10px}
.goal-type-row{display:flex;gap:8px;align-items:center;margin-bottom:10px}
.goal-type-select{flex:1;border:1px solid #e2e8f0;border-radius:6px;padding:6px 10px;font-size:12px;font-weight:600;color:#1e293b;background:#fff;outline:none;cursor:pointer}
.goalfirst-inputs{display:grid;grid-template-columns:1fr 1fr;gap:8px}
.gf-label{font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin-bottom:3px}

/* BENCH TABLE */
.bench-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}
@media(max-width:900px){.bench-grid{grid-template-columns:1fr}}
.bench-table{width:100%;border-collapse:collapse;font-size:12px}
.bench-table th{background:#f8fafc;color:#475569;font-weight:700;font-size:11px;text-transform:uppercase;letter-spacing:.4px;padding:7px 10px;border-bottom:2px solid #e2e8f0;text-align:left}
.bench-table td{padding:6px 10px;border-bottom:1px solid #f1f5f9;vertical-align:middle}
.bench-table tr:last-child td{border-bottom:none}
.bench-table input[type=number]{width:100%;border:1px solid #e2e8f0;border-radius:5px;padding:4px 7px;font-size:12px;text-align:right;background:#fff;outline:none;transition:border .15s}
.bench-table input[type=number]:focus{border-color:#2563eb;box-shadow:0 0 0 2px rgba(37,99,235,.1)}
.bench-table input.overridden{background:#fffbeb;border-color:#f59e0b}
.src-badge{font-size:10px;padding:2px 6px;border-radius:10px;font-weight:600}
.src-auto{background:#dbeafe;color:#1d4ed8}.src-manual{background:#fef3c7;color:#92400e}

/* SPLIT SLIDERS */
.split-row{display:flex;align-items:center;gap:8px;margin-bottom:8px}
.split-label{width:105px;font-size:12px;font-weight:600;color:#374151;display:flex;align-items:center;gap:5px;flex-shrink:0}
.split-label .dot{width:8px;height:8px;border-radius:50%;flex-shrink:0}
.split-slider{flex:1;accent-color:#2563eb}
.split-input{width:48px;border:1px solid #e2e8f0;border-radius:5px;padding:3px 5px;font-size:12px;text-align:center}

/* KPI GRID */
.kpi-grid{display:grid;grid-template-columns:repeat(6,1fr);gap:10px}
@media(max-width:1100px){.kpi-grid{grid-template-columns:repeat(3,1fr)}}
.kpi-card{border:1px solid #e2e8f0;border-radius:8px;padding:12px 14px;background:#fff;text-align:center}
.kpi-card.highlight{background:#eff6ff;border-color:#bfdbfe}
.kpi-label{font-size:10px;color:#64748b;text-transform:uppercase;letter-spacing:.5px;font-weight:600;margin-bottom:4px}
.kpi-value{font-size:1.3rem;font-weight:800;color:#0f172a;letter-spacing:-.5px}
.kpi-card.highlight .kpi-value{color:#2563eb}

/* MEDIA PLAN TABLES - NEW STYLE */
.mp-section{margin-bottom:20px}
.mp-month-label{font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;padding:8px 0 6px;display:flex;align-items:center;gap:8px}
.mp-month-label .month-badge{background:#1e293b;color:#e2e8f0;font-size:10px;padding:2px 8px;border-radius:10px}
.output-table-wrap{overflow-x:auto;border-radius:0 0 8px 8px}
.output-table{width:100%;border-collapse:collapse;font-size:11.5px;min-width:900px}
.output-table thead th{background:#1e293b;color:#e2e8f0;padding:9px 10px;font-size:10px;font-weight:700;letter-spacing:.4px;white-space:nowrap;text-transform:uppercase}
.output-table thead th:first-child{border-radius:0}
.output-table tbody td{padding:7px 10px;border-bottom:1px solid #f1f5f9;vertical-align:middle;white-space:nowrap}
.output-table tbody tr:hover td{background:#f8fafc}
.output-table tbody tr.platform-google td:first-child{border-left:3px solid #4285f4}
.output-table tbody tr.platform-meta td:first-child{border-left:3px solid #1877f2}
.output-table tfoot td{padding:8px 10px;background:#f8fafc;font-weight:700;border-top:2px solid #e2e8f0;font-size:11px}
.output-table input[type=number]{width:100%;min-width:70px;border:1px solid transparent;border-radius:4px;padding:3px 6px;text-align:right;background:transparent;font-size:11px;font-weight:500;transition:all .15s}
.output-table input[type=number]:hover{border-color:#cbd5e1;background:#fff}
.output-table input[type=number]:focus{border-color:#2563eb;background:#fff;outline:none}
.output-table input.overridden{background:#fffbeb;border-color:#f59e0b}
.output-table td.calc{color:#374151;font-weight:500}
.output-table td.meta-col{color:#64748b;font-size:11px}
.plat-badge{display:inline-flex;align-items:center;gap:4px;font-weight:700;font-size:11px}
.plat-badge.google{color:#4285f4}.plat-badge.meta{color:#1877f2}
.channel-tag{display:inline-block;font-size:10px;padding:2px 7px;border-radius:10px;font-weight:600;background:#f1f5f9;color:#475569}
.buying-tag{display:inline-block;font-size:10px;padding:2px 7px;border-radius:10px;font-weight:700}
.buying-cpm{background:#dbeafe;color:#1d4ed8}
.buying-cpc{background:#dcfce7;color:#166534}
.buying-cpv{background:#fef9c3;color:#854d0e}
.buying-cpl{background:#fce7f3;color:#9d174d}

/* MONTH GROWTH INDICATOR */
.mom-badge{font-size:10px;padding:2px 6px;border-radius:8px;font-weight:700;margin-left:6px}
.mom-up{background:#dcfce7;color:#166534}
.mom-base{background:#f1f5f9;color:#64748b}

/* AUDIENCE */
.aud-platform-tabs{display:flex;gap:6px;margin-bottom:14px}
.aud-tab-btn{padding:8px 18px;border:2px solid #e2e8f0;border-radius:8px;background:#fff;font-size:12px;font-weight:600;color:#64748b;cursor:pointer;transition:all .15s;display:flex;align-items:center;gap:6px}
.aud-tab-btn.active.google{border-color:#4285f4;background:#f0f4ff;color:#4285f4}
.aud-tab-btn.active.meta{border-color:#1877f2;background:#f0f4ff;color:#1877f2}
.aud-section{margin-bottom:16px}
.aud-section-head{font-size:11px;font-weight:700;color:#1e293b;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px;display:flex;align-items:center;gap:6px}
.aud-section-head .aud-path{font-size:10px;font-weight:400;color:#94a3b8;text-transform:none;letter-spacing:0}
.aud-textarea{font-size:12px;min-height:72px;resize:vertical;border:1px solid #e2e8f0;border-radius:6px;padding:8px;width:100%;outline:none;transition:border .15s;line-height:1.5;background:#fff}
.aud-textarea:focus{border-color:#2563eb;box-shadow:0 0 0 2px rgba(37,99,235,.1)}
.aud-input{width:100%;border:1px solid #e2e8f0;border-radius:6px;padding:6px 10px;font-size:12px;outline:none;transition:border .15s}
.aud-input:focus{border-color:#2563eb;box-shadow:0 0 0 2px rgba(37,99,235,.1)}
.demo-row{display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin-bottom:8px}

/* KEYWORD TABLE */
.kw-comp{font-size:10px;padding:2px 7px;border-radius:10px;font-weight:600}
.kw-High{background:#fee2e2;color:#991b1b}.kw-Medium{background:#fef3c7;color:#92400e}.kw-Low{background:#dcfce7;color:#166534}
.kw-used-badge{font-size:10px;padding:2px 7px;border-radius:10px;background:#dbeafe;color:#1d4ed8;font-weight:600}
.kw-fetch-indicator{display:inline-flex;align-items:center;gap:5px;font-size:11px;color:#64748b}

/* COMING SOON PANEL */
.coming-soon-panel{border:2px dashed #e2e8f0;border-radius:8px;padding:14px 18px;background:#f8fafc;display:flex;align-items:center;gap:12px}
.coming-soon-panel .cs-icon{font-size:22px;opacity:.4}
.coming-soon-panel .cs-text{font-size:12px;color:#94a3b8;font-weight:500}
.coming-soon-panel .cs-badge{font-size:10px;padding:2px 8px;background:#f1f5f9;color:#64748b;border-radius:10px;font-weight:700;margin-left:8px}

/* FORMS */
.form-label-sm{font-size:10px;font-weight:700;text-transform:uppercase;color:#64748b;letter-spacing:.5px;margin-bottom:4px;display:block}
.form-ctrl{width:100%;border:1px solid #e2e8f0;border-radius:6px;padding:7px 10px;font-size:13px;outline:none;transition:border .15s;background:#fff}
.form-ctrl:focus{border-color:#2563eb;box-shadow:0 0 0 2px rgba(37,99,235,.1)}
.form-ctrl.fw{font-weight:700}

/* INDUSTRY DROPDOWN */
.industry-search{position:relative}
.industry-search .bi-search{position:absolute;right:10px;top:50%;transform:translateY(-50%);color:#94a3b8;pointer-events:none;font-size:12px}
.ind-dropdown{position:absolute;top:100%;left:0;right:0;background:#fff;border:1px solid #e2e8f0;border-radius:8px;max-height:240px;overflow-y:auto;z-index:300;box-shadow:0 8px 24px rgba(0,0,0,.12);display:none}
.ind-dropdown.open{display:block}
.ind-group-label{padding:5px 12px;font-size:10px;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:.5px;background:#f8fafc;position:sticky;top:0}
.ind-item{padding:7px 14px;cursor:pointer;font-size:12px;color:#374151;display:flex;justify-content:space-between;align-items:center}
.ind-item:hover{background:#eff6ff;color:#2563eb}
.ind-item.selected{color:#2563eb;font-weight:600}
.ind-item .ind-group-tag{font-size:10px;color:#94a3b8}

/* CHART */
.chart-row{display:grid;grid-template-columns:1fr 1fr;gap:14px}
@media(max-width:800px){.chart-row{grid-template-columns:1fr}}
.chart-box{background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:14px}
.chart-title{font-size:11px;font-weight:700;color:#475569;margin-bottom:10px;text-transform:uppercase;letter-spacing:.4px}

/* PRINT */
@media print{
  @page{size:A4 landscape;margin:12mm 10mm}
  *{-webkit-print-color-adjust:exact!important;print-color-adjust:exact!important}
  .sidebar,.topbar,.tab-nav-bar,.no-print{display:none!important}
  .app-shell,.main-wrap{display:block}
  .page-content{padding:0}.tab-pane{display:block!important}
  .pcard{border:1px solid #d1d5db;break-inside:avoid;margin-bottom:8px}
  .output-table thead th{background:#1e293b!important;color:#fff!important;padding:6px 8px;font-size:10px}
  .output-table tbody td{padding:5px 8px;font-size:10px}
  .output-table input[type=number]{border:none!important;background:transparent!important;text-align:right;font-size:10px;padding:0;width:auto}
  .kpi-grid{grid-template-columns:repeat(6,1fr)!important}
  #print-header{display:block!important}
}
#print-header{display:none}
.print-logo{font-size:20px;font-weight:800;color:#0f172a}
.print-divider{border:none;border-top:2px solid #1e293b;margin:10px 0}

/* MISC */
.section-row{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px}
@media(max-width:900px){.section-row{grid-template-columns:1fr}}
.section-row-4{display:grid;grid-template-columns:repeat(4,1fr);gap:12px}
@media(max-width:900px){.section-row-4{grid-template-columns:1fr 1fr}}
.mt10{margin-top:10px}.mt14{margin-top:14px}.mt16{margin-top:16px}
.fw7{font-weight:700}.fs11{font-size:11px}.c-slate{color:#64748b}
.split-warn{font-size:11px;font-weight:600}
.fade-row{transition:opacity .2s}.fade-row.hidden{opacity:.3;pointer-events:none}
</style>
</head>
<body>
<div class="app-shell">
<?php
// Derive URL paths for sidebar
$_ppcDir   = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? '/PPC/media_plan.php'), '/');
$savitBase = dirname($_ppcDir); // /Savit (URL path, not filesystem)

$activeEngine     = 'ppc';
$engineBadgeLabel = 'PPC Engine';
$engineSubnav = [
    ['label' => 'Media Planner',    'icon' => 'layout-text-window-reverse', 'url' => 'media_plan.php', 'active' => true],
    ['label' => 'Keyword Planner',  'icon' => 'search',     'url' => '#', 'active' => false],
    ['label' => 'Budget Estimator', 'icon' => 'calculator', 'url' => '#', 'active' => false],
    ['label' => 'ROAS Calculator',  'icon' => 'pie-chart',  'url' => '#', 'active' => false],
];
?>
<?php require SAVIT_ROOT . '/Common/views/layout/sidebar.php'; ?>



<!-- MAIN -->
<div class="main-wrap">


<!-- TOPBAR -->
<div class="topbar no-print">
  <div class="topbar-title"><i class="bi bi-bar-chart-fill" style="color:#2563eb"></i> PPC Media Planner</div>
  <div class="topbar-actions">
    <span id="api_status_badge" class="api-status api-off"><i class="bi bi-circle-fill" style="font-size:8px"></i> No API</span>
    <button class="btn-tb btn-tb-outline no-print" onclick="exportCSV()"><i class="bi bi-file-earmark-spreadsheet"></i> CSV</button>
    <button class="btn-tb btn-tb-red no-print" onclick="window.print()"><i class="bi bi-printer"></i> Print</button>
    <button class="btn-tb btn-tb-green no-print" onclick="savePlanToFile()"><i class="bi bi-save2"></i> Save</button>
    <label class="btn-tb btn-tb-outline no-print mb-0" for="loadFile" style="cursor:pointer"><i class="bi bi-folder2-open"></i> Load</label>
    <input type="file" id="loadFile" accept=".json" class="d-none" onchange="loadPlanFromFile(event)">
  </div>
</div>

<!-- PRINT HEADER -->
<div id="print-header" style="padding:14px 18px 10px;margin-bottom:12px">
  <div style="display:flex;justify-content:space-between;align-items:flex-start">
    <div>
      <div class="print-logo">PPC Media Plan</div>
      <div style="font-size:12px;color:#475569;margin-top:2px">
        <span id="ph_website_lbl" style="font-weight:700;color:#1e293b"></span>
        &nbsp;&middot;&nbsp;<span id="ph_industry_lbl"></span>
        &nbsp;&middot;&nbsp;<span id="ph_location_lbl"></span>
      </div>
    </div>
    <div style="text-align:right">
      <div style="font-size:13px;font-weight:700;color:#1e293b" id="ph_budget_lbl"></div>
      <div style="font-size:11px;color:#475569;margin-top:2px" id="ph_date_lbl"></div>
      <div style="font-size:11px;color:#475569" id="ph_duration_lbl"></div>
    </div>
  </div>
  <hr class="print-divider">
  <div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:2px" id="ph_chips"></div>
</div>

<!-- TAB NAV BAR -->
<div class="tab-nav-bar no-print">
  <button class="tab-btn active" id="tabBtn-settings"    onclick="showTab('settings')"><i class="bi bi-sliders"></i> Project Settings</button>
  <button class="tab-btn"        id="tabBtn-benchmarks"  onclick="showTab('benchmarks')"><i class="bi bi-sliders2-vertical"></i> Benchmarks &amp; Budget</button>
  <button class="tab-btn"        id="tabBtn-summary"     onclick="showTab('summary')"><i class="bi bi-stars"></i> Campaign Summary</button>
  <button class="tab-btn"        id="tabBtn-tables"      onclick="showTab('tables')"><i class="bi bi-table"></i> Media Plan Tables</button>
  <button class="tab-btn"        id="tabBtn-audience"    onclick="showTab('audience')"><i class="bi bi-people-fill"></i> Audience Targeting</button>
  <button class="tab-btn"        id="tabBtn-keywords"    onclick="showTab('keywords')"><i class="bi bi-key-fill"></i> Keyword Intelligence</button>
</div>

<!-- PAGE CONTENT -->
<div class="page-content">
<!-- ═══ TAB 1: PROJECT SETTINGS ═══ -->
<div class="tab-pane active" id="tab-settings">

  <!-- Row 1: Basic Info -->
  <div class="pcard">
    <div class="pcard-head"><span class="ph-icon blue"><i class="bi bi-sliders"></i></span> Project Settings</div>
    <div class="pcard-body">
      <div class="section-row">
        <!-- Industry -->
        <div>
          <label class="form-label-sm">Industry</label>
          <div class="industry-search">
            <input type="text" id="industry_search" class="form-ctrl" placeholder="Search industry..." autocomplete="off" oninput="filterIndustries(this.value)" onfocus="openIndDropdown()">
            <i class="bi bi-search"></i>
            <div class="ind-dropdown" id="ind_dropdown">
              <?php foreach ($grouped as $group => $inds): ?>
              <div class="ind-group-label"><?= htmlspecialchars($group) ?></div>
              <?php foreach ($inds as $key => $name): ?>
              <div class="ind-item" data-key="<?= htmlspecialchars($key) ?>" onclick="selectIndustry('<?= htmlspecialchars($key) ?>','<?= htmlspecialchars($name) ?>')">
                <?= htmlspecialchars($name) ?>
                <span class="ind-group-tag"><?= htmlspecialchars($group) ?></span>
              </div>
              <?php endforeach; ?>
              <?php endforeach; ?>
            </div>
          </div>
          <input type="hidden" id="inp_industry" value="ecommerce">
          <div style="margin-top:3px;font-size:10px;color:#94a3b8" id="ind_vertical_lbl"></div>
        </div>

        <!-- Website -->
        <div>
          <label class="form-label-sm">Website / Brand Domain</label>
          <div style="position:relative">
            <input type="text" id="inp_website" class="form-ctrl" placeholder="https://yourbrand.com" oninput="onWebsiteInput();updatePrintHeader()">
            <span id="kw_fetch_spinner" style="display:none;position:absolute;right:10px;top:50%;transform:translateY(-50%);font-size:11px;color:#64748b"><i class="bi bi-arrow-repeat" style="animation:spin 1s linear infinite"></i> Fetching...</span>
          </div>
          <div style="margin-top:3px;font-size:10px;color:#94a3b8" id="website_kw_hint">Keywords will auto-fetch when domain is entered</div>
        </div>

        <!-- Location -->
        <div>
          <label class="form-label-sm">Target Location</label>
          <input type="text" id="inp_location" class="form-ctrl" placeholder="e.g. India, Mumbai, PAN India">
        </div>
      </div>

      <div class="section-row-4 mt14">
        <!-- Budget -->
        <div>
          <label class="form-label-sm">Monthly Budget (<?= htmlspecialchars($currency) ?>)</label>
          <input type="number" id="inp_budget" class="form-ctrl fw" value="100000" min="0" oninput="recalculate();updatePrintHeader()">
        </div>

        <!-- Duration Pills -->
        <div>
          <label class="form-label-sm">Campaign Duration</label>
          <div class="dur-pills" id="dur_pills">
            <button class="dur-pill active" data-days="30"  onclick="setDuration(30)">30d</button>
            <button class="dur-pill"        data-days="60"  onclick="setDuration(60)">60d</button>
            <button class="dur-pill"        data-days="90"  onclick="setDuration(90)">90d</button>
            <button class="dur-pill"        data-days="180" onclick="setDuration(180)">180d</button>
            <button class="dur-pill"        data-days="365" onclick="setDuration(365)">365d</button>
          </div>
          <input type="hidden" id="inp_duration" value="30">
        </div>

        <!-- AOV -->
        <div>
          <label class="form-label-sm">Avg. Order Value / AOV (<?= htmlspecialchars($currency) ?>)</label>
          <input type="number" id="inp_aov" class="form-ctrl" value="1500" min="0" oninput="recalculate()">
        </div>

        <!-- Calc Mode -->
        <div>
          <label class="form-label-sm">Calculation Mode</label>
          <div class="calc-mode-pill">
            <button id="btn_topdown"  class="active" onclick="setCalcMode('topdown')">Top-Down</button>
            <button id="btn_goalfirst"              onclick="setCalcMode('goalfirst')">Goal-First</button>
          </div>
        </div>
      </div>

      <!-- Goal-First Panel -->
      <div id="goalfirst_panel" class="goalfirst-panel" style="display:none">
        <div class="goal-type-row">
          <div style="font-size:11px;font-weight:700;color:#64748b;white-space:nowrap">Goal Type:</div>
          <select id="sel_goal_type" class="goal-type-select" onchange="updateGoalType()">
            <option value="revenue">Revenue Target</option>
            <option value="leads">Lead Volume (CPL-based)</option>
            <option value="transactions">Transaction Target (CPA-based)</option>
            <option value="cac">CAC Target (Max Cost per Acquisition)</option>
            <option value="roas">ROAS Target</option>
          </select>
        </div>
        <div class="goalfirst-inputs" id="goalfirst_inputs">
          <!-- Dynamic inputs rendered by JS -->
        </div>
      </div>

      <!-- Objectives & Platforms -->
      <div class="mt16">
        <div style="display:flex;align-items:center;gap:24px;flex-wrap:wrap">
          <div>
            <div class="form-label-sm" style="margin-bottom:8px">Campaign Objectives</div>
            <div class="goal-chips">
              <div class="goal-chip selected awareness" data-goal="awareness" onclick="toggleGoal(this)">
                <span class="chip-icon">📢</span><span>Awareness</span>
                <i class="bi bi-check-circle-fill chip-check" style="display:none"></i>
                <input type="hidden" class="goal-value" value="1">
              </div>
              <div class="goal-chip selected consideration" data-goal="consideration" onclick="toggleGoal(this)">
                <span class="chip-icon">🤝</span><span>Consideration</span>
                <i class="bi bi-check-circle-fill chip-check" style="display:none"></i>
                <input type="hidden" class="goal-value" value="1">
              </div>
              <div class="goal-chip selected conversion" data-goal="conversion" onclick="toggleGoal(this)">
                <span class="chip-icon">💰</span><span>Conversion</span>
                <i class="bi bi-check-circle-fill chip-check" style="display:none"></i>
                <input type="hidden" class="goal-value" value="1">
              </div>
            </div>
          </div>
          <div>
            <div class="form-label-sm" style="margin-bottom:8px">Advertising Platforms</div>
            <div class="platform-chips">
              <div class="platform-chip selected google" data-platform="google" onclick="togglePlatform(this)">
                <div class="plat-mini-logo google">G</div>
                <span>Google Ads</span>
                <input type="hidden" class="platform-value" value="1">
              </div>
              <div class="platform-chip selected meta" data-platform="meta" onclick="togglePlatform(this)">
                <div class="plat-mini-logo meta"><i class="bi bi-facebook" style="font-size:11px"></i></div>
                <span>Meta Ads</span>
                <input type="hidden" class="platform-value" value="1">
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
</div><!-- /tab-settings -->
<!-- ═══ TAB 2: BENCHMARKS ═══ -->
<div class="tab-pane" id="tab-benchmarks">
  <div class="pcard">
    <div class="pcard-head">
      <span class="ph-icon purple"><i class="bi bi-sliders2-vertical"></i></span>
      Benchmarks &amp; Budget Controls
      <span class="ms-auto" style="font-size:11px;color:#94a3b8">Edit any field to override &middot; auto values shown in blue</span>
    </div>
    <div class="pcard-body">
      <div class="bench-grid">
        <!-- Performance Benchmarks -->
        <div>
          <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px">Performance Benchmarks</div>
          <table class="bench-table">
            <thead><tr><th>Metric</th><th>Google</th><th>Meta</th><th>Source</th></tr></thead>
            <tbody>
              <tr>
                <td style="font-weight:600">CPC (<?= htmlspecialchars($currency) ?>)</td>
                <td><input type="number" id="b_cpc_google" step="0.01" oninput="markOverride('cpc_google');recalculate()"></td>
                <td><input type="number" id="b_cpc_meta"   step="0.01" oninput="markOverride('cpc_meta');recalculate()"></td>
                <td><span id="src_cpc" class="src-badge src-auto">Auto</span></td>
              </tr>
              <tr>
                <td style="font-weight:600">CTR (%)</td>
                <td><input type="number" id="b_ctr_google" step="0.01" oninput="markOverride('ctr_google');recalculate()"></td>
                <td><input type="number" id="b_ctr_meta"   step="0.01" oninput="markOverride('ctr_meta');recalculate()"></td>
                <td><span id="src_ctr" class="src-badge src-auto">Auto</span></td>
              </tr>
              <tr>
                <td style="font-weight:600">CVR (%)</td>
                <td><input type="number" id="b_cvr_google" step="0.01" oninput="markOverride('cvr_google');recalculate()"></td>
                <td><input type="number" id="b_cvr_meta"   step="0.01" oninput="markOverride('cvr_meta');recalculate()"></td>
                <td><span id="src_cvr" class="src-badge src-auto">Auto</span></td>
              </tr>
              <tr>
                <td style="font-weight:600">CPM (<?= htmlspecialchars($currency) ?>)</td>
                <td><input type="number" id="b_cpm_google" step="0.01" oninput="markOverride('cpm_google');recalculate()"></td>
                <td><input type="number" id="b_cpm_meta"   step="0.01" oninput="markOverride('cpm_meta');recalculate()"></td>
                <td><span id="src_cpm" class="src-badge src-auto">Auto</span></td>
              </tr>
              <tr>
                <td style="font-weight:600">CPV (<?= htmlspecialchars($currency) ?>)</td>
                <td><input type="number" id="b_cpv_google" step="0.01" value="1.20" oninput="markOverride('cpv_google');recalculate()"></td>
                <td><input type="number" id="b_cpv_meta"   step="0.01" value="0.80" oninput="markOverride('cpv_meta');recalculate()"></td>
                <td><span id="src_cpv" class="src-badge src-auto">Auto</span></td>
              </tr>
              <tr>
                <td style="font-weight:600">VTR (%)</td>
                <td><input type="number" id="b_vtr_google" step="0.1" value="40" oninput="markOverride('vtr_google');recalculate()"></td>
                <td><input type="number" id="b_vtr_meta"   step="0.1" value="35" oninput="markOverride('vtr_meta');recalculate()"></td>
                <td><span id="src_vtr" class="src-badge src-auto">Auto</span></td>
              </tr>
              <tr>
                <td style="font-weight:600">Frequency</td>
                <td colspan="2"><input type="number" id="b_frequency" step="0.1" oninput="markOverride('frequency');recalculate()"></td>
                <td><span id="src_freq" class="src-badge src-auto">Auto</span></td>
              </tr>
              <tr>
                <td style="font-weight:600">Target ROAS</td>
                <td colspan="2"><input type="number" id="b_roas" step="0.01" oninput="markOverride('roas');recalculate()"></td>
                <td><span id="src_roas" class="src-badge src-auto">Auto</span></td>
              </tr>
              <tr>
                <td style="font-weight:600">Target CPL (<?= htmlspecialchars($currency) ?>)</td>
                <td colspan="2"><input type="number" id="b_cpl" step="1" placeholder="e.g. 500" oninput="recalculate()"></td>
                <td><span class="src-badge src-manual">Manual</span></td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Splits -->
        <div>
          <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin-bottom:10px">Budget &amp; Platform Splits</div>
          <div style="font-size:11px;font-weight:600;color:#94a3b8;margin-bottom:6px">Budget by Objective</div>
          <div class="split-row">
            <div class="split-label"><span class="dot" style="background:#7c3aed"></span>Awareness</div>
            <input type="range" class="split-slider" id="sl_aw" min="0" max="100" value="20" oninput="syncSplit('aw',this.value)">
            <input type="number" class="split-input" id="bs_awareness" value="20" min="0" max="100" onchange="syncSplitInput('aw',this.value)">
            <span style="font-size:11px;color:#94a3b8">%</span>
          </div>
          <div class="split-row">
            <div class="split-label"><span class="dot" style="background:#0891b2"></span>Consideration</div>
            <input type="range" class="split-slider" id="sl_con" min="0" max="100" value="30" oninput="syncSplit('con',this.value)">
            <input type="number" class="split-input" id="bs_consideration" value="30" min="0" max="100" onchange="syncSplitInput('con',this.value)">
            <span style="font-size:11px;color:#94a3b8">%</span>
          </div>
          <div class="split-row">
            <div class="split-label"><span class="dot" style="background:#16a34a"></span>Conversion</div>
            <input type="range" class="split-slider" id="sl_cv" min="0" max="100" value="50" oninput="syncSplit('cv',this.value)">
            <input type="number" class="split-input" id="bs_conversion" value="50" min="0" max="100" onchange="syncSplitInput('cv',this.value)">
            <span style="font-size:11px;color:#94a3b8">%</span>
          </div>
          <div style="margin-bottom:14px">
            <span id="split_warn" class="split-warn text-danger d-none">&#9888; Must total 100%</span>
            <span id="split_ok"   class="split-warn text-success">&#10003; Total: <span id="split_total">100</span>%</span>
          </div>
          <div style="font-size:11px;font-weight:600;color:#94a3b8;margin-bottom:6px">Platform Split</div>
          <div class="split-row">
            <div class="split-label"><span class="dot" style="background:#4285f4"></span>Google Ads</div>
            <input type="range" class="split-slider" style="accent-color:#4285f4" id="sl_google" min="0" max="100" value="60" oninput="syncPlatSplit(this.value)">
            <input type="number" class="split-input" id="pct_google" value="60" min="0" max="100" onchange="syncPlatSplit(this.value)">
            <span style="font-size:11px;color:#94a3b8">%</span>
          </div>
          <div class="split-row">
            <div class="split-label"><span class="dot" style="background:#1877f2"></span>Meta Ads</div>
            <input type="range" class="split-slider" style="accent-color:#1877f2" id="sl_meta" min="0" max="100" value="40" readonly>
            <input type="number" class="split-input" id="pct_meta" value="40" readonly style="background:#f8fafc">
            <span style="font-size:11px;color:#94a3b8">%</span>
          </div>
        </div>
      </div>

      <!-- CPL Benchmarks Coming Soon -->
      <div class="mt14">
        <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px">Industry CPL Benchmarks <span style="font-size:10px;padding:2px 8px;background:#f1f5f9;color:#64748b;border-radius:10px;font-weight:700;margin-left:6px">Coming Soon</span></div>
        <div class="coming-soon-panel">
          <div class="cs-icon">&#128202;</div>
          <div>
            <div class="cs-text" style="font-weight:600;color:#64748b;margin-bottom:2px">Industry-wise CPL Benchmarks</div>
            <div class="cs-text">Auto-populated CPL benchmarks per industry will be available in the next release. For now, use the <strong>Target CPL</strong> field above to manually set your CPL target.</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div><!-- /tab-benchmarks -->
<!-- ═══ TAB 3: CAMPAIGN SUMMARY ═══ -->
<div class="tab-pane" id="tab-summary">
  <div class="pcard">
    <div class="pcard-head"><span class="ph-icon amber"><i class="bi bi-stars"></i></span> Consolidated Campaign Summary</div>
    <div class="pcard-body">
      <div class="kpi-grid">
        <div class="kpi-card"><div class="kpi-label">Total Budget</div><div class="kpi-value" id="sum_budget">&#8377;0</div></div>
        <div class="kpi-card"><div class="kpi-label">Impressions</div><div class="kpi-value" id="sum_impressions">0</div></div>
        <div class="kpi-card"><div class="kpi-label">Total Clicks</div><div class="kpi-value" id="sum_clicks">0</div></div>
        <div class="kpi-card"><div class="kpi-label" id="sum_conv_label">Conversions</div><div class="kpi-value" id="sum_conversions">0</div></div>
        <div class="kpi-card"><div class="kpi-label" id="sum_rev_label">Total Revenue</div><div class="kpi-value" id="sum_revenue">&#8377;0</div></div>
        <div class="kpi-card highlight"><div class="kpi-label" id="sum_roas_label">Final ROAS</div><div class="kpi-value" id="sum_roas">0x</div></div>
      </div>
      <div class="chart-row mt14 no-print">
        <div class="chart-box"><div class="chart-title">Budget Distribution</div><canvas id="chartBudget" height="160"></canvas></div>
        <div class="chart-box"><div class="chart-title">Funnel Performance</div><canvas id="chartFunnel" height="160"></canvas></div>
      </div>
    </div>
  </div>
</div><!-- /tab-summary -->

<!-- ═══ TAB 4: MEDIA PLAN TABLES ═══ -->
<div class="tab-pane" id="tab-tables">

  <!-- Awareness -->
  <div id="sec_awareness" class="pcard">
    <div class="pcard-head">
      <span class="ph-icon purple"><i class="bi bi-eye"></i></span>
      Awareness &mdash; Reach &amp; Visibility
      <span class="ms-auto fw-normal" style="font-size:12px;color:#64748b">Budget: <strong id="aw_budget_lbl" class="text-dark">&#8377;0</strong></span>
    </div>
    <div id="aw_tables_wrap">
      <!-- Monthly tables rendered by JS -->
    </div>
  </div>

  <!-- Consideration -->
  <div id="sec_consideration" class="pcard">
    <div class="pcard-head">
      <span class="ph-icon teal"><i class="bi bi-cursor-fill"></i></span>
      Consideration &mdash; Traffic &amp; Engagement
      <span class="ms-auto fw-normal" style="font-size:12px;color:#64748b">Budget: <strong id="con_budget_lbl" class="text-dark">&#8377;0</strong></span>
    </div>
    <div id="con_tables_wrap">
      <!-- Monthly tables rendered by JS -->
    </div>
  </div>

  <!-- Conversion -->
  <div id="sec_conversion" class="pcard">
    <div class="pcard-head">
      <span class="ph-icon green"><i class="bi bi-currency-rupee"></i></span>
      <span id="cvr_head_label">Conversion &mdash; Revenue &amp; ROI</span>
      <span class="ms-auto fw-normal" style="font-size:12px;color:#64748b">Budget: <strong id="cvr_budget_lbl" class="text-dark">&#8377;0</strong></span>
    </div>
    <div id="cvr_tables_wrap">
      <!-- Monthly tables rendered by JS -->
    </div>
  </div>

</div><!-- /tab-tables -->
<!-- ═══ TAB 5: AUDIENCE TARGETING ═══ -->
<div class="tab-pane" id="tab-audience">
  <div class="pcard">
    <div class="pcard-head" style="align-items:center;gap:10px">
      <span><span class="ph-icon slate"><i class="bi bi-people-fill"></i></span> Audience Targeting</span>
      <span class="ms-auto" style="display:flex;align-items:center;gap:8px">
        <span id="aud_reach_badge" style="font-size:11px;color:#94a3b8"></span>
        <button class="btn-tb btn-tb-outline" onclick="estimateAudienceReach()" style="height:26px;font-size:11px"><i class="bi bi-calculator"></i> Estimate Reach</button>
        <button class="btn-tb btn-tb-outline" onclick="refineAudienceWithAI()" style="height:26px;font-size:11px"><i class="bi bi-robot"></i> Refine with AI</button>
        <button class="btn-tb btn-tb-outline" onclick="fetchAudienceTargets()" style="height:26px;font-size:11px"><i class="bi bi-cloud-download"></i> Auto-Fetch</button>
        <span id="aud_fetch_status" style="font-size:11px;color:#64748b">Auto-fill from Google / Meta when configured</span>
      </span>
    </div>
    <div class="pcard-body">
      <!-- Platform Tab Switcher -->
      <div class="aud-platform-tabs">
        <button class="aud-tab-btn active google" id="audTabBtn-google" onclick="showAudTab('google')">
          <span style="font-weight:800;color:#4285f4;font-size:14px">G</span> Google Ads
        </button>
        <button class="aud-tab-btn meta" id="audTabBtn-meta" onclick="showAudTab('meta')">
          <i class="bi bi-facebook" style="color:#1877f2"></i> Meta Ads
        </button>
      </div>

      <!-- Google Ads Panel -->
      <div id="aud_panel_google">
        <div style="font-size:11px;color:#94a3b8;margin-bottom:12px;background:#f8fafc;border-radius:6px;padding:8px 12px">
          <i class="bi bi-info-circle"></i>&nbsp; Path: <strong>Google Ads &rarr; Tools &rarr; Shared Library &rarr; Audience Manager &rarr; New Custom Segment</strong>
        </div>
        <div class="section-row">
          <div class="aud-section">
            <div class="aud-section-head">
              <i class="bi bi-search" style="color:#4285f4"></i> Custom Segment (Keywords / Interests)
              <span class="aud-path">Custom Segment &rarr; Interests/Keywords</span>
            </div>
            <textarea class="aud-textarea" id="aud_g_custom" placeholder="Enter keywords or interests that your audience searches for&#10;e.g. best skincare brand, buy running shoes online, crm software comparison"></textarea>
            <div style="font-size:10px;color:#94a3b8;margin-top:3px"><i class="bi bi-lightbulb"></i> People who search for any of these terms on Google</div>
          </div>
          <div class="aud-section">
            <div class="aud-section-head">
              <i class="bi bi-graph-up" style="color:#ea4335"></i> In-Market Segments
              <span class="aud-path">Audience Manager &rarr; Browse &rarr; In-Market</span>
            </div>
            <textarea class="aud-textarea" id="aud_g_inmarket" placeholder="e.g. Consumer Electronics, Business Software, Personal Loans&#10;People actively comparing and researching products/services"></textarea>
            <div style="font-size:10px;color:#94a3b8;margin-top:3px"><i class="bi bi-lightbulb"></i> People actively researching/comparing in your category</div>
          </div>
          <div class="aud-section">
            <div class="aud-section-head">
              <i class="bi bi-heart" style="color:#fbbc04"></i> Affinity Audiences
              <span class="aud-path">Audience Manager &rarr; Browse &rarr; Affinity</span>
            </div>
            <textarea class="aud-textarea" id="aud_g_affinity" placeholder="e.g. Tech Enthusiasts, Foodies, Frequent Travelers&#10;Interest-based audiences with long-term lifestyle interests"></textarea>
            <div style="font-size:10px;color:#94a3b8;margin-top:3px"><i class="bi bi-lightbulb"></i> Broad lifestyle interests and habitual behaviours</div>
          </div>
        </div>
        <div class="aud-section mt10">
          <div class="aud-section-head">
            <i class="bi bi-arrow-repeat" style="color:#34a853"></i> Remarketing &amp; Customer Match
            <span class="aud-path">Audience Manager &rarr; Website visitors / Customer lists</span>
          </div>
          <textarea class="aud-textarea" id="aud_g_remarketing" placeholder="e.g. Website visitors last 30 days, Cart abandoners, Existing customers&#10;Upload customer emails for Customer Match targeting" style="min-height:55px"></textarea>
        </div>
      </div>

      <!-- Meta Ads Panel -->
      <div id="aud_panel_meta" style="display:none">
        <div style="font-size:11px;color:#94a3b8;margin-bottom:12px;background:#f8fafc;border-radius:6px;padding:8px 12px">
          <i class="bi bi-info-circle"></i>&nbsp; Path: <strong>Meta Ad Manager &rarr; Audiences &rarr; Create Audience &rarr; Saved Audience</strong>
        </div>
        <div style="font-size:10px;color:#64748b;margin-bottom:8px"><i class="bi bi-lightbulb"></i> Targeting suggestions are auto-fetched from Meta based on industry keywords. Audience sizes vary by location/targeting - check Ad Manager for exact estimates when creating audiences.</div>
        <div class="section-row">
          <div class="aud-section">
            <div class="aud-section-head">
              <i class="bi bi-bookmark-heart" style="color:#1877f2"></i> Interests
              <span class="aud-path">Saved Audience &rarr; Interests</span>
            </div>
            <textarea class="aud-textarea" id="aud_m_interests" placeholder="e.g. Online Shopping, Fashion, Technology, Fitness&#10;Based on pages liked, topics followed, activities"></textarea>
            <div style="font-size:10px;color:#94a3b8;margin-top:3px"><i class="bi bi-lightbulb"></i> Pages liked, topics followed, interests expressed on Meta</div>
          </div>
          <div class="aud-section">
            <div class="aud-section-head">
              <i class="bi bi-activity" style="color:#e91e63"></i> Behaviours
              <span class="aud-path">Saved Audience &rarr; Behaviours</span>
            </div>
            <textarea class="aud-textarea" id="aud_m_behaviour" placeholder="e.g. Online Buyers (All), Engaged Shoppers, Frequent International Travelers&#10;Device usage, purchase behaviour, travel patterns"></textarea>
            <div style="font-size:10px;color:#94a3b8;margin-top:3px"><i class="bi bi-lightbulb"></i> Purchase history, device use, travel &amp; lifestyle signals</div>
          </div>
          <div class="aud-section">
            <div class="aud-section-head">
              <i class="bi bi-person-badge" style="color:#9c27b0"></i> Demographics
              <span class="aud-path">Saved Audience &rarr; Demographics</span>
            </div>
            <div class="demo-row">
              <div>
                <div class="gf-label">Age Range</div>
                <div style="display:flex;gap:4px;align-items:center">
                  <input type="number" id="aud_m_age_min" class="aud-input" value="18" min="13" max="65" style="width:60px">
                  <span style="font-size:11px;color:#94a3b8">to</span>
                  <input type="number" id="aud_m_age_max" class="aud-input" value="45" min="13" max="65" style="width:60px">
                </div>
              </div>
              <div>
                <div class="gf-label">Gender</div>
                <select id="aud_m_gender" class="aud-input">
                  <option value="all">All Genders</option>
                  <option value="male">Male</option>
                  <option value="female">Female</option>
                </select>
              </div>
              <div>
                <div class="gf-label">Language</div>
                <input type="text" id="aud_m_language" class="aud-input" value="English, Hindi" placeholder="e.g. English, Hindi">
              </div>
            </div>
            <div class="gf-label" style="margin-top:6px">Education / Job Title (optional)</div>
            <input type="text" id="aud_m_education" class="aud-input" placeholder="e.g. College Grad, IT Professionals, Business Owners">
          </div>
        </div>
        <div class="aud-section mt10">
          <div class="aud-section-head">
            <i class="bi bi-people" style="color:#1877f2"></i> Custom Audience &amp; Lookalike
            <span class="aud-path">Ad Manager &rarr; Audiences &rarr; Custom Audience / Lookalike</span>
          </div>
          <textarea class="aud-textarea" id="aud_m_custom" placeholder="e.g. Website Visitors (last 30d), Customer List Upload, 1% Lookalike of Purchasers&#10;Lookalike Audience from best customers" style="min-height:55px"></textarea>
        </div>
      </div>

    </div>
  </div>
</div><!-- /tab-audience -->
<!-- ═══ TAB 6: KEYWORD INTELLIGENCE ═══ -->
<div class="tab-pane" id="tab-keywords">
  <div class="pcard">
    <div class="pcard-head">
      <span class="ph-icon amber"><i class="bi bi-key-fill"></i></span>
      Keyword Intelligence
      <span class="ms-auto no-print" style="display:flex;align-items:center;gap:8px">
        <span id="kw_source_badge" style="font-size:11px;color:#94a3b8"></span>
        <button class="btn-tb btn-tb-outline" onclick="fetchKeywordsFromAPI()" style="height:26px;font-size:11px"><i class="bi bi-cloud-download"></i> Fetch</button>
        <button class="btn-tb btn-tb-outline" onclick="addKeywordRow()" style="height:26px;font-size:11px"><i class="bi bi-plus"></i> Add</button>
      </span>
      <span class="ms-2" style="font-size:11px;color:#64748b">Avg CPC: <strong id="kw_avg_g" class="text-dark">&mdash;</strong> (Google) &nbsp;&middot;&nbsp; <strong id="kw_avg_m" class="text-dark">&mdash;</strong> (Meta)</span>
    </div>
    <div style="padding:10px 16px;background:#eff6ff;border-bottom:1px solid #e2e8f0;font-size:11px;color:#1d4ed8">
      <i class="bi bi-info-circle-fill"></i>&nbsp;
      Top 10 keywords shown below are used for all CPC calculations. Enter your domain in <strong>Project Settings</strong> to auto-fetch real keyword data.
    </div>
    <div style="padding:10px 16px;background:#f8fafc;border-bottom:1px solid #e2e8f0;">
      <div style="font-size:11px;color:#64748b;margin-bottom:6px;">
        Competitor domains (optional) for paid-keyword mining:
      </div>
      <input
        type="text"
        id="inp_competitors"
        class="form-control form-control-sm"
        placeholder="competitor1.com, competitor2.com, competitor3.com"
        style="max-width:560px;font-size:12px;"
      >
    </div>
    <div class="output-table-wrap">
      <table class="output-table">
        <thead>
          <tr>
            <th style="width:32px">#</th>
            <th>Keyword</th>
            <th>CPC (<?= htmlspecialchars($currency) ?>)</th>
            <th>Monthly Volume</th>
            <th>Competition</th>
            <th>Intent</th>
            <th>Commercial Score</th>
            <th>Status</th>
            <th class="no-print">Remove</th>
          </tr>
        </thead>
        <tbody id="tbody_keywords"></tbody>
      </table>
    </div>
  </div>
</div><!-- /tab-keywords -->

</div><!-- /page-content -->
</div><!-- /main-wrap -->
</div><!-- /app-shell -->

<!-- TOAST -->
<div class="position-fixed bottom-0 end-0 p-3 no-print" style="z-index:9999">
  <div id="toast" class="toast align-items-center border-0" role="alert">
    <div class="d-flex">
      <div class="toast-body fw-semibold" id="toast_body">Done.</div>
      <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast"></button>
    </div>
  </div>
</div>

<style>
@keyframes spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}
</style>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
// ═══════════════════════════════════════════════════════
// CONFIG & STATE
// ═══════════════════════════════════════════════════════
const CONFIG   = <?= $config_json ?>;
const CUR      = CONFIG.defaults?.currency ?? '₹';
const CALC_MODE = { mode: 'topdown' };
const overrides = {};
let keywords  = [];
let budgetChart = null, funnelChart = null;
let currentDuration = 30;
let currentGoalType = 'revenue';
let selectedIndustry = 'ecommerce';
let kwFetchTimer = null;

// ═══════════════════════════════════════════════════════
// FORMATTERS
// ═══════════════════════════════════════════════════════
const fC  = v => CUR + fN(v,0);
const fC2 = v => CUR + fN(v,2);
const fN  = (v,d=0) => (parseFloat(v)||0).toLocaleString('en-IN',{minimumFractionDigits:d,maximumFractionDigits:d});
const fP  = v => fN(v,2)+'%';
const fX  = v => fN(v,2)+'x';
const gv  = id => parseFloat(document.getElementById(id)?.value)||0;
const sv  = (id,v) => { const e=document.getElementById(id); if(e) e.value=v; };
const st  = (id,t) => { const e=document.getElementById(id); if(e) e.textContent=t; };
const cap = s => s.charAt(0).toUpperCase()+s.slice(1);
const escH= s => (s??'').replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;');

// ═══════════════════════════════════════════════════════
// TAB NAVIGATION
// ═══════════════════════════════════════════════════════
function showTab(id) {
  document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
  document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
  const pane = document.getElementById('tab-'+id);
  const btn  = document.getElementById('tabBtn-'+id);
  if (pane) pane.classList.add('active');
  if (btn)  btn.classList.add('active');
}

// ═══════════════════════════════════════════════════════
// AUDIENCE TABS
// ═══════════════════════════════════════════════════════
function showAudTab(platform) {
  ['google','meta'].forEach(p => {
    document.getElementById('aud_panel_'+p).style.display = p===platform ? '' : 'none';
    const btn = document.getElementById('audTabBtn-'+p);
    btn.classList.toggle('active', p===platform);
    btn.classList.toggle(p, true);
  });
}

// ═══════════════════════════════════════════════════════
// INDUSTRY DROPDOWN
// ═══════════════════════════════════════════════════════
function openIndDropdown() {
  document.getElementById('ind_dropdown').classList.add('open');
  document.addEventListener('click', closeIndOnOutside, true);
}
function closeIndOnOutside(e) {
  if (!document.querySelector('.industry-search').contains(e.target)) {
    document.getElementById('ind_dropdown').classList.remove('open');
    document.removeEventListener('click', closeIndOnOutside, true);
  }
}
function filterIndustries(q) {
  q = q.toLowerCase();
  document.querySelectorAll('.ind-item').forEach(el => {
    el.style.display = el.dataset.key.includes(q)||el.textContent.toLowerCase().includes(q) ? '' : 'none';
  });
  document.querySelectorAll('.ind-group-label').forEach(lbl => {
    let sib=lbl.nextElementSibling, any=false;
    while (sib && !sib.classList.contains('ind-group-label')) { if(sib.style.display!=='none') any=true; sib=sib.nextElementSibling; }
    lbl.style.display = any ? '' : 'none';
  });
  openIndDropdown();
}
function selectIndustry(key, name) {
  selectedIndustry = key;
  sv('inp_industry', key);
  document.getElementById('industry_search').value = name;
  document.getElementById('ind_dropdown').classList.remove('open');
  document.querySelectorAll('.ind-item').forEach(e => e.classList.toggle('selected', e.dataset.key===key));
  const ind = CONFIG.industries?.[key];
  if (ind) st('ind_vertical_lbl', ind.google_vertical ? `Google: ${ind.google_vertical} · Meta: ${ind.meta_vertical}` : '');
  loadIndustryDefaults();
}

// ═══════════════════════════════════════════════════════
// DURATION PILLS
// ═══════════════════════════════════════════════════════
function setDuration(days) {
  currentDuration = days;
  sv('inp_duration', days);
  document.querySelectorAll('.dur-pill').forEach(b => b.classList.toggle('active', parseInt(b.dataset.days)===days));
  recalculate();
  updatePrintHeader();
}

// ═══════════════════════════════════════════════════════
// GOALS & PLATFORMS
// ═══════════════════════════════════════════════════════
function toggleGoal(chip) {
  chip.classList.toggle('selected');
  chip.querySelector('.goal-value').value = chip.classList.contains('selected') ? 1 : 0;
  recalculate(); updatePrintHeader();
}
function togglePlatform(chip) {
  const allChips = document.querySelectorAll('.platform-chip');
  const selected = [...allChips].filter(c => c.classList.contains('selected'));
  if (selected.length===1 && chip.classList.contains('selected')) return;
  chip.classList.toggle('selected');
  chip.querySelector('.platform-value').value = chip.classList.contains('selected') ? 1 : 0;
  recalculate(); updatePrintHeader();
}
function getGoals()     { return [...document.querySelectorAll('.goal-chip.selected')].map(c=>c.dataset.goal); }
function getPlatforms() { return [...document.querySelectorAll('.platform-chip.selected')].map(c=>c.dataset.platform); }

// ═══════════════════════════════════════════════════════
// CALC MODE + GOAL TYPE
// ═══════════════════════════════════════════════════════
function setCalcMode(mode) {
  CALC_MODE.mode = mode;
  document.getElementById('btn_topdown').classList.toggle('active', mode==='topdown');
  document.getElementById('btn_goalfirst').classList.toggle('active', mode==='goalfirst');
  document.getElementById('goalfirst_panel').style.display = mode==='goalfirst' ? '' : 'none';
  recalculate();
}
function updateGoalType() {
  currentGoalType = document.getElementById('sel_goal_type').value;
  renderGoalFirstInputs();
  updateConversionLabels();
  recalculate();
}
function renderGoalFirstInputs() {
  const wrap = document.getElementById('goalfirst_inputs');
  const c = CUR;
  const inputs = {
    revenue:      `<div><div class="gf-label">Target Revenue (${c})</div><input type="number" id="gf_revenue" class="form-ctrl" placeholder="e.g. 500000" oninput="recalculate()"></div><div><div class="gf-label">Using ROAS from Benchmarks tab</div><input type="number" id="gf_roas_display" class="form-ctrl" readonly style="background:#f8fafc"></div>`,
    leads:        `<div><div class="gf-label">Target Leads (count)</div><input type="number" id="gf_leads" class="form-ctrl" placeholder="e.g. 200" oninput="recalculate()"></div><div><div class="gf-label">Target CPL (${c})</div><input type="number" id="gf_cpl" class="form-ctrl" placeholder="e.g. 500" oninput="recalculate()"></div>`,
    transactions: `<div><div class="gf-label">Target Transactions (count)</div><input type="number" id="gf_transactions" class="form-ctrl" placeholder="e.g. 100" oninput="recalculate()"></div><div><div class="gf-label">Target CPA (${c})</div><input type="number" id="gf_cpa" class="form-ctrl" placeholder="e.g. 1000" oninput="recalculate()"></div>`,
    cac:          `<div><div class="gf-label">Max CAC / Cost per Acquisition (${c})</div><input type="number" id="gf_cac" class="form-ctrl" placeholder="e.g. 800" oninput="recalculate()"></div><div><div class="gf-label">Est. Monthly Conversions (target)</div><input type="number" id="gf_conv_target" class="form-ctrl" placeholder="e.g. 150" oninput="recalculate()"></div>`,
    roas:         `<div><div class="gf-label">Target ROAS (x)</div><input type="number" id="gf_target_roas" class="form-ctrl" placeholder="e.g. 4" oninput="recalculate()"></div><div><div class="gf-label">Target Revenue (${c})</div><input type="number" id="gf_revenue" class="form-ctrl" placeholder="e.g. 500000" oninput="recalculate()"></div>`
  };
  wrap.innerHTML = inputs[currentGoalType] || '';
}
function updateConversionLabels() {
  const labels = {
    revenue:      {conv:'Conversions',rev:'Revenue ('+CUR+')',roas:'ROAS',head:'Conversion — Revenue & ROI'},
    leads:        {conv:'Leads',rev:'CPL ('+CUR+')',roas:'vs Target CPL',head:'Conversion — Lead Generation'},
    transactions: {conv:'Transactions',rev:'CPA ('+CUR+')',roas:'vs Target CPA',head:'Conversion — Transactions'},
    cac:          {conv:'Acquisitions',rev:'Actual CAC ('+CUR+')',roas:'vs Target CAC',head:'Conversion — Acquisition'},
    roas:         {conv:'Conversions',rev:'Revenue ('+CUR+')',roas:'ROAS',head:'Conversion — Revenue & ROAS'}
  };
  const l = labels[currentGoalType] || labels.revenue;
  st('sum_conv_label', l.conv);
  st('sum_rev_label', l.rev);
  st('sum_roas_label', l.roas);
  const headEl = document.getElementById('cvr_head_label');
  if (headEl) headEl.textContent = l.head;
}

// ═══════════════════════════════════════════════════════
// OVERRIDE TRACKING
// ═══════════════════════════════════════════════════════
const srcMap = {cpc_google:'src_cpc',cpc_meta:'src_cpc',ctr_google:'src_ctr',ctr_meta:'src_ctr',
                cvr_google:'src_cvr',cvr_meta:'src_cvr',cpm_google:'src_cpm',cpm_meta:'src_cpm',
                cpv_google:'src_cpv',cpv_meta:'src_cpv',vtr_google:'src_vtr',vtr_meta:'src_vtr',
                frequency:'src_freq',roas:'src_roas'};
function markOverride(key) {
  overrides[key]=true;
  const el=document.getElementById('b_'+key); if(el) el.classList.add('overridden');
  const s=document.getElementById(srcMap[key]); if(s){s.textContent='Manual';s.className='src-badge src-manual';}
}
function clearOverride(key) {
  overrides[key]=false;
  const el=document.getElementById('b_'+key); if(el) el.classList.remove('overridden');
  const s=document.getElementById(srcMap[key]); if(s){s.textContent='Auto';s.className='src-badge src-auto';}
}

// ═══════════════════════════════════════════════════════
// LOAD INDUSTRY DEFAULTS
// ═══════════════════════════════════════════════════════
function loadIndustryDefaults() {
  const key = document.getElementById('inp_industry').value || selectedIndustry;
  const d   = CONFIG.industries?.[key];
  if (!d) return;
  set('b_cpl', d.cpl ?? 500, 'cpl');
  set('b_ctr_google', ((d.ctr?.conversion??0.05)*100).toFixed(2),'ctr_google');
  set('b_ctr_meta',   ((d.ctr?.conversion??0.04)*100).toFixed(2),'ctr_meta');
  set('b_cvr_google', ((d.cvr?.google??0.025)*100).toFixed(2),  'cvr_google');
  set('b_cvr_meta',   ((d.cvr?.meta??0.018)*100).toFixed(2),    'cvr_meta');
  set('b_cpm_google', d.cpm?.google??110,                       'cpm_google');
  set('b_cpm_meta',   d.cpm?.meta??78,                          'cpm_meta');
  set('b_frequency',  d.frequency??3,                           'frequency');
  set('b_roas',       d.roas_target??4.0,                       'roas');
  const bs = d.budget_split??{awareness:20,consideration:30,conversion:50};
  sv('bs_awareness',bs.awareness);sv('sl_aw',bs.awareness);
  sv('bs_consideration',bs.consideration);sv('sl_con',bs.consideration);
  sv('bs_conversion',bs.conversion);sv('sl_cv',bs.conversion);
  const ps = d.platform_split??{google:60,meta:40};
  sv('sl_google',ps.google);sv('pct_google',ps.google);
  sv('sl_meta',ps.meta);sv('pct_meta',ps.meta);
  if (d.audience) {
    const ga=d.audience.google??{};
    setTA('aud_g_custom',ga.custom??'');
    setTA('aud_g_inmarket',ga.in_market??ga.inmarket??'');
    setTA('aud_g_affinity',ga.affinity??'');
    const ma=d.audience.meta??{};
    setTA('aud_m_interests',ma.interests??'');
    setTA('aud_m_behaviour',ma.behaviour??'');
    setTA('aud_m_education',ma.education??ma.demographics??'');
    setTA('aud_m_custom',ma.custom??'');
    if (ma.language) sv('aud_m_language', ma.language);
    if (ma.age_min) sv('aud_m_age_min', ma.age_min);
    if (ma.age_max) sv('aud_m_age_max', ma.age_max);
    if (ma.gender) document.getElementById('aud_m_gender').value = ma.gender;
  }
  const seeds=d.seed_keywords??[];
  const cpc=d.cpc?.google??30;
  const vols=[90500,74000,49500,40500,33100,27100,22200,18100,14800,12100];
  const comps=['High','High','Medium','Medium','High','Medium','High','Low','Medium','Low'];
  keywords=seeds.slice(0,10).map((kw,i)=>({
    keyword:kw,
    cpc:+(cpc*(0.7+i*0.08)).toFixed(2),
    volume:vols[i]??5000,
    competition:comps[i]??'Medium',
    intent:'Commercial',
    commercial_score:0
  }));
  renderKeywordsTable(); updateAvgCpc(); recalculate();
  if (CONFIG.api?.google_ads?.enabled || CONFIG.api?.meta?.enabled) {
    fetchAudienceTargets();
  }
}
function setTA(id,val){const e=document.getElementById(id);if(e)e.value=val;}

// ═══════════════════════════════════════════════════════
// SPLITS
// ═══════════════════════════════════════════════════════
function syncSplit(sl,val){
  val=Math.min(100,Math.max(0,parseInt(val)||0));
  const map={aw:'awareness',con:'consideration',cv:'conversion'};
  sv('sl_'+sl,val);sv('bs_'+map[sl],val);
  validateBudgetSplit();recalculate();
}
function syncSplitInput(sl,val){syncSplit(sl,val);}
function syncPlatSplit(val){
  val=Math.min(100,Math.max(0,parseInt(val)||0));
  const other=100-val;
  sv('sl_google',val);sv('pct_google',val);sv('sl_meta',other);sv('pct_meta',other);
  recalculate();
}
function validateBudgetSplit(){
  const total=gv('bs_awareness')+gv('bs_consideration')+gv('bs_conversion');
  st('split_total',total);
  const ok=Math.abs(total-100)<1;
  document.getElementById('split_warn').classList.toggle('d-none',ok);
  document.getElementById('split_ok').classList.toggle('d-none',!ok);
}

// ═══════════════════════════════════════════════════════
// DOMAIN AUTO-FETCH KEYWORDS
// ═══════════════════════════════════════════════════════
function onWebsiteInput() {
  clearTimeout(kwFetchTimer);
  const val = document.getElementById('inp_website').value.trim();
  if (!val || val.length < 4) return;
  kwFetchTimer = setTimeout(() => {
    const spinner = document.getElementById('kw_fetch_spinner');
    const hint    = document.getElementById('website_kw_hint');
    if (spinner) spinner.style.display='';
    if (hint)    hint.textContent = 'Fetching keywords for this domain...';
    fetchKeywordsFromAPI(true);
  }, 800);
}

// ═══════════════════════════════════════════════════════
// CORE CALCULATION ENGINE
// ═══════════════════════════════════════════════════════
function recalculate() {
  const goals     = getGoals();
  const platforms = getPlatforms();
  let   budget    = gv('inp_budget');
  const aov       = gv('inp_aov');
  const pG        = gv('pct_google')/100;
  const pM        = gv('pct_meta')/100;

  // Goal-first mode: derive budget from goal
  if (CALC_MODE.mode==='goalfirst') {
    let derived = 0;
    if (currentGoalType==='revenue') {
      const rev=gv('gf_revenue'), roas=gv('b_roas')||4;
      if (rev>0) derived=rev/roas;
      sv('gf_roas_display', (gv('b_roas')||4).toFixed(2));
    } else if (currentGoalType==='leads') {
      derived=(gv('gf_leads')||0)*(gv('gf_cpl')||gv('b_cpl')||500);
    } else if (currentGoalType==='transactions') {
      derived=(gv('gf_transactions')||0)*(gv('gf_cpa')||1000);
    } else if (currentGoalType==='cac') {
      derived=(gv('gf_cac')||0)*(gv('gf_conv_target')||0);
    } else if (currentGoalType==='roas') {
      const rev=gv('gf_revenue'), roas=gv('gf_target_roas')||4;
      if (rev>0) derived=rev/roas;
    }
    if (derived>0) { budget=derived; sv('inp_budget',Math.round(derived)); }
  }

  const bsAw  = gv('bs_awareness')/100;
  const bsCon = gv('bs_consideration')/100;
  const bsCv  = gv('bs_conversion')/100;
  const budgets = {awareness:budget*bsAw, consideration:budget*bsCon, conversion:budget*bsCv};

  ['awareness','consideration','conversion'].forEach(g=>{
    const sec=document.getElementById('sec_'+g);
    if(sec) sec.style.display=goals.includes(g)?'':'none';
  });

  const totals={impr:0,clicks:0,convs:0,revenue:0};
  const months = Math.max(1, Math.round(currentDuration/30));

  if(goals.includes('awareness'))     renderObjective('awareness',    budgets.awareness,    platforms,pG,pM,totals,months,aov);
  if(goals.includes('consideration')) renderObjective('consideration',budgets.consideration,platforms,pG,pM,totals,months,aov);
  if(goals.includes('conversion'))    renderObjective('conversion',   budgets.conversion,   platforms,pG,pM,totals,months,aov);

  st('sum_budget',fC(budget));
  st('sum_impressions',fN(totals.impr));
  st('sum_clicks',fN(totals.clicks));
  st('sum_conversions',fN(totals.convs));
  const revLabel = currentGoalType==='leads' ? fN(totals.convs)+' Leads' : fC(totals.revenue);
  st('sum_revenue',revLabel);
  const roasVal = budget>0 ? totals.revenue/budget : 0;
  st('sum_roas', currentGoalType==='leads' ? (totals.convs>0?fC2(budget/totals.convs):'-') : fX(roasVal));

  updateCharts(budgets,totals,goals);
  updatePrintHeader();
  st('aw_budget_lbl',fC(budgets.awareness));
  st('con_budget_lbl',fC(budgets.consideration));
  st('cvr_budget_lbl',fC(budgets.conversion));
}

// MOM GROWTH FACTORS per month (efficiency improves as campaign matures)
const MOM_GROWTH = [1.0,1.10,1.20,1.27,1.32,1.36,1.39,1.41,1.43,1.45,1.46,1.47];

// PLACEMENT ROW TEMPLATES
const ROWS = {
  awareness: {
    google: [
      {channel:'Display',publisher:'Google',targeting:'Affinity / In-Market',placements:'Display Network',format:'Responsive Display Ad',buying:'CPM',weight:0.35},
      {channel:'Video',publisher:'YouTube',targeting:'Custom Segment / Affinity',placements:'YouTube Pre-roll',format:'15s / 30s Skippable',buying:'CPV',weight:0.65}
    ],
    meta: [
      {channel:'Social',publisher:'Meta',targeting:'Interest + Behaviour',placements:'FB & IG Feed',format:'Video / Image (4:5)',buying:'CPM',weight:0.50},
      {channel:'Social',publisher:'Meta',targeting:'Interest + Lookalike',placements:'Stories',format:'Vertical Video (9:16)',buying:'CPM',weight:0.30},
      {channel:'Social',publisher:'Meta',targeting:'Broad + Retargeting',placements:'Reels',format:'Short Video 15-30s',buying:'CPM',weight:0.20}
    ]
  },
  consideration: {
    google: [
      {channel:'Search',publisher:'Google',targeting:'Keywords (Broad + Phrase)',placements:'Google Search Results',format:'Responsive Search Ad',buying:'CPC',weight:0.70},
      {channel:'Display',publisher:'Google',targeting:'In-Market Segments',placements:'Display Network',format:'Responsive Display',buying:'CPC',weight:0.30}
    ],
    meta: [
      {channel:'Social',publisher:'Meta',targeting:'Interest + Behaviour',placements:'FB & IG Feed',format:'Carousel / Video',buying:'CPC',weight:0.60},
      {channel:'Social',publisher:'Meta',targeting:'Retargeting (Website)',placements:'Stories',format:'Vertical Card',buying:'CPC',weight:0.40}
    ]
  },
  conversion: {
    google: [
      {channel:'Search',publisher:'Google',targeting:'Keywords (Exact + Phrase)',placements:'Google Search Results',format:'Responsive Search Ad',buying:'CPC',weight:0.60},
      {channel:'Shopping/PMAX',publisher:'Google',targeting:'All Google Channels',placements:'Search + Display + YT',format:'Performance Max',buying:'CPC',weight:0.40}
    ],
    meta: [
      {channel:'Social',publisher:'Meta',targeting:'Custom Audience + LAL',placements:'FB & IG Feed',format:'Dynamic / Single Image',buying:'CPC',weight:0.50},
      {channel:'Lead Gen',publisher:'Meta',targeting:'Interest + Lookalike 1%',placements:'Facebook Feed',format:'Lead Form Ad',buying:'CPL',weight:0.50}
    ]
  }
};

function platIcon(p){
  return p==='google'
    ? '<span style="font-weight:800;color:#4285f4;font-size:12px">G</span>'
    : '<i class="bi bi-facebook" style="color:#1877f2;font-size:12px"></i>';
}
function buyingTag(b){
  const cls={CPM:'buying-cpm',CPC:'buying-cpc',CPV:'buying-cpv',CPL:'buying-cpl'}[b]||'buying-cpc';
  return `<span class="buying-tag ${cls}">${b}</span>`;
}

// ═══════════════════════════════════════════════════════
// RENDER OBJECTIVE (multi-month)
// ═══════════════════════════════════════════════════════
function renderObjective(objective, totalBudget, platforms, pG, pM, totals, months, aov) {
  const wrap = document.getElementById(objective[0]+objective.slice(1).replace('awareness','w').replace('consideration','on').replace('conversion','vr')+'_tables_wrap');
  const wrapId = {awareness:'aw',consideration:'con',conversion:'cvr'}[objective];
  const wrapEl = document.getElementById(wrapId+'_tables_wrap');
  if (!wrapEl) return;

  let html = '';
  for (let m=0; m<months; m++) {
    const growth = MOM_GROWTH[Math.min(m, MOM_GROWTH.length-1)];
    const momLabel = m===0 ? '<span class="mom-badge mom-base">Baseline</span>'
                           : `<span class="mom-badge mom-up">+${Math.round((growth-1)*100)}% efficiency</span>`;
    const start = m*30+1, end = Math.min((m+1)*30, currentDuration);
    html += `<div class="mp-section">`;
    if (months>1) {
      html += `<div class="mp-month-label"><span class="month-badge">Month ${m+1} &nbsp;·&nbsp; Days ${start}–${end}</span>${momLabel}</div>`;
    }
    html += `<div class="output-table-wrap">`;
    html += buildObjectiveTable(objective, totalBudget, platforms, pG, pM, totals, aov, growth, m);
    html += `</div></div>`;
  }
  wrapEl.innerHTML = html;
}

function buildObjectiveTable(objective, totalBudget, platforms, pG, pM, totals, aov, growth, monthIdx) {
  if (objective==='awareness')     return buildAwarenessTable(totalBudget,platforms,pG,pM,totals,growth,monthIdx);
  if (objective==='consideration') return buildConsiderationTable(totalBudget,platforms,pG,pM,totals,growth,monthIdx);
  if (objective==='conversion')    return buildConversionTable(totalBudget,platforms,pG,pM,totals,aov,growth,monthIdx);
  return '';
}

// ── AWARENESS TABLE ──────────────────────────────────
function buildAwarenessTable(totalBudget, platforms, pG, pM, totals, growth, mIdx) {
  const freq = gv('b_frequency')||3;
  let rows=[], tBudget=0, tImpr=0, tReach=0;
  platforms.forEach(p => {
    const platBudget = totalBudget * (p==='google'?pG:pM);
    const trows = ROWS.awareness[p]||[];
    trows.forEach(t => {
      const rowBudget = platBudget * t.weight;
      let impr=0, reach=0, views=0, vtr=0, cpv=0, unitCost=0;
      if (t.buying==='CPM') {
        const cpm = (gv('b_cpm_'+p)||100) * (1/growth);
        unitCost = cpm;
        impr = cpm>0 ? (rowBudget/cpm)*1000 : 0;
        reach = freq>0 ? impr/freq : 0;
      } else if (t.buying==='CPV') {
        cpv = (gv('b_cpv_'+p)||1.20) * (1/growth);
        unitCost = cpv;
        views = cpv>0 ? rowBudget/cpv : 0;
        vtr = gv('b_vtr_'+p)||40;
        impr = vtr>0 ? views/(vtr/100) : 0;
        reach = freq>0 ? impr/freq : 0;
      }
      totals.impr += impr;
      tBudget+=rowBudget; tImpr+=impr; tReach+=reach;
      rows.push({p,t,rowBudget,unitCost,impr,reach,views,vtr,cpv});
    });
  });

  let html = `<table class="output-table">
    <thead><tr>
      <th>Channel</th><th>Publisher</th><th>Targeting</th><th>Placements</th>
      <th>Format / Specs</th><th>Buying</th><th>Unit Cost</th>
      <th>Reach</th><th>Impressions</th><th>Views</th><th>VTR %</th><th>Total Cost</th>
    </tr></thead><tbody>`;

  rows.forEach(r => {
    html += `<tr class="platform-${r.p}">
      <td><span class="channel-tag">${r.t.channel}</span></td>
      <td><span class="plat-badge ${r.p}">${platIcon(r.p)} ${r.p==='google'?'Google':'Meta'}</span></td>
      <td class="meta-col" style="max-width:160px;white-space:normal;font-size:10.5px">${r.t.targeting}</td>
      <td class="meta-col" style="font-size:10.5px">${r.t.placements}</td>
      <td class="meta-col" style="font-size:10.5px">${r.t.format}</td>
      <td>${buyingTag(r.t.buying)}</td>
      <td class="calc">${fC2(r.unitCost)}</td>
      <td class="calc">${fN(r.reach)}</td>
      <td class="calc">${fN(r.impr)}</td>
      <td class="calc">${r.views>0?fN(r.views):'—'}</td>
      <td class="calc">${r.vtr>0?fP(r.vtr):'—'}</td>
      <td class="calc" style="font-weight:700">${fC(r.rowBudget)}</td>
    </tr>`;
  });

  html += `</tbody><tfoot><tr>
    <td colspan="7"><strong>Total</strong></td>
    <td><strong>${fN(tReach)}</strong></td>
    <td><strong>${fN(tImpr)}</strong></td>
    <td>—</td><td>—</td>
    <td><strong>${fC(tBudget)}</strong></td>
  </tr></tfoot></table>`;
  return html;
}

// ── CONSIDERATION TABLE ──────────────────────────────
function buildConsiderationTable(totalBudget, platforms, pG, pM, totals, growth, mIdx) {
  let rows=[], tBudget=0, tClicks=0, tImpr=0;
  platforms.forEach(p => {
    const platBudget = totalBudget*(p==='google'?pG:pM);
    (ROWS.consideration[p]||[]).forEach(t => {
      const rowBudget = platBudget*t.weight;
      const cpc  = (gv('b_cpc_'+p)||25) * (1/growth);
      const ctr  = (gv('b_ctr_'+p)||3) * growth / 100;
      const clicks = cpc>0 ? rowBudget/cpc : 0;
      const impr   = ctr>0 ? clicks/ctr : 0;
      totals.clicks+=clicks; totals.impr+=impr;
      tBudget+=rowBudget; tClicks+=clicks; tImpr+=impr;
      rows.push({p,t,rowBudget,cpc,ctr:ctr*100,clicks,impr});
    });
  });

  let html = `<table class="output-table">
    <thead><tr>
      <th>Channel</th><th>Publisher</th><th>Targeting</th><th>Placements</th>
      <th>Format / Specs</th><th>Buying</th><th>Unit Cost (CPC)</th>
      <th>CTR %</th><th>Clicks</th><th>Impressions</th><th>Total Cost</th>
    </tr></thead><tbody>`;

  rows.forEach(r => {
    html += `<tr class="platform-${r.p}">
      <td><span class="channel-tag">${r.t.channel}</span></td>
      <td><span class="plat-badge ${r.p}">${platIcon(r.p)} ${r.p==='google'?'Google':'Meta'}</span></td>
      <td class="meta-col" style="max-width:160px;white-space:normal;font-size:10.5px">${r.t.targeting}</td>
      <td class="meta-col" style="font-size:10.5px">${r.t.placements}</td>
      <td class="meta-col" style="font-size:10.5px">${r.t.format}</td>
      <td>${buyingTag(r.t.buying)}</td>
      <td class="calc">${fC2(r.cpc)}</td>
      <td class="calc">${fP(r.ctr)}</td>
      <td class="calc">${fN(r.clicks)}</td>
      <td class="calc">${fN(r.impr)}</td>
      <td class="calc" style="font-weight:700">${fC(r.rowBudget)}</td>
    </tr>`;
  });

  html += `</tbody><tfoot><tr>
    <td colspan="7"><strong>Total</strong></td>
    <td>—</td>
    <td><strong>${fN(tClicks)}</strong></td>
    <td><strong>${fN(tImpr)}</strong></td>
    <td><strong>${fC(tBudget)}</strong></td>
  </tr></tfoot></table>`;
  return html;
}

// ── CONVERSION TABLE ─────────────────────────────────
function buildConversionTable(totalBudget, platforms, pG, pM, totals, aov, growth, mIdx) {
  let rows=[], tBudget=0, tConvs=0, tRev=0;
  platforms.forEach(p => {
    const platBudget = totalBudget*(p==='google'?pG:pM);
    (ROWS.conversion[p]||[]).forEach(t => {
      const rowBudget = platBudget*t.weight;
      const cpc  = (gv('b_cpc_'+p)||25) * (1/growth);
      const cvr  = (gv('b_cvr_'+p)||2.5) * growth / 100;
      const clicks = cpc>0 ? rowBudget/cpc : 0;
      const convs  = clicks*cvr;
      const cpa    = convs>0 ? rowBudget/convs : 0;
      const revenue= convs*aov;
      const roas   = rowBudget>0 ? revenue/rowBudget : 0;
      const cpl    = gv('b_cpl')||cpa;
      totals.clicks+=clicks; totals.convs+=convs; totals.revenue+=revenue;
      tBudget+=rowBudget; tConvs+=convs; tRev+=revenue;
      rows.push({p,t,rowBudget,cpc,cvr:cvr*100,clicks,convs,cpa,revenue,roas,cpl});
    });
  });

  const isLeads = currentGoalType==='leads';
  const convLabel = {revenue:'Conversions',leads:'Leads',transactions:'Transactions',cac:'Acquisitions',roas:'Conversions'}[currentGoalType]||'Conversions';
  const revLabel  = isLeads ? 'CPL' : 'Revenue';
  const roasLabel = isLeads ? 'vs Target' : 'ROAS';

  let html = `<table class="output-table">
    <thead><tr>
      <th>Channel</th><th>Publisher</th><th>Targeting</th><th>Placements</th>
      <th>Format / Specs</th><th>Buying</th><th>Unit Cost</th>
      <th>CVR %</th><th>${convLabel}</th><th>CPA</th><th>${revLabel}</th><th>${roasLabel}</th><th>Total Cost</th>
    </tr></thead><tbody>`;

  rows.forEach(r => {
    const revCell  = isLeads ? fC2(r.cpl) : fC(r.revenue);
    const roasCell = isLeads ? (gv('b_cpl')>0?fX(gv('b_cpl')/r.cpa):'—') : fX(r.roas);
    html += `<tr class="platform-${r.p}">
      <td><span class="channel-tag">${r.t.channel}</span></td>
      <td><span class="plat-badge ${r.p}">${platIcon(r.p)} ${r.p==='google'?'Google':'Meta'}</span></td>
      <td class="meta-col" style="max-width:160px;white-space:normal;font-size:10.5px">${r.t.targeting}</td>
      <td class="meta-col" style="font-size:10.5px">${r.t.placements}</td>
      <td class="meta-col" style="font-size:10.5px">${r.t.format}</td>
      <td>${buyingTag(r.t.buying)}</td>
      <td class="calc">${fC2(r.cpc)}</td>
      <td class="calc">${fP(r.cvr)}</td>
      <td class="calc">${fN(r.convs)}</td>
      <td class="calc">${fC2(r.cpa)}</td>
      <td class="calc">${revCell}</td>
      <td class="calc">${roasCell}</td>
      <td class="calc" style="font-weight:700">${fC(r.rowBudget)}</td>
    </tr>`;
  });

  const tRoas = tBudget>0?tRev/tBudget:0;
  html += `</tbody><tfoot><tr>
    <td colspan="7"><strong>Total</strong></td>
    <td>—</td>
    <td><strong>${fN(tConvs)}</strong></td>
    <td>—</td>
    <td><strong>${isLeads?'—':fC(tRev)}</strong></td>
    <td><strong>${isLeads?'—':fX(tRoas)}</strong></td>
    <td><strong>${fC(tBudget)}</strong></td>
  </tr></tfoot></table>`;
  return html;
}

// ═══════════════════════════════════════════════════════
// KEYWORDS
// ═══════════════════════════════════════════════════════
function renderKeywordsTable() {
  const tbody = document.getElementById('tbody_keywords');
  if (!tbody) return;
  tbody.innerHTML = keywords.slice(0,10).map((kw,i) => `
    <tr>
      <td style="color:#94a3b8">${i+1}</td>
      <td><input type="text" class="form-control form-control-sm" value="${escH(kw.keyword)}" style="min-width:180px;font-size:12px" onchange="keywords[${i}].keyword=this.value"></td>
      <td><input type="number" class="form-control form-control-sm" value="${kw.cpc}" step="0.01" style="width:80px;font-size:12px;text-align:right" onchange="keywords[${i}].cpc=parseFloat(this.value)||0;updateAvgCpc()"></td>
      <td style="font-weight:500">${fN(kw.volume)}</td>
      <td><span class="kw-comp kw-${kw.competition}">${kw.competition}</span></td>
      <td><span class="kw-intent-badge kw-${kw.intent}">${kw.intent||'N/A'}</span></td>
      <td style="font-weight:700;color:#0f766e">${kw.commercial_score!=null ? kw.commercial_score : '—'}</td>
      <td><span class="kw-used-badge">Used</span></td>
      <td class="no-print"><button class="btn btn-sm btn-outline-danger py-0 px-2" style="font-size:10px" onclick="removeKw(${i})"><i class="bi bi-trash"></i></button></td>
    </tr>`).join('');
}
function removeKw(i)  { keywords.splice(i,1); renderKeywordsTable(); updateAvgCpc(); }
function addKeywordRow() {
  if (keywords.length>=10) { showToast('Max 10 keywords (used for calculations)','warning'); return; }
  keywords.push({keyword:'New Keyword',cpc:0,volume:0,competition:'Medium',intent:'Commercial',commercial_score:0});
  renderKeywordsTable();
}
function updateAvgCpc() {
  const valid = keywords.filter(k=>k.cpc>0);
  if (!valid.length) return;
  const avg = valid.reduce((a,k)=>a+k.cpc,0)/valid.length;
  st('kw_avg_g', fC2(avg));
  st('kw_avg_m', fC2(avg*0.70));
  if (!overrides['cpc_google']) sv('b_cpc_google', avg.toFixed(2));
  if (!overrides['cpc_meta'])   sv('b_cpc_meta',   (avg*0.70).toFixed(2));
}

// ═══════════════════════════════════════════════════════
// FETCH KEYWORDS FROM API
// ═══════════════════════════════════════════════════════
function fetchKeywordsFromAPI(autoTriggered=false) {
  const website  = document.getElementById('inp_website')?.value??'';
  const industry = document.getElementById('inp_industry')?.value??'ecommerce';
  const competitors = document.getElementById('inp_competitors')?.value??'';
  if (!autoTriggered) showToast('Fetching keyword data…','primary');
  const fd = new FormData();
  fd.append('website',website); fd.append('industry',industry);
  fd.append('competitors', competitors);
  fetch('?action=fetch_keywords',{method:'POST',body:fd})
    .then(r=>r.json()).then(data=>{
      const spinner = document.getElementById('kw_fetch_spinner');
      const hint    = document.getElementById('website_kw_hint');
      if (spinner) spinner.style.display='none';
      if (data.keywords?.length) {
        keywords = data.keywords.slice(0,10);
        // Keep backend commercial ranking; secondary tie-break by competition.
        keywords.sort((a,b) => {
          const scoreA = parseInt(a.commercial_score ?? 0, 10);
          const scoreB = parseInt(b.commercial_score ?? 0, 10);
          if (scoreB !== scoreA) return scoreB - scoreA;
          const compOrder = {High:3, Medium:2, Low:1};
          return (compOrder[b.competition] || 0) - (compOrder[a.competition] || 0);
        });
        renderKeywordsTable(); updateAvgCpc(); recalculate();
        const badge = document.getElementById('kw_source_badge');
        if (badge) badge.textContent = 'Source: '+data.source;
        const apiEl = document.getElementById('api_status_badge');
        if (data.source!=='Seed (no API)') {
          apiEl.textContent='● '+data.source; apiEl.className='api-status api-ok';
        }
        if (hint) hint.textContent = keywords.length+' keywords loaded from '+data.source;
        showToast(`${keywords.length} keywords loaded (${data.source})`,'success');
      }
    }).catch(()=>{
      const spinner=document.getElementById('kw_fetch_spinner');
      if(spinner) spinner.style.display='none';
      showToast('Keyword fetch failed','danger');
    });
}

function getActiveAudiencePlatform() {
  return document.getElementById('aud_panel_google')?.style.display !== 'none' ? 'google' : 'meta';
}
function fetchAudienceTargets(platform = null) {
  platform = platform || getActiveAudiencePlatform();
  const website  = document.getElementById('inp_website')?.value??'';
  const industry = document.getElementById('inp_industry')?.value??'ecommerce';
  const status = document.getElementById('aud_fetch_status');
  if (status) status.textContent = 'Fetching audience data…';
  showToast('Fetching audience targeting…','primary');
  const fd = new FormData();
  fd.append('platform', platform); fd.append('website', website); fd.append('industry', industry);
  fetch('?action=fetch_audience',{method:'POST',body:fd})
    .then(r=>r.json()).then(data=>{
      if (data.audience?.google) {
        setTA('aud_g_custom', data.audience.google.custom ?? '');
        setTA('aud_g_inmarket', data.audience.google.in_market ?? '');
        setTA('aud_g_affinity', data.audience.google.affinity ?? '');
        setTA('aud_g_remarketing', data.audience.google.remarketing ?? '');
      }
      if (data.audience?.meta) {
        setTA('aud_m_interests', data.audience.meta.interests ?? '');
        setTA('aud_m_behaviour', data.audience.meta.behaviour ?? '');
        setTA('aud_m_education', data.audience.meta.demographics ?? data.audience.meta.education ?? '');
      }
      if (status) status.textContent = data.source ? `Fetched from ${data.source}` : 'Audience data loaded';
      showToast('Audience targeting updated','success');
    }).catch(err=>{
      if (status) status.textContent = 'Audience fetch failed';
      console.error(err);
      showToast('Audience fetch failed','danger');
    });
}

// ═══════════════════════════════════════════════════════
// CHARTS
// ═══════════════════════════════════════════════════════
function updateCharts(budgets, totals, goals) {
  const bCtx = document.getElementById('chartBudget')?.getContext('2d');
  if (bCtx) {
    const labels=[], data=[], colors=[];
    if(goals.includes('awareness'))     {labels.push('Awareness');    data.push(budgets.awareness);    colors.push('#7c3aed');}
    if(goals.includes('consideration')) {labels.push('Consideration');data.push(budgets.consideration);colors.push('#0891b2');}
    if(goals.includes('conversion'))    {labels.push('Conversion');   data.push(budgets.conversion);   colors.push('#16a34a');}
    if (budgetChart) budgetChart.destroy();
    budgetChart = new Chart(bCtx,{type:'doughnut',
      data:{labels,datasets:[{data,backgroundColor:colors,borderWidth:2,borderColor:'#fff'}]},
      options:{responsive:true,plugins:{legend:{position:'right',labels:{font:{size:11},padding:12}}},cutout:'65%'}
    });
  }
  const fCtx = document.getElementById('chartFunnel')?.getContext('2d');
  if (fCtx) {
    const raw=[totals.impr,totals.clicks,totals.convs];
    const maxV=Math.max(...raw,1);
    const pct=raw.map(v=>(v/maxV)*100);
    const fmtV=v=>v>=1e6?fN(v/1e6,1)+'M':v>=1e3?fN(v/1e3,1)+'K':fN(v);
    if (funnelChart) funnelChart.destroy();
    funnelChart = new Chart(fCtx,{type:'bar',
      data:{labels:['Impressions','Clicks','Conversions'],datasets:[{data:pct,backgroundColor:['#7c3aed','#0891b2','#16a34a'],borderRadius:6,barThickness:32}]},
      options:{responsive:true,indexAxis:'y',animation:{duration:400},plugins:{legend:{display:false},tooltip:{callbacks:{label:()=>''}}},
        scales:{x:{display:false,max:105},y:{grid:{display:false},ticks:{font:{size:11},color:'#475569'}}}},
      plugins:[{id:'funnelLabels',afterDatasetsDraw(chart){
        const {ctx}=chart;
        pct.forEach((p,i)=>{
          const meta=chart.getDatasetMeta(0).data[i];
          ctx.save();ctx.font='bold 11px Inter,system-ui,sans-serif';ctx.fillStyle='#1e293b';ctx.textAlign='left';
          ctx.fillText(fmtV(raw[i]),meta.x+6,meta.y+4);ctx.restore();
        });
      }}]
    });
  }
}

// ═══════════════════════════════════════════════════════
// PRINT HEADER
// ═══════════════════════════════════════════════════════
function updatePrintHeader() {
  const site    =document.getElementById('inp_website')?.value||'—';
  const indName =document.getElementById('industry_search')?.value||'—';
  const location=document.getElementById('inp_location')?.value||'—';
  const budget  =gv('inp_budget');
  const dur     =gv('inp_duration');
  const goals   =getGoals();
  const platforms=getPlatforms();
  const dateStr =new Date().toLocaleDateString('en-IN',{year:'numeric',month:'long',day:'numeric'});
  st('ph_website_lbl',site);st('ph_industry_lbl',indName);st('ph_location_lbl',location);
  st('ph_budget_lbl',`Monthly Budget: ${fC(budget)}`);
  st('ph_date_lbl',`Prepared: ${dateStr}`);
  st('ph_duration_lbl',`Campaign: ${dur} Days`);
  const chipEl=document.getElementById('ph_chips');
  if(chipEl){
    const gc={awareness:'#7c3aed',consideration:'#0891b2',conversion:'#16a34a'};
    const pc={google:'#4285f4',meta:'#1877f2'};
    chipEl.innerHTML=[
      ...goals.map(g=>`<span style="background:${gc[g]};color:#fff;font-size:10px;font-weight:700;padding:2px 9px;border-radius:12px;text-transform:capitalize">${g}</span>`),
      ...platforms.map(p=>`<span style="background:${pc[p]};color:#fff;font-size:10px;font-weight:700;padding:2px 9px;border-radius:12px">${p==='google'?'Google Ads':'Meta Ads'}</span>`)
    ].join('');
  }
}

// ═══════════════════════════════════════════════════════
// SAVE / LOAD
// ═══════════════════════════════════════════════════════
function collectPlan() {
  return {
    v:'3.0', savedAt:new Date().toISOString(),
    inputs:{website:document.getElementById('inp_website')?.value,industry:document.getElementById('inp_industry')?.value,
      industryName:document.getElementById('industry_search')?.value,location:document.getElementById('inp_location')?.value,
      budget:gv('inp_budget'),duration:currentDuration,aov:gv('inp_aov'),calcMode:CALC_MODE.mode,goalType:currentGoalType,
      goals:getGoals(),platforms:getPlatforms()},
    benchmarks:{cpc_google:gv('b_cpc_google'),cpc_meta:gv('b_cpc_meta'),ctr_google:gv('b_ctr_google'),ctr_meta:gv('b_ctr_meta'),
      cvr_google:gv('b_cvr_google'),cvr_meta:gv('b_cvr_meta'),cpm_google:gv('b_cpm_google'),cpm_meta:gv('b_cpm_meta'),
      cpv_google:gv('b_cpv_google'),cpv_meta:gv('b_cpv_meta'),vtr_google:gv('b_vtr_google'),vtr_meta:gv('b_vtr_meta'),
      frequency:gv('b_frequency'),roas:gv('b_roas'),cpl:gv('b_cpl')},
    splits:{awareness:gv('bs_awareness'),consideration:gv('bs_consideration'),conversion:gv('bs_conversion'),google:gv('pct_google'),meta:gv('pct_meta')},
    audience:{google:{custom:document.getElementById('aud_g_custom')?.value,inmarket:document.getElementById('aud_g_inmarket')?.value,
      affinity:document.getElementById('aud_g_affinity')?.value,remarketing:document.getElementById('aud_g_remarketing')?.value},
      meta:{interests:document.getElementById('aud_m_interests')?.value,behaviour:document.getElementById('aud_m_behaviour')?.value,
        ageMin:gv('aud_m_age_min'),ageMax:gv('aud_m_age_max'),gender:document.getElementById('aud_m_gender')?.value,
        language:document.getElementById('aud_m_language')?.value,education:document.getElementById('aud_m_education')?.value,
        custom:document.getElementById('aud_m_custom')?.value}},
    keywords,overrides
  };
}
function savePlanToFile() {
  const blob=new Blob([JSON.stringify(collectPlan(),null,2)],{type:'application/json'});
  const a=document.createElement('a'); a.href=URL.createObjectURL(blob);
  a.download='media_plan_'+Date.now()+'.json'; a.click(); URL.revokeObjectURL(a.href);
  showToast('Plan saved','success');
}
function loadPlanFromFile(e) {
  const file=e.target.files[0]; if(!file) return;
  const reader=new FileReader();
  reader.onload=ev=>{ try{const p=JSON.parse(ev.target.result);applyPlan(p);recalculate();showToast('Plan loaded','success');}catch{showToast('Invalid file','danger');} };
  reader.readAsText(file); e.target.value='';
}
function applyPlan(p) {
  const i=p.inputs??{},b=p.benchmarks??{},s=p.splits??{},a=p.audience??{};
  if(i.industry&&i.industryName) selectIndustry(i.industry,i.industryName);
  if(i.website)  document.getElementById('inp_website').value=i.website;
  if(i.location) document.getElementById('inp_location').value=i.location;
  if(i.budget)   sv('inp_budget',i.budget);
  if(i.duration) setDuration(i.duration);
  if(i.aov)      sv('inp_aov',i.aov);
  if(i.calcMode) setCalcMode(i.calcMode);
  if(i.goalType) { document.getElementById('sel_goal_type').value=i.goalType; updateGoalType(); }
  if(i.goals) document.querySelectorAll('.goal-chip').forEach(c=>{ const on=i.goals.includes(c.dataset.goal);c.classList.toggle('selected',on);c.querySelector('.goal-value').value=on?1:0; });
  if(i.platforms) document.querySelectorAll('.platform-chip').forEach(c=>{ const on=i.platforms.includes(c.dataset.platform);c.classList.toggle('selected',on);c.querySelector('.platform-value').value=on?1:0; });
  const setB=(id,v)=>{if(v!==undefined)sv(id,v);};
  setB('b_cpc_google',b.cpc_google);setB('b_cpc_meta',b.cpc_meta);setB('b_ctr_google',b.ctr_google);setB('b_ctr_meta',b.ctr_meta);
  setB('b_cvr_google',b.cvr_google);setB('b_cvr_meta',b.cvr_meta);setB('b_cpm_google',b.cpm_google);setB('b_cpm_meta',b.cpm_meta);
  setB('b_cpv_google',b.cpv_google);setB('b_cpv_meta',b.cpv_meta);setB('b_vtr_google',b.vtr_google);setB('b_vtr_meta',b.vtr_meta);
  setB('b_frequency',b.frequency);setB('b_roas',b.roas);setB('b_cpl',b.cpl);
  if(s.awareness!==undefined){sv('bs_awareness',s.awareness);sv('sl_aw',s.awareness);}
  if(s.consideration!==undefined){sv('bs_consideration',s.consideration);sv('sl_con',s.consideration);}
  if(s.conversion!==undefined){sv('bs_conversion',s.conversion);sv('sl_cv',s.conversion);}
  if(s.google!==undefined){sv('pct_google',s.google);sv('sl_google',s.google);}
  if(s.meta!==undefined){sv('pct_meta',s.meta);sv('sl_meta',s.meta);}
  if(a.google){setTA('aud_g_custom',a.google.custom??'');setTA('aud_g_inmarket',a.google.inmarket??'');setTA('aud_g_affinity',a.google.affinity??'');setTA('aud_g_remarketing',a.google.remarketing??'');}
  if(a.meta){setTA('aud_m_interests',a.meta.interests??'');setTA('aud_m_behaviour',a.meta.behaviour??'');setTA('aud_m_education',a.meta.education??'');setTA('aud_m_custom',a.meta.custom??'');
    if(a.meta.ageMin) sv('aud_m_age_min',a.meta.ageMin); if(a.meta.ageMax) sv('aud_m_age_max',a.meta.ageMax);
    if(a.meta.gender) document.getElementById('aud_m_gender').value=a.meta.gender;
    if(a.meta.language) document.getElementById('aud_m_language').value=a.meta.language;}
  if(p.keywords){keywords=p.keywords;renderKeywordsTable();updateAvgCpc();}
  if(p.overrides) Object.assign(overrides,p.overrides);
}

// ═══════════════════════════════════════════════════════
// EXPORT CSV
// ═══════════════════════════════════════════════════════
function exportCSV() {
  let csv=`PPC Media Plan v3\nWebsite,${document.getElementById('inp_website')?.value??''}\nIndustry,${document.getElementById('industry_search')?.value??''}\nBudget,${gv('inp_budget')}\nDuration,${currentDuration} days\nDate,${new Date().toLocaleDateString('en-IN')}\n\n`;
  csv+='SUMMARY\n';
  ['sum_budget','sum_impressions','sum_clicks','sum_conversions','sum_revenue','sum_roas'].forEach(id=>{
    csv+=`"${id.replace('sum_','').replace('_',' ')}","${document.getElementById(id)?.textContent}"\n`;
  });
  csv+='\nKEYWORDS\nKeyword,CPC,Volume,Competition\n';
  keywords.forEach(k=>{csv+=`"${k.keyword}","${k.cpc}","${k.volume}","${k.competition}"\n`;});
  const blob=new Blob([csv],{type:'text/csv'});
  const a=document.createElement('a'); a.href=URL.createObjectURL(blob);
  a.download='media_plan_'+new Date().toISOString().slice(0,10)+'.csv'; a.click();
  URL.revokeObjectURL(a.href); showToast('CSV downloaded','success');
}

// ═══════════════════════════════════════════════════════
// TOAST
// ═══════════════════════════════════════════════════════
function showToast(msg,type='success'){
  const t=document.getElementById('toast');
  t.className=`toast align-items-center text-bg-${type} border-0`;
  document.getElementById('toast_body').textContent=msg;
  bootstrap.Toast.getOrCreateInstance(t,{delay:3000}).show();
}

// ═══════════════════════════════════════════════════════
// AUDIENCE REACH ESTIMATION
// ═══════════════════════════════════════════════════════
function estimateAudienceReach() {
  const interests = (document.getElementById('aud_m_interests')?.value ?? '').split(',').filter(x=>x.trim()).length;
  const behaviors = (document.getElementById('aud_m_behaviour')?.value ?? '').split(',').filter(x=>x.trim()).length;
  const demographics = (document.getElementById('aud_m_education')?.value ?? '').split(',').filter(x=>x.trim()).length;
  const base = 1000000; // 1M base
  const reach = base + (interests * 2000000) + (behaviors * 1500000) + (demographics * 500000);
  document.getElementById('aud_reach_badge').textContent = `Est. Reach: ${(reach / 1000000).toFixed(1)}M`;
  showToast('Audience reach estimated','info');
}

// ═══════════════════════════════════════════════════════
// AI AUDIENCE REFINEMENT
// ═══════════════════════════════════════════════════════
function refineAudienceWithAI() {
  const industry = document.getElementById('inp_industry')?.value ?? 'ecommerce';
  const goals = Array.from(document.querySelectorAll('.goal-chip.selected')).map(c => c.dataset.goal).join(', ');
  const current = {
    interests: document.getElementById('aud_m_interests')?.value ?? '',
    behaviors: document.getElementById('aud_m_behaviour')?.value ?? '',
    demographics: document.getElementById('aud_m_education')?.value ?? ''
  };
  const currentStr = `Interests: ${current.interests}, Behaviors: ${current.behaviors}, Demographics: ${current.demographics}`;
  fetch('?action=refine_audience', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({industry, goals, current_audience: currentStr})
  })
  .then(r => r.json())
  .then(data => {
    if (data.error) {
      showToast('AI Error: ' + data.error, 'danger');
    } else {
      if (data.interests) document.getElementById('aud_m_interests').value = data.interests;
      if (data.behaviors) document.getElementById('aud_m_behaviour').value = data.behaviors;
      if (data.demographics) document.getElementById('aud_m_education').value = data.demographics;
      showToast('Audience refined with AI','success');
    }
  })
  .catch(() => showToast('AI refinement failed','danger'));
}
</script>
</body>
</html>
