/**
 * Central blog data module: single source of truth for the listing page,
 * the /blog/[slug] route, the sidebar, related posts and prev/next nav.
 *
 * The site is a static export (next.config.ts → output: "export"), so all of
 * this is plain data resolved at build time. No CMS, no runtime fetching.
 */

export const SITE_URL = "https://doormile.com";

export type ContentBlock =
  | { type: "paragraph"; text: string }
  | { type: "heading"; level: 2 | 3; text: string }
  | { type: "list"; ordered?: boolean; items: string[] }
  | { type: "quote"; text: string; cite?: string }
  | { type: "image"; src: string; alt: string; caption?: string };

export interface BlogPost {
  slug: string;
  title: string;
  excerpt: string;
  category: string;
  image: string;
  date: string; // ISO (YYYY-MM-DD)
  author: string;
  intro: string;
  content: ContentBlock[];
}

const AUTHOR = "Doormile Team";

/**
 * Shared rich-content template for non-flagship posts. Seeded with the post's
 * own title / category so every element type (h2, h3, lists, quote, image)
 * renders and every route is complete. Flagship posts below override `content`
 * with fully authored copy.
 */
function templateContent(post: {
  title: string;
  category: string;
  image: string;
}): ContentBlock[] {
  return [
    {
      type: "paragraph",
      text: `In last-mile logistics, a missed SLA is rarely caused by one big failure. It usually comes from small delays adding up across a route. ${post.title} looks at how delivery teams can spot those delays early and plan around them before vehicles leave the hub.`,
    },
    {
      type: "heading",
      level: 2,
      text: "Why this matters for fleet teams",
    },
    {
      type: "paragraph",
      text: "Every extra kilometre costs money. It uses fuel or charge, adds rider time, wears down vehicles, and increases the chance of a late delivery. When routes are built from fixed zones or old habits, those costs repeat every day.",
    },
    {
      type: "list",
      items: [
        "Fewer vehicles needed for the same number of drops",
        "Lower cost per drop through better stop sequencing",
        "ETAs that match traffic, distance, and delivery windows",
        "Less fuel or charge used per completed order",
      ],
    },
    {
      type: "heading",
      level: 3,
      text: "From orders to dispatch",
    },
    {
      type: "paragraph",
      text: `A good dispatch plan starts with the basics: order locations, promised delivery windows, rider capacity, vehicle range, and known traffic trouble spots. MileTruth™ checks those inputs before dispatch so the team is not fixing avoidable mistakes on the road.`,
    },
    {
      type: "image",
      src: post.image,
      alt: post.title,
      caption: `${post.category}: route planning decisions made before dispatch.`,
    },
    {
      type: "quote",
      text: "A route should be checked before the rider leaves, not explained after the customer calls.",
      cite: "Doormile Operations",
    },
    {
      type: "heading",
      level: 2,
      text: "Putting it into practice",
    },
    {
      type: "paragraph",
      text: "The best improvements usually start with simple measurements. Track distance per route, failed delivery windows, rider idle time, and orders moved between vehicles after dispatch. Those numbers show where the operation is leaking time.",
    },
    {
      type: "list",
      ordered: true,
      items: [
        "Benchmark today's distance, fleet size, and on-time rate.",
        "Include vehicle capacity, delivery windows, rider shifts, and battery charge.",
        "Check routes against traffic and customer commitments before dispatch.",
        "Compare the next dispatch cycle against the old plan.",
      ],
    },
    {
      type: "paragraph",
      text: "Better routing is not about pushing riders harder. It is about giving them a plan that already accounts for the real day ahead.",
    },
  ];
}

interface SeedPost {
  slug: string;
  title: string;
  excerpt: string;
  category: string;
  image: string;
  date: string;
  intro: string;
  content?: ContentBlock[]; // present only for flagship posts
}

const seeds: SeedPost[] = [
  // ── Flagship 1 ───────────────────────────────────────────────────────────
  {
    slug: "how-ai-is-transforming-last-mile-ev-delivery",
    title: "How Better Planning Improves Last-Mile EV Delivery",
    excerpt:
      "A practical look at how EV fleets can plan routes, manage charging, and keep delivery promises without adding unnecessary vehicles.",
    category: "Technology",
    image: "/images/blog-post-pic-17.webp",
    date: "2025-10-02",
    intro:
      "The last mile is already difficult to plan. With electric vehicles, the team also has to think about battery range, charging time, rider load, traffic, and delivery windows. Good planning turns those moving parts into a workable dispatch plan.",
    content: [
      {
        type: "paragraph",
        text: "For a long time, last-mile planning depended on dispatchers, spreadsheets, and local experience. That experience still matters. The problem is that it gets stretched thin when order volume rises and the fleet includes EVs.",
      },
      {
        type: "heading",
        level: 2,
        text: "The shift from fixed rules to daily planning",
      },
      {
        type: "paragraph",
        text: "A fixed-zone plan may look clean in the morning, but the road rarely follows the plan. A rider may get delayed near Hitec City, a gated community may hold a vehicle for ten extra minutes, or a battery may drain faster because the load is heavier than usual.",
      },
      {
        type: "list",
        items: [
          "Order volumes by area, time slot, and customer type",
          "Travel times based on the city's actual traffic patterns",
          "Battery use by vehicle type, rider load, and route length",
          "Feedback from completed deliveries, failed attempts, and late arrivals",
        ],
      },
      { type: "heading", level: 3, text: "Adjusting during the day" },
      {
        type: "paragraph",
        text: "The first plan is only the starting point. By 11 a.m., traffic may change, a high-priority order may arrive, or one vehicle may return with less charge than expected. The dispatch team needs a way to adjust without rebuilding the whole day by hand.",
      },
      {
        type: "paragraph",
        text: "During peak traffic hours in Hyderabad, some vehicles were arriving 20 to 30 minutes later than planned. By adjusting routes based on live traffic and battery levels, the hub reduced missed delivery windows and improved on-time performance.",
      },
      {
        type: "image",
        src: "/images/ev-paradox.webp",
        alt: "Electric delivery vehicle routing visualisation",
        caption:
          "EV route plans need to account for range, load, traffic, and charging time before riders leave the hub.",
      },
      {
        type: "quote",
        text: "With EVs, a route is only useful if the vehicle can finish it and still return safely.",
        cite: "Doormile Operations",
      },
      {
        type: "heading",
        level: 2,
        text: "What this means for operators",
      },
      {
        type: "paragraph",
        text: "For a fleet manager, this is not about fancy software. It is about fewer emergency calls, fewer mid-route swaps, and fewer customers asking why their delivery missed the promised window.",
      },
      {
        type: "list",
        ordered: true,
        items: [
          "Record delivery times, failed attempts, traffic delays, and charging cycles.",
          "Build travel-time estimates from the areas your riders actually serve.",
          "Check every route against battery capacity before dispatch.",
          "Replan when traffic, orders, or vehicle availability changes.",
        ],
      },
      {
        type: "paragraph",
        text: "The fleets that improve fastest are usually not the ones adding vehicles first. They are the ones removing wasted distance, planning charging properly, and giving riders routes they can complete on time.",
      },
    ],
  },

  // ── Flagship 2 ───────────────────────────────────────────────────────────
  {
    slug: "42-less-distance-insights-from-our-hyderabad-hub",
    title: "42% Less Distance: Insights from Our Hyderabad Hub",
    excerpt:
      "A practical look at how one Hyderabad hub reduced distance, used fewer vehicles, and protected delivery windows with better route planning.",
    category: "Case Study",
    image: "/images/blog-post-pic-15.webp",
    date: "2025-09-18",
    intro:
      "Numbers settle arguments. At our Hyderabad hub, the goal was simple: reduce avoidable distance without missing customer commitments. The result was a 42% reduction in total distance travelled.",
    content: [
      {
        type: "paragraph",
        text: "Hyderabad is not an easy city for delivery planning. Dense commercial areas, fast-growing suburbs, flyover work, narrow service lanes, apartment security checks, and sudden traffic build-up can all change the day.",
      },
      {
        type: "heading",
        level: 2,
        text: "The baseline",
      },
      {
        type: "paragraph",
        text: "Before MileTruth, the hub planned routes in the usual way. Zones were drawn from experience, dispatchers sequenced stops manually, and riders adjusted on the road when something changed.",
      },
      {
        type: "paragraph",
        text: "That process worked, but it carried hidden costs. Two riders might cross the same area in the same hour. A vehicle might take a longer loop to avoid one late stop. A dispatcher might hold back an order because the best vehicle was not obvious in the moment.",
      },
      {
        type: "list",
        items: [
          "Zone-based allocation that missed nearby cross-zone drops",
          "Manual stop sequencing during busy dispatch windows",
          "ETAs checked after routing instead of before dispatch",
          "Traffic and delay handling that depended on phone calls from riders",
        ],
      },
      {
        type: "heading",
        level: 3,
        text: "What changed",
      },
      {
        type: "paragraph",
        text: "The main change was treating the day's orders as one connected plan instead of separate zone lists. The route plan considered distance, rider capacity, delivery windows, traffic, and vehicle availability together.",
      },
      {
        type: "paragraph",
        text: "During peak traffic hours in Hyderabad, some vehicles were arriving 20 to 30 minutes later than planned. By adjusting routes based on live traffic and battery levels, we reduced missed delivery windows and improved on-time performance.",
      },
      {
        type: "image",
        src: "/images/last-mile-approach.webp",
        alt: "Hyderabad delivery hub routing analysis",
        caption:
          "Planning the day's deliveries together removed repeated cross-town travel.",
      },
      {
        type: "heading",
        level: 2,
        text: "The results",
      },
      {
        type: "list",
        items: [
          "42% reduction in total distance travelled across the hub",
          "37% fewer vehicles required for the same delivery volume",
          "No SLA misses during the measured deployment window",
          "Lower fuel use and fewer unnecessary kilometres per parcel",
        ],
      },
      {
        type: "quote",
        text: "The improvement did not come from asking riders to work harder. It came from giving the team a better route plan before the vehicles left.",
        cite: "Hyderabad Hub Operations",
      },
      {
        type: "heading",
        level: 3,
        text: "Why this applies beyond one hub",
      },
      {
        type: "paragraph",
        text: "The Hyderabad result was not a one-city exception. Most hubs deal with the same issues: overlapping routes, conservative sequencing, traffic surprises, charging constraints, and last-minute order changes.",
      },
      {
        type: "paragraph",
        text: "A 42% cut in distance changes the cost of running the operation. It also gives dispatchers more breathing room when the day gets messy.",
      },
    ],
  },

  // ── Flagship 3 ───────────────────────────────────────────────────────────
  {
    slug: "miletruth-ai-10-stages-to-smarter-dispatch",
    title: "MileTruth™: 10 Stages to Smarter Dispatch",
    excerpt:
      "From order intake to final route output, here is how a dispatch plan is checked before riders leave the hub.",
    category: "MileTruth",
    image: "/images/blog-post-pic-31.webp",
    date: "2025-09-05",
    intro:
      "Behind every Doormile dispatch is a step-by-step route planning process. Each stage removes a common source of error before the plan reaches the rider.",
    content: [
      {
        type: "paragraph",
        text: "A dispatch plan has to be fast, but it also has to be usable. A quick route that ignores a bad address, low battery, or tight delivery window creates problems later in the day.",
      },
      {
        type: "heading",
        level: 2,
        text: "The ten stages",
      },
      {
        type: "list",
        ordered: true,
        items: [
          "Order intake: new orders, rider availability, and vehicle status are collected.",
          "Address check: delivery points, time windows, and service notes are verified.",
          "Stop planning: each stop gets an expected service time and delivery priority.",
          "Travel-time check: routes are compared against time-of-day traffic.",
          "Constraint check: capacity, shift time, customer windows, and range are applied.",
          "Route options: several possible plans are built for the same order set.",
          "Plan selection: the lowest-cost workable route plan is selected.",
          "Battery check: EV routes are checked against real charge capacity.",
          "ETA check: promised delivery times are verified before dispatch.",
          "Dispatch output: the final route is sent to the operations team.",
        ],
      },
      {
        type: "heading",
        level: 3,
        text: "Why staging matters",
      },
      {
        type: "paragraph",
        text: "When everything is checked in one step, small errors slip through. A wrong pin, a missing apartment note, or a low battery warning can reach the rider and become a customer issue.",
      },
      {
        type: "image",
        src: "/images/blog-post-pic-31.webp",
        alt: "MileTruth routing pipeline diagram",
        caption:
          "A staged dispatch process catches address, range, and ETA issues before riders leave.",
      },
      {
        type: "quote",
        text: "Each stage should remove one kind of mistake. By dispatch time, the route should already be practical.",
        cite: "MileTruth Engineering",
      },
      {
        type: "heading",
        level: 2,
        text: "Comparing route options",
      },
      {
        type: "paragraph",
        text: "The useful part is not only building one route. It is comparing a few workable route options before choosing the plan. One option may save distance, another may protect a tight delivery window, and another may keep an EV closer to a charger.",
      },
      {
        type: "list",
        items: [
          "Several route plans checked before dispatch",
          "Distance, time windows, capacity, and range considered together",
          "Range and ETA checked before the route reaches the rider",
          "Fast output that still leaves room for dispatcher review",
        ],
      },
      {
        type: "paragraph",
        text: "The goal is simple: give the dispatch team a route plan they can trust before the first vehicle leaves the hub.",
      },
    ],
  },

  // ── Template-backed posts ────────────────────────────────────────────────
  {
    slug: "the-ev-paradox-solving-range-anxiety-for-urban-fleets",
    title: "The EV Paradox: Solving Range Anxiety for Urban Fleets",
    excerpt:
      "Electric vehicles lower running costs, but battery range changes how routes must be planned before dispatch.",
    category: "EV Fleet",
    image: "/images/ev-paradox.webp",
    date: "2025-08-21",
    intro:
      "Electric fleets can lower running costs, but range becomes a daily planning constraint. The route has to match the battery, the load, the traffic, and the return plan.",
  },
  {
    slug: "why-mathematical-precision-beats-heuristics-in-routing",
    title: "Why Mathematical Precision Beats Heuristics in Routing",
    excerpt:
      "Fixed routing rules are easy to start with, but they often miss better stop sequences as order volume grows.",
    category: "Technology",
    image: "/images/blog-post-pic-14.webp",
    date: "2025-08-07",
    intro:
      "Simple routing rules are fast to set up, but they can quietly add distance every day. Better planning compares more route options before dispatch.",
  },
  {
    slug: "fleet-reduction-without-compromising-delivery-volume",
    title: "Fleet Reduction Without Compromising Delivery Volume",
    excerpt:
      "Handling the same order volume with fewer vehicles starts by removing avoidable kilometres and overlapping routes.",
    category: "Fleet Management",
    image: "/images/blog-post-pic-8.webp",
    date: "2025-07-24",
    intro:
      "Cutting vehicles usually means cutting capacity unless the removed kilometres were never needed. Better route planning turns wasted distance into operating headroom.",
  },
  {
    slug: "building-a-greener-city-the-future-of-urban-logistics",
    title: "Building a Greener City: The Future of Urban Logistics",
    excerpt:
      "Cities are asking for cleaner delivery. The practical challenge is planning EV routes that can meet customer windows without wasting charge.",
    category: "Sustainability",
    image: "/images/blog-post-pic-6.webp",
    date: "2025-07-10",
    intro:
      "Cleaner delivery is becoming an operating requirement, not just a brand message. It depends on EV adoption and route plans that make those vehicles practical every day.",
  },
  {
    slug: "how-doormile-maintains-99-9-sla-compliance-at-scale",
    title: "How Doormile Maintains 99.9% SLA Compliance at Scale",
    excerpt:
      "High SLA performance comes from checking ETAs before dispatch, reacting early to delays, and keeping customer commitments visible throughout the day.",
    category: "Operations",
    image: "/images/last-mile-approach.webp",
    date: "2025-06-26",
    intro:
      "Strong SLA performance is not luck. It comes from planning the day so late deliveries are the exception, not the expected risk.",
  },
  {
    slug: "battery-simulation-the-secret-to-ev-route-pre-validation",
    title: "Battery Simulation: The Secret to EV Route Pre-Validation",
    excerpt:
      "Before a rider leaves the hub, every EV route should be checked against real charge capacity and the expected return plan.",
    category: "EV Fleet",
    image: "/images/blog-post-pic-3.webp",
    date: "2025-06-12",
    intro:
      "A stranded EV is not just a late delivery. It means a vehicle is out of service, a customer is waiting, and the hub has to arrange recovery. Range checks need to happen before dispatch.",
  },
];

export const blogPosts: BlogPost[] = seeds.map((s) => ({
  slug: s.slug,
  title: s.title,
  excerpt: s.excerpt,
  category: s.category,
  image: s.image,
  date: s.date,
  author: AUTHOR,
  intro: s.intro,
  content:
    s.content ??
    templateContent({ title: s.title, category: s.category, image: s.image }),
}));

// ── Helpers ────────────────────────────────────────────────────────────────

export function getPostBySlug(slug: string): BlogPost | undefined {
  return blogPosts.find((p) => p.slug === slug);
}

export function getAllSlugs(): string[] {
  return blogPosts.map((p) => p.slug);
}

/** Same-category posts first (most recent), then fill by recency. Excludes self. */
export function getRelatedPosts(slug: string, n = 3): BlogPost[] {
  const current = getPostBySlug(slug);
  if (!current) return blogPosts.slice(0, n);
  const others = blogPosts.filter((p) => p.slug !== slug);
  const byDateDesc = (a: BlogPost, b: BlogPost) => b.date.localeCompare(a.date);
  const sameCat = others
    .filter((p) => p.category === current.category)
    .sort(byDateDesc);
  const rest = others
    .filter((p) => p.category !== current.category)
    .sort(byDateDesc);
  return [...sameCat, ...rest].slice(0, n);
}

/** Previous / next by array order (publication sequence). */
export function getAdjacentPosts(slug: string): {
  prev: BlogPost | null;
  next: BlogPost | null;
} {
  const i = blogPosts.findIndex((p) => p.slug === slug);
  if (i === -1) return { prev: null, next: null };
  return {
    prev: i > 0 ? blogPosts[i - 1] : null,
    next: i < blogPosts.length - 1 ? blogPosts[i + 1] : null,
  };
}

export function getRecentPosts(n = 4): BlogPost[] {
  return [...blogPosts].sort((a, b) => b.date.localeCompare(a.date)).slice(0, n);
}

export function getCategories(): { name: string; count: number }[] {
  const counts = new Map<string, number>();
  for (const p of blogPosts) {
    counts.set(p.category, (counts.get(p.category) ?? 0) + 1);
  }
  return Array.from(counts, ([name, count]) => ({ name, count })).sort((a, b) =>
    a.name.localeCompare(b.name)
  );
}

export function formatDate(iso: string): string {
  // Parse as UTC to keep static output deterministic across build environments.
  const d = new Date(`${iso}T00:00:00Z`);
  return d.toLocaleDateString("en-US", {
    year: "numeric",
    month: "short",
    day: "numeric",
    timeZone: "UTC",
  });
}

export function estimateReadingTime(post: BlogPost): number {
  const wordsFromBlocks = post.content.reduce((sum, b) => {
    if (b.type === "paragraph" || b.type === "quote") {
      return sum + b.text.trim().split(/\s+/).length;
    }
    if (b.type === "heading") return sum + b.text.trim().split(/\s+/).length;
    if (b.type === "list") {
      return sum + b.items.join(" ").trim().split(/\s+/).length;
    }
    return sum;
  }, 0);
  const total = wordsFromBlocks + post.intro.trim().split(/\s+/).length;
  return Math.max(1, Math.round(total / 200));
}
