import React from "react";
import Link from "next/link";
import Image from "next/image";
import { ScrollReveal } from "@/animations/Reveal";
import BlogSidebar from "@/components/blog/BlogSidebar";
import {
  type BlogPost,
  type ContentBlock,
  formatDate,
  estimateReadingTime,
} from "@/data/blog";

function ContentRenderer({ block }: { block: ContentBlock }) {
  switch (block.type) {
    case "paragraph":
      return <p className="dm-article-p">{block.text}</p>;
    case "heading":
      return block.level === 2 ? (
        <h2 className="dm-article-h2">{block.text}</h2>
      ) : (
        <h3 className="dm-article-h3">{block.text}</h3>
      );
    case "list":
      return block.ordered ? (
        <ol className="dm-article-ol">
          {block.items.map((it, i) => (
            <li key={i}>{it}</li>
          ))}
        </ol>
      ) : (
        <ul className="dm-article-ul">
          {block.items.map((it, i) => (
            <li key={i}>{it}</li>
          ))}
        </ul>
      );
    case "quote":
      return (
        <blockquote className="dm-article-quote">
          <p>{block.text}</p>
          {block.cite && <cite>{block.cite}</cite>}
        </blockquote>
      );
    case "image":
      return (
        <figure className="dm-article-figure">
          <span className="dm-article-figure-img">
            <Image
              src={block.src}
              alt={block.alt}
              fill
              sizes="(max-width: 768px) 100vw, 760px"
              style={{ objectFit: "cover" }}
            />
          </span>
          {block.caption && <figcaption>{block.caption}</figcaption>}
        </figure>
      );
    default:
      return null;
  }
}

export default function SingleBlog({ post }: { post: BlogPost }) {
  const readingTime = estimateReadingTime(post);

  // Banner background: a subtle dark overlay over the article's featured image,
  // light enough to let the photograph remain the primary visual element.
  const bannerStyle = {
    backgroundImage: `url(${post.image})`,
    "--hero-overlay":
      "linear-gradient(180deg, rgba(0,0,0,0.38) 0%, rgba(0,0,0,0.46) 55%, rgba(0,0,0,0.60) 100%)",
  } as React.CSSProperties;

  return (
    <article className="dm-single-blog">
      <link rel="preload" as="image" href={post.image} />
      <style dangerouslySetInnerHTML={{ __html: STYLES }} />

      {/* ── Full-width page banner (image + badge + title only) ──────── */}
      <div className="custom-standard-hero-container">
        <div className="custom-standard-hero-card dm-banner-card" style={bannerStyle}>
          <div className="e-con-inner dm-banner-inner">
            <span className="dm-banner-category">{post.category}</span>
            <h1 className="dm-banner-title">{post.title}</h1>
          </div>
        </div>
      </div>

      {/* ── Article meta bar (breadcrumb + author / date / reading time) ── */}
      <div className="dm-blog-wrap">
        <div className="dm-meta-bar">
          <nav className="dm-meta-breadcrumb" aria-label="Breadcrumb">
            <ol>
              <li>
                <Link href="/">Home</Link>
              </li>
              <li aria-hidden="true" className="dm-meta-sep">/</li>
              <li>
                <Link href="/blog">Blog</Link>
              </li>
              <li aria-hidden="true" className="dm-meta-sep">/</li>
              <li aria-current="page" className="dm-meta-current">
                {post.title}
              </li>
            </ol>
          </nav>

          <div className="dm-meta-items">
            <span className="dm-meta-item dm-meta-author">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" /><circle cx="12" cy="7" r="4" />
              </svg>
              {post.author}
            </span>
            <span className="dm-meta-item">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <rect x="3" y="4" width="18" height="18" rx="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" />
              </svg>
              <time dateTime={post.date}>{formatDate(post.date)}</time>
            </span>
            <span className="dm-meta-item">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <circle cx="12" cy="12" r="9" /><polyline points="12 7 12 12 15 14" />
              </svg>
              {readingTime} min read
            </span>
          </div>
        </div>

        {/* ── Content + sidebar ──────────────────────────────────────── */}
        <div className="dm-blog-layout">
          <div className="dm-blog-main">
            <p className="dm-blog-intro">{post.intro}</p>

            <div className="dm-article-body">
              {post.content.map((block, i) => (
                <ScrollReveal key={i} delay={0} duration={0.6} yOffset={20}>
                  <ContentRenderer block={block} />
                </ScrollReveal>
              ))}
            </div>
          </div>

          <div className="dm-blog-aside-wrap">
            <BlogSidebar current={post} />
          </div>
        </div>
      </div>
    </article>
  );
}

const STYLES = `
  .dm-single-blog {
    --dm-red: #c01227;
    --dm-red-hover: #e31d32;
    --dm-radius-card: 22px;
    --dm-radius-img: 20px;
    --dm-radius-badge: 8px;
    --dm-shadow-card: 0 4px 24px rgba(15, 23, 42, 0.05);
    --dm-border: 1px solid rgba(15, 23, 42, 0.09);
    --dm-space-p: 24px;
    --dm-space-h: 32px;
    --dm-space-img: 32px;
    --dm-space-quote: 40px;
    --dm-sticky-top: 138px;
    --dm-measure: min(1100px, 100%);
    font-family: var(--font-manrope), sans-serif;
  }

  /* Heading normalization. Beat the global theme's .elementor-kit-5 h1-h6
     (120/80/60px UPPERCASE) rules with !important on our own classes. */
  .dm-single-blog :where(h1, h2, h3, h4, h5, h6) {
    font-family: var(--font-manrope), sans-serif !important;
    text-transform: none !important;
    font-style: normal !important;
    font-weight: 800;
  }
  /* Neutralize the theme's .elementor-kit-5 a (red color + underline,
     specificity 0-1-1) so blog links keep our colors and never get underlined. */
  .dm-single-blog a { text-decoration: none !important; }

  /* Page banner: tall homepage-scale frame with only badge + title inside */
  /* Compound selector (specificity 20) + !important beats the global 800px
     single-class height rules so the blog banner can use viewport heights. */
  .custom-standard-hero-card.dm-banner-card {
    height: 90vh !important;
    min-height: 85vh !important;
  }
  @media (max-width: 1024px) {
    .custom-standard-hero-card.dm-banner-card { height: 80vh !important; min-height: 75vh !important; }
  }
  @media (max-width: 600px) {
    .custom-standard-hero-card.dm-banner-card { height: 78vh !important; min-height: 72vh !important; }
  }

  .dm-banner-inner {
    position: relative; width: 100%; height: 100%;
    display: flex; flex-direction: column; align-items: center; justify-content: center;
    text-align: center; gap: clamp(22px, 2.6vw, 34px);
    padding: clamp(48px, 8vh, 96px) clamp(20px, 5vw, 48px);
  }

  .dm-banner-category {
    display: inline-block; background: var(--dm-red); color: #fff;
    font-size: 12px; font-weight: 800; text-transform: uppercase; letter-spacing: 1.6px;
    padding: 9px 18px; border-radius: 999px; box-shadow: 0 8px 22px rgba(192,18,39,0.45);
  }
  .dm-banner-title {
    font-family: var(--font-manrope), sans-serif !important;
    font-size: clamp(34px, 5vw, 60px) !important; font-weight: 850 !important;
    line-height: 1.16 !important; letter-spacing: -1.2px !important;
    color: #ffffff !important; margin: 0; max-width: 820px;
    text-wrap: balance; text-shadow: 0 2px 30px rgba(0,0,0,0.38);
  }
  @media (max-width: 1024px) { .dm-banner-title { font-size: clamp(32px, 6vw, 48px) !important; max-width: 90%; } }
  @media (max-width: 600px)  { .dm-banner-title { font-size: clamp(28px, 8vw, 38px) !important; max-width: 90%; } }

  /* Content wrap begins immediately below the banner */
  /* Shared content container: the SAME max-width + horizontal padding is used
     by BlogPostFooter (.dm-blog-footer-inner) so the article body, headings,
     images, Prev/Next, Related Articles and the CTA banner all align to one
     grid with identical left/right edges. Keep both in sync. */
  .dm-blog-wrap {
    max-width: 1280px; margin: 0 auto;
    /* 20px mobile padding floor → 40px on desktop; matches the footer container. */
    padding: clamp(14px, 2vw, 26px) clamp(20px, 4vw, 40px) 0;
  }
  @media (max-width: 767px) {
    .dm-blog-wrap {
      padding-left: 16px;
      padding-right: 16px;
    }
  }

  /* ── Article meta bar (directly under the hero) ── */
  .dm-meta-bar {
    display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 14px 24px;
    padding: clamp(20px, 2.6vw, 30px) 0; margin-bottom: clamp(26px, 3vw, 44px);
    border-bottom: 1px solid rgba(15,23,42,0.10);
  }
  .dm-meta-breadcrumb ol {
    list-style: none; display: flex; flex-wrap: wrap; align-items: center;
    gap: 8px; margin: 0; padding: 0; font-size: 13px; font-weight: 600; color: #64748b;
  }
  .dm-meta-breadcrumb a { color: #64748b !important; text-decoration: none; transition: color .2s ease; }
  .dm-meta-breadcrumb a:hover { color: var(--dm-red) !important; }
  .dm-meta-sep { color: #cbd5e1; }
  .dm-meta-current {
    color: #0f172a; font-weight: 700;
    max-width: min(40ch, 46vw); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  }
  @media (max-width: 600px) { .dm-meta-current { max-width: 56vw; } }
  .dm-meta-items { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 20px; }
  .dm-meta-item {
    display: inline-flex; align-items: center; gap: 7px;
    font-size: 13.5px; font-weight: 600; color: #475569;
  }
  .dm-meta-item svg { color: var(--dm-red); flex: 0 0 auto; }
  .dm-meta-author { color: #0f172a; font-weight: 700; }
  @media (max-width: 600px) { .dm-meta-bar { gap: 12px; } }
  .dm-blog-layout {
    display: grid; grid-template-columns: minmax(0,1fr) 320px;
    /* Tighter gap gives the reading column more room next to the 320px sidebar. */
    gap: clamp(28px, 3vw, 56px); align-items: start;
  }
  @media (max-width: 1024px) {
    .dm-blog-layout { grid-template-columns: 1fr; gap: 48px; }
    /* Single-column (tablet/mobile): cap the reading column and centre it so the
       article never sits left-aligned with a large empty right gutter. */
    .dm-blog-main { max-width: 900px; margin-inline: auto; }
  }
  .dm-blog-main { min-width: 0; }

  /* ── Intro lead ── */
  .dm-blog-intro {
    max-width: var(--dm-measure);
    font-size: clamp(18px, 1.5vw, 20px); line-height: 1.65; font-weight: 500;
    color: #475569; margin: 0 0 clamp(26px, 3vw, 38px); padding-left: 20px;
    border-left: 3px solid var(--dm-red);
  }

  /* ── Article body ── */
  .dm-article-body { max-width: var(--dm-measure); }
  .dm-article-p {
    font-size: 18px !important; line-height: 1.8 !important; color: #334155; font-weight: 450;
    margin: 0 0 var(--dm-space-p);
  }
  .dm-article-h2 {
    font-size: clamp(23px, 2vw, 30px) !important; font-weight: 800 !important; letter-spacing: -.3px !important;
    color: #0f172a !important; line-height: 1.3 !important; margin: 48px 0 var(--dm-space-h);
    text-wrap: balance;
  }
  /* Each article block is wrapped in its OWN ScrollReveal <div>, so a bare
     :first-child rule matched every heading (each is the only child of its
     wrapper) and zeroed its top margin, collapsing the gap above every
     section heading. Scope the reset to only the article body's first block. */
  .dm-article-body > :first-child :where(.dm-article-h2, .dm-article-h3),
  .dm-article-body > .dm-article-h2:first-child,
  .dm-article-body > .dm-article-h3:first-child { margin-top: 0; }
  .dm-article-h3 {
    font-size: clamp(19px, 1.5vw, 23px) !important; font-weight: 800 !important; letter-spacing: -.2px !important;
    color: #1e293b !important; line-height: 1.34 !important; margin: 40px 0 18px;
    text-wrap: balance;
  }
  @media (max-width: 600px) {
    .dm-article-p { font-size: 16px !important; }
    .dm-article-ul li, .dm-article-ol li { font-size: 15.5px; }
    .dm-article-h2 { font-size: clamp(22px, 6vw, 28px) !important; margin-top: 38px; }
    .dm-article-h3 { font-size: clamp(18px, 5vw, 22px) !important; }
  }

  .dm-article-ul, .dm-article-ol {
    /* Top margin (was 0) separates the list from the paragraph above it;
       matching bottom margin keeps it clear of the next heading/paragraph.
       Slightly larger than --dm-space-p so the list reads as its own block. */
    margin: clamp(26px, 2.4vw, 32px) 0 clamp(26px, 2.4vw, 32px);
    padding-left: 2px; list-style: none;
    display: flex; flex-direction: column; gap: 15px;
  }
  /* Prefixed with .dm-article-body so these beat the theme's global
     ".logico-front-end ul li:before" fontello-glyph bullet (specificity 0,1,3),
     which otherwise replaces our clean red dot with a misaligned checkmark glyph
     and adds its own 1.7em indent. */
  .dm-article-body .dm-article-ul li, .dm-article-body .dm-article-ol li {
    position: relative; padding-left: 34px;
    font-size: 17px; line-height: 1.65; color: #334155; font-weight: 450;
  }
  .dm-article-body .dm-article-ul li::before {
    content: ""; position: absolute; left: 7px; top: 10px;
    width: 8px; height: 8px; border-radius: 50%; background: var(--dm-red);
    /* kill any inherited fontello glyph from the global rule */
    font-size: 0; line-height: 0;
  }
  .dm-article-ol { counter-reset: dm-li; }
  .dm-article-body .dm-article-ol li { counter-increment: dm-li; }
  .dm-article-body .dm-article-ol li::before {
    content: counter(dm-li); position: absolute; left: 0; top: 0;
    width: 24px; height: 24px; border-radius: 7px;
    background: rgba(192,18,39,0.10); color: var(--dm-red);
    font-size: 12px; font-weight: 800; display: flex; align-items: center; justify-content: center;
  }

  /* ── Quote ── */
  .dm-article-quote {
    position: relative; margin: var(--dm-space-quote) 0; padding: 30px 32px 30px 64px;
    background: linear-gradient(135deg, #fbf2f3 0%, #fdf7f8 100%);
    border-left: 4px solid var(--dm-red); border-radius: 0 18px 18px 0;
    box-shadow: 0 8px 28px rgba(192, 18, 39, 0.06);
  }
  .dm-article-quote::before {
    content: "\\201C"; position: absolute; left: 22px; top: 8px;
    font-family: Georgia, "Times New Roman", serif;
    font-size: 64px; line-height: 1; color: rgba(192, 18, 39, 0.28); font-weight: 700;
  }
  .dm-article-quote p {
    font-size: clamp(19px, 2vw, 23px); line-height: 1.5; font-weight: 600;
    font-style: italic; color: #1e293b; margin: 0;
  }
  .dm-article-quote cite {
    display: block; margin-top: 16px; font-size: 13px; font-weight: 700;
    font-style: normal; color: var(--dm-red); text-transform: uppercase; letter-spacing: .6px;
  }
  @media (max-width: 600px) { .dm-article-quote { padding: 26px 22px; } .dm-article-quote::before { display: none; } }

  /* ── Images ── */
  .dm-article-figure { margin: var(--dm-space-img) 0; }
  .dm-article-figure-img {
    position: relative; display: block; width: 100%; aspect-ratio: 16 / 9;
    border-radius: var(--dm-radius-img); overflow: hidden; box-shadow: 0 14px 34px rgba(15,23,42,0.10);
  }
  .dm-article-figure figcaption {
    margin-top: 14px; font-size: 13.5px; color: #94a3b8; font-weight: 500;
    text-align: center; font-style: italic;
  }

  /* ── Sidebar ── */
  .dm-blog-aside-wrap { position: relative; }
  .dm-blog-sidebar {
    display: flex; flex-direction: column; gap: 18px;
    position: sticky; top: var(--dm-sticky-top);
  }
  @media (max-width: 1024px) { .dm-blog-sidebar { position: static; gap: 20px; } }

  .dm-blog-widget {
    background: #fff; border: var(--dm-border); border-radius: var(--dm-radius-card);
    padding: 20px; box-shadow: var(--dm-shadow-card);
  }
  .dm-blog-widget-title {
    font-size: 13px !important; font-weight: 700 !important; text-transform: uppercase !important;
    letter-spacing: .8px !important; line-height: 1.35 !important; color: #0f172a !important;
    margin: 0 0 15px; padding: 0 0 12px;
    border-bottom: 1px solid rgba(15,23,42,0.08);
    overflow: visible; white-space: normal; word-break: normal;
  }

  /* Search */
  .dm-sr-only {
    position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
    overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0;
  }
  .dm-blog-search { position: relative; }
  .dm-blog-search-form { position: relative; }
  .dm-blog-search-input {
    width: 100%; height: 46px; border: 1.5px solid #e2e8f0; border-radius: 12px;
    padding: 0 42px 0 15px; font-size: 14px; font-family: inherit; color: #0f172a;
    background: #f8fafc; transition: border-color .2s ease, box-shadow .2s ease, background .2s ease;
  }
  .dm-blog-search-input::placeholder { color: #9c9c9c; }
  .dm-blog-search-input:focus {
    outline: none; border-color: var(--dm-red); background: #fff;
    box-shadow: 0 0 0 3px rgba(192,18,39,0.11);
  }
  .dm-blog-search-icon {
    position: absolute; right: 14px; top: 50%; transform: translateY(-50%);
    color: #94a3b8; pointer-events: none; display: flex;
  }
  .dm-blog-search-results {
    position: absolute; z-index: 20; top: calc(100% + 8px); left: 0; right: 0;
    background: #fff; border: 1px solid rgba(15,23,42,0.10); border-radius: 14px;
    box-shadow: 0 18px 42px rgba(15,23,42,0.14); overflow: hidden;
  }
  .dm-blog-search-results ul { list-style: none; margin: 0; padding: 6px; }
  .dm-blog-search-result {
    display: flex; flex-direction: column; gap: 3px; padding: 10px 12px;
    border-radius: 10px; text-decoration: none; transition: background .15s ease;
  }
  .dm-blog-search-result:hover { background: #f8fafc; }
  .dm-blog-search-result-cat {
    font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .8px; color: var(--dm-red);
  }
  .dm-blog-search-result-title { font-size: 13.5px; font-weight: 600; color: #1e293b; line-height: 1.35; }
  .dm-blog-search-empty { margin: 0; padding: 14px 12px; font-size: 13px; color: #64748b; }

  /* Recent posts */
  .dm-blog-recent { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 15px; }
  .dm-blog-recent-item { display: flex; gap: 13px; align-items: center; text-decoration: none; }
  .dm-blog-recent-thumb {
    position: relative; flex: 0 0 62px; width: 62px; height: 62px;
    border-radius: 13px; overflow: hidden; background: #f1f5f9;
  }
  .dm-blog-recent-meta { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
  .dm-blog-recent-title {
    font-size: 13.5px; font-weight: 700; color: #1e293b; line-height: 1.35;
    display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
    transition: color .2s ease;
  }
  .dm-blog-recent-item:hover .dm-blog-recent-title { color: var(--dm-red); }
  .dm-blog-recent-date { font-size: 11.5px; font-weight: 600; color: #94a3b8; }

  /* Categories */
  .dm-blog-categories { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; }
  .dm-blog-category-item {
    display: flex; align-items: center; justify-content: space-between; gap: 10px;
    padding: 11px 2px; text-decoration: none; font-size: 14px; font-weight: 600; color: #334155 !important;
    border-bottom: 1px solid rgba(15,23,42,0.06); transition: color .2s ease, padding-left .2s ease;
  }
  .dm-blog-categories li:last-child .dm-blog-category-item { border-bottom: none; }
  .dm-blog-category-item:hover { color: var(--dm-red); padding-left: 6px; }
  .dm-blog-category-item > span:first-child { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .dm-blog-category-count {
    flex: 0 0 auto; font-size: 11px; font-weight: 800; color: #94a3b8; background: #f1f5f9;
    min-width: 24px; height: 22px; border-radius: 7px; display: inline-flex;
    align-items: center; justify-content: center; padding: 0 7px;
  }

  /* CTA card */
  .dm-blog-cta-card { background: #1f1f1f; border-color: #1f1f1f; }
  .dm-blog-cta-title { font-size: 18px !important; font-weight: 800 !important; color: #fff !important; line-height: 1.32 !important; margin: 0 0 10px; letter-spacing: -.2px !important; }
  .dm-blog-cta-text { font-size: 13.5px; line-height: 1.6; color: #c7c7c7; margin: 0 0 20px; font-weight: 450; }
  .dm-blog-cta-btn {
    display: inline-flex; align-items: center; gap: 8px;
    background: var(--dm-red); color: #fff !important; font-size: 13.5px; font-weight: 700;
    padding: 12px 22px; border-radius: 12px; text-decoration: none;
    transition: background .2s ease, transform .2s ease;
  }
  .dm-blog-cta-btn:hover { background: var(--dm-red-hover); transform: translateY(-2px); }
`;
