/**
 * DataMaturityNotice
 * --------------------
 * Reusable banner that explains why Site Tag data is sparse during the
 * first ~30 days of installation. Three stages:
 *
 *   • <  7 days  → amber/warning, baseline metrics not yet available
 *   • 7-29 days  → blue/info, day-over-day works but week/month don't
 *   • 30+ days   → render nothing (data is fully mature)
 *
 * The compact variant collapses the whole banner into a single line for
 * inline use (e.g. AI Strategist welcome message).
 *
 * Importing pages should already know `installedDays` — typically derived
 * from `TrackedSite.createdAt` and surfaced via the page's API response
 * (see `siteTagAge` in /api/site-tag, /api/site-tag/analytics,
 * /api/dashboard).
 */

import { Hourglass, BarChart3, type LucideIcon } from "lucide-react";

export const FULL_MATURITY_DAYS = 30;

export interface DataMaturityNoticeProps {
  /** Days of real data collected for the active brand (first-event-based). */
  installedDays: number;
  /** ISO timestamp of the first captured event — shown in the banner copy
   *  so users know the exact date data collection started (not when the
   *  TrackedSite row was created). */
  installedAt?: string | Date | null;
  /** When true, render the single-line variant for inline UIs. */
  compact?: boolean;
  /** Optional className for layout overrides. */
  className?: string;
}

interface Stage {
  label: string;
  title: string;
  description: string;
  icon: LucideIcon;
  bg: string;
  border: string;
  text: string;
  iconColor: string;
  bar: string;
}

function formatShortDate(input: string | Date): string {
  const d = typeof input === "string" ? new Date(input) : input;
  if (!Number.isFinite(d.getTime())) return "";
  return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}

function stageFor(days: number, sinceLabel: string): Stage | null {
  if (days >= FULL_MATURITY_DAYS) return null;
  const dayWord = days === 1 ? "day" : "days";
  const since = sinceLabel ? `since ${sinceLabel}` : "";
  if (days < 7) {
    return {
      label: "Baseline forming",
      title: sinceLabel
        ? `Site Tag has been capturing data ${since} (${days} ${dayWord})`
        : `Site Tag has been capturing data for ${days} ${dayWord}`,
      description:
        "Day-over-day analysis will be available after 7 days of data collection. Week-over-week comparisons unlock at 14 days. Full monthly analysis requires 30+ days.",
      icon: Hourglass,
      bg: "bg-amber-50",
      border: "border-amber-200",
      text: "text-amber-900",
      iconColor: "text-amber-600",
      bar: "bg-amber-500",
    };
  }
  // 7-29 days
  return {
    label: "Building history",
    title: sinceLabel
      ? `Site Tag has been capturing data ${since} (${days} ${dayWord})`
      : `Site Tag has been capturing data for ${days} ${dayWord}`,
    description:
      "Day-over-day analysis is available now. Week-over-week comparisons unlock at 14 days. Full monthly analysis and seasonal trends require 30+ days of data.",
    icon: BarChart3,
    bg: "bg-blue-50",
    border: "border-blue-200",
    text: "text-blue-900",
    iconColor: "text-blue-600",
    bar: "bg-blue-500",
  };
}

export function DataMaturityNotice({ installedDays, installedAt, compact = false, className = "" }: DataMaturityNoticeProps) {
  // "Don't render the baseline-forming banner when we can't actually
  // confirm the install date": if the install timestamp is missing and
  // the day count is 0, we're in the "unknown" state — typically the
  // /api/site-tag/analytics race returned `partial: true` because the
  // installedAt sub-query timed out. Showing "Site Tag has been
  // capturing data for 0 days" in that case is misleading; the tag may
  // be weeks or months old. Bail and let the next poll fill in the gap.
  if (!installedAt && installedDays <= 0) return null;
  const sinceLabel = installedAt ? formatShortDate(installedAt) : "";
  const stage = stageFor(installedDays, sinceLabel);
  if (!stage) return null;

  const pct = Math.max(0, Math.min(100, Math.round((installedDays / FULL_MATURITY_DAYS) * 100)));
  const Icon = stage.icon;

  if (compact) {
    return (
      <div className={`flex items-center gap-2 text-[11px] ${stage.text} ${className}`}>
        <Icon className={`w-3.5 h-3.5 shrink-0 ${stage.iconColor}`} />
        <span className="truncate">
          Site Tag · {sinceLabel ? `since ${sinceLabel} · ` : ""}
          {installedDays}/{FULL_MATURITY_DAYS} days collected ({pct}% maturity).{" "}
          {installedDays < 7
            ? "Baseline metrics still forming."
            : "Day-over-day available; week/month unlock at 14/30 days."}
        </span>
      </div>
    );
  }

  return (
    <div
      className={`flex items-start gap-3 rounded-xl border ${stage.border} ${stage.bg} px-4 py-3 ${className}`}
      role="status"
    >
      <Icon className={`w-4 h-4 mt-0.5 shrink-0 ${stage.iconColor}`} />
      <div className="flex-1 min-w-0">
        <div className="flex items-center justify-between gap-3 flex-wrap">
          <p className={`text-sm font-semibold ${stage.text}`}>{stage.title}</p>
          <span className={`text-[10px] font-bold uppercase tracking-widest ${stage.text} opacity-70`}>
            {stage.label}
          </span>
        </div>
        <p className={`text-xs mt-1 leading-relaxed ${stage.text} opacity-90`}>{stage.description}</p>

        {/* Progress bar — visualises days collected vs the 30-day full-maturity threshold */}
        <div className="mt-2.5">
          <div className="flex items-center gap-2">
            <div className="flex-1 h-1.5 rounded-full bg-white/70 overflow-hidden">
              <div className={`h-full ${stage.bar} transition-all`} style={{ width: `${pct}%` }} />
            </div>
            <span className={`text-[10px] font-semibold tabular-nums ${stage.text} shrink-0`}>
              {installedDays}/{FULL_MATURITY_DAYS} days · {pct}%
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}

/**
 * Helper to compute days since a Date / ISO string. Returns 0 for missing
 * inputs and never returns negative numbers (clock skew tolerance).
 */
export function daysSince(input: string | Date | null | undefined): number {
  if (!input) return 0;
  const t = typeof input === "string" ? new Date(input).getTime() : input.getTime();
  if (!Number.isFinite(t)) return 0;
  const diff = Date.now() - t;
  return Math.max(0, Math.floor(diff / 86_400_000));
}
