import { For, Show, createMemo } from "solid-js";
import { Title } from "@solidjs/meta";
import { A, useParams } from "@solidjs/router";
import { cn } from "~/lib/utils";
import { Badge, Card, Button } from "~/components/ui";
import PageContainer from "~/components/layout/PageContainer";

interface BlogPost {
  slug: string;
  title: string;
  excerpt: string;
  content: string;
  author: string;
  authorRole: string;
  date: string;
  readingTime: string;
  coverImage: string;
  tags: string[];
}

const blogPosts: BlogPost[] = [
  {
    slug: "ai-scam-trends-2026",
    title: "AI Scam Trends to Watch in 2026",
    excerpt: "As AI technology advances, scammers are finding new ways to exploit it.",
    content: `## The Rise of AI-Powered Scams

Artificial intelligence has become a double-edged sword. While it powers innovation across industries, it also arms bad actors with sophisticated tools for deception.

### Voice Cloning Scams

One of the most alarming trends is the use of AI voice cloning. Scammers need only a few seconds of audio—often scraped from social media videos—to create convincing voice replicas. These are used to impersonate family members in distress, requesting urgent money transfers.

### Deepfake Video Conferencing

In 2025, we saw the first wave of deepfake video calls used in corporate impersonation scams. Attackers use real-time face-swapping technology to pose as executives during Zoom calls, authorizing fraudulent wire transfers.

### Automated Phishing at Scale

AI-generated phishing emails are now nearly indistinguishable from legitimate correspondence. Language models craft personalized messages that reference real events, contacts, and context, dramatically increasing click-through rates.

## How to Protect Yourself

1. **Verify voice requests** — If someone calls asking for money or sensitive information, hang up and call them back on a trusted number.
2. **Use a safe word** — Establish a family safe word that can be used to verify identity in suspicious situations.
3. **Enable ShieldAI VoicePrint** — Our AI detects voice clones by analyzing acoustic fingerprints that deepfakes cannot replicate.
4. **Stay skeptical of urgency** — Scammers create false urgency to bypass your critical thinking.

## The ShieldAI Advantage

ShieldAI's multi-layered protection uses machine learning models trained on millions of scam attempts to identify emerging threats before they reach you. Our DarkWatch service continuously scans the dark web for exposed credentials, while VoicePrint protects against audio deepfakes.`,
    author: "Sarah Chen",
    authorRole: "Security Researcher",
    date: "May 15, 2026",
    readingTime: "5 min read",
    coverImage: "",
    tags: ["AI Safety", "Scam Alerts", "Deepfakes"],
  },
  {
    slug: "dark-web-monitoring-guide",
    title: "The Complete Guide to Dark Web Monitoring",
    excerpt: "Learn how dark web monitoring works and how ShieldAI keeps your information safe.",
    content: `## What Is Dark Web Monitoring?

The dark web is a hidden part of the internet where cybercriminals trade stolen data. Dark web monitoring services scan these hidden marketplaces, forums, and chat channels for your personal information.

### What Data Gets Exposed

When data breaches occur, the following types of information are commonly stolen and sold:

- **Email addresses and passwords** — The most common credential type traded on dark web markets
- **Social Security numbers** — Often used for identity theft and tax fraud
- **Credit card details** — Sold in bulk with CVV codes and billing addresses
- **Medical records** — Highly valuable on the black market for insurance fraud
- **Phone numbers** — Used for SIM swapping and phishing attacks`,
    author: "Mike Reynolds",
    authorRole: "Cybersecurity Analyst",
    date: "May 10, 2026",
    readingTime: "8 min read",
    coverImage: "",
    tags: ["Dark Web", "Privacy"],
  },
  {
    slug: "protecting-family-identity",
    title: "Protecting Your Family's Digital Identity",
    excerpt: "Discover steps to protect everyone in your household from identity theft.",
    content: `## Why Family Identity Protection Matters

Identity thieves don't discriminate. Children, elderly parents, and everyone in between are potential targets. In fact, child identity theft is particularly insidious because it often goes undetected for years.

### Common Family Identity Threats

- **Child identity theft** — Stolen SSNs used to open credit lines, often discovered when the child applies for college loans
- **Elder financial exploitation** — Scammers target seniors with tech support scams, grandparent scams, and Medicare fraud
- **Family account sharing** — Shared passwords across family streaming services can expose personal data`,
    author: "Emily Torres",
    authorRole: "Privacy Advocate",
    date: "May 5, 2026",
    readingTime: "6 min read",
    coverImage: "",
    tags: ["Identity Theft", "Privacy"],
  },
  {
    slug: "deepfake-voice-scams",
    title: "Deepfake Voice Scams: How They Work and How to Spot Them",
    excerpt: "AI-generated voice clones are being used to impersonate loved ones.",
    content: `## The Mechanics of Voice Cloning

Modern AI voice cloning requires surprisingly little source material. Just 30 seconds of audio—from a voicemail, social media video, or recorded phone call—is enough to generate a convincing voice clone.

### Real Cases

In 2024, a family in Arizona received a frantic call from what sounded like their daughter, claiming she had been kidnapped and demanding ransom. The voice was so convincing that the family almost transferred $50,000 before reaching the real daughter.

### How VoicePrint Detects Clones

VoicePrint analyzes over 200 acoustic features that are nearly impossible for AI to replicate perfectly, including micro-tremors, breathing patterns, and formant transitions unique to each person's vocal tract.`,
    author: "Sarah Chen",
    authorRole: "Security Researcher",
    date: "April 28, 2026",
    readingTime: "7 min read",
    coverImage: "",
    tags: ["Deepfakes", "AI Safety", "Scam Alerts"],
  },
  {
    slug: "what-is-data-broker",
    title: "What Is a Data Broker and How to Remove Your Information",
    excerpt: "Data brokers collect and sell your personal information.",
    content: `## Understanding Data Brokers

Data brokers are companies that collect personal information from various sources—public records, purchasing history, social media activity, and website tracking—then compile and sell this data to third parties.

### Why It Matters

Your data broker profile can include your home address, phone number, email address, income level, purchasing habits, political affiliation, and even health-related interests. This information can be used for targeted scams, identity theft, or unwanted marketing.

### How RemoveBrokers Helps

ShieldAI's RemoveBrokers service automates the opt-out process for hundreds of data broker sites, sending removal requests on your behalf and verifying that your information has been deleted.`,
    author: "Alex Kim",
    authorRole: "Data Privacy Specialist",
    date: "April 20, 2026",
    readingTime: "4 min read",
    coverImage: "",
    tags: ["Privacy", "Identity Theft"],
  },
  {
    slug: "shieldai-product-update-may-2026",
    title: "ShieldAI Product Update — May 2026",
    excerpt: "New features including improved VoicePrint detection and redesigned dashboard.",
    content: `## What's New in ShieldAI

We're excited to announce our May 2026 product update, packed with new features and improvements based on your feedback.

### Enhanced VoicePrint Detection

Our voice clone detection model has been retrained on a dataset 3x larger than before, improving detection accuracy to 99.7% while reducing false positives by 40%.

### Redesigned Dashboard

The dashboard has been completely redesigned for faster access to critical information. Key metrics are now displayed at a glance, and each service has its own dedicated section with detailed analytics.

### Expanded Dark Web Coverage

We've added monitoring for 50 additional dark web forums and marketplaces, bringing our total coverage to over 200 sources.`,
    author: "Product Team",
    authorRole: "ShieldAI",
    date: "April 15, 2026",
    readingTime: "3 min read",
    coverImage: "",
    tags: ["Product News"],
  },
];

function contentToHtml(markdown: string): string {
  const lines = markdown.split("\n");
  let html = "";
  let inList = false;

  for (const line of lines) {
    if (line.startsWith("## ")) {
      if (inList) { html += "</ul>"; inList = false; }
      html += `<h2 class="text-xl font-semibold text-[var(--color-text-primary)] mt-8 mb-3">${line.slice(3)}</h2>`;
    } else if (line.startsWith("### ")) {
      if (inList) { html += "</ul>"; inList = false; }
      html += `<h3 class="text-lg font-semibold text-[var(--color-text-primary)] mt-6 mb-2">${line.slice(4)}</h3>`;
    } else if (line.startsWith("**") && line.endsWith("**")) {
      if (inList) { html += "</ul>"; inList = false; }
      html += `<p class="font-semibold text-[var(--color-text-primary)] mt-4 mb-1">${line.slice(2, -2)}</p>`;
    } else if (line.startsWith("- ")) {
      if (!inList) { html += '<ul class="list-disc pl-6 space-y-1.5 my-3 text-[var(--color-text-secondary)]">'; inList = true; }
      html += `<li>${line.slice(2)}</li>`;
    } else if (line.match(/^\d+\. /)) {
      if (inList) { html += "</ul>"; inList = false; }
      const content = line.replace(/^\d+\. /, "");
      html += `<p class="text-[var(--color-text-secondary)] my-1">${content}</p>`;
    } else if (line.trim() === "") {
      if (inList) { html += "</ul>"; inList = false; }
    } else {
      if (inList) { html += "</ul>"; inList = false; }
      html += `<p class="text-[var(--color-text-secondary)] leading-relaxed mb-3">${line}</p>`;
    }
  }
  if (inList) html += "</ul>";
  return html;
}

function getRelatedPosts(current: BlogPost, all: BlogPost[], count: number): BlogPost[] {
  const shared = all
    .filter((p) => p.slug !== current.slug)
    .map((p) => ({
      post: p,
      sharedTags: p.tags.filter((t) => current.tags.includes(t)).length,
    }))
    .filter((p) => p.sharedTags > 0)
    .sort((a, b) => b.sharedTags - a.sharedTags)
    .slice(0, count);
  return shared.map((s) => s.post);
}

export default function BlogPostPage() {
  const params = useParams();
  const post = createMemo(() => blogPosts.find((p) => p.slug === params.slug));
  const contentHtml = createMemo(() => post() ? contentToHtml(post()!.content) : "");
  const relatedPosts = createMemo(() => post() ? getRelatedPosts(post()!, blogPosts, 2) : []);

  return (
    <Show
      when={post()}
      fallback={
        <main class="py-20 text-center">
          <Title>Post Not Found — ShieldAI</Title>
          <PageContainer>
            <div class="max-w-md mx-auto">
              <h1 class="text-2xl font-bold text-[var(--color-text-primary)] mb-3">Post Not Found</h1>
              <p class="text-[var(--color-text-secondary)] mb-8">The blog post you're looking for doesn't exist or has been removed.</p>
              <A href="/blog">
                <Button variant="primary">Back to Blog</Button>
              </A>
            </div>
          </PageContainer>
        </main>
      }
    >
      <main>
        <Title>{post()!.title} — ShieldAI Blog</Title>

        <article>
          <section class="relative py-16 md:py-20 overflow-hidden">
            <div class="absolute inset-0 bg-gradient-to-b from-[var(--color-brand-primary)]/5 to-transparent" />
            <PageContainer class="relative z-10">
              <A href="/blog" class="inline-flex items-center gap-1.5 text-sm text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] mb-6 transition-colors">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M10 12L6 8l4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                Back to Blog
              </A>

              <div class="flex flex-wrap gap-2 mb-4">
                <For each={post()!.tags}>
                  {(tag) => <Badge variant="info">{tag}</Badge>}
                </For>
              </div>

              <h1 class="text-3xl md:text-4xl lg:text-5xl font-bold text-[var(--color-text-primary)] mb-4 max-w-3xl">
                {post()!.title}
              </h1>

              <div class="flex items-center gap-4 text-sm text-[var(--color-text-tertiary)] mb-8">
                <div class="flex items-center gap-2">
                  <div class="w-8 h-8 rounded-full bg-[var(--color-brand-primary)]/20 flex items-center justify-center text-[var(--color-brand-primary)] text-xs font-bold">
                    {post()!.author.split(" ").map(n => n[0]).join("")}
                  </div>
                  <div>
                    <p class="text-sm font-medium text-[var(--color-text-primary)]">{post()!.author}</p>
                    <p class="text-xs text-[var(--color-text-tertiary)]">{post()!.authorRole}</p>
                  </div>
                </div>
                <span class="text-[var(--color-text-tertiary)]">·</span>
                <span>{post()!.date}</span>
                <span class="text-[var(--color-text-tertiary)]">·</span>
                <span>{post()!.readingTime}</span>
              </div>
            </PageContainer>
          </section>

          <section class="pb-16">
            <PageContainer>
              <div class="grid grid-cols-1 lg:grid-cols-[1fr_300px] gap-10">
                <div class="prose-custom" innerHTML={contentHtml()} />

                <aside class="space-y-6">
                  <Card>
                    <div class="text-center">
                      <div class="w-16 h-16 rounded-full bg-[var(--color-brand-primary)]/20 flex items-center justify-center text-[var(--color-brand-primary)] text-xl font-bold mx-auto mb-3">
                        {post()!.author.split(" ").map(n => n[0]).join("")}
                      </div>
                      <h3 class="text-sm font-semibold text-[var(--color-text-primary)]">{post()!.author}</h3>
                      <p class="text-xs text-[var(--color-text-tertiary)] mb-3">{post()!.authorRole}</p>
                      <p class="text-xs text-[var(--color-text-secondary)]">Security researcher and writer covering digital identity protection and AI safety.</p>
                    </div>
                  </Card>

                  <div>
                    <h3 class="text-sm font-semibold text-[var(--color-text-primary)] mb-3">Share this article</h3>
                    <div class="flex gap-2">
                      <button
                        type="button"
                        class="p-2 rounded-lg bg-[var(--color-bg-secondary)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"
                        aria-label="Share on Twitter"
                        onClick={() => window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(post()!.title)}&url=${encodeURIComponent(window.location.href)}`, "_blank")}
                      >
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
                      </button>
                      <button
                        type="button"
                        class="p-2 rounded-lg bg-[var(--color-bg-secondary)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"
                        aria-label="Share on LinkedIn"
                        onClick={() => window.open(`https://linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(window.location.href)}`, "_blank")}
                      >
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>
                      </button>
                      <button
                        type="button"
                        class="p-2 rounded-lg bg-[var(--color-bg-secondary)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"
                        aria-label="Copy link"
                        onClick={() => navigator.clipboard.writeText(window.location.href)}
                      >
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71"/></svg>
                      </button>
                    </div>
                  </div>

                  <Show when={relatedPosts().length > 0}>
                    <div>
                      <h3 class="text-sm font-semibold text-[var(--color-text-primary)] mb-3">Related Posts</h3>
                      <div class="space-y-3">
                        <For each={relatedPosts()}>
                          {(rp) => (
                            <A href={`/blog/${rp.slug}`}>
                              <Card class="hover:shadow-md transition-shadow">
                                <p class="text-sm font-medium text-[var(--color-text-primary)] mb-1">{rp.title}</p>
                                <div class="flex flex-wrap gap-1">
                                  <For each={rp.tags}>
                                    {(tag) => <Badge>{tag}</Badge>}
                                  </For>
                                </div>
                              </Card>
                            </A>
                          )}
                        </For>
                      </div>
                    </div>
                  </Show>
                </aside>
              </div>
            </PageContainer>
          </section>
        </article>
      </main>
    </Show>
  );
}
