import { db, storage } from "@/utils/firebase-templates";
import { doc, getDoc } from "firebase/firestore";
import { getDownloadURL, ref } from "firebase/storage";

// ---- Types your page wants ----
export type LogoTemplate = {
  id: string;
  name: string;
  previewUrl?: string;
  svg: string; // inline SVG with {Brand_Name} {Tagline} {Est_Year} tokens
  defaultFields: Record<string, string>;
  fieldOrder?: string[];
  defaultColors: { primary: string; secondary: string; accent: string };
};

// ---- Helpers ----
async function resolveUrl(p?: string) {
  return p ? await getDownloadURL(ref(storage, p)) : undefined;
}
async function fetchText(u?: string) {
  if (!u) return undefined;
  const res = await fetch(u);
  if (!res.ok) throw new Error(`Failed to fetch SVG: ${res.status}`);
  return await res.text();
}

async function readDoc(collectionName: string, id: string) {
  const snap = await getDoc(doc(db, collectionName, id));
  if (!snap.exists()) return null;
  const d = snap.data() as any;

  // Prefer downloadURLs.*; fall back to storagePaths.*
  const svgUrl =
    d?.downloadURLs?.svg || (d?.storagePaths?.svg ? await resolveUrl(d.storagePaths.svg) : undefined);
  const previewUrl =
    d?.downloadURLs?.preview ||
    d?.downloadURLs?.raster ||
    (d?.storagePaths?.preview ? await resolveUrl(d.storagePaths.preview) : undefined) ||
    (d?.storagePaths?.raster ? await resolveUrl(d.storagePaths.raster) : undefined);

  // Inline SVG string (required by LogoCustomizerPage)
  const svgString = await fetchText(svgUrl); // may be undefined if template is raster-only

  // Defaults mapping (tolerant to different field names)
  const defaults = {
    Brand_Name: d?.defaults?.Brand_Name ?? d?.defaults?.brandName ?? d?.brandName ?? "Your Brand",
    Tagline:    d?.defaults?.Tagline    ?? d?.defaults?.tagline    ?? d?.tagline    ?? "Your Tagline",
    Est_Year:   d?.defaults?.Est_Year   ?? d?.defaults?.estYear    ?? d?.estYear    ?? "2025",
  };

  // Colors (fallbacks)
  const defaultColors = {
    primary:   d?.defaultColors?.primary   ?? "#222222",
    secondary: d?.defaultColors?.secondary ?? "#666666",
    accent:    d?.defaultColors?.accent    ?? "#000000",
  };

  const name = d?.name || id;

  const result: LogoTemplate = {
    id,
    name,
    previewUrl,
    svg: svgString || "",                       // keep empty string if not available
    defaultFields: defaults,
    fieldOrder: d?.fieldOrder ?? ["Brand_Name", "Tagline", "Est_Year"],
    defaultColors,
  };

  return result;
}

/**
 * getTemplateById
 * Tries 'templates' first, then 'logo_templates'.
 * Also tries a short id if incoming id is prefixed (e.g., "logo-wordmark-").
 */
export async function getTemplateById(id: string): Promise<LogoTemplate | null> {
  let t = await readDoc("templates", id);
  if (!t) t = await readDoc("logo_templates", id);

  if (!t && id.startsWith("logo-wordmark-")) {
    const shortId = id.replace(/^logo-wordmark-/, "");
    t = (await readDoc("templates", shortId)) || (await readDoc("logo_templates", shortId));
    if (t) t.id = shortId;
  }
  return t || null;
}
