/**
 * Brand Data Injector
 * ───────────────────
 * Replaces placeholder tokens in page sections with real brand data.
 * Used in live preview and when auto-populating newly generated pages.
 * Never breaks if data is missing — uses safe fallbacks.
 */

import type { Section } from "./section-registry";

export interface BrandData {
  name: string;
  phone: string;
  address: string;
  city: string;
  state: string;
  rating: number | null;
  reviewCount: number | null;
  hours: string;
  domain: string;
  services: string[];
  targetKeyword: string;
  logoUrl: string | null;
}

const TOKEN_MAP: Record<string, keyof BrandData> = {
  "{brand.name}": "name",
  "{brand.phone}": "phone",
  "{brand.address}": "address",
  "{brand.city}": "city",
  "{brand.state}": "state",
  "{brand.domain}": "domain",
  "{brand.hours}": "hours",
};

function replaceTokens(text: string, data: BrandData): string {
  let result = text;
  for (const [token, key] of Object.entries(TOKEN_MAP)) {
    const val = data[key];
    if (typeof val === "string" && val) {
      result = result.replaceAll(token, val);
    }
  }
  // Special tokens
  if (data.rating != null) {
    result = result.replaceAll("{brand.rating}", data.rating.toFixed(1));
  }
  if (data.reviewCount != null) {
    result = result.replaceAll("{brand.reviewCount}", String(data.reviewCount));
  }
  return result;
}

function processValue(value: unknown, data: BrandData): unknown {
  if (typeof value === "string") return replaceTokens(value, data);
  if (Array.isArray(value)) return value.map((v) => processValue(v, data));
  if (value && typeof value === "object") {
    const out: Record<string, unknown> = {};
    for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
      out[k] = processValue(v, data);
    }
    return out;
  }
  return value;
}

/**
 * Inject real brand data into all sections, replacing tokens and
 * auto-populating smart defaults for known section types.
 */
export function injectBrandData(sections: Section[], data: BrandData): Section[] {
  return sections.map((section) => {
    const content = processValue(section.content, data) as Record<string, unknown>;

    // Smart defaults per section type
    switch (section.type) {
      case "hero":
      case "hero_with_form":
      case "hero_with_video":
        if (!content.headline || content.headline === "Your Headline Here") {
          content.headline = `${data.name} — ${data.targetKeyword || "Expert Services"} in ${data.city || "Your Area"}`;
        }
        break;

      case "phone_cta":
        if (data.phone) {
          content.phoneNumber = content.phoneNumber || data.phone;
          content.ctaText = content.ctaText || `Call ${data.phone}`;
        }
        break;

      case "contact_form":
        if (data.phone) content.phoneNumber = content.phoneNumber || data.phone;
        if (data.address) content.address = content.address || data.address;
        break;

      case "cta_banner":
        if (data.phone && !content.phoneNumber) {
          content.phoneNumber = data.phone;
        }
        break;

      case "reviews":
      case "testimonials":
        if (data.rating != null && !content.averageRating) {
          content.averageRating = data.rating;
        }
        if (data.reviewCount != null && !content.totalReviews) {
          content.totalReviews = data.reviewCount;
        }
        break;
    }

    return { ...section, content };
  });
}

/**
 * Calculate smart defaults for a new page based on brand data.
 * Called when initializing a page before AI generation.
 */
export function getSmartDefaults(data: BrandData): {
  ctaType: "form" | "phone" | "both";
  ctaText: string;
  heroHeadline: string;
  services: string[];
} {
  const hasPhone = !!data.phone;
  return {
    ctaType: hasPhone ? "both" : "form",
    ctaText: hasPhone ? `Call ${data.phone}` : "Get a Free Quote",
    heroHeadline: `${data.name} — Trusted ${data.targetKeyword || "Services"} in ${data.city || "Your Area"}`,
    services: data.services.slice(0, 6),
  };
}
