( ′∀`)σ≡σ☆))Д′)レ(゚∀゚;)ヘ=З=З=Зε≡(ノ´_ゝ`)ノ HEX
HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux mail.thebrand.ai 6.8.0-107-generic #107-Ubuntu SMP PREEMPT_DYNAMIC Fri Mar 13 19:51:50 UTC 2026 x86_64
User: www-data (33)
PHP: 8.3.6
Disabled: NONE
Upload Files
File: /var/www/html/tmpr/..//tmpr/..//tmpr/..//tmpr/..//industry/industry-landing09032026.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

$segmentsPath = 'segments.json';

$segments = [];

if (is_file($segmentsPath)) {
    $raw = file_get_contents($segmentsPath);
    if ($raw !== false && $raw !== '') {
        $data = json_decode($raw, true);
        // Debug: uncomment below to catch JSON errors
        // if (json_last_error() !== JSON_ERROR_NONE) { die('JSON Error: ' . json_last_error_msg()); }
        if (is_array($data)) {
            if (isset($data['segments']) && is_array($data['segments'])) {
                $segments = $data['segments'];
            } elseif (isset($data[0]) && is_array($data[0])) {
                $segments = $data;
            }
        }
    }
}

$segmentId  = isset($_GET['id'])      ? (int)$_GET['id']                        : null;
$segmentKey = isset($_GET['segment']) ? trim((string)$_GET['segment'])           : null;
$segmentSlug = isset($_GET['slug'])   ? trim((string)$_GET['slug'], " \t\n\r\0\x0B/") : null;
if ($segmentSlug !== null) {
    $segmentSlug = urldecode($segmentSlug);
}
$segmentSlugKey = null;
$segment = null;

function normalize_key($value) {
    $v = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
    $v = strtolower($v);
    $v = str_replace('+', ' ', $v);
    $v = str_replace('&', ' ', $v);
    $v = str_replace('/', ' ', $v);
    $v = preg_replace('/[^a-z0-9 ]+/u', ' ', $v);
    $v = preg_replace('/\s+/u', ' ', $v);
    return trim($v);
}

if ($segmentSlug !== null && $segmentSlug !== '') {
    $normalizedSlug = normalize_key($segmentSlug);
    $segmentSlugKey = $normalizedSlug;
    foreach ($segments as $s) {
        $creator = isset($s['creator']) ? normalize_key($s['creator']) : '';
        if ($creator === $normalizedSlug) {
            $segment = $s;
            break;
        }
        $label = isset($s['segment']) ? normalize_key($s['segment']) : '';
        if ($label === $normalizedSlug) {
            $segment = $s;
            break;
        }
        if (isset($s['url_slugs']) && is_array($s['url_slugs'])) {
            foreach ($s['url_slugs'] as $slug) {
                $slugKey = normalize_key(trim((string)$slug, '/'));
                if ($slugKey === $normalizedSlug) {
                    $segment = $s;
                    break 2;
                }
            }
        }
    }
} elseif ($segmentId !== null && $segmentId > 0) {
    foreach ($segments as $s) {
        if (isset($s['id']) && (int)$s['id'] === $segmentId) {
            $segment = $s;
            break;
        }
    }
} elseif ($segmentKey !== null && $segmentKey !== '') {
    $normalizedKey = normalize_key($segmentKey);
    foreach ($segments as $s) {
        $label = isset($s['segment']) ? normalize_key($s['segment']) : '';
        if ($label === $normalizedKey) {
            $segment = $s;
            break;
        }
        if (isset($s['url_slugs']) && is_array($s['url_slugs'])) {
            foreach ($s['url_slugs'] as $slug) {
                $slugKey = normalize_key(trim((string)$slug, '/'));
                if ($slugKey === $normalizedKey) {
                    $segment = $s;
                    break 2;
                }
            }
        }
    }
}

if (!$segment) {
    http_response_code(404);
    ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Brand AI | Industry Landing Not Found</title>
    <link rel="icon" type="image/svg+xml" href="/favicon.svg">
    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
    <link href="/index_files/css2.css" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'brand-cyan': '#03bef3',
                        'brand-midnight': '#0b0f29'
                    }
                }
            }
        };
    </script>
    <style>
        html { scroll-behavior: smooth; }
        body { margin: 0; font-family: 'Inter', sans-serif; }
    </style>
</head>
<body class="bg-white text-gray-800">
<div class="min-h-screen flex items-center justify-center bg-gray-50">
    <div class="max-w-lg text-center p-8">
        <h1 class="text-3xl md:text-4xl font-extrabold mb-4 text-gray-900">Industry page not found</h1>
        <p class="text-gray-600 mb-6">The requested Brand AI industry landing could not be loaded.</p>
        <a href="https://www.thebrand.ai" class="inline-flex items-center px-6 py-3 rounded-lg bg-brand-cyan text-white font-semibold hover:opacity-90 transition">
            Back to Brand AI
        </a>
    </div>
</div>
</body>
</html>
<?php
    exit;
}

function h($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

$bdIsLoggedIn = false;
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (isset($_SESSION['euserid']) || isset($_COOKIE['euserid'])) {
    $bdIsLoggedIn = true;
}

$curatedTemplates = [];
$segmentCreator = isset($segment['creator']) ? trim((string)$segment['creator']) : '';
$interestsInput = '';
if ($segmentCreator !== '') {
    $interestsInput = $segmentCreator;
}
if (isset($segment['interests']) && $segment['interests'] !== '') {
    $interestsInput = $interestsInput !== ''
        ? $interestsInput . ', ' . trim((string)$segment['interests'])
        : trim((string)$segment['interests']);
}

if ($interestsInput !== '') {
    // Manually define DB connection instead of requiring the auth-protected config
    $servername = "localhost";
    $username = "root";
    $password = "Pw4TheBrand!";
    $dbname = "thebrand";
    
    $conn = new mysqli($servername, $username, $password, $dbname);
    if (!$conn->connect_error) {
        $conn->set_charset("utf8");
        
        $sql = "SELECT id, title, poster, alias, keywords FROM profilepicture WHERE isdisplay='13' AND type='2' AND public='1' AND catalogid=152";
        // ... rest of logic continues below ...
    $params = [];
    $types = "";
    $mode = 'default';
    $kw_parts = preg_split('/[,;]+/', $interestsInput);
    $keywords = [];
    foreach ($kw_parts as $p) {
        $p2 = preg_replace('/[^A-Za-z0-9\- ]/', '', (string)$p);
        $p2 = trim($p2);
        if ($p2 !== '') {
            $keywords[] = $p2;
        }
        if (count($keywords) >= 10) {
            break;
        }
    }
    if (!empty($keywords)) {
        $mode = 'interests';
        $where_parts = [];
        foreach ($keywords as $kw) {
            $k = "%" . str_replace(" ", "%", $kw) . "%";
            $where_parts[] = "(title LIKE ? OR keywords LIKE ?)";
            $params[] = $k;
            $params[] = $k;
            $types .= "ss";
        }
        $sql .= " AND (" . implode(' OR ', $where_parts) . ")";
    }
    if ($mode === 'default') {
        $sql .= " ORDER BY RAND()";
    } elseif ($mode === 'interests') {
        $sql .= " ORDER BY id DESC";
    } else {
        $sql .= " ORDER BY viewnum DESC";
    }
    $sql .= " LIMIT 50";

    $stmt = $conn->prepare($sql);
    if ($stmt) {
        if (!empty($params)) {
            $stmt->bind_param($types, ...$params);
        }
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $curatedTemplates[] = [
                'post_id' => $row['id'],
                'post_title' => $row['title'],
                'post_poster' => $row['poster'],
                'post_description' => $row['alias'],
                'post_keywords' => isset($row['keywords']) ? $row['keywords'] : ''
            ];
        }
        $stmt->close();
    }
    $conn->close();
}
}

$relevantTools = [];
$segmentCreatorTrimmed = $segmentCreator !== '' ? $segmentCreator : '';
if ($segmentCreatorTrimmed === '') {
    echo 'Segment creator is empty; URL-tool mapping skipped.' . "<br>";
}
if ($segmentCreatorTrimmed !== '') {
    $mappingPath = __DIR__ . '/url-tool-mapping.json';
    $ctaPath = __DIR__ . '/cta-url-tool.json';
    if (!file_exists($mappingPath)) {
        echo 'Mapping file not found: ' . $mappingPath . "<br>";
    }
    if (!file_exists($ctaPath)) {
        echo 'CTA mapping file not found: ' . $ctaPath . "<br>";
    }
    if (file_exists($mappingPath) && file_exists($ctaPath)) {
        $mappingJson = file_get_contents($mappingPath);
        $ctaJson = file_get_contents($ctaPath);
        if ($mappingJson === false || $mappingJson === '') {
            echo 'Failed to read or empty mapping JSON: ' . $mappingPath . "<br>";
        }
        if ($ctaJson === false || $ctaJson === '') {
            echo 'Failed to read or empty CTA JSON: ' . $ctaPath . "<br>";
        }
        if ($mappingJson !== false && $mappingJson !== '' && $ctaJson !== false && $ctaJson !== '') {
            $mappingData = json_decode($mappingJson, true);
            $mappingError = json_last_error();
            if ($mappingError !== JSON_ERROR_NONE) {
                echo 'Mapping JSON decode error: ' . json_last_error_msg() . "<br>";
            }
            $ctaData = json_decode($ctaJson, true);
            $ctaError = json_last_error();
            if ($ctaError !== JSON_ERROR_NONE) {
                echo 'CTA JSON decode error: ' . json_last_error_msg() . "<br>";
            }
            if (is_array($mappingData) && is_array($ctaData)) {
                $ctaByUrl = [];
                foreach ($ctaData as $ctaRow) {
                    if (!is_array($ctaRow)) {
                        continue;
                    }
                    if (!isset($ctaRow['url'])) {
                        continue;
                    }
                    $url = trim((string)$ctaRow['url']);
                    if ($url === '') {
                        continue;
                    }
                    $ctaByUrl[$url] = $ctaRow;
                }
                $foundCreator = false;
                foreach ($mappingData as $entry) {
                    if (!is_array($entry)) {
                        continue;
                    }
                    if (!isset($entry['creator']) || !isset($entry['relevant_urls']) || !is_array($entry['relevant_urls'])) {
                        continue;
                    }
                    $creatorName = trim((string)$entry['creator']);
                    if ($creatorName === '' || strcasecmp($creatorName, $segmentCreatorTrimmed) !== 0) {
                        continue;
                    }
                    $foundCreator = true;
                    foreach ($entry['relevant_urls'] as $url) {
                        $urlStr = trim((string)$url);
                        if ($urlStr === '') {
                            continue;
                        }
                        $ctaRow = isset($ctaByUrl[$urlStr]) && is_array($ctaByUrl[$urlStr]) ? $ctaByUrl[$urlStr] : [];
                        $title = '';
                        if (isset($ctaRow['tool_name']) && $ctaRow['tool_name'] !== '') {
                            $title = (string)$ctaRow['tool_name'];
                        } elseif (isset($ctaRow['resource_name']) && $ctaRow['resource_name'] !== '') {
                            $title = (string)$ctaRow['resource_name'];
                        }
                        if ($title === '') {
                            $title = 'Brand AI Tool';
                        }
                        $headline = isset($ctaRow['hero_headline']) ? (string)$ctaRow['hero_headline'] : '';
                        $valueProp = isset($ctaRow['value_prop']) ? (string)$ctaRow['value_prop'] : '';
                        $relevantTools[] = [
                            'url' => $urlStr,
                            'title' => $title,
                            'headline' => $headline,
                            'value_prop' => $valueProp
                        ];
                    }
                    break;
                }
                if (!$foundCreator) {
                    // echo 'No mapping entry found for creator: ' . $segmentCreatorTrimmed . "<br>";
                }
                if ($foundCreator && empty($relevantTools)) {
                    // echo 'Mapping entry found for creator but produced no tools: ' . $segmentCreatorTrimmed . "<br>";
                }
            } else {
                if (!is_array($mappingData)) {
                    // echo 'Mapping JSON structure is not an array.' . "<br>";
                }
                if (!is_array($ctaData)) {
                    // echo 'CTA JSON structure is not an array.' . "<br>";
                }
            }
        }
    }
}

if (empty($relevantTools) && !empty($segment) && isset($segment['tools']) && is_array($segment['tools'])) {
    $ctaPathFallback = __DIR__ . '/../cta-url-tool.json';
    $ctaByUrlFallback = [];
    if (file_exists($ctaPathFallback)) {
        $ctaJsonFallback = file_get_contents($ctaPathFallback);
        if ($ctaJsonFallback !== false && $ctaJsonFallback !== '') {
            $ctaDataFallback = json_decode($ctaJsonFallback, true);
            if (is_array($ctaDataFallback)) {
                foreach ($ctaDataFallback as $row) {
                    if (!is_array($row) || !isset($row['url'])) {
                        continue;
                    }
                    $u = trim((string)$row['url']);
                    if ($u === '') {
                        continue;
                    }
                    $ctaByUrlFallback[$u] = $row;
                }
            }
        }
    }
    foreach ($segment['tools'] as $toolRow) {
        if (!is_array($toolRow) || !isset($toolRow['url'])) {
            continue;
        }
        $urlStr = trim((string)$toolRow['url']);
        if ($urlStr === '') {
            continue;
        }
        $ctaRow = isset($ctaByUrlFallback[$urlStr]) && is_array($ctaByUrlFallback[$urlStr]) ? $ctaByUrlFallback[$urlStr] : [];
        $title = '';
        if (isset($toolRow['title']) && $toolRow['title'] !== '') {
            $title = (string)$toolRow['title'];
        } elseif (isset($ctaRow['tool_name']) && $ctaRow['tool_name'] !== '') {
            $title = (string)$ctaRow['tool_name'];
        } elseif (isset($ctaRow['resource_name']) && $ctaRow['resource_name'] !== '') {
            $title = (string)$ctaRow['resource_name'];
        }
        if ($title === '') {
            $title = 'Brand AI Tool';
        }
        $headline = isset($ctaRow['hero_headline']) ? (string)$ctaRow['hero_headline'] : '';
        $valueProp = isset($ctaRow['value_prop']) ? (string)$ctaRow['value_prop'] : '';
        $relevantTools[] = [
            'url' => $urlStr,
            'title' => $title,
            'headline' => $headline,
            'value_prop' => $valueProp
        ];
    }
}

$seo          = isset($segment['seo'])            && is_array($segment['seo'])            ? $segment['seo']            : [];
$og           = isset($seo['open_graph'])          && is_array($seo['open_graph'])          ? $seo['open_graph']          : [];
$copy         = isset($segment['copy'])            && is_array($segment['copy'])            ? $segment['copy']            : [];
$hero         = isset($copy['hero'])               && is_array($copy['hero'])               ? $copy['hero']               : [];
$painPromise  = isset($copy['pain_promise'])       && is_array($copy['pain_promise'])       ? $copy['pain_promise']       : [];
$promiseBlock = isset($copy['promise_block'])      && is_array($copy['promise_block'])      ? $copy['promise_block']      : [];
$faq          = isset($segment['faq'])             && is_array($segment['faq'])             ? $segment['faq']             : [];

$metaTitle       = isset($seo['meta_title'])       ? $seo['meta_title']       : ('Brand AI for ' . ($segment['segment'] ?? 'Industry'));
$metaDescription = isset($seo['meta_description']) ? $seo['meta_description'] : ($segment['intent_summary'] ?? '');
$keywords        = isset($seo['keywords']) && is_array($seo['keywords']) ? implode(', ', $seo['keywords']) : '';

$primarySlug = '';
if (isset($segment['url_slugs']) && is_array($segment['url_slugs']) && count($segment['url_slugs']) > 0) {
    $primarySlug = ltrim((string)$segment['url_slugs'][0], '/');
}

$seoPath = $primarySlug !== '' ? ('/brand-ai-' . $primarySlug) : '';

$canonicalBase = 'https://www.thebrand.ai';
$canonical     = $seoPath !== '' ? ($canonicalBase . $seoPath) : (isset($og['og:url']) ? $og['og:url'] : null);

$ogTitle         = isset($og['og:title'])          ? $og['og:title']          : $metaTitle;
$ogDescription   = isset($og['og:description'])    ? $og['og:description']    : $metaDescription;
$ogImage         = isset($og['og:image'])          ? $og['og:image']          : 'https://www.thebrand.ai/i/uploads/logo/logo_62a4de26e93f0.png';
$ogImageWidth    = isset($og['og:image:width'])    ? $og['og:image:width']    : '1200';
$ogImageHeight   = isset($og['og:image:height'])   ? $og['og:image:height']   : '630';
$ogImageAlt      = isset($og['og:image:alt'])      ? $og['og:image:alt']      : $metaTitle;
$ogUrl           = $seoPath !== '' ? ($canonicalBase . $seoPath) : (isset($og['og:url']) ? $og['og:url'] : 'https://www.thebrand.ai/');
$ogSiteName      = isset($og['og:site_name'])      ? $og['og:site_name']      : 'Brand AI';
$twitterCard     = isset($og['twitter:card'])      ? $og['twitter:card']      : 'summary_large_image';
$twitterTitle    = isset($og['twitter:title'])     ? $og['twitter:title']     : $metaTitle;
$twitterDesc     = isset($og['twitter:description']) ? $og['twitter:description'] : $metaDescription;
$twitterImage    = isset($og['twitter:image'])     ? $og['twitter:image']     : $ogImage;
$twitterSite     = isset($og['twitter:site'])      ? $og['twitter:site']      : '@thebrandhq';

$faqJson = [
    '@context'   => 'https://schema.org',
    '@type'      => 'FAQPage',
    'mainEntity' => isset($faq['mainEntity']) && is_array($faq['mainEntity']) ? $faq['mainEntity'] : []
];

$softwareJson = [
    '@context'            => 'https://schema.org',
    '@type'               => 'SoftwareApplication',
    'name'                => 'Brand AI',
    'url'                 => 'https://www.thebrand.ai/',
    'applicationCategory' => 'DesignApplication',
    'operatingSystem'     => 'Web',
    'description'         => 'Brand AI is an intelligent platform to design, analyze, and grow your brand with AI-powered tools, templates, and insights.',
    'image'               => 'https://www.thebrand.ai/i/uploads/logo/logo_62a4de26e93f0.png',
    'publisher'           => [
        '@type' => 'Organization',
        'name'  => 'Brand AI',
        'url'   => 'https://www.thebrand.ai/'
    ],
    'offers' => [
        '@type'        => 'Offer',
        'price'        => '0',
        'priceCurrency'=> 'USD',
        'availability' => 'https://schema.org/InStock',
        'url'          => 'https://www.thebrand.ai/brandpay/choose'
    ]
];

$orgJson = [
    '@context' => 'https://schema.org',
    '@type'    => 'Organization',
    'name'     => 'Brand AI',
    'url'      => 'https://www.thebrand.ai/',
    'logo'     => 'https://www.thebrand.ai/i/uploads/logo/logo_62a4de26e93f0.png',
    'sameAs'   => [
        'https://facebook.com/TheBrandApp',
        'https://twitter.com/thebrandhq',
        'https://www.instagram.com/thebrandapp',
        'https://www.linkedin.com/company/the-brand-app'
    ]
];

$ctaJoinUrl = 'https://www.thebrand.ai/brandcreator/dashboard/auth-join.php?url=' . urlencode($primarySlug !== '' ? $primarySlug : 'home');

$interestTags = [];
$interests = isset($segment['interests']) ? $segment['interests'] : '';
if ($interests !== '') {
    foreach (explode(',', $interests) as $part) {
        $trimmed = trim($part);
        if ($trimmed !== '') {
            $interestTags[] = $trimmed;
        }
    }
}

$teams_sites_liked = [];
$teams_sites_cards = [];
$teams_sites_reason = '';
$teams_sites_headline = 'Curated websites for you';
$teams_sites_subheadline = 'If you don’t have a website yet, you’re leaving trust and opportunities on the table. Launch a clean, mobile-first site that matches your brand and helps people book, buy, or contact you.';
$teams_sites_cta = 'Create a website';
$teams_sites_cta_href = 'https://www.thebrand.ai/sites/welcome.php';

$teams_creator_raw = $segmentCreatorTrimmed;
$teams_type_raw = isset($segment['segment']) ? (string)$segment['segment'] : '';
$teams_slug_raw = $segmentSlugKey !== null ? (string)$segmentSlugKey : '';

$teams_norm = function($s) {
    $s = strtolower(trim((string)$s));
    $s = preg_replace('/\s+/', ' ', $s);
    return $s;
};

$teams_sites_liked_path = __DIR__ . '/../wowX/json/data/selected/brand_sites_creators_liked.json';
$teams_sites_all_path = __DIR__ . '/../wowX/json/data/selected/Brand Sites for Every Industry.json';

if (is_file($teams_sites_liked_path) && is_readable($teams_sites_liked_path)) {
    $raw = @file_get_contents($teams_sites_liked_path);
    $rows = json_decode((string)$raw, true);
    if (is_array($rows)) {
        $want1 = $teams_norm($teams_creator_raw);
        $want2 = $teams_norm($teams_type_raw);
        $wantSlug = $teams_slug_raw !== '' ? $teams_norm(str_replace(['-', '_'], ' ', $teams_slug_raw)) : '';
        $selected = null;
        foreach ($rows as $row) {
            if (!is_array($row)) {
                continue;
            }
            $creator = isset($row['creator']) ? (string)$row['creator'] : '';
            $n = $teams_norm($creator);
            if (
                ($want1 !== '' && $n === $want1) ||
                ($wantSlug !== '' && $n === $wantSlug) ||
                ($want1 === '' && $want2 !== '' && $n === $want2)
            ) {
                $selected = $row;
                break;
            }
        }
        if ($selected === null && isset($rows[0]) && is_array($rows[0])) {
            $selected = $rows[0];
        }
        if (is_array($selected)) {
            $teams_sites_liked = (isset($selected['liked_categories']) && is_array($selected['liked_categories'])) ? $selected['liked_categories'] : [];
            $teams_sites_reason = isset($selected['reason']) ? (string)$selected['reason'] : '';
            $sitesHero = (isset($selected['hero']) && is_array($selected['hero'])) ? $selected['hero'] : [];
            if (isset($sitesHero['headline']) && (string)$sitesHero['headline'] !== '') {
                $teams_sites_headline = (string)$sitesHero['headline'];
            }
            if (isset($sitesHero['subheadline']) && (string)$sitesHero['subheadline'] !== '') {
                $teams_sites_subheadline = (string)$sitesHero['subheadline'];
            }
            if (isset($sitesHero['cta']) && (string)$sitesHero['cta'] !== '') {
                $teams_sites_cta = (string)$sitesHero['cta'];
            }
        }
    }
}

$teams_sites_all = [];
if (is_file($teams_sites_all_path) && is_readable($teams_sites_all_path)) {
    $raw = @file_get_contents($teams_sites_all_path);
    $rows = json_decode((string)$raw, true);
    if (is_array($rows)) {
        $teams_sites_all = $rows;
    }
}

$teams_sites_by_title = [];
foreach ($teams_sites_all as $row) {
    if (!is_array($row)) {
        continue;
    }
    $title = isset($row['Title']) ? trim((string)$row['Title']) : '';
    $img = isset($row['Image']) ? trim((string)$row['Image']) : '';
    if ($title === '' || $img === '') {
        continue;
    }
    $teams_sites_by_title[$teams_norm($title)] = ['title' => $title, 'image' => $img];
}

$teams_sites_find = function($cat) use ($teams_norm, $teams_sites_by_title, $teams_sites_all) {
    $cat = trim((string)$cat);
    if ($cat === '') {
        return null;
    }
    $k = $teams_norm($cat);
    if (isset($teams_sites_by_title[$k])) {
        return $teams_sites_by_title[$k];
    }
    foreach ($teams_sites_all as $row) {
        if (!is_array($row)) {
            continue;
        }
        $title = isset($row['Title']) ? trim((string)$row['Title']) : '';
        $img = isset($row['Image']) ? trim((string)$row['Image']) : '';
        if ($title === '' || $img === '') {
            continue;
        }
        $t = strtolower($title);
        $c = strtolower($cat);
        if ($c !== '' && ($t === $c || strpos($t, $c) !== false || strpos($c, $t) !== false)) {
            return ['title' => $title, 'image' => $img];
        }
    }
    return null;
};

$teams_sites_seen = [];
foreach ($teams_sites_liked as $cat) {
    $found = $teams_sites_find($cat);
    if (!$found || !is_array($found)) {
        continue;
    }
    $key = $teams_norm($found['title']);
    if (isset($teams_sites_seen[$key])) {
        continue;
    }
    $teams_sites_seen[$key] = true;
    $teams_sites_cards[] = $found;
    if (count($teams_sites_cards) >= 6) {
        break;
    }
}
if (!count($teams_sites_cards)) {
    foreach ($teams_sites_all as $row) {
        if (!is_array($row)) {
            continue;
        }
        $title = isset($row['Title']) ? trim((string)$row['Title']) : '';
        $img = isset($row['Image']) ? trim((string)$row['Image']) : '';
        if ($title === '' || $img === '') {
            continue;
        }
        $teams_sites_cards[] = ['title' => $title, 'image' => $img];
        if (count($teams_sites_cards) >= 6) {
            break;
        }
    }
}
?><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo h($metaTitle); ?></title>
    <link rel="icon" type="image/svg+xml" href="/favicon.svg">
    <meta name="description" content="<?php echo h($metaDescription); ?>">
    <?php if ($keywords !== '') { ?>
    <meta name="keywords" content="<?php echo h($keywords); ?>">
    <?php } ?>
    <?php if ($canonical) { ?>
    <link rel="canonical" href="<?php echo h($canonical); ?>">
    <?php } ?>
    <meta property="og:type"        content="website">
    <meta property="og:url"         content="<?php echo h($ogUrl); ?>">
    <meta property="og:title"       content="<?php echo h($ogTitle); ?>">
    <meta property="og:description" content="<?php echo h($ogDescription); ?>">
    <meta property="og:image"       content="<?php echo h($ogImage); ?>">
    <meta property="og:image:width" content="<?php echo h($ogImageWidth); ?>">
    <meta property="og:image:height"content="<?php echo h($ogImageHeight); ?>">
    <meta property="og:image:alt"   content="<?php echo h($ogImageAlt); ?>">
    <meta property="og:site_name"   content="<?php echo h($ogSiteName); ?>">
    <meta name="twitter:card"       content="<?php echo h($twitterCard); ?>">
    <meta name="twitter:title"      content="<?php echo h($twitterTitle); ?>">
    <meta name="twitter:description"content="<?php echo h($twitterDesc); ?>">
    <meta name="twitter:image"      content="<?php echo h($twitterImage); ?>">
    <meta name="twitter:site"       content="<?php echo h($twitterSite); ?>">

    <script async src="https://www.googletagmanager.com/gtag/js?id=G-ENHHZKM53C"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-ENHHZKM53C');
    </script>

    <script type="application/ld+json">
<?php echo json_encode($faqJson,      JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); ?>
    </script>
    <script type="application/ld+json">
<?php echo json_encode($softwareJson, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); ?>
    </script>
    <script type="application/ld+json">
<?php echo json_encode($orgJson,      JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); ?>
    </script>
    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
    <link href="/index_files/css2.css" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: { sans: ['Inter', 'sans-serif'] },
                    colors: {
                        'brand-cyan':     '#03bef3',
                        'brand-midnight': '#0b0f29',
                        'brand-magenta':  '#ff00a8'
                    }
                }
            }
        };
    </script>
    <style>
        html { scroll-behavior: smooth; }
        body { margin: 0; font-family: 'Inter', sans-serif; }
        #curated-websites .curated-sites-card{padding:16px;overflow:hidden}
        #curated-websites .curated-sites-head{display:flex;align-items:flex-end;justify-content:space-between;gap:14px;flex-wrap:wrap;margin-bottom:14px}
        #curated-websites .curated-sites-head-copy{min-width:260px;flex:1}
        #curated-websites .curated-sites-eyebrow{display:inline-flex;align-items:center;padding:6px 10px;border-radius:999px;background:rgba(124,58,237,.10);border:1px solid rgba(124,58,237,.18);font-weight:900;color:rgba(15,23,42,.72);font-size:.78rem;line-height:1.2;max-width:80ch;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
        #curated-websites .curated-sites-title{margin-top:10px;font-weight:950;letter-spacing:-.03em;color:rgba(15,23,42,.92);font-size:1.2rem;line-height:1.1}
        #curated-websites .curated-sites-subtitle{margin-top:6px;font-weight:750;color:rgba(15,23,42,.66);font-size:.92rem;line-height:1.45;max-width:88ch}
        #curated-websites .curated-sites-cta{display:inline-flex;align-items:center;justify-content:center;gap:8px;padding:10px 14px;border-radius:12px;font-weight:950;letter-spacing:.01em;text-decoration:none;color:#fff;background:linear-gradient(135deg, #7c3aed, #3b82f6, #06b6d4);box-shadow:0 18px 48px rgba(10, 20, 30, .16);transition:transform .16s ease, box-shadow .16s ease}
        #curated-websites .curated-sites-cta:hover{transform:translateY(-1px);box-shadow:0 26px 70px rgba(10, 20, 30, .16)}
        #curated-websites .curated-sites-cta:focus-visible{outline:0;box-shadow:0 0 0 3px rgba(92, 144, 255, .35), 0 18px 50px rgba(10, 20, 30, .14)}
        #curated-websites .curated-sites-grid{display:grid;grid-template-columns:repeat(5, minmax(0, 1fr));gap:12px}
        @media (max-width: 1400px){#curated-websites .curated-sites-grid{grid-template-columns:repeat(4, minmax(0, 1fr))}}
        @media (max-width: 980px){#curated-websites .curated-sites-grid{grid-template-columns:repeat(2, minmax(0, 1fr))}}
        @media (max-width: 520px){#curated-websites .curated-sites-grid{grid-template-columns:1fr}}
        #curated-websites .curated-site-card{display:block;text-decoration:none;border-radius:18px;overflow:hidden;background:#fff;border:1px solid rgba(15, 23, 42, .06);box-shadow:0 16px 44px rgba(10, 20, 30, .08);transform:translateZ(0);transition:transform .18s ease, box-shadow .18s ease}
        #curated-websites .curated-site-card:hover{transform:translateY(-3px);box-shadow:0 26px 70px rgba(10, 20, 30, .14)}
        #curated-websites .curated-site-card:focus-visible{outline:0;box-shadow:0 0 0 3px rgba(92, 144, 255, .35), 0 20px 55px rgba(10, 20, 30, .12)}
        #curated-websites .curated-site-media{position:relative;width:100%;aspect-ratio:16/9;background:linear-gradient(135deg, rgba(40, 44, 58, .14), rgba(78, 95, 140, .08));overflow:hidden}
        #curated-websites .curated-site-img{width:100%;height:100%;object-fit:cover;display:block;filter:saturate(1.06) contrast(1.02)}
        #curated-websites .curated-site-media::after{content:"";position:absolute;inset:0;background:linear-gradient(180deg, rgba(12,18,32,0) 35%, rgba(12,18,32,.72) 100%);pointer-events:none}
        #curated-websites .curated-site-badge{position:absolute;left:10px;right:10px;bottom:10px;z-index:2;font-weight:950;letter-spacing:-.02em;color:#fff;font-size:.92rem;line-height:1.1;text-shadow:0 10px 30px rgba(0,0,0,.35);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
        #curated-websites .curated-site-body{padding:10px 12px 12px 12px}
        #curated-websites .curated-site-action{font-weight:900;color:rgba(56,58,63,.86);font-size:.82rem;letter-spacing:.01em}
    </style>
</head>
<body class="bg-white text-gray-800">
<noscript>
  <div style="padding:12px;text-align:center;background:#fff3cd;color:#664d03;font-family:Inter,sans-serif;">
    JavaScript is required to use Brand AI. Please enable JavaScript.
  </div>
</noscript>

<div class="bg-white text-gray-800 font-sans min-h-screen flex flex-col">

    <!-- ===== HEADER ===== -->
    <header class="bg-white/80 backdrop-blur-sm sticky top-0 z-50 shadow-sm">
        <div class="container mx-auto px-6 py-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-8">
                    <a href="https://www.thebrand.ai" aria-label="Brand AI Homepage">
                        <img src="https://www.thebrand.ai/i/uploads/logo/logo_62a4de26e93f0.png" alt="Brand AI Logo" width="110" height="30">
                    </a>
                    <nav class="hidden md:flex items-center space-x-6">
                        <a href="https://www.thebrand.ai/brandcreator/index" class="text-gray-600 hover:text-brand-cyan font-medium transition-colors">Brand Creator</a>
                        <a href="https://www.thebrand.ai/i"                  class="text-gray-600 hover:text-brand-cyan font-medium transition-colors">Templates</a>
                        <a href="https://www.thebrand.ai/insights/"          class="text-gray-600 hover:text-brand-cyan font-medium transition-colors">Insights</a>
                        <a href="https://www.thebrand.ai/blogs"              class="text-gray-600 hover:text-brand-cyan font-medium transition-colors">Blogs</a>
                        <a href="https://www.thebrand.ai/wowX/tools"         class="text-gray-600 hover:text-brand-cyan font-medium transition-colors">Resources</a>
                    </nav>
                </div>
                <div class="hidden md:flex items-center space-x-4">
                    <a href="https://bit.ly/2LpQJmO" target="_blank" rel="noopener noreferrer"
                       class="font-semibold text-gray-600 hover:text-brand-cyan transition-colors border border-gray-300 rounded-lg py-2 px-4 text-sm hover:border-brand-cyan">
                        Download App
                    </a>
                    <a href="https://www.thebrand.ai/connect/index.php" data-auth="login"
                       class="font-bold text-gray-600 hover:text-brand-cyan transition-colors">Log in</a>
                    <a href="https://www.thebrand.ai/connect/index.php?action=register" data-auth="signup"
                       class="bg-brand-cyan text-white font-bold py-2 px-4 rounded-lg hover:opacity-90 transition-opacity">
                        Sign up for free
                    </a>
                </div>
                <div class="md:hidden">
                    <button id="mobileMenuToggle" class="text-gray-800 focus:outline-none" aria-label="Toggle menu">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path id="mobileMenuIcon" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"/>
                        </svg>
                    </button>
                </div>
            </div>
            <!-- Mobile nav -->
            <div id="mobileMenu" class="md:hidden hidden mt-4">
                <nav class="flex flex-col space-y-4">
                    <a href="https://www.thebrand.ai/brandcreator/index" class="text-gray-600 hover:text-brand-cyan font-medium transition-colors">Brand Creator</a>
                    <a href="https://www.thebrand.ai/i"                  class="text-gray-600 hover:text-brand-cyan font-medium transition-colors">Templates</a>
                    <a href="https://www.thebrand.ai/insights/"          class="text-gray-600 hover:text-brand-cyan font-medium transition-colors">Insights</a>
                    <a href="https://www.thebrand.ai/blogs"              class="text-gray-600 hover:text-brand-cyan font-medium transition-colors">Blogs</a>
                    <a href="https://www.thebrand.ai/wowX/tools"         class="text-gray-600 hover:text-brand-cyan font-medium transition-colors">Resources</a>
                    <div class="flex flex-col space-y-3 pt-4 border-t border-gray-200">
                        <a href="https://bit.ly/2LpQJmO" target="_blank" rel="noopener noreferrer"
                           class="w-full text-center border border-gray-300 text-gray-600 font-bold py-2 px-4 rounded-lg hover:border-brand-cyan hover:text-brand-cyan transition-colors">
                            Download App
                        </a>
                        <a href="https://www.thebrand.ai/connect/index.php" data-auth="login"
                           class="w-full text-center font-bold text-gray-600 hover:text-brand-cyan transition-colors">Log in</a>
                        <a href="https://www.thebrand.ai/connect/index.php?action=register" data-auth="signup"
                           class="w-full text-center bg-brand-cyan text-white font-bold py-2 px-4 rounded-lg hover:opacity-90 transition-opacity">
                            Sign up for free
                        </a>
                    </div>
                </nav>
            </div>
        </div>
    </header>

    <main class="flex-1">

        <!-- ===== HERO ===== -->
        <section class="relative text-white overflow-hidden bg-brand-midnight">
            <div aria-hidden="true" class="absolute inset-0 z-0 opacity-50">
                <div class="absolute top-[-30%] left-[-30%] w-4/5 h-4/5 rounded-full bg-gradient-to-br from-brand-cyan to-transparent filter blur-3xl"></div>
                <div class="absolute bottom-[-30%] right-[-30%] w-4/5 h-4/5 rounded-full bg-gradient-to-tl from-brand-cyan to-transparent filter blur-3xl"></div>
            </div>
            <div class="relative z-10 flex flex-col items-center justify-center min-h-[70vh] md:min-h-[80vh] px-4 text-center">
                <h1 class="text-4xl md:text-6xl lg:text-7xl font-extrabold mb-4 tracking-tight">
                    <span class="block"><?php echo h($hero['headline'] ?? ($segment['segment'] ?? 'Brand AI Industry')); ?></span>
                </h1>
                <?php if (!empty($hero['subheadline'])) { ?>
                <p class="text-md md:text-lg max-w-2xl mb-3 opacity-90">
                    <?php echo h($hero['subheadline']); ?>
                </p>
                <?php } ?>
                <?php if (!empty($hero['body'])) { ?>
                <p class="text-lg md:text-2xl max-w-3xl mb-8">
                    <?php echo h($hero['body']); ?>
                </p>
                <?php } ?>
                <div class="flex flex-wrap justify-center gap-4">
                    <a href="<?php echo h($ctaJoinUrl); ?>"
                       class="bg-white text-brand-midnight font-bold py-3 px-8 rounded-lg text-lg hover:bg-gray-200 transition-all duration-300 transform hover:scale-105">
                        <?php echo h($hero['cta_primary'] ?? 'Build My Personal Brand Free →'); ?>
                    </a>
                    <a href="https://www.thebrand.ai/i/"
                       class="bg-white/10 backdrop-blur-sm text-white font-bold py-3 px-8 rounded-lg text-lg hover:bg-white/20 transition-all duration-300 transform hover:scale-105">
                        Browse Templates
                    </a>
                </div>
                <?php if (!empty($interestTags)) { ?>
                <div class="mt-8 flex flex-wrap justify-center gap-3 text-xs md:text-sm text-gray-200">
                    <?php foreach ($interestTags as $tag) { ?>
                    <span class="inline-flex items-center px-3 py-1 rounded-full bg-white/10 border border-white/20">
                        <?php echo h($tag); ?>
                    </span>
                    <?php } ?>
                </div>
                <?php } ?>
            </div>
        </section>

        <!-- ===== PAIN / PROMISE ===== -->
        <section class="py-20 md:py-28 bg-white">
            <div class="container mx-auto px-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-10 items-stretch">
                    <!-- Pain -->
                    <div class="bg-gray-50 border border-gray-200 rounded-2xl p-8 shadow-sm">
                        <p class="text-sm font-semibold uppercase tracking-tight text-brand-cyan mb-2">The Pain</p>
                        <h2 class="text-2xl md:text-3xl font-bold mb-4 text-gray-800">
                            <?php echo h($segment['intent_summary'] ?? 'You need a brand that matches your work.'); ?>
                        </h2>
                        <?php if (!empty($painPromise['pain'])) { ?>
                        <p class="text-gray-700 text-base md:text-lg">
                            <?php echo h($painPromise['pain']); ?>
                        </p>
                        <?php } ?>
                    </div>
                    <!-- Promise -->
                    <div class="bg-brand-midnight text-white rounded-2xl p-8 shadow-md relative overflow-hidden">
                        <div aria-hidden="true" class="absolute inset-0 opacity-60">
                            <div class="absolute top-[-40%] right-[-30%] w-3/5 h-3/5 rounded-full bg-gradient-to-br from-brand-cyan to-transparent blur-3xl"></div>
                        </div>
                        <div class="relative z-10">
                            <p class="text-sm font-semibold uppercase tracking-tight text-brand-cyan mb-2">The Promise</p>
                            <h2 class="text-2xl md:text-3xl font-bold mb-4">
                                Look premium on every channel in minutes, not months.
                            </h2>
                            <?php if (!empty($painPromise['promise'])) { ?>
                            <p class="text-gray-100 text-base md:text-lg mb-6">
                                <?php echo h($painPromise['promise']); ?>
                            </p>
                            <?php } ?>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- ===== PROMISE BLOCK / FEATURES ===== -->
        <section class="py-20 md:py-28 bg-white">
            <div class="container mx-auto px-6">
                <div class="text-center mb-12">
                    <p class="text-sm font-semibold uppercase tracking-tight text-brand-cyan mb-2">One Brand System</p>
                    <h2 class="text-3xl md:text-5xl font-bold mb-4">
                        <?php echo h($promiseBlock['headline'] ?? 'One Brand System. Infinite On-Brand Outputs.'); ?>
                    </h2>
                    <?php if (!empty($promiseBlock['body'])) { ?>
                    <p class="text-lg md:text-xl text-gray-600 max-w-3xl mx-auto">
                        <?php echo h($promiseBlock['body']); ?>
                    </p>
                    <?php } ?>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                    <?php if (!empty($promiseBlock['features']) && is_array($promiseBlock['features'])) { ?>
                        <?php foreach ($promiseBlock['features'] as $feature) { ?>
                        <div class="bg-gray-50 border border-gray-200 rounded-2xl p-8 shadow-sm hover:shadow-md hover:-translate-y-1 transition-all duration-300">
                            <h3 class="text-xl font-bold mb-2 text-gray-800"><?php echo h($feature['name'] ?? ''); ?></h3>
                            <p class="text-gray-600"><?php echo h($feature['description'] ?? ''); ?></p>
                        </div>
                        <?php } ?>
                    <?php } ?>
                </div>
            </div>
        </section>

        <section class="py-20 md:py-28 bg-white">
            <div class="container mx-auto px-6">
                <div class="text-center mb-12">
                    <p class="text-sm font-semibold uppercase tracking-tight text-brand-cyan mb-2">Curated for this segment</p>
                    <h2 class="text-3xl md:text-5xl font-bold mb-4">
                        Curated templates for <?php echo h($segment['segment'] ?? 'this segment'); ?>.
                    </h2>
                    <div class="max-w-3xl mx-auto">
                        <p class="text-lg md:text-xl text-gray-600">
                            Templates selected to match creators like <?php echo h($segmentCreator !== '' ? $segmentCreator : ($segment['segment'] ?? 'you')); ?>.
                        </p>
                        <?php if (!empty($interestTags)) { ?>
                        <div class="mt-6 flex flex-wrap justify-center gap-3 text-xs md:text-sm">
                            <button type="button"
                                    class="bd-curated-filter inline-flex items-center px-4 py-2 rounded-full border border-brand-cyan/60 bg-brand-cyan text-white font-medium tracking-tight hover:bg-brand-cyan/90 hover:border-brand-cyan transition-colors"
                                    data-interest="">
                                All
                            </button>
                            <?php foreach ($interestTags as $tag) { ?>
                            <button type="button"
                                    class="bd-curated-filter inline-flex items-center px-4 py-2 rounded-full border border-gray-300 bg-white text-gray-800 font-medium tracking-tight hover:border-brand-cyan hover:text-brand-cyan transition-colors"
                                    data-interest="<?php echo h($tag); ?>">
                                <?php echo h($tag); ?>
                            </button>
                            <?php } ?>
                        </div>
                        <?php } ?>
                    </div>
                </div>
                <?php if (!empty($curatedTemplates)) { ?>
                    <div class="bd-curated-grid grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
                        <?php foreach ($curatedTemplates as $tpl) { ?>
                            <div class="bd-curated-card bg-gray-50 border border-gray-200 rounded-2xl overflow-hidden shadow-sm hover:shadow-md hover:-translate-y-1 transition-all duration-300"
                                 data-keywords="<?php echo h($tpl['post_keywords'] ?? ''); ?>"
                                 data-template-id="<?php echo isset($tpl['post_id']) ? (int)$tpl['post_id'] : 0; ?>">
                                <?php if (!empty($tpl['post_poster'])) { ?>
                                    <div class="bg-gray-100 overflow-hidden" style="aspect-ratio: 4 / 5;">
                                        <img src="https://www.thebrand.ai/taswira.php?width=560&height=560&quality=70&cropratio=1:1&image=/v/uploads/gallery/<?php echo h($tpl['post_poster']); ?>" alt="<?php echo h($tpl['post_title'] ?? 'Brand AI template'); ?>" class="w-full h-full object-cover">
                                    </div>
                                <?php } ?>
                                <div class="p-4">
                                    <h3 class="bd-curated-title text-sm font-semibold text-gray-800 truncate">
                                        <?php echo h($tpl['post_title'] ?? 'Brand AI Template'); ?>
                                    </h3>
                                </div>
                            </div>
                        <?php } ?>
                    </div>
                    <div id="bd-curated-pagination" class="mt-8 flex items-center justify-between text-sm text-gray-600" data-per-page="12">
                        <button type="button" data-page="prev" class="px-3 py-2 rounded-full border border-gray-300 bg-white text-gray-700 hover:border-brand-cyan hover:text-brand-cyan transition-colors">
                            Previous
                        </button>
                        <div class="px-3 py-2">
                            <span id="bd-curated-page-info"></span>
                        </div>
                        <button type="button" data-page="next" class="px-3 py-2 rounded-full border border-gray-300 bg-white text-gray-700 hover:border-brand-cyan hover:text-brand-cyan transition-colors">
                            Next
                        </button>
                    </div>
                <?php } else { ?>
                    <div class="text-center text-gray-500">
                        No curated templates available yet for this segment.
                    </div>
                <?php } ?>
                <?php if (!empty($relevantTools)) { ?>
                    <div class="mt-16">
                        <div class="text-center mb-10">
                            <p class="text-sm font-semibold uppercase tracking-tight text-brand-cyan mb-2">
                                Tools tuned for <?php echo h($segmentCreatorTrimmed !== '' ? $segmentCreatorTrimmed : ($segment['segment'] ?? 'this segment')); ?>
                            </p>
                            <h3 class="text-2xl md:text-3xl font-bold mb-3">
                                Recommended Brand AI tools for <?php echo h($segment['segment'] ?? 'this segment'); ?>
                            </h3>
                            <p class="text-base md:text-lg text-gray-600 max-w-3xl mx-auto">
                                Handpicked tools, calculators, and playbooks that support how creators like you grow, convert, and retain customers.
                            </p>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                            <?php foreach ($relevantTools as $tool) { ?>
                                <a href="<?php echo h($tool['url'] ?? '#'); ?>"
                                   class="group bg-gradient-to-br from-brand-cyan to-transparent rounded-3xl p-0.5 shadow-lg hover:shadow-2xl hover:-translate-y-2 transition-all duration-300">
                                    <div class="bg-white rounded-3xl p-6 h-full flex flex-col justify-between">
                                        <div>
                                            <p class="text-xs font-semibold uppercase tracking-[0.18em] text-brand-cyan mb-3">
                                                Recommended tool
                                            </p>
                                            <h4 class="text-lg md:text-xl font-bold mb-3 text-gray-900 group-hover:text-brand-midnight transition-colors">
                                                <?php echo h($tool['title'] ?? 'Brand AI Tool'); ?>
                                            </h4>
                                            <?php if (!empty($tool['value_prop'])) { ?>
                                                <p class="text-sm text-gray-600">
                                                    <?php echo h($tool['value_prop']); ?>
                                                </p>
                                            <?php } elseif (!empty($tool['headline'])) { ?>
                                                <p class="text-sm text-gray-600">
                                                    <?php echo h($tool['headline']); ?>
                                                </p>
                                            <?php } ?>
                                        </div>
                                        <div class="mt-4 inline-flex items-center text-sm font-semibold text-brand-cyan">
                                            Explore this tool
                                            <svg class="w-4 h-4 ml-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                                            </svg>
                                        </div>
                                    </div>
                                </a>
                            <?php } ?>
                        </div>
                    </div>
                <?php } ?>
            </div>
        </section>

        <section class="py-20 md:py-28 bg-white">
            <div class="container mx-auto px-6">
                <div id="curated-websites" class="teams-section" style="margin-top:14px">
                    <h2 class="text-3xl md:text-5xl font-extrabold tracking-tight text-gray-900">Do you have a website?</h2>
                    <div class="teams-card curated-sites-card">
                        <div class="curated-sites-head">
                            <div class="curated-sites-head-copy">
                                <div class="curated-sites-eyebrow"><?php echo htmlspecialchars($teams_sites_headline, ENT_QUOTES, 'UTF-8'); ?></div>
                                <div class="curated-sites-title">Get a website today - <?php echo htmlspecialchars($teams_sites_subheadline, ENT_QUOTES, 'UTF-8'); ?></div>
                                <div class="curated-sites-subtitle"><?php echo htmlspecialchars($teams_sites_reason !== '' ? $teams_sites_reason : 'A website turns attention into trust, bookings, and sales.', ENT_QUOTES, 'UTF-8'); ?></div>
                            </div>
                            <a class="curated-sites-cta" href="<?php echo htmlspecialchars($teams_sites_cta_href, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener"><?php echo htmlspecialchars($teams_sites_cta, ENT_QUOTES, 'UTF-8'); ?></a>
                        </div>

                        <div class="curated-sites-grid" aria-label="Recommended website categories">
                            <?php if (!empty($teams_sites_cards)) { ?>
                                <?php foreach ($teams_sites_cards as $card): ?>
                                    <?php
                                        $t = isset($card['title']) ? (string)$card['title'] : '';
                                        $img = isset($card['image']) ? (string)$card['image'] : '';
                                        if ($t === '' || $img === '') { continue; }
                                    ?>
                                    <a class="curated-site-card" href="<?php echo htmlspecialchars($teams_sites_cta_href, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener">
                                        <div class="curated-site-media">
                                            <img class="curated-site-img" loading="lazy" src="<?php echo htmlspecialchars($img, ENT_QUOTES, 'UTF-8'); ?>" alt="<?php echo htmlspecialchars($t, ENT_QUOTES, 'UTF-8'); ?>">
                                            <div class="curated-site-badge"><?php echo htmlspecialchars($t, ENT_QUOTES, 'UTF-8'); ?></div>
                                        </div>
                                        <div class="curated-site-body">
                                            <div class="curated-site-action">Start this site</div>
                                        </div>
                                    </a>
                                <?php endforeach; ?>
                            <?php } else { ?>
                                <div class="text-gray-500 text-sm col-span-full">
                                    No curated sites available yet for this segment.
                                </div>
                            <?php } ?>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <?php
        $relatedSegmentsData = [];
        $relatedSegmentStr = isset($segment['related_segment']) ? trim((string)$segment['related_segment']) : '';
        
        if ($relatedSegmentStr !== '' && !empty($segments)) {
            $relatedNames = array_map('trim', explode(',', $relatedSegmentStr));
            $relatedNames = array_unique(array_filter($relatedNames));
            
            if (!empty($relatedNames)) {
                foreach ($relatedNames as $rName) {
                    foreach ($segments as $s) {
                        $sName = isset($s['segment']) ? trim((string)$s['segment']) : '';
                        if (strcasecmp($sName, $rName) === 0) {
                            $relatedSegmentsData[] = $s;
                            break; 
                        }
                    }
                }
            }
        }

        if (!empty($relatedSegmentsData)) {
            $relatedSegmentsSchema = [
                '@context' => 'https://schema.org',
                '@type' => 'ItemList',
                'name' => 'Related industries',
                'itemListElement' => [],
            ];
        ?>
        <section class="py-20 md:py-28 bg-gradient-to-b from-gray-50 to-white">
            <div class="container mx-auto px-6">
                <div class="max-w-5xl mx-auto">
                    <div class="flex flex-col md:flex-row md:items-end md:justify-between gap-6 mb-10">
                        <div>
                            <p class="text-sm font-semibold uppercase tracking-tight text-brand-cyan mb-2">Related</p>
                            <h2 class="text-3xl md:text-5xl font-extrabold tracking-tight text-gray-900">You may also like</h2>
                            <p class="mt-3 text-base md:text-lg text-gray-600 max-w-2xl">
                                Hand-picked industries that overlap your audience, offers, and content.
                            </p>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <?php
                        $relatedPosition = 1;
                        foreach ($relatedSegmentsData as $rSeg) {
                            $rTitle = isset($rSeg['segment']) ? trim((string)$rSeg['segment']) : '';
                            if ($rTitle === '') { continue; }

                            $rLink = 'https://www.thebrand.ai/industry/' . urlencode($rTitle);

                            $rDesc = isset($rSeg['intent_summary']) ? trim((string)$rSeg['intent_summary']) : '';
                            if ($rDesc === '' && isset($rSeg['seo']['meta_description'])) {
                                $rDesc = trim((string)$rSeg['seo']['meta_description']);
                            }

                            $words = preg_split('/\s+/', $rTitle, -1, PREG_SPLIT_NO_EMPTY);
                            $badge = '';
                            if (!empty($words)) {
                                $badge .= strtoupper(substr($words[0], 0, 1));
                                if (count($words) > 1) {
                                    $badge .= strtoupper(substr($words[1], 0, 1));
                                }
                            }
                            if ($badge === '') { $badge = 'AI'; }

                            $relatedSegmentsSchema['itemListElement'][] = [
                                '@type' => 'ListItem',
                                'position' => $relatedPosition,
                                'item' => [
                                    '@type' => 'Thing',
                                    'name' => $rTitle,
                                    'url' => $rLink,
                                ],
                            ];
                            $relatedPosition++;
                        ?>
                        <a href="<?php echo h($rLink); ?>" class="group block h-full">
                            <div class="h-full rounded-2xl border border-gray-200 bg-white shadow-sm hover:shadow-xl transition-all duration-300 p-7 flex flex-col">
                                <div class="flex items-start gap-4">
                                    <div class="flex-none w-11 h-11 rounded-xl bg-gradient-to-br from-brand-midnight to-brand-cyan text-white font-extrabold flex items-center justify-center text-sm tracking-wide">
                                        <?php echo h($badge); ?>
                                    </div>
                                    <div class="min-w-0">
                                        <h3 class="text-lg md:text-xl font-extrabold text-gray-900 group-hover:text-brand-cyan transition-colors leading-snug">
                                            <?php echo h($rTitle); ?>
                                        </h3>
                                        <?php if ($rDesc !== '') { ?>
                                            <p class="mt-2 text-sm text-gray-600 leading-relaxed">
                                                <?php echo h($rDesc); ?>
                                            </p>
                                        <?php } ?>
                                    </div>
                                </div>
                                <div class="mt-6 flex items-center text-brand-cyan font-bold text-sm uppercase tracking-wide">
                                    Explore industry
                                    <svg class="w-4 h-4 ml-2 transform group-hover:translate-x-1 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3"></path></svg>
                                </div>
                            </div>
                        </a>
                        <?php } ?>
                    </div>
                    <script type="application/ld+json"><?php echo json_encode($relatedSegmentsSchema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?></script>
                </div>
            </div>
        </section>
        <?php } ?>

        <!-- ===== KEY MESSAGES ===== -->
        <section class="py-20 md:py-28 bg-gray-50">
            <div class="container mx-auto px-6">
                <div class="text-center mb-12">
                    <p class="text-sm font-semibold uppercase tracking-tight text-brand-cyan mb-2">Key Outcomes</p>
                    <h2 class="text-3xl md:text-5xl font-bold mb-4">What you get with Brand AI.</h2>
                    <p class="text-lg md:text-xl text-gray-600 max-w-3xl mx-auto">
                        Built to give you a consistent, professional brand without agency friction.
                    </p>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <?php if (!empty($segment['key_messages']) && is_array($segment['key_messages'])) { ?>
                        <?php foreach ($segment['key_messages'] as $message) { ?>
                        <div class="bg-white rounded-2xl p-8 shadow-md hover:shadow-xl hover:-translate-y-2 transition-all duration-300">
                            <h3 class="text-xl md:text-2xl font-bold mb-2 text-gray-800"><?php echo h($message['point'] ?? ''); ?></h3>
                            <p class="text-gray-600"><?php echo h($message['detail'] ?? ''); ?></p>
                        </div>
                        <?php } ?>
                    <?php } ?>
                </div>
            </div>
        </section>

        <!-- ===== FAQ ===== -->
        <section class="py-20 md:py-28 bg-white">
            <div class="container mx-auto px-6">
                <div class="text-center mb-12">
                    <p class="text-sm font-semibold uppercase tracking-tight text-brand-cyan mb-2">Questions, answered</p>
                    <h2 class="text-3xl md:text-5xl font-bold mb-4">What people in this field ask us.</h2>
                    <p class="text-lg md:text-xl text-gray-600 max-w-3xl mx-auto">
                        A quick tour of how Brand AI fits into your branding and daily workflow.
                    </p>
                </div>
                <div class="max-w-3xl mx-auto space-y-6">
                    <?php
                    if (!empty($faq['mainEntity']) && is_array($faq['mainEntity'])) {
                        foreach ($faq['mainEntity'] as $item) {
                            $q = isset($item['name']) ? $item['name'] : '';
                            $a = (isset($item['acceptedAnswer']['text'])) ? $item['acceptedAnswer']['text'] : '';
                            if ($q === '' && $a === '') continue;
                            ?>
                            <div class="border border-gray-200 rounded-2xl p-6 shadow-sm">
                                <?php if ($q !== '') { ?>
                                <h3 class="text-lg md:text-xl font-bold mb-2 text-gray-800"><?php echo h($q); ?></h3>
                                <?php } ?>
                                <?php if ($a !== '') { ?>
                                <p class="text-gray-600"><?php echo h($a); ?></p>
                                <?php } ?>
                            </div>
                            <?php
                        }
                    }
                    ?>
                </div>
            </div>
        </section>

        <!-- ===== BOTTOM CTA ===== -->
        <section class="py-16 md:py-20 bg-brand-midnight text-white">
            <div class="container mx-auto px-6 text-center">
                <h2 class="text-3xl md:text-5xl font-extrabold mb-4 tracking-tight">
                    Ready to make your brand look as strong as your work?
                </h2>
                <p class="text-lg md:text-xl opacity-90 max-w-3xl mx-auto mb-8">
                    Start by setting your brand once, then let Brand AI handle the heavy lifting for every asset, campaign, and conversation.
                </p>
                <a href="<?php echo h($ctaJoinUrl); ?>"
                   class="bg-white text-brand-midnight font-bold py-3 px-8 rounded-lg text-lg hover:bg-gray-200 transition-all duration-300 transform hover:scale-105">
                    <?php echo h($hero['cta_primary'] ?? 'Build My Personal Brand Free →'); ?>
                </a>
            </div>
        </section>

    </main>

    <!-- ===== FOOTER ===== -->
    <footer class="bg-brand-midnight text-white">
        <div class="container mx-auto px-6 py-12">
            <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-8">
                <div class="col-span-2 lg:col-span-1">
                    <a href="https://www.thebrand.ai" aria-label="Brand AI Homepage">
                        <img src="https://www.thebrand.ai/i/uploads/logo/logo_62a4de26e93f0.png" alt="Brand AI Logo" width="110" height="30">
                    </a>
                    <p class="mt-4 text-gray-400">Your vision, amplified.</p>
                </div>
                <div>
                    <h3 class="font-bold uppercase text-gray-400">Features</h3>
                    <ul class="mt-4 space-y-2">
                        <li><a href="https://www.thebrand.ai/brandcreator/index"              class="text-gray-300 hover:text-brand-cyan transition-colors">Brand Creator</a></li>
                        <li><a href="https://www.thebrand.ai/i/account/designs"               class="text-gray-300 hover:text-brand-cyan transition-colors">My Designs</a></li>
                        <li><a href="https://www.thebrand.ai/i"                               class="text-gray-300 hover:text-brand-cyan transition-colors">Templates</a></li>
                        <li><a href="https://www.thebrand.ai/insights/dashboard?feature=brandtoolkit" class="text-gray-300 hover:text-brand-cyan transition-colors">Brand Toolkit</a></li>
                    </ul>
                </div>
                <div>
                    <h3 class="font-bold uppercase text-gray-400">Resources</h3>
                    <ul class="mt-4 space-y-2">
                        <li><a href="https://www.thebrand.ai/insights/"                              class="text-gray-300 hover:text-brand-cyan transition-colors">Insights</a></li>
                        <li><a href="https://www.thebrand.ai/blogs"                                  class="text-gray-300 hover:text-brand-cyan transition-colors">Blogs</a></li>
                        <li><a href="https://www.thebrand.ai/insights/dashboard?feature=browsejourneys" class="text-gray-300 hover:text-brand-cyan transition-colors">Brand Journeys</a></li>
                        <li><a href="https://www.thebrand.ai/sites/index"                            class="text-gray-300 hover:text-brand-cyan transition-colors">Sites</a></li>
                    </ul>
                </div>
                <div>
                    <h3 class="font-bold uppercase text-gray-400">Account</h3>
                    <ul class="mt-4 space-y-2">
                        <li><a href="https://www.thebrand.ai/i/account/build_brand"    class="text-gray-300 hover:text-brand-cyan transition-colors">My Brand Identity</a></li>
                        <li><a href="https://www.thebrand.ai/insights/auth-onboard"    class="text-gray-300 hover:text-brand-cyan transition-colors">Onboarding</a></li>
                    </ul>
                </div>
                <div>
                    <h3 class="font-bold uppercase text-gray-400">Company</h3>
                    <ul class="mt-4 space-y-2">
                        <li><a href="https://www.thebrand.ai/i/contact" class="text-gray-300 hover:text-brand-cyan transition-colors">Contact Us</a></li>
                    </ul>
                    <div class="flex space-x-4 mt-4">
                        <a href="https://facebook.com/TheBrandApp" class="text-gray-400 hover:text-brand-cyan transition-colors" aria-label="Facebook">
                            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M22 12c0-5.523-4.477-10-10-10S2 6.477 2 12c0 4.991 3.657 9.128 8.438 9.878v-6.987h-2.54V12h2.54V9.797c0-2.506 1.492-3.89 3.777-3.89 1.094 0 2.238.195 2.238.195v2.46h-1.26c-1.243 0-1.63.771-1.63 1.562V12h2.773l-.443 2.89h-2.33v6.988C18.343 21.128 22 16.991 22 12z" clip-rule="evenodd"/></svg>
                        </a>
                        <a href="https://twitter.com/thebrandhq" class="text-gray-400 hover:text-brand-cyan transition-colors" aria-label="Twitter">
                            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24"><path d="M8.29 20.251c7.547 0 11.675-6.253 11.675-11.675 0-.178 0-.355-.012-.53A8.348 8.348 0 0022 5.92a8.19 8.19 0 01-2.357.646 4.118 4.118 0 001.804-2.27 8.224 8.224 0 01-2.605.996 4.107 4.107 0 00-6.993 3.743 11.65 11.65 0 01-8.457-4.287 4.106 4.106 0 001.27 5.477A4.072 4.072 0 012.8 9.71v.052a4.105 4.105 0 003.292 4.022 4.095 4.095 0 01-1.853.07 4.108 4.108 0 003.834 2.85A8.233 8.233 0 012 18.407a11.616 11.616 0 006.29 1.84"/></svg>
                        </a>
                        <a href="https://www.instagram.com/thebrandapp" class="text-gray-400 hover:text-brand-cyan transition-colors" aria-label="Instagram">
                            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M12.315 2c2.43 0 2.784.013 3.808.06 1.064.049 1.791.218 2.427.465a4.902 4.902 0 011.772 1.153 4.902 4.902 0 011.153 1.772c.247.636.416 1.363.465 2.427.048 1.024.06 1.378.06 3.808s-.012 2.784-.06 3.808c-.049 1.064-.218 1.791-.465 2.427a4.902 4.902 0 01-1.153 1.772 4.902 4.902 0 01-1.772 1.153c-.636.247-1.363.416-2.427.465-1.024.048-1.378.06-3.808.06s-2.784-.012-3.808-.06c-1.064-.049-1.791-.218-2.427-.465a4.902 4.902 0 01-1.772-1.153 4.902 4.902 0 01-1.153-1.772c-.247-.636-.416-1.363-.465-2.427-.048-1.024-.06-1.378-.06-3.808s.012-2.784.06-3.808c.049-1.064.218-1.791.465-2.427a4.902 4.902 0 011.153-1.772A4.902 4.902 0 016.08 2.525c.636-.247 1.363-.416 2.427-.465C9.53 2.013 9.884 2 12.315 2zM12 7.044c-2.583 0-4.666 2.083-4.666 4.666s2.083 4.666 4.666 4.666 4.666-2.083 4.666-4.666S14.583 7.044 12 7.044zm0 7.666c-1.657 0-3-1.343-3-3s1.343-3 3-3 3 1.343 3 3-1.343 3-3 3zm4.917-7.916a1.146 1.146 0 100-2.292 1.146 1.146 0 000 2.292z" clip-rule="evenodd"/></svg>
                        </a>
                        <a href="https://www.linkedin.com/company/the-brand-app" class="text-gray-400 hover:text-brand-cyan transition-colors" aria-label="LinkedIn">
                            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24"><path d="M19 0h-14c-2.761 0-5 2.239-5 5v14c0 2.761 2.239 5 5 5h14c2.762 0 5-2.239 5-5v-14c0-2.761-2.238-5-5-5zm-11 19h-3v-11h3v11zm-1.5-12.268c-.966 0-1.75-.79-1.75-1.764s.784-1.764 1.75-1.764 1.75.79 1.75 1.764-.783 1.764-1.75 1.764zm13.5 12.268h-3v-5.604c0-3.368-4-3.113-4 0v5.604h-3v-11h3v1.765c1.396-2.586 7-2.777 7 2.476v6.759z"/></svg>
                        </a>
                    </div>
                </div>
            </div>
            <div class="mt-8 pt-8 border-t border-gray-800 flex flex-col md:flex-row justify-between items-center">
                <p class="text-gray-400">© <?php echo date('Y'); ?> Brand AI. All rights reserved.</p>
                <div class="flex space-x-4 mt-4 md:mt-0 text-sm text-gray-500">
                    <span><?php echo h($segment['segment'] ?? 'Industry'); ?></span>
                    <span class="hidden md:inline-block">|</span>
                    <span>Brand AI Industry Landing</span>
                </div>
            </div>
        </div>
    </footer>

</div>

<script>
var bdCuratedIsLoggedIn = <?php echo $bdIsLoggedIn ? 'true' : 'false'; ?>;
var bdCuratedLoginUrl = "https://www.thebrand.ai/connect/index.php";
var bdCuratedDashboardBase = "https://www.thebrand.ai/wowX/dashboard/index.php?tab=templates&picID=";
(function () {
    var toggle = document.getElementById('mobileMenuToggle');
    var menu   = document.getElementById('mobileMenu');
    var icon   = document.getElementById('mobileMenuIcon');
    if (!toggle || !menu || !icon) return;
    toggle.addEventListener('click', function () {
        var isHidden = menu.classList.contains('hidden');
        if (isHidden) {
            menu.classList.remove('hidden');
            icon.setAttribute('d', 'M6 18L18 6M6 6l12 12');
        } else {
            menu.classList.add('hidden');
            icon.setAttribute('d', 'M4 6h16M4 12h16M4 18h16');
        }
    });
})();
(function() {
    var filters = document.querySelectorAll('.bd-curated-filter');
    if (!filters.length) {
        return;
    }
    var cards = Array.prototype.slice.call(document.querySelectorAll('.bd-curated-card'));
    if (!cards.length) {
        return;
    }
    var pagination = document.getElementById('bd-curated-pagination');
    var perPage = 12;
    if (pagination) {
        var attr = pagination.getAttribute('data-per-page');
        var parsed = parseInt(attr, 10);
        if (!isNaN(parsed) && parsed > 0) {
            perPage = parsed;
        }
    }
    var prevBtn = pagination ? pagination.querySelector('[data-page="prev"]') : null;
    var nextBtn = pagination ? pagination.querySelector('[data-page="next"]') : null;
    var infoEl = document.getElementById('bd-curated-page-info');
    var currentInterest = '';
    var currentPage = 1;
    function normalizeText(s) {
        return (s || '').toString().toLowerCase();
    }
    function getKeywords(el) {
        var v = el.getAttribute('data-keywords') || '';
        if (!v) {
            var t = el.querySelector('.bd-curated-title');
            v = t ? (t.textContent || t.innerText || '') : '';
        }
        return normalizeText(v);
    }
    function getFilteredCards() {
        if (!currentInterest) {
            return cards;
        }
        var filtered = [];
        cards.forEach(function(card) {
            var haystack = getKeywords(card);
            if (haystack.indexOf(currentInterest) !== -1) {
                filtered.push(card);
            }
        });
        return filtered;
    }
    function updatePaginationControls(total) {
        if (!pagination) {
            return;
        }
        if (!total || total <= perPage) {
            pagination.classList.add('hidden');
        } else {
            pagination.classList.remove('hidden');
        }
        if (!infoEl) {
            return;
        }
        var totalPages = total > 0 ? Math.ceil(total / perPage) : 1;
        if (currentPage < 1) {
            currentPage = 1;
        }
        if (currentPage > totalPages) {
            currentPage = totalPages;
        }
        var start = total === 0 ? 0 : (currentPage - 1) * perPage + 1;
        var end = total === 0 ? 0 : Math.min(total, currentPage * perPage);
        infoEl.textContent = "Page " + currentPage + " of " + totalPages + " \u2022 Showing " + start + "-" + end + " of " + total;
        if (prevBtn) {
            if (currentPage <= 1) {
                prevBtn.setAttribute('disabled', 'disabled');
                prevBtn.classList.add('opacity-50', 'cursor-not-allowed');
            } else {
                prevBtn.removeAttribute('disabled');
                prevBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            }
        }
        if (nextBtn) {
            if (currentPage >= totalPages) {
                nextBtn.setAttribute('disabled', 'disabled');
                nextBtn.classList.add('opacity-50', 'cursor-not-allowed');
            } else {
                nextBtn.removeAttribute('disabled');
                nextBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            }
        }
    }
    function render() {
        var filtered = getFilteredCards();
        var total = filtered.length;
        var totalPages = total > 0 ? Math.ceil(total / perPage) : 1;
        if (currentPage > totalPages) {
            currentPage = totalPages;
        }
        if (currentPage < 1) {
            currentPage = 1;
        }
        cards.forEach(function(card) {
            card.classList.add('hidden');
        });
        var startIndex = (currentPage - 1) * perPage;
        var endIndex = startIndex + perPage;
        filtered.forEach(function(card, index) {
            if (index >= startIndex && index < endIndex) {
                card.classList.remove('hidden');
            }
        });
        updatePaginationControls(total);
    }
    function attachCardClicks() {
        cards.forEach(function(card) {
            var id = card.getAttribute('data-template-id');
            if (!id || id === "0") {
                return;
            }
            card.style.cursor = 'pointer';
            card.addEventListener('click', function() {
                if (window.bdCuratedIsLoggedIn) {
                    window.location.href = window.bdCuratedDashboardBase + encodeURIComponent(id);
                } else {
                    window.location.href = window.bdCuratedLoginUrl;
                }
            });
        });
    }
    function setActive(button) {
        filters.forEach(function(b) {
            b.classList.remove('bg-brand-cyan', 'text-white', 'border-brand-cyan');
            b.classList.add('bg-white', 'text-gray-800', 'border-gray-300');
        });
        button.classList.remove('bg-white', 'text-gray-800', 'border-gray-300');
        button.classList.add('bg-brand-cyan', 'text-white', 'border-brand-cyan');
    }
    filters.forEach(function(btn) {
        btn.addEventListener('click', function() {
            var interest = normalizeText(btn.getAttribute('data-interest'));
            currentInterest = interest;
            currentPage = 1;
            setActive(btn);
            render();
        });
    });
    if (prevBtn) {
        prevBtn.addEventListener('click', function() {
            if (currentPage > 1) {
                currentPage -= 1;
                render();
            }
        });
    }
    if (nextBtn) {
        nextBtn.addEventListener('click', function() {
            currentPage += 1;
            render();
        });
    }
    attachCardClicks();
    render();
})();
</script>
</body>
</html>