import { inferDigitalPresenceFromBusiness } from "@/lib/demo-digital-presence";
import { isWordPressConnected, wordPressAdminUrl } from "@/lib/integrations/wordpress";
import type {
  Business,
  ConnectedSoftware,
  WebsiteAestheticAnalysis,
  WebsiteAestheticRecommendation,
  WebsiteAestheticUploadItem,
  WebsiteAestheticUploadReceipt,
  WebsiteHostConnection,
  WebsiteAestheticDimension,
} from "@/lib/types";

const CMS_KEYWORDS = ["website cms", "marketing site", "idx website", "catalog site"];

function now() {
  return new Date().toISOString();
}

function uuid() {
  return crypto.randomUUID();
}

export function resolveWebsiteHost(business: Business): WebsiteHostConnection | null {
  const wp = business.integrations?.wordpress;
  if (isWordPressConnected(wp)) {
    return {
      name: "WordPress",
      category: "Website CMS",
      adminUrl: wp!.adminUrl ?? wordPressAdminUrl(wp!.siteUrl),
      websiteUrl: wp!.siteUrl,
      mode: "live",
    };
  }

  const presence = inferDigitalPresenceFromBusiness(business);
  const websiteUrl = presence?.websiteUrl ?? business.input.websiteUrl ?? "";
  if (!websiteUrl) return null;

  const cms =
    presence?.connectedSoftware.find(
      (tool) =>
        CMS_KEYWORDS.some((k) => tool.category.toLowerCase().includes(k)) ||
        tool.category.toLowerCase().includes("cms"),
    ) ?? inferCmsFromUrl(websiteUrl);

  if (!cms) {
    return {
      name: "Website host",
      category: "CMS",
      adminUrl: websiteUrl,
      websiteUrl,
      mode: "demo",
    };
  }

  return {
    name: cms.name,
    category: cms.category,
    adminUrl: cms.url,
    websiteUrl,
    mode: "demo",
  };
}

function inferCmsFromUrl(websiteUrl: string): ConnectedSoftware | null {
  const host = websiteUrl.toLowerCase();
  if (host.includes("wordpress") || host.includes("wp-admin")) {
    return { name: "WordPress", category: "Website CMS", url: `${websiteUrl.replace(/\/$/, "")}/wp-admin`, usedByRoles: [] };
  }
  if (host.includes("webflow")) {
    return { name: "Webflow", category: "Website CMS", url: "https://webflow.com/dashboard", usedByRoles: [] };
  }
  if (host.includes("wix")) {
    return { name: "Wix", category: "Website CMS", url: "https://wix.com/dashboard", usedByRoles: [] };
  }
  if (host.includes("squarespace")) {
    return { name: "Squarespace", category: "Website CMS", url: `${websiteUrl}/config`, usedByRoles: [] };
  }
  if (host.includes("vercel") || host.includes("stackline")) {
    return { name: "Vercel", category: "Marketing site", url: "https://vercel.com/dashboard", usedByRoles: [] };
  }
  return null;
}

const SECTION_BY_DIMENSION: Record<WebsiteAestheticDimension | "identity", string> = {
  typography: "Global styles / typography",
  colorPalette: "Theme colors & CSS variables",
  layout: "Homepage hero & section order",
  imagery: "Hero & gallery blocks",
  trustSignals: "Trust bar / review strip",
  mobileExperience: "Mobile layout & sticky CTA",
  conversionPath: "Primary CTA & form blocks",
  identity: "Brand voice & meta",
};

function cmsActionForHost(hostName: string, section: string): string {
  const h = hostName.toLowerCase();
  if (h.includes("wordpress")) return `Save ${section} as draft page revision in WordPress`;
  if (h.includes("webflow")) return `Stage ${section} changes in Webflow Designer (unpublished)`;
  if (h.includes("wix")) return `Queue ${section} edit in Wix Editor draft`;
  if (h.includes("squarespace")) return `Save ${section} to Squarespace style & section drafts`;
  if (h.includes("vercel")) return `Open PR with ${section} content update on marketing repo`;
  return `Save ${section} as draft on website host`;
}

function buildPayload(
  host: WebsiteHostConnection,
  rec: WebsiteAestheticRecommendation,
  business: Business,
): string {
  const section = SECTION_BY_DIMENSION[rec.category] ?? "Homepage";
  const headline =
    business.recommendations[0]?.landingHeadline ??
    `${business.input.businessName}: ${business.profile.brandPositioning.slice(0, 72)}`;

  if (host.name.toLowerCase().includes("wordpress")) {
    return [
      `<!-- BrandLxft draft · ${rec.title} -->`,
      `<!-- Section: ${section} -->`,
      `<!-- Preserve: ${rec.preserveIndependence} -->`,
      "",
      `<!-- wp:heading {"level":1} -->`,
      `<h1>${headline}</h1>`,
      `<!-- /wp:heading -->`,
      "",
      `<!-- wp:paragraph -->`,
      `<p>${rec.action}</p>`,
      `<!-- /wp:paragraph -->`,
      "",
      `<!-- wp:group {"className":"brandlxft-trust-bar"} -->`,
      `<div class="wp-block-group brandlxft-trust-bar">`,
      `  <p><strong>Pattern applied:</strong> ${rec.industryPattern}</p>`,
      `  <p><em>Your brand stays independent — ${business.input.businessName} colors & proof unchanged.</em></p>`,
      `</div>`,
      `<!-- /wp:group -->`,
    ].join("\n");
  }

  if (host.name.toLowerCase().includes("webflow")) {
    return [
      `Webflow Designer draft — ${section}`,
      `Class: .hero-headline → text: "${headline}"`,
      `Class: .hero-sub → text: "${rec.action}"`,
      `Component: TrustBar → show Google rating + "${rec.preserveIndependence.slice(0, 80)}…"`,
      `Style guide note: Apply industry ${rec.category} pattern without copying competitor palette`,
      `Publish: Staged only — approve in BrandLxft before going live`,
    ].join("\n");
  }

  if (host.name.toLowerCase().includes("wix") || host.name.toLowerCase().includes("squarespace")) {
    return [
      `${host.name} section editor draft`,
      `Target: ${section}`,
      `Hero headline: ${headline}`,
      `Supporting copy: ${rec.action}`,
      `Trust strip: Add review badge + guarantee near primary button`,
      `Brand guardrail: ${rec.preserveIndependence}`,
    ].join("\n");
  }

  return [
    `Draft update — ${section}`,
    `Headline: ${headline}`,
    `Body: ${rec.action}`,
    `Industry pattern: ${rec.industryPattern}`,
    `Independence: ${rec.preserveIndependence}`,
  ].join("\n");
}

export function uploadWebsiteAestheticToHost(
  business: Business,
  options?: { recommendationIds?: string[]; publish?: boolean },
): { receipt: WebsiteAestheticUploadReceipt; business: Business } {
  const analysis = business.websiteAestheticAnalysis;
  if (!analysis) {
    throw new Error("Run website aesthetic analysis before uploading to host.");
  }

  const host = resolveWebsiteHost(business);
  if (!host) {
    throw new Error("No website URL found. Add a website in Settings or load a demo with digital presence.");
  }

  const ids = options?.recommendationIds;
  let recs = analysis.recommendations.filter((r) => r.category !== "identity");
  if (ids?.length) {
    recs = recs.filter((r) => ids.includes(r.id));
  } else {
    recs = recs.filter((r) => r.priority === "high" || r.priority === "medium").slice(0, 3);
  }

  if (!recs.length) {
    throw new Error("No recommendations selected for upload.");
  }

  const items: WebsiteAestheticUploadItem[] = recs.map((rec) => {
    const section = SECTION_BY_DIMENSION[rec.category] ?? "Homepage";
    return {
      recommendationId: rec.id,
      title: rec.title,
      targetSection: section,
      cmsAction: cmsActionForHost(host.name, section),
      payload: buildPayload(host, rec, business),
    };
  });

  const publish = options?.publish ?? false;
  const status = publish ? "published" : "draft_saved";
  const previewUrl = publish
    ? `${host.websiteUrl}?brandlxft_preview=${Date.now()}`
    : `${host.adminUrl}${host.adminUrl.includes("?") ? "&" : host.adminUrl.includes("wp-admin") ? "" : "?"}draft=1`;

  const receipt: WebsiteAestheticUploadReceipt = {
    id: uuid(),
    hostName: host.name,
    hostAdminUrl: host.adminUrl,
    websiteUrl: host.websiteUrl,
    uploadedAt: now(),
    mode: host.mode,
    status,
    summary:
      `${items.length} aesthetic update${items.length === 1 ? "" : "s"} ${publish ? "published" : "saved as draft"} on ${host.name}. ` +
      `Patterns from top ${business.input.industry} performers applied while preserving ${business.input.businessName}'s independent brand.`,
    items,
    previewUrl,
    approvalNote: publish
      ? "Changes are live on your site. Review preview URL and revert in CMS if needed."
      : "Draft saved on host — nothing is live until you approve publish in BrandLxft or your CMS.",
  };

  const updatedAnalysis: WebsiteAestheticAnalysis = {
    ...analysis,
    lastHostUpload: receipt,
  };

  const history = business.websiteHostUploads ?? [];
  const nextBusiness: Business = {
    ...business,
    websiteAestheticAnalysis: updatedAnalysis,
    websiteHostUploads: [receipt, ...history].slice(0, 10),
    updatedAt: now(),
  };

  return { receipt, business: nextBusiness };
}

export function publishWebsiteHostDraft(business: Business): { receipt: WebsiteAestheticUploadReceipt; business: Business } {
  const draft = business.websiteAestheticAnalysis?.lastHostUpload;
  if (!draft || draft.status === "published") {
    throw new Error("No draft upload waiting for approval.");
  }

  const published: WebsiteAestheticUploadReceipt = {
    ...draft,
    id: uuid(),
    uploadedAt: now(),
    status: "published",
    previewUrl: `${draft.websiteUrl}?brandlxft_live=${Date.now()}`,
    summary: draft.summary.replace("saved as draft", "published live"),
    approvalNote: "Published to your website host. Monitor analytics for conversion lift over the next 7 days.",
  };

  const nextBusiness: Business = {
    ...business,
    websiteAestheticAnalysis: business.websiteAestheticAnalysis
      ? { ...business.websiteAestheticAnalysis, lastHostUpload: published }
      : undefined,
    websiteHostUploads: [published, ...(business.websiteHostUploads ?? [])].slice(0, 10),
    updatedAt: now(),
  };

  return { receipt: published, business: nextBusiness };
}
