<?php
$tt_page_info = array(
  'Page_Info' =>   array(
    'Title' => $the_post['PostTitle'],
    'Description' => articleContentClean(trim(strip_tags($the_post['PostContent']))),
    'Keyword' =>str_replace(['[', ']', '"'], '', $the_post['PostTopic']) ,
  ),
  'Social_og' => array(
    'Image' => articleImg($the_post['PostId'], 'og'),
    'Type' => 'website',
    'URL' => str_replace($site_domain, '', articleLink($the_post['PostId'])),
  ),
);

// Count View
UpdateData('mahamudfutureit_article', 'PostId', $the_post['PostId'],   array("ViewCount"=> $the_post['ViewCount'] + 1));

// Post Writer Information
if ($the_post['PostWriterName'] !='') {
  $post_writer = $the_post['PostWriterName'];
  $post_writer_profile = "#";
  $post_writer_avater = $advancenews['PostWriterDefaultImage'];
  $post_writer_designation = $the_post['PostWriterDesignation'];
}else{
  $post_writer = getSingleValue('tt_accounts', 'UserID',  $the_post['PostAuthor'], 'UserName');
  $post_writer_profile = userProfile($the_post['PostAuthor']);
  $post_writer_avater = userAvater($the_post['PostAuthor']);
  $post_writer_designation = getSingleValue('tt_accounts', 'UserID',  $the_post['PostAuthor'], 'UserDesignation');
}

require_once('./header.php');
?>
<script type="application/ld+json">
  {
       "@context": "https://schema.org",
       "@type": "NewsArticle",
       "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "<?php echo articleLink($the_post['PostId']) ?>"
       },
       "headline": "<?php echo htmlentities($the_post['PostTitle'], ENT_QUOTES, 'utf-8'); ?>",
       "description":  "<?php echo strip_tags($the_post['PostContent']) ?>",
       "image": "<?php echo articleImg($the_post['PostId'], 'featured') ?>",
       "datePublished": "<?php echo $the_post['PostDatePublic'] ?>",
       "dateModified": "<?php echo $the_post['PostModified'] ?>",
     "author": {
            "@type": "Person",
            "name": "<?php echo $post_writer ?>",
            "url": "<?php echo $post_writer_profile ?>"
       },
       "publisher": {
            "@type": "Organization",
            "name": "<?php echo $advancenews['Website_title'] ?>",
            "logo": {
                 "@type": "ImageObject",
                 "url": "<?php echo $advancenews['Website_Logo'] ?>"
            }
       }
  }
</script>
<script type="application/ld+json">
  {
    "@context": "http://schema.org",
    "@type": "BreadcrumbList",
    "itemListElement": [{
        "@type": "ListItem",
        "position": 1,
        "item": {
          "@id": "<?php echo $site_domain ?>",
          "name": "Home"
        }
      },
      {
        "@type": "ListItem",
        "position": 2,
        "item": {
          "@id": "<?php echo articleCategory($the_post['PostId'],'url') ?>",
          "name": "<?php echo articleCategory($the_post['PostId'],'name') ?>"
        }
      },
      {
        "@type": "ListItem",
        "position": 3,
        "item": {
          "name": "<?php echo htmlentities($the_post['PostTitle'], ENT_QUOTES, 'utf-8'); ?>",
          "@id": "<?php echo articleLink($the_post['PostId']) ?>"
        }
      }
    ]
  }
</script>

<style>
    @media print {
      @page {
        size: A4;
      }
      .d-print-none {
        display: none !important;
      }
      .d-print-block {
        display: block !important;
      }
      footer,
      .mobile_header,
      .mahamudfutureit_header{
        display: none !important;
      }
    }
    
    .verified-badge {
        color: #3b82f6;
        font-size: 14px;
        margin-left: 3px;
        vertical-align: middle;
    }
    
    /* থিম কালার লিংক - প্রিন্ট, ডাউনলোড */
    .theme-link {
        color: #004bad !important;
        font-weight: 500;
        transition: color 0.3s ease;
    }
    
    .theme-link:hover {
        color: #003a8a !important;
    }
    
    .theme-link i {
        color: #004bad !important;
    }
    
    /* ফলো বাটন - ছবির মতো ডিজাইন */
    .follow-buttons-section {
        margin: 20px 0;
        padding: 10px 0;
    }
    
    .follow-buttons-wrapper {
        display: flex;
        align-items: center;
        gap: 15px;
        flex-wrap: wrap;
    }
    
    .follow-btn {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 8px 18px;
        border-radius: 6px;
        text-decoration: none;
        font-size: 13px;
        font-weight: 500;
        transition: all 0.3s ease;
        cursor: pointer;
        border: none;
    }
    
    .follow-btn i {
        font-size: 14px;
    }
    
    .follow-btn:hover {
        transform: translateY(-2px);
        opacity: 0.9;
        text-decoration: none;
    }
    
    /* সব ফলো বাটন একই কালার (থিম কালার) */
    .follow-facebook,
    .follow-whatsapp,
    .follow-app {
        background: var(--tt_theme_color, #dc2626);
        color: white;
    }
    
    .follow-facebook:hover,
    .follow-whatsapp:hover,
    .follow-app:hover {
        background: var(--tt_theme_hover, #b91c1c);
        color: white;
    }

    /* Writer Name Theme Color */
    .writer-name {
        color: #004bad !important;
        transition: color 0.3s ease;
    }
    .writer-name:hover {
        color: #003a8a !important;
    }

    /* Designation Theme Color */
    .writer-designation {
        color: #004bad !important;
        opacity: 0.85;
    }
    
    /* News Title Theme Color */
    .post-main-title {
        color: #004bad !important;
    }

    /* Auto Load More Posts */
    .auto-load-post {
        margin-top: 40px;
        padding-top: 30px;
        border-top: 3px solid var(--tt_theme_color, #dc2626);
    }

    /* ShareThis বাটন থিম কালার override */
    .st-btn {
        background-color: #004bad !important;
        border-color: #004bad !important;
    }

    .st-btn:hover {
        background-color: #003a8a !important;
        border-color: #003a8a !important;
        opacity: 1 !important;
    }

    .st-btn[data-network] {
        background-color: #004bad !important;
    }

    /* ShareThis icon সাদা */
    .st-btn svg,
    .st-btn svg path,
    .st-btn svg circle,
    .st-btn svg rect,
    .st-btn svg polygon,
    .st-btn img {
        fill: #ffffff !important;
        color: #ffffff !important;
        filter: brightness(0) invert(1) !important;
    }

    .st-btn span {
        color: #ffffff !important;
    }
</style>

<section class="d-print-none py-4">
  <div class="container" id="content-area">
    <div class="auto_load_next pb-5">
      <?php
      $post_ads_1 = showAds($advancenews['PostAds1'], $advancenews['PostAdsCtl']);
      if ($post_ads_1 != '') {
        ?>
        <div class="mb-3">
          <?php echo $post_ads_1 ?>
        </div>
        <?php
      }
      ?>
      <div class="mb-4">
        <a href="<?php echo articleCategory($the_post['PostId'],'url') ?>">
          <h4 class="m-0 p_post_cat2 d-inline-block"><?php echo articleCategory($the_post['PostId'],'name') ?></h4>
        </a>
      </div>
      <?php
      $post_ads_2 = showAds($advancenews['PostAds2'], $advancenews['PostAdsCtl']);
      if ($post_ads_2 != '') {
        ?>
        <div class="tt-white my-3">
          <?php echo $post_ads_2 ?>
        </div>
        <?php
      }
      ?>
      <div class="row g-4">
        <div class="col-lg-8">
          <div class="">
            <?php
              if ($the_post['PostSubtitle']!='') {
                ?>
                <h2 class="h4 text-muted mb-2"><?php echo $the_post['PostSubtitle']; ?></h2>
                <?php
              }
             ?> 
            <h1 class="m-0 mb-4 h1 fw-bold tt-text post-main-title" style="font-size:var(--tt_post_title_fs)"><?php echo htmlentities($the_post['PostTitle'], ENT_QUOTES, 'utf-8'); ?></h1>
            <hr class="d-block d-lg-none">

            <div class="row g-4 align-items-center">
              <div class="col-12 col-md-6">
                <div class="d-flex align-items-start">
                  <a href="<?php echo $post_writer_profile ?>">
                    <img class="rounded-circle" height="50px" width="auto" src="<?php echo $post_writer_avater ?>" alt="<?php echo htmlentities($post_writer, ENT_QUOTES, 'utf-8'); ?>">
                  </a>
                  <div class="ms-2">
                    <a href="<?php echo $post_writer_profile ?>" class="tt-text writer-name">
                      <h5 class="m-0 h5 fw-bold">
                        <?php echo htmlentities($post_writer, ENT_QUOTES, 'utf-8'); ?>
                        <i class="fas fa-check-circle verified-badge" title="Verified"></i>
                        <?php
                        if ($post_writer_designation !='') {
                          ?>
                          <small class="fw-normal writer-designation"><?php echo $post_writer_designation ?></small>
                          <?php
                        }
                        ?>
                      </h5>
                    </a>
                    <span class="tt-text">প্রকাশ : <?php echo dokanDate($the_post['PostDatePublic']) ?></span>
                    <?php
                    if ($advancenews['NewsPrintView'] == 'on') {
                      ?>
                      <span><small>|</small> <a class="theme-link" href="<?php echo $site_domain ?>print-post/<?php echo $the_post['PostId'] ?>/"><i class="fas fa-print"></i> প্রিন্ট সংস্করণ </a></span>
                      <?php
                    }
                    if($c_user !='' || $advancenews['PhotoCardPublic'] == 'on'){
                      ?>
                      <span><small>|</small> <a class="theme-link" href="<?php echo $site_domain ?>mahamudfutureit-photocard/<?php echo $the_post['PostId'] ?>/"><i class="fas fa-download"></i> ডাউনলোড কার্ড  </a></span>
                      <?php
                    }
                    ?>
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-6">
                <div class="myshare-mahamudfutureit mb-3 mb-md-0">
                  <div class="sharethis-inline-share-buttons text-start text-lg-end" data-title="<?php echo $the_post['PostTitle'] ?>" data-url="<?php echo articleLink($the_post['PostId']) ?>"></div>
                </div>
              </div>
            </div>
            
            <hr class="d-none d-lg-block">
            <?php
            if ($the_post['PageContentType'] == 'video') {
              $videoLink = $the_post['PostVideoLink'];
              function getVideoId($url) {
                  if (preg_match('/youtu\.be\/([a-zA-Z0-9_-]+)/', $url, $matches)) {
                      return $matches[1];
                  }
                  parse_str(parse_url($url, PHP_URL_QUERY), $query);
                  return $query['v'] ?? null;
              }
              $videoId = getVideoId($videoLink);
              $embedUrl = "https://www.youtube.com/embed/$videoId";
              ?>
              <div class="video-container rounded-top">
                  <iframe src="<?php echo $embedUrl; ?>" frameborder="0" allowfullscreen></iframe>
              </div>
              <?php
            }else {
              ?>
              <div class="story-image popup-gallery">
                <a title="<?php echo htmlentities($the_post['PostTitle'], ENT_QUOTES, 'utf-8'); ?>" href="<?php echo articleImg($the_post['PostId'], 'featured') ?>">
                  <img class="w-100" src="<?php echo $advancenews['ArticlePreloader'] ?>" data-src="<?php echo articleImg($the_post['PostId'], 'featured') ?>" alt="<?php echo htmlentities($the_post['PostTitle'], ENT_QUOTES, 'utf-8'); ?>">
                </a>
                <?php
                $post_ads_3 = showAds($advancenews['PostAds3'], $advancenews['PostAdsCtl']);
                if ($post_ads_3 != '') {
                  ?>
                  <div class="story-image-ads">
                    <?php echo $post_ads_3 ?>
                  </div>
                  <?php
                }
                ?>
              </div>
              <?php
              if ($the_post['PostImageCaption'] !='') {
                ?>
                <div class="p-2 py-1 text-center" style="background:#e9f5f5">
                  <h5 class="m-0 news-title-4"><?php echo $the_post['PostImageCaption'] ?></h5>
                </div>
                <?php
              }
            }
            ?>
            
            <!-- ============================================ -->
            <!-- ফলো সেকশন - সেন্টারিং + থিম কালার -->
            <!-- ============================================ -->
            <style>
            .follow-wrapper {
                display: flex;
                justify-content: center;
                margin: 15px 0;
            }

            .follow-connector {
                display: inline-flex;
                border: 1px solid #ddd;
                border-radius: 6px;
                overflow: hidden;
            }

            .follow-connector a {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                gap: 8px;
                padding: 8px 18px;
                text-decoration: none;
                font-size: 14px;
                font-weight: 500;
                border-right: 1px solid #ddd;
                background: white;
                transition: all 0.2s ease;
            }

            .follow-connector a:last-child {
                border-right: none;
            }

            .follow-connector a:hover {
                background: #f5f5f5;
            }

            /* ফলো করুন - থিম কালার ব্যাকগ্রাউন্ড */
            .follow-connector .follow-link {
                background: var(--tt_theme_color, #dc2626);
                color: white;
                border-right: 1px solid var(--tt_theme_color, #dc2626);
            }

            .follow-connector .follow-link:hover {
                background: var(--tt_theme_hover, #b91c1c);
            }

            /* মেসেঞ্জার */
            .follow-connector .messenger-link {
                color: #0d95fd;
            }
            .follow-connector .messenger-link i {
                color: #0d95fd;
                font-size: 14px;
            }

            /* হোয়াটসঅ্যাপ */
            .follow-connector .whatsapp-link {
                color: #07a21b;
            }
            .follow-connector .whatsapp-link i {
                color: #07a21b;
                font-size: 14px;
            }

            /* মোবাইল রেসপন্সিভ */
            @media (max-width: 576px) {
                .follow-connector a {
                    padding: 6px 12px;
                    font-size: 12px;
                    gap: 5px;
                }
                .follow-wrapper {
                    margin: 10px 0;
                }
            }
            </style>

            <div class="follow-wrapper">
                <div class="follow-connector">
                    <a href="#" class="follow-link">ফলো করুন</a>
                    <a href="https://m.me/yourpagename" target="_blank" class="messenger-link">
                        <i class="fab fa-facebook-messenger"></i> মেসেঞ্জার
                    </a>
                    <a href="https://wa.me/yournumber" target="_blank" class="whatsapp-link">
                        <i class="fab fa-whatsapp"></i> হোয়াটসঅ্যাপ
                    </a>
                </div>
            </div>
            
            <div class="story-details tt-text">
              <?php
              echo articleContent($the_post['PostContent']);
              ?>
            </div>
            <?php
            if ($the_post['PostAttachment'] !='') {
              ?>
              <div class="my-2">
                <?php renderMediaByType($the_post['PostAttachment']); ?>
              </div>
              <?php
            }
            $post_topic = json_decode($the_post['PostTopic'], TRUE);
            if (!empty($post_topic)) {
              ?>
              <div class="mt-2 post-tipics">
                <p class="m-0"> <strong>বিষয় :</strong>
                  <?php
                    foreach ($post_topic as $the_ptopic) {
                      ?>
                      <a class="border" href="<?php echo getTopicsUrl($the_ptopic) ?>"><?php echo $the_ptopic ?></a>
                      <?php
                    }
                  ?>
                </p>
              </div>
              <?php
            }
            ?>
          </div>
          <?php
          $post_ads_5 = showAds($advancenews['PostAds5'], $advancenews['PostAdsCtl']);
          if ($post_ads_5 != '') {
            ?>
            <div class="tt-white my-3">
              <?php echo $post_ads_5 ?>
            </div>
            <?php
          }
          ?>
        </div>
        <div class="col-lg-4 d-lg-block d-none">
          <?php
          $post_ads_6 = showAds($advancenews['PostAds6'], $advancenews['PostAdsCtl']);
          if ($post_ads_6 != '') {
            ?>
            <div class="tt-white mb-3">
              <?php echo $post_ads_6 ?>
            </div>
            <?php
          }
          ?>
          <div class="sidebar">
            <div class="related-post mb-1">
              <?php
                $ps_block_this_post = $the_post['PostCategory'];
              ?>
              <div class="row g-2">
                <div class="col-12">
                  <?php
                    echo getBlockTitle($ps_block_this_post);
                  ?>
                </div>
                <?php
                $ps_block_this_post_article = getArticles($ps_block_this_post, 8);
                $ps_block_this_post_count = 1;
                if (!empty($ps_block_this_post_article)) {
                  foreach ($ps_block_this_post_article as $this_post_the_ps) {
                    if ($ps_block_this_post_count == 1) {
                      ?>
                      <div class="col-12">
                        <div class="ps-category-lead-news position-relative rounded-2">
                          <a href="<?php echo articleLink($this_post_the_ps['PostId']) ?>">
                            <div class="ps-clead-img">
                              <img class="w-100" src="<?php echo $advancenews['ArticlePreloader'] ?>" data-src="<?php echo articleImg($this_post_the_ps['PostId']) ?>" alt="<?php echo $this_post_the_ps['PostTitle'] ?>">
                            </div>
                            <div class="ps-clead-title">
                              <h1 class="p-2 news-title-3 m-0 text-white"><?php echo $this_post_the_ps['PostTitle'] ?></h1>
                            </div>
                          </a>
                        </div>
                      </div>
                      <?php
                      $post_ads_7 = showAds($advancenews['PostAds7'], $advancenews['PostAdsCtl']);
                      if ($post_ads_7 != '') {
                        ?>
                        <div class="col-12">
                          <?php echo $post_ads_7 ?>
                        </div>
                        <?php
                      }
                      ?>
                      <?php
                    }else {
                      ?>
                      <div class="col-12">
                        <a href="<?php echo articleLink($this_post_the_ps['PostId']) ?>" class="d-block prothom-songbad-post-style py-1">
                          <div class="row g-2 align-items-center">
                              <div class="col-5">
                                <div class="position-relative overflow-hidden rounded-2">
                                  <img class="w-100 ps-post-line-img" src="<?php echo $advancenews['ArticlePreloader'] ?>" data-src="<?php echo articleImg($this_post_the_ps['PostId']) ?>" alt="<?php echo $this_post_the_ps['PostTitle'] ?>">
                                </div>
                              </div>
                              <div class="col-7">
                                <h1 class="news-title-4 m-0 tt-text"><?php echo $this_post_the_ps['PostTitle'] ?></h1>
                              </div>
                          </div>
                        </a>
                      </div>
                      <?php
                    }
                    $ps_block_this_post_count++;
                  }
                }else {
                  ?>
                  <div class="col-12">
                    <?php echo noPost(); ?>
                  </div>
                  <?php
                }
                ?>
              </div>
            </div>

            <?php
            $post_ads_8 = showAds($advancenews['PostAds8'], $advancenews['PostAdsCtl']);
            if ($post_ads_8 != '') {
              ?>
              <div class="my-3">
                <?php echo $post_ads_8 ?>
              </div>
              <?php
            }
            ?>
            <div class="most-recent mt-2">
              <?php require_once('template-part/most-recent-2.php'); ?>
            </div>
            <?php
            $post_ads_9 = showAds($advancenews['PostAds9'], $advancenews['PostAdsCtl']);
            if ($post_ads_9 != '') {
              ?>
              <div class="my-3">
                <?php echo $post_ads_9 ?>
              </div>
              <?php
            }
            ?>
          </div>
        </div>
      </div>
      <?php
      $post_ads_10 = showAds($advancenews['PostAds10'], $advancenews['PostAdsCtl']);
      if ($post_ads_10 != '') {
        ?>
        <div class="my-3">
          <?php echo $post_ads_10 ?>
        </div>
        <?php
      }
      ?>
      <div class="load_next"
                data-page-title="<?php echo htmlentities($the_post['PostTitle'], ENT_QUOTES, 'utf-8'); ?>"
                data-page-url="<?php echo articleLink($the_post['PostId']) ?>"></div>
    </div>
  </div>
</section>

<div class="d-none d-print-block">
  <div class="row align-items-center">
    <div class="col-6">
      <img style="height:60px; width:auto" src="<?php echo $advancenews['Website_Logo'] ?>" alt="<?php echo $advancenews['Website_title'] ?>"><br>
    </div>
    <div class="col-6 text-end">
      <p class="m-0 news-title-1"><?php echo dokanDateWithDay(date('Y-m-d H:i:s')) ?></p>
    </div>
    <div class="col-12">
      <hr>
    </div>
    <div class="col-12">
      <h1><?php echo htmlentities($the_post['PostTitle'], ENT_QUOTES, 'utf-8'); ?></h1>
      <p class="m-0 news-title-1">প্রকাশের তারিখ : <?php echo dokanDate($the_post['PostDatePublic']) ?></p>
      <div class="my-3">
        <img class="w-100" src="<?php echo articleImg($the_post['PostId'], 'featured') ?>" alt="featured Image">
      </div>
      <div class="mt-2" style="text-align:justify; font-size:18px;">
        <?php echo articleContentClean($the_post['PostContent']) ?>
      </div>
    </div>
    <div class="col-12 text-center">
      <hr>
      <img style="height:60px; width:auto" src="<?php echo $advancenews['Website_Logo'] ?>" alt="<?php echo $advancenews['Website_title'] ?>"><br><br>
      <strong>
        <?php echo $advancenews['Publisher_Info'] ?> <br>
      </strong>
      <?php
        if ($advancenews['NewsPrintViewFooter'] !='') {
          echo $advancenews['NewsPrintViewFooter'];
        }else {
        echo 'কপিরাইট © '.bnNumber(date('Y')).' '.$advancenews['Website_title'].' । সর্বস্বত্ব সংরক্ষিত ';
        }
       ?>
    </div>
  </div>
</div>

<script>
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(function() {
        alert('লিংক কপি হয়েছে!');
    }, function() {
        var textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        alert('লিংক কপি হয়েছে!');
    });
}

// ShareThis বাটন থিম কালার JS override
window.addEventListener('load', function() {
    setTimeout(function() {
        var themeColor = '#004bad';
        var themeHover = '#003a8a';
        document.querySelectorAll('.st-btn').forEach(function(btn) {
            btn.style.setProperty('background-color', themeColor, 'important');
            btn.style.setProperty('border-color', themeColor, 'important');
            // icon সাদা
            btn.querySelectorAll('svg, svg path, svg circle, svg rect, svg polygon').forEach(function(el) {
                el.style.setProperty('fill', '#ffffff', 'important');
            });
            btn.querySelectorAll('img').forEach(function(el) {
                el.style.setProperty('filter', 'brightness(0) invert(1)', 'important');
            });
            btn.querySelectorAll('span').forEach(function(el) {
                el.style.setProperty('color', '#ffffff', 'important');
            });
            btn.addEventListener('mouseenter', function() {
                this.style.setProperty('background-color', themeHover, 'important');
            });
            btn.addEventListener('mouseleave', function() {
                this.style.setProperty('background-color', themeColor, 'important');
            });
        });
    }, 1500);
});

let loading=false, nextPage=2;
const currentCategoryId = "<?php echo $the_post['PostCategory']; ?>";
const siteDomain = "<?php echo $site_domain; ?>";

function debounce(f,d){let t;return()=>{clearTimeout(t);t=setTimeout(f,d)}}

function updateTitleAndUrl(){
    let blocks=document.querySelectorAll(".auto_load_next");
    let middle=window.innerHeight/2;
    let active=null;
    blocks.forEach(b=>{
        let r=b.getBoundingClientRect();
        if(r.top<=middle && r.bottom>=middle) active=b
    });
    if(!active) return;
    let m=active.querySelector(".load_next");
    if(!m) return;
    let title=m.getAttribute("data-page-title");
    let url=m.getAttribute("data-page-url");
    if(title && document.title!==title){
        document.title=title;
        history.replaceState(null,title,url)
    }
}

function loadNextBlock(){
    if(loading) return;
    loading=true;
    
    const formData = new URLSearchParams();
    formData.append('page', nextPage);
    formData.append('mahamudfutureit_identity', currentCategoryId);
    
    fetch(siteDomain + "ajax_master/load_more/", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        body: formData.toString()
    })
    .then(response => response.text())
    .then(html => {
        if(html.trim() === '') {
            loading=false;
            return;
        }
        const container = document.getElementById("content-area");
        container.insertAdjacentHTML("beforeend", html);
        
        if(typeof window.__sharethis__ !== "undefined") {
            window.__sharethis__.initialize();
        }
        if(typeof FB !== "undefined") {
            FB.XFBML.parse(container);
        }
        if(typeof window.adsbygoogle !== "undefined") {
            try {
                (adsbygoogle = window.adsbygoogle || []).push({});
            } catch(e) {}
        }
        nextPage++;
        loading=false;
    })
    .catch(error => {
        console.error("Failed to load next block:", error);
        loading=false;
    });
}

window.addEventListener("scroll", () => {
    const lastBlock = document.querySelector(".auto_load_next:last-of-type");
    if(!lastBlock) return;
    const loader = lastBlock.querySelector(".load_next");
    if(!loader) return;
    const rect = loader.getBoundingClientRect();
    if(!loading && rect.top < window.innerHeight && rect.bottom >= 0) {
        loadNextBlock();
    }
});

window.addEventListener("scroll", debounce(updateTitleAndUrl, 100), {passive: true});
</script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<!-- TTS Player - আগের ডিজাইন অপরিবর্তিত -->
<?php
$tts_check_conn = new mysqli('localhost', 'mahamudf_skytimesphp', 'mahamudf_skytimesphp', 'mahamudf_skytimesphp');
$tts_status_result = $tts_check_conn->query("SELECT setting_value FROM mahamudfutureit_tts_settings WHERE setting_key = 'tts_enabled'");
$tts_is_enabled = ($tts_status_result->num_rows > 0 && $tts_status_result->fetch_assoc()['setting_value'] == '1');

if($tts_is_enabled) {
    $tts_post_title = html_entity_decode($the_post['PostTitle'], ENT_QUOTES, 'UTF-8');
    $tts_post_content = strip_tags($the_post['PostContent']);
    $tts_post_image = articleImg($the_post['PostId'], 'featured');
    
    $color_conn = new mysqli('localhost', 'mahamudf_skytimesphp', 'mahamudf_skytimesphp', 'mahamudf_skytimesphp');
    $colors = [];
    $result = $color_conn->query("SELECT color_key, color_value FROM mahamudfutureit_tts_colors");
    while($row = $result->fetch_assoc()) {
        $colors[$row['color_key']] = $row['color_value'];
    }
    
    $primary_color = $colors['primary_color'] ?? '#6366f1';
    $secondary_color = $colors['secondary_color'] ?? '#a855f7';
    $wave_color = $colors['wave_color'] ?? '#6366f1';
    $progress_color = $colors['progress_color'] ?? '#6366f1';
    $play_bg = $colors['play_bg'] ?? '#ffffff';
    $play_icon = $colors['play_icon'] ?? '#1e293b';
    $text_color = $colors['text_color'] ?? '#f1f5f9';
    $bg_start = $colors['bg_start'] ?? '#1e293b';
    $bg_end = $colors['bg_end'] ?? '#0f172a';
    ?>

<style>
.mft-tts-player {
    position: fixed;
    bottom: 20px;
    right: 20px;
    z-index: 99999;
    width: 340px;
    background: linear-gradient(135deg, <?php echo $bg_start; ?> 0%, <?php echo $bg_end; ?> 100%);
    border-radius: 12px;
    padding: 10px 15px 10px 12px;
    box-shadow: 0 8px 25px rgba(0,0,0,0.3), 0 0 0 1px rgba(255,255,255,0.08);
    font-family: inherit;
    opacity: 0;
    transform: translateY(100px);
    animation: slideUpPlayer 0.5s cubic-bezier(0.2, 0.9, 0.4, 1.1) forwards;
}

@keyframes slideUpPlayer {
    0% {
        opacity: 0;
        transform: translateY(100px);
    }
    100% {
        opacity: 1;
        transform: translateY(0);
    }
}

.mft-tts-player:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 30px rgba(0,0,0,0.4);
    transition: all 0.3s ease;
}

.mft-tts-inner {
    display: flex;
    align-items: center;
    gap: 12px;
}

.mft-tts-album {
    width: 45px;
    height: 45px;
    border-radius: 8px;
    background-size: cover;
    background-position: center;
    background-color: #334155;
    flex-shrink: 0;
    box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}

.mft-tts-content {
    flex: 1;
    min-width: 0;
}

.mft-tts-title {
    font-size: 11px;
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    margin-bottom: 6px;
}

.mft-tts-title marquee {
    font-size: 11px;
    font-weight: 500;
    color: <?php echo $text_color; ?>;
}

.mft-tts-controls {
    display: flex;
    align-items: center;
    gap: 8px;
}

.mft-tts-progress-area {
    flex: 1;
    height: 3px;
    background: #334155;
    border-radius: 3px;
    cursor: pointer;
    position: relative;
}

.mft-tts-progress-fill {
    width: 0%;
    height: 100%;
    background: linear-gradient(90deg, <?php echo $progress_color; ?>, <?php echo $secondary_color; ?>);
    border-radius: 3px;
    position: relative;
}

.mft-tts-progress-fill::after {
    content: '';
    position: absolute;
    right: -5px;
    top: -3.5px;
    width: 10px;
    height: 10px;
    background: white;
    border-radius: 50%;
    opacity: 0;
    transition: opacity 0.2s;
    box-shadow: 0 1px 3px rgba(0,0,0,0.2);
}

.mft-tts-progress-area:hover .mft-tts-progress-fill::after {
    opacity: 1;
}

.mft-tts-time {
    font-size: 9px;
    color: <?php echo $text_color; ?>80;
    font-family: monospace;
    min-width: 65px;
    text-align: right;
}

.mft-tts-buttons {
    display: flex;
    align-items: center;
    gap: 10px;
}

.mft-tts-buttons i {
    cursor: pointer;
    font-size: 14px;
    color: <?php echo $text_color; ?>;
    transition: all 0.2s;
}

.mft-tts-buttons i:hover {
    color: <?php echo $primary_color; ?>;
    transform: scale(1.1);
}

.mft-tts-play {
    width: 32px;
    height: 32px;
    background: <?php echo $play_bg; ?>;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
    box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}

.mft-tts-play:hover {
    transform: scale(1.05);
    background: <?php echo $play_bg; ?>dd;
}

.mft-tts-play i {
    font-size: 12px;
    color: <?php echo $play_icon; ?>;
    margin-left: 2px;
}

.mft-tts-speed {
    display: flex;
    align-items: center;
    gap: 4px;
    background: <?php echo $bg_end; ?>;
    padding: 3px 8px;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s;
}

.mft-tts-speed:hover {
    background: <?php echo $primary_color; ?>40;
}

.mft-tts-speed i {
    font-size: 10px;
    margin: 0;
    color: <?php echo $text_color; ?>;
}

.mft-tts-speed span {
    font-size: 10px;
    font-weight: 600;
    color: <?php echo $text_color; ?>;
}

.mft-tts-wave {
    display: flex;
    align-items: center;
    gap: 2px;
    height: 20px;
}

.mft-tts-wave span {
    width: 3px;
    background: <?php echo $wave_color; ?>;
    border-radius: 2px;
    transition: height 0.1s ease;
    height: 6px;
}

.mft-tts-wave.playing span {
    animation: mftWaveAnim 0.6s ease infinite alternate;
}

.mft-tts-wave.playing span:nth-child(1) { animation-delay: 0s; }
.mft-tts-wave.playing span:nth-child(2) { animation-delay: 0.08s; }
.mft-tts-wave.playing span:nth-child(3) { animation-delay: 0.16s; }
.mft-tts-wave.playing span:nth-child(4) { animation-delay: 0.24s; }
.mft-tts-wave.playing span:nth-child(5) { animation-delay: 0.32s; }
.mft-tts-wave.playing span:nth-child(6) { animation-delay: 0.40s; }

@keyframes mftWaveAnim {
    0% { height: 4px; opacity: 0.5; }
    100% { height: 18px; opacity: 1; }
}

@media (max-width: 768px) {
    .mft-tts-player {
        width: calc(100% - 30px);
        left: 15px;
        right: 15px;
        bottom: 10px;
        border-radius: 12px;
    }
}
</style>

<div class="mft-tts-player" id="mftTTSPlayer">
    <div class="mft-tts-inner">
        <div class="mft-tts-album" id="mftAlbum" style="background-image: url('<?php echo htmlspecialchars($tts_post_image); ?>');"></div>
        <div class="mft-tts-content">
            <div class="mft-tts-title">
                <marquee scrollamount="2" id="mftMarquee"><?php echo htmlspecialchars($tts_post_title); ?></marquee>
            </div>
            <div class="mft-tts-controls">
                <div class="mft-tts-wave" id="mftWave">
                    <span></span><span></span><span></span><span></span><span></span><span></span>
                </div>
                <div class="mft-tts-progress-area" id="mftProgressArea">
                    <div class="mft-tts-progress-fill" id="mftProgressFill"></div>
                </div>
                <div class="mft-tts-time">
                    <span id="mftCurrent">0:00</span> / <span id="mftTotal">0:00</span>
                </div>
            </div>
        </div>
        <div class="mft-tts-buttons">
            <i class="fas fa-backward" id="mftPrevBtn"></i>
            <div class="mft-tts-play" id="mftPlayBtn">
                <i class="fas fa-play" id="mftPlayIcon"></i>
            </div>
            <i class="fas fa-forward" id="mftNextBtn"></i>
            <div class="mft-tts-speed" id="mftSpeedBtn">
                <i class="fas fa-tachometer-alt"></i>
                <span id="mftSpeedText">1x</span>
            </div>
        </div>
    </div>
</div>

<script>
(function() {
    const postContent = <?php echo json_encode($tts_post_content); ?>;
    const apiUrl = '/mahamudfutureit_tts_api.php';
    
    if (!postContent || postContent.length < 30) return;
    
    let textChunks = [];
    let currentIndex = 0;
    let currentAudio = null;
    let isPlaying = false;
    let isPaused = false;
    let chunkDurations = [];
    let totalDuration = 0;
    let progressInterval;
    let currentSpeed = 1.0;
    
    const waveContainer = document.getElementById('mftWave');
    const playIcon = document.getElementById('mftPlayIcon');
    const progressFill = document.getElementById('mftProgressFill');
    const currentTimeEl = document.getElementById('mftCurrent');
    const totalTimeEl = document.getElementById('mftTotal');
    const speedBtn = document.getElementById('mftSpeedBtn');
    const speedText = document.getElementById('mftSpeedText');
    const progressArea = document.getElementById('mftProgressArea');
    const playBtn = document.getElementById('mftPlayBtn');
    const prevBtn = document.getElementById('mftPrevBtn');
    const nextBtn = document.getElementById('mftNextBtn');
    const marquee = document.getElementById('mftMarquee');
    
    const speeds = [0.75, 1.0, 1.25, 1.5];
    let speedIndex = 1;
    
    function formatTime(sec) {
        if (isNaN(sec) || sec < 0) return '0:00';
        let m = Math.floor(sec / 60);
        let s = Math.floor(sec % 60);
        return m + ':' + (s < 10 ? '0' + s : s);
    }
    
    function splitTextIntoChunks(text) {
        text = text.replace(/\n/g, ' ');
        let sentences = text.split(/(?<=[।?!;:])/g);
        let chunks = [];
        for (let s of sentences) {
            s = s.trim();
            if (!s) continue;
            if (s.length > 200) {
                let words = s.split(' ');
                let current = '';
                for (let w of words) {
                    if ((current + ' ' + w).length <= 200) {
                        current += (current ? ' ' : '') + w;
                    } else {
                        if (current) chunks.push(current);
                        current = w;
                    }
                }
                if (current) chunks.push(current);
            } else {
                chunks.push(s);
            }
        }
        return chunks;
    }
    
    function estimateChunkDurations(chunks) {
        let durations = [], total = 0;
        for (let c of chunks) {
            let d = Math.max(1.5, c.length / 12);
            durations.push(d);
            total += d;
        }
        return { durations, total };
    }
    
    function updateWaveform(playing) {
        if (playing) {
            waveContainer.classList.add('playing');
        } else {
            waveContainer.classList.remove('playing');
        }
    }
    
    function playChunk(startTime = 0) {
        if (currentIndex >= textChunks.length || currentIndex < 0) {
            stopTTS();
            return;
        }
        
        isPlaying = true;
        isPaused = false;
        playIcon.className = 'fas fa-pause';
        updateWaveform(true);
        
        if (currentAudio) {
            currentAudio.pause();
        }
        
        currentAudio = new Audio();
        let url = apiUrl + '?q=' + encodeURIComponent(textChunks[currentIndex]);
        currentAudio.src = url;
        currentAudio.playbackRate = currentSpeed;
        currentAudio.preservesPitch = true;
        
        currentAudio.onended = function() {
            currentIndex++;
            playChunk();
        };
        
        currentAudio.onerror = function() {
            currentIndex++;
            playChunk();
        };
        
        currentAudio.onloadedmetadata = function() {
            if (startTime > 0) currentAudio.currentTime = startTime;
            currentAudio.play().catch(e => console.log(e));
        };
        
        startProgress();
    }
    
    function startProgress() {
        clearInterval(progressInterval);
        progressInterval = setInterval(() => {
            if (!isPlaying || isPaused || !currentAudio) return;
            
            let elapsed = 0;
            for (let i = 0; i < currentIndex; i++) elapsed += chunkDurations[i];
            elapsed += currentAudio.currentTime;
            
            currentTimeEl.innerText = formatTime(elapsed);
            let percent = (elapsed / totalDuration) * 100;
            if (percent > 100) percent = 100;
            progressFill.style.width = percent + '%';
        }, 150);
    }
    
    function stopTTS() {
        if (currentAudio) {
            currentAudio.pause();
            currentAudio.currentTime = 0;
            currentAudio = null;
        }
        currentIndex = 0;
        isPlaying = false;
        isPaused = false;
        clearInterval(progressInterval);
        progressFill.style.width = '0%';
        currentTimeEl.innerText = '0:00';
        playIcon.className = 'fas fa-play';
        updateWaveform(false);
        if(marquee) marquee.start();
    }
    
    function startTTS() {
        stopTTS();
        textChunks = splitTextIntoChunks(postContent);
        if (textChunks.length === 0) return;
        
        let { durations, total } = estimateChunkDurations(textChunks);
        chunkDurations = durations;
        totalDuration = total;
        totalTimeEl.innerText = formatTime(totalDuration);
        currentIndex = 0;
        playChunk();
    }
    
    playBtn.onclick = function() {
        if (isPlaying && !isPaused && currentAudio) {
            currentAudio.pause();
            isPaused = true;
            playIcon.className = 'fas fa-play';
            updateWaveform(false);
            if(marquee) marquee.stop();
        } else if (isPlaying && isPaused && currentAudio) {
            currentAudio.play();
            isPaused = false;
            playIcon.className = 'fas fa-pause';
            updateWaveform(true);
            if(marquee) marquee.start();
        } else {
            startTTS();
        }
    };
    
    nextBtn.onclick = function() {
        if (isPlaying) {
            currentIndex++;
            playChunk();
        }
    };
    
    prevBtn.onclick = function() {
        if (isPlaying) {
            if (currentIndex > 0) {
                currentIndex--;
                playChunk();
            } else if (currentAudio) {
                currentAudio.currentTime = 0;
            }
        }
    };
    
    speedBtn.onclick = function() {
        speedIndex = (speedIndex + 1) % speeds.length;
        currentSpeed = speeds[speedIndex];
        speedText.innerText = currentSpeed + 'x';
        if (currentAudio) currentAudio.playbackRate = currentSpeed;
    };
    
    progressArea.onclick = function(e) {
        if (!totalDuration || !currentAudio) return;
        let rect = progressArea.getBoundingClientRect();
        let percent = (e.clientX - rect.left) / rect.width;
        let target = percent * totalDuration;
        
        let acc = 0;
        for (let i = 0; i < chunkDurations.length; i++) {
            if (acc + chunkDurations[i] >= target) {
                currentIndex = i;
                playChunk(target - acc);
                return;
            }
            acc += chunkDurations[i];
        }
    };
    
    if(marquee) marquee.start();
})();
</script>

<?php
}

require_once(__DIR__ . '/../footer.php');
?>
