'use client';

import { useState, useEffect } from 'react';
import { cn } from '@/lib/utils';

interface LoadingSpinnerProps {
  size?: 'sm' | 'md' | 'lg';
  className?: string;
}

const sizeClasses = {
  sm: 'h-4 w-4',
  md: 'h-5 w-5',
  lg: 'h-8 w-8',
};

export default function LoadingSpinner({
  size = 'md',
  className,
}: LoadingSpinnerProps) {
  const [logoUrl, setLogoUrl] = useState('/favicon.svg');

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const cached = localStorage.getItem('store_settings');
      if (cached) {
        try {
          const parsed = JSON.parse(cached);
          const favicon = parsed.favicon_url;
          const storeLogo = parsed.store_logo;
          const apiBase = process.env.NEXT_PUBLIC_API_URL || 'http://127.0.0.1:8000/api';
          const baseUrl = apiBase.replace('/api', '');
          
          if (favicon) {
            setLogoUrl(`${baseUrl}/storage/${favicon}`);
          } else if (storeLogo) {
            setLogoUrl(`${baseUrl}/storage/${storeLogo}`);
          }
        } catch {}
      }
    }
  }, []);

  if (size === 'lg') {
    return (
      <div className={cn('flex flex-col items-center justify-center gap-3', className)}>
        <div className="relative">
          <div className="h-12 w-12 rounded-full border-2 border-brand-100 border-t-brand-500 animate-spin" />
          <img
            src={logoUrl}
            alt="Logo"
            className="absolute inset-0 m-auto h-6 w-6 rounded-full object-cover animate-pulse-soft"
            onError={(e) => {
              e.currentTarget.src = '/favicon.svg';
            }}
          />
        </div>
        <p className="text-sm text-brand-400 font-medium">Memuat...</p>
      </div>
    );
  }

  return (
    <div className={cn('flex items-center justify-center', className)}>
      <div
        className={cn(
          'animate-spin rounded-full border-2 border-brand-100 border-t-brand-500',
          sizeClasses[size]
        )}
      />
    </div>
  );
}
