'use client';

// Small building blocks shared by the Marketing pages, on the admin's own
// design tokens (var(--color-*)) so they match the rest of the dashboard.
import type { ReactNode, ButtonHTMLAttributes, InputHTMLAttributes, TextareaHTMLAttributes, SelectHTMLAttributes } from 'react';
import { Loader2 } from 'lucide-react';

export function Card({ title, subtitle, actions, children, className = '' }: {
  title?: ReactNode; subtitle?: ReactNode; actions?: ReactNode; children: ReactNode; className?: string;
}) {
  return (
    <section
      className={`rounded-2xl p-4 sm:p-5 ${className}`}
      style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)' }}
    >
      {(title || actions) && (
        <div className="flex flex-wrap items-start justify-between gap-3 mb-4">
          <div className="min-w-0">
            {title && <h2 className="text-base font-semibold" style={{ color: 'var(--color-text)' }}>{title}</h2>}
            {subtitle && <p className="text-xs mt-1" style={{ color: 'var(--color-text-secondary)' }}>{subtitle}</p>}
          </div>
          {actions && <div className="flex flex-wrap gap-2">{actions}</div>}
        </div>
      )}
      {children}
    </section>
  );
}

const STATUS_STYLE: Record<string, { label: string; bg: string; fg: string }> = {
  pending_review: { label: 'Pending review', bg: 'rgba(217,119,6,0.12)', fg: '#B45309' },
  approved: { label: 'Approved (not live)', bg: 'rgba(37,99,235,0.12)', fg: '#1D4ED8' },
  rejected: { label: 'Rejected', bg: 'rgba(220,38,38,0.12)', fg: '#B91C1C' },
  active: { label: 'Active', bg: 'rgba(5,150,105,0.12)', fg: '#047857' },
  paused: { label: 'Paused', bg: 'rgba(100,116,139,0.15)', fg: '#475569' },
  archived: { label: 'Archived', bg: 'rgba(100,116,139,0.12)', fg: '#64748B' },
  draft: { label: 'Draft', bg: 'rgba(100,116,139,0.12)', fg: '#475569' },
};

export function StatusBadge({ status }: { status: string }) {
  const s = STATUS_STYLE[status] ?? { label: status, bg: 'var(--color-surface-alt)', fg: 'var(--color-text-secondary)' };
  return (
    <span className="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap" style={{ background: s.bg, color: s.fg }}>
      {s.label}
    </span>
  );
}

type Variant = 'primary' | 'secondary' | 'danger' | 'ghost';
const VARIANT_STYLE: Record<Variant, React.CSSProperties> = {
  primary: { background: 'var(--color-cta)', color: '#fff', border: '1px solid transparent' },
  secondary: { background: 'var(--color-surface)', color: 'var(--color-text)', border: '1px solid var(--color-border)' },
  danger: { background: 'var(--color-danger)', color: '#fff', border: '1px solid transparent' },
  ghost: { background: 'transparent', color: 'var(--color-text-secondary)', border: '1px solid transparent' },
};

export function Btn({ variant = 'secondary', loading, children, className = '', disabled, ...rest }: ButtonHTMLAttributes<HTMLButtonElement> & {
  variant?: Variant; loading?: boolean;
}) {
  return (
    <button
      type="button"
      {...rest}
      disabled={disabled || loading}
      className={`inline-flex items-center justify-center gap-1.5 rounded-lg px-3.5 py-2 text-sm font-medium transition-opacity hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer ${className}`}
      style={VARIANT_STYLE[variant]}
    >
      {loading && <Loader2 size={15} className="animate-spin" />}
      {children}
    </button>
  );
}

export function Field({ label, hint, error, children, className = '' }: {
  label: ReactNode; hint?: ReactNode; error?: string | null; children: ReactNode; className?: string;
}) {
  return (
    <label className={`block ${className}`}>
      <span className="block text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-secondary)' }}>{label}</span>
      {children}
      {error ? (
        <span className="block text-xs mt-1" style={{ color: 'var(--color-danger)' }}>{error}</span>
      ) : hint ? (
        <span className="block text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>{hint}</span>
      ) : null}
    </label>
  );
}

const inputStyle: React.CSSProperties = {
  background: 'var(--color-surface-alt)',
  border: '1px solid var(--color-border)',
  color: 'var(--color-text)',
};
const inputClass = 'w-full px-3.5 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 disabled:opacity-50';

export function TextInput(props: InputHTMLAttributes<HTMLInputElement>) {
  return <input {...props} className={`${inputClass} ${props.className ?? ''}`} style={{ ...inputStyle, ...props.style }} />;
}
export function TextArea(props: TextareaHTMLAttributes<HTMLTextAreaElement>) {
  return <textarea {...props} className={`${inputClass} ${props.className ?? ''}`} style={{ ...inputStyle, ...props.style }} />;
}
export function Select(props: SelectHTMLAttributes<HTMLSelectElement>) {
  return <select {...props} className={`${inputClass} ${props.className ?? ''}`} style={{ ...inputStyle, ...props.style }} />;
}

export function Notice({ tone = 'info', children }: { tone?: 'info' | 'warning' | 'danger' | 'success'; children: ReactNode }) {
  const colors = {
    info: { bg: 'var(--color-surface-alt)', fg: 'var(--color-text-secondary)' },
    warning: { bg: 'rgba(217,119,6,0.1)', fg: '#B45309' },
    danger: { bg: 'rgba(220,38,38,0.08)', fg: 'var(--color-danger)' },
    success: { bg: 'rgba(5,150,105,0.1)', fg: '#047857' },
  }[tone];
  return (
    <div className="rounded-lg px-3.5 py-2.5 text-sm" style={{ background: colors.bg, color: colors.fg }}>
      {children}
    </div>
  );
}

export function Stat({ label, value, hint }: { label: string; value: ReactNode; hint?: string }) {
  return (
    <div className="rounded-xl p-3" style={{ background: 'var(--color-surface-alt)' }}>
      <p className="text-xs" style={{ color: 'var(--color-text-secondary)' }}>{label}</p>
      <p className="text-lg font-semibold mt-0.5" style={{ color: 'var(--color-text)' }}>{value}</p>
      {hint && <p className="text-[11px] mt-0.5" style={{ color: 'var(--color-text-tertiary)' }}>{hint}</p>}
    </div>
  );
}

export function money(value: number | null | undefined, currency: string | null | undefined): string {
  const n = Number(value ?? 0);
  try {
    return new Intl.NumberFormat(undefined, { style: 'currency', currency: currency || 'USD', maximumFractionDigits: 2 }).format(n);
  } catch {
    return `${currency ?? ''} ${n.toFixed(2)}`.trim();
  }
}

export const CTA_LABELS: Record<string, string> = {
  SHOP_NOW: 'Shop now',
  ORDER_NOW: 'Order now',
  BUY_NOW: 'Buy now',
  GET_OFFER: 'Get offer',
  LEARN_MORE: 'Learn more',
  SIGN_UP: 'Sign up',
};

export async function api<T = unknown>(url: string, init?: RequestInit): Promise<{ ok: boolean; data: T; message: string; details: string[] }> {
  try {
    const res = await fetch(url, {
      credentials: 'include',
      cache: 'no-store',
      ...init,
      headers: init?.body ? { 'Content-Type': 'application/json', ...(init.headers ?? {}) } : init?.headers,
    });
    const json = await res.json().catch(() => ({}));
    return {
      ok: res.ok && json.success !== false,
      data: json.data as T,
      message: json.message ?? (res.ok ? 'Done' : `Request failed (${res.status})`),
      details: Array.isArray(json.details) ? json.details : [],
    };
  } catch {
    return { ok: false, data: undefined as T, message: 'Could not reach the server. Check your connection.', details: [] };
  }
}
