'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Card, CardBody } from '@/components/ui/Card';
import Button from '@/components/ui/Button';

interface DomainConfig {
  subdomainUrl: string | null;
  customDomain: string | null;
  customDomainStatus: string;
  customDomainMethod: string | null;
  customDomainVerifiedAt: string | null;
  customDomainError: string | null;
  hasCustomDomainAccess: boolean;
  // Server IP for A record instructions (new certbot-based system)
  serverIp: string | null;
  needsMigration: boolean;
  // Legacy fields for Cloudflare for SaaS domains
  isLegacyCloudflareDomain: boolean;
  txtValidation: { name: string; value: string } | null;
}

interface DomainSettingsContentProps {
  isAuthenticated: boolean;
}

export function DomainSettingsContent({ isAuthenticated }: DomainSettingsContentProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [config, setConfig] = useState<DomainConfig | null>(null);

  // Error/message state conventions:
  // - error: Global errors shown at page top (network failures, server errors, unexpected issues)
  // - successMessage: Global success messages shown at page top
  // - nameserverWarning: Contextual validation error shown near the "Start Setup" button
  //   (used specifically for Cloudflare nameserver detection, displayed close to the action)
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  // Form state for new custom domain
  const [newDomain, setNewDomain] = useState('');
  const [setupInstructions, setSetupInstructions] = useState<{
    serverIp?: string;
    instructions?: string;
  } | null>(null);
  const [copied, setCopied] = useState(false);
  const [copiedIp, setCopiedIp] = useState(false);
  const [checking, setChecking] = useState(false);
  const [checkResult, setCheckResult] = useState<{ success: boolean; message: string } | null>(
    null
  );
  const [nameserverWarning, setNameserverWarning] = useState<string | null>(null);
  const [purchasingAddon, setPurchasingAddon] = useState(false);

  async function handlePurchaseAddon() {
    setPurchasingAddon(true);
    try {
      const response = await fetch('/api/checkout/custom-domain-addon', {
        method: 'POST',
      });
      const data = await response.json();

      if (data.url) {
        window.location.href = data.url;
      } else {
        setError(data.error || 'Failed to start checkout');
        setPurchasingAddon(false);
      }
    } catch {
      setError('Failed to start checkout');
      setPurchasingAddon(false);
    }
  }

  useEffect(() => {
    if (isAuthenticated) {
      fetchDomainConfig();
    }
  }, [isAuthenticated]);

  async function fetchDomainConfig() {
    try {
      setLoading(true);
      const response = await fetch('/api/dealer/custom-domain');
      const data = await response.json();

      if (data.success) {
        setConfig(data.data);
      } else {
        setError(data.error || 'Failed to load domain configuration');
      }
    } catch {
      setError('Failed to load domain configuration');
    } finally {
      setLoading(false);
    }
  }

  function handleCopySubdomain() {
    if (config?.subdomainUrl) {
      navigator.clipboard.writeText(config.subdomainUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  }

  function handleCopyIp() {
    const ip = setupInstructions?.serverIp || config?.serverIp;
    if (ip) {
      navigator.clipboard.writeText(ip);
      setCopiedIp(true);
      setTimeout(() => setCopiedIp(false), 2000);
    }
  }

  async function handleConfigureDomain(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setSuccessMessage(null);
    setNameserverWarning(null);
    setSaving(true);

    try {
      // First, check if the domain's nameservers point to Cloudflare
      // This helps prevent issues with domains connected to Empowerkit or other services
      const nsCheckResponse = await fetch('/api/dealer/custom-domain/check-nameservers', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ domain: newDomain }),
      });

      const nsCheckData = await nsCheckResponse.json();

      if (nsCheckData.success && nsCheckData.data.isCloudflare) {
        setNameserverWarning(nsCheckData.data.message);
        setSaving(false);
        return;
      }

      // If nameserver check passed (or had a lookup error), proceed with domain setup
      const response = await fetch('/api/dealer/custom-domain', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          domain: newDomain,
        }),
      });

      const data = await response.json();

      if (data.success) {
        setSetupInstructions({
          serverIp: data.data.serverIp,
          instructions: data.data.instructions,
        });
        setSuccessMessage(
          'Step 1 complete! Now complete Step 2 below to configure your DNS. Your domain will not be active until you finish all steps.'
        );
        await fetchDomainConfig();
      } else {
        setError(data.error || 'Failed to configure domain');
      }
    } catch {
      setError('Failed to configure domain');
    } finally {
      setSaving(false);
    }
  }

  async function handleCheckDns() {
    setCheckResult(null);
    setChecking(true);

    try {
      const response = await fetch('/api/dealer/custom-domain/verify', {
        method: 'POST',
      });

      const data = await response.json();

      if (data.success) {
        if (data.data.verified) {
          setCheckResult({
            success: true,
            message: 'DNS is configured correctly! You can now activate your domain.',
          });
          await fetchDomainConfig();
        } else {
          setCheckResult({
            success: false,
            message:
              data.data.error ||
              'DNS not configured yet. Please check your settings and try again.',
          });
        }
      } else {
        setCheckResult({
          success: false,
          message: data.error || 'Could not check DNS configuration.',
        });
      }
    } catch {
      setCheckResult({ success: false, message: 'Failed to check DNS. Please try again.' });
    } finally {
      setChecking(false);
    }
  }

  async function handleActivateDomain() {
    setError(null);
    setSuccessMessage(null);
    setSaving(true);

    try {
      const response = await fetch('/api/dealer/custom-domain/activate', {
        method: 'POST',
      });

      const data = await response.json();

      if (data.success) {
        setSuccessMessage('Custom domain activated! Your site is now live at your domain.');
        await fetchDomainConfig();
      } else {
        setError(data.error || 'Activation failed');
      }
    } catch {
      setError('Activation failed');
    } finally {
      setSaving(false);
    }
  }

  async function handleRemoveDomain() {
    if (!confirm('Are you sure you want to remove your custom domain? This cannot be undone.')) {
      return;
    }

    setError(null);
    setSuccessMessage(null);
    setSaving(true);

    try {
      const response = await fetch('/api/dealer/custom-domain', {
        method: 'DELETE',
      });

      const data = await response.json();

      if (data.success) {
        setSuccessMessage('Custom domain removed.');
        setNewDomain('');
        setSetupInstructions(null);
        await fetchDomainConfig();
      } else {
        setError(data.error || 'Failed to remove domain');
      }
    } catch {
      setError('Failed to remove domain');
    } finally {
      setSaving(false);
    }
  }

  // Get the effective server IP to display for A record instructions
  const displayServerIp = setupInstructions?.serverIp || config?.serverIp;

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-cyan-500"></div>
      </div>
    );
  }

  return (
    <div>
      {error && (
        <div className="mb-4 p-4 bg-red-900/50 border border-red-500 rounded-lg text-red-200">
          {error}
        </div>
      )}

      {successMessage && (
        <div className="mb-4 p-4 bg-green-900/50 border border-green-500 rounded-lg text-green-200">
          {successMessage}
        </div>
      )}

      {/* Migration Banner for Legacy Domains */}
      {config?.needsMigration && (
        <div className="mb-4 p-4 bg-amber-900/50 border border-amber-500 rounded-lg">
          <h4 className="font-semibold text-amber-300 mb-2">Action Required: DNS Migration</h4>
          <p className="text-sm text-gray-300 mb-3">
            We&apos;ve simplified our custom domain system. Your current setup uses the old{' '}
            {config.customDomainMethod === 'managed' ? 'nameserver' : 'A record'} method. Please
            migrate to the new CNAME-based setup for better reliability.
          </p>
          <Button
            variant="secondary"
            size="sm"
            onClick={() => router.push('/dashboard/settings/domains/migrate')}
          >
            Start Migration
          </Button>
        </div>
      )}

      {/* Current Subdomain */}
      <div className="mb-6 p-4 bg-slate-700/50 rounded-lg">
        <h3 className="text-base font-semibold mb-3">Your Subdomain</h3>
        {config?.subdomainUrl ? (
          <div>
            <div className="flex items-center gap-3">
              <a
                href={config.subdomainUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="text-cyan-400 hover:text-cyan-300 underline"
              >
                {config.subdomainUrl}
              </a>
              <button
                onClick={handleCopySubdomain}
                className="px-3 py-1 text-sm bg-slate-600 hover:bg-slate-500 rounded transition-colors"
              >
                {copied ? 'Copied!' : 'Copy'}
              </button>
            </div>
            <p className="text-sm text-gray-400 mt-2">
              This is your primary site URL. It cannot be changed.
            </p>
          </div>
        ) : (
          <p className="text-gray-400">No subdomain configured yet.</p>
        )}
      </div>

      {/* Custom Domain Section */}
      <div className="p-4 bg-slate-700/50 rounded-lg">
        <h3 className="text-base font-semibold mb-3">Custom Domain</h3>

        {!config?.hasCustomDomainAccess ? (
          <Card variant="surface">
            <CardBody>
              <div className="text-center py-4">
                <h4 className="text-lg font-semibold mb-2">Custom Domain Add-On</h4>
                <p className="text-gray-400 mb-4">
                  Use your own domain name (e.g., www.yourdomain.com) instead of a subdomain.
                </p>

                {/* Add-on purchase option for Starter tier */}
                <div className="mb-6 p-4 bg-slate-600/50 rounded-lg">
                  <div className="flex items-center justify-between mb-3">
                    <span className="font-medium">Custom Domain Add-On</span>
                    <span className="text-cyan-400 font-semibold">$36/year</span>
                  </div>
                  <ul className="text-left text-sm text-slate-300/90 leading-relaxed list-disc pl-6 mb-4">
                    <li>Use your own domain (e.g., www.yourdomain.com)</li>
                    <li>Simple A record setup</li>
                    <li>Automatic SSL certificate provisioning</li>
                    <li>Professional branding for your dealership</li>
                  </ul>
                  <Button
                    variant="primary"
                    size="md"
                    onClick={handlePurchaseAddon}
                    disabled={purchasingAddon}
                  >
                    {purchasingAddon ? 'Loading...' : 'Add Custom Domain - $36/year'}
                  </Button>
                </div>

                <div className="text-sm text-gray-500">
                  Or{' '}
                  <button
                    onClick={() => router.push('/dashboard/subscription')}
                    className="text-cyan-400 hover:underline"
                  >
                    upgrade to Growth tier
                  </button>{' '}
                  for custom domains plus lead forms, media library, and more.
                </div>
              </div>
            </CardBody>
          </Card>
        ) : config?.customDomain ? (
          /* Custom domain is configured */
          <div>
            {/* Setup Progress Indicator */}
            {config.customDomainStatus !== 'active' && !config.customDomainMethod && (
              <div className="mb-6 p-4 bg-slate-600/50 rounded-lg border border-slate-500">
                <h4 className="font-medium text-white mb-3">Setup Progress</h4>
                <div className="flex items-center gap-2">
                  {/* Step 1: Domain Entered */}
                  <div className="flex items-center gap-2">
                    <div className="w-6 h-6 rounded-full bg-green-600 flex items-center justify-center text-xs font-bold">
                      1
                    </div>
                    <span className="text-sm text-gray-300">Domain entered</span>
                  </div>
                  <div className="flex-1 h-0.5 bg-slate-500 mx-2" />
                  {/* Step 2: DNS Configured */}
                  <div className="flex items-center gap-2">
                    <div
                      className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${
                        config.customDomainStatus === 'verified'
                          ? 'bg-green-600'
                          : 'bg-yellow-600 animate-pulse'
                      }`}
                    >
                      2
                    </div>
                    <span
                      className={`text-sm ${config.customDomainStatus === 'verified' ? 'text-gray-300' : 'text-yellow-300 font-medium'}`}
                    >
                      {config.customDomainStatus === 'verified' ? 'DNS verified' : 'Add A records'}
                    </span>
                  </div>
                  <div className="flex-1 h-0.5 bg-slate-500 mx-2" />
                  {/* Step 3: Activated */}
                  <div className="flex items-center gap-2">
                    <div className="w-6 h-6 rounded-full bg-slate-500 flex items-center justify-center text-xs font-bold">
                      3
                    </div>
                    <span className="text-sm text-gray-400">Activate</span>
                  </div>
                </div>
              </div>
            )}

            <div className="flex items-center justify-between mb-4">
              <div>
                <p className="font-medium">{config.customDomain}</p>
                {config.customDomainMethod && (
                  <p className="text-sm text-gray-400">
                    Method:{' '}
                    {config.customDomainMethod === 'managed'
                      ? 'Managed DNS (Legacy)'
                      : 'Self-Managed DNS (Legacy)'}
                  </p>
                )}
              </div>
              <span
                className={`px-3 py-1 rounded-full text-sm ${
                  config.customDomainStatus === 'active'
                    ? 'bg-green-900 text-green-300'
                    : config.customDomainStatus === 'verified'
                      ? 'bg-blue-900 text-blue-300'
                      : 'bg-yellow-900 text-yellow-300'
                }`}
              >
                {config.customDomainStatus === 'pending'
                  ? 'Setup Incomplete'
                  : config.customDomainStatus}
              </span>
            </div>

            {config.customDomainError && (
              <div className="mb-4 p-3 bg-red-900/30 border border-red-700 rounded text-sm text-red-300">
                {config.customDomainError}
              </div>
            )}

            {config.customDomainStatus === 'pending' && (
              <div className="mb-4">
                <div className="p-4 bg-yellow-900/30 border border-yellow-700 rounded-lg mb-4">
                  <h4 className="font-medium text-yellow-300 mb-2">
                    Action Required: Configure Your DNS
                  </h4>
                  <p className="text-sm text-yellow-200 mb-3">
                    Your domain is not yet active. Complete the DNS setup below to finish connecting
                    your custom domain.
                  </p>
                  {config.customDomainMethod ? (
                    // Legacy instructions
                    <p className="text-sm text-gray-300 mb-3">
                      {config.customDomainMethod === 'managed'
                        ? "Update your domain's nameservers at your registrar to point to ours. This usually takes a few minutes to propagate, but may take up to 48 hours."
                        : 'Add an A record pointing to our server IP. DNS changes can take a few minutes to a few hours to propagate.'}
                    </p>
                  ) : (
                    // A record instructions (new certbot-based system)
                    <div className="text-sm text-gray-300 mb-3">
                      <p className="mb-2">
                        Add <strong>two A records</strong> at your domain registrar:
                      </p>
                      <ol className="list-decimal pl-5 space-y-1 mb-3">
                        <li>Log in to your domain registrar (GoDaddy, Namecheap, etc.)</li>
                        <li>Find DNS settings or DNS Management</li>
                        <li>Add the following A records (both are required):</li>
                      </ol>
                      {displayServerIp && (
                        <div className="mt-3 p-3 bg-slate-700 rounded space-y-4">
                          {/* Header row */}
                          <div className="grid grid-cols-3 gap-2 text-xs text-gray-400 border-b border-slate-600 pb-2">
                            <span>Type</span>
                            <span>Name/Host</span>
                            <span>Value/Target</span>
                          </div>
                          {/* A record for apex domain */}
                          <div>
                            <p className="text-xs text-gray-400 mb-1">
                              1. A record for root domain (example.com):
                            </p>
                            <div className="grid grid-cols-3 gap-2 items-center">
                              <span className="text-cyan-300">A</span>
                              <span className="text-cyan-300">@ (or leave blank)</span>
                              <div className="flex items-center gap-2">
                                <code className="text-cyan-300 text-xs break-all">
                                  {displayServerIp}
                                </code>
                                <button
                                  onClick={handleCopyIp}
                                  className="px-2 py-0.5 text-xs bg-slate-600 hover:bg-slate-500 rounded shrink-0"
                                >
                                  {copiedIp ? 'Copied!' : 'Copy'}
                                </button>
                              </div>
                            </div>
                          </div>
                          {/* A record for www subdomain */}
                          <div>
                            <p className="text-xs text-gray-400 mb-1">
                              2. A record for www (www.example.com):
                            </p>
                            <div className="grid grid-cols-3 gap-2 items-center">
                              <span className="text-cyan-300">A</span>
                              <span className="text-cyan-300">www</span>
                              <code className="text-cyan-300 text-xs break-all">
                                {displayServerIp}
                              </code>
                            </div>
                          </div>
                          <p className="text-xs text-gray-400">
                            Both records must point to the same IP address. This ensures your site
                            works whether visitors type &quot;example.com&quot; or
                            &quot;www.example.com&quot;.
                          </p>
                        </div>
                      )}
                    </div>
                  )}
                  <button
                    onClick={handleCheckDns}
                    disabled={checking}
                    className="px-4 py-2 bg-yellow-600 hover:bg-yellow-700 disabled:opacity-50 rounded-lg"
                  >
                    {checking ? 'Checking...' : 'Check My DNS'}
                  </button>
                </div>
                {checkResult && (
                  <div
                    className={`p-3 rounded-lg text-sm ${checkResult.success ? 'bg-green-900/30 border border-green-700 text-green-300' : 'bg-red-900/30 border border-red-700 text-red-300'}`}
                  >
                    {checkResult.message}
                  </div>
                )}
              </div>
            )}

            {config.customDomainStatus === 'verified' && (
              <div className="mb-4">
                <div className="p-4 bg-blue-900/30 border border-blue-700 rounded-lg">
                  <h4 className="font-medium text-blue-300 mb-2">DNS Verified!</h4>
                  <p className="text-sm text-gray-300 mb-3">
                    Your DNS is configured correctly. Click activate to make your custom domain
                    live.
                  </p>
                  <button
                    onClick={handleActivateDomain}
                    disabled={saving}
                    className="px-4 py-2 bg-green-600 hover:bg-green-700 disabled:opacity-50 rounded-lg"
                  >
                    {saving ? 'Activating...' : 'Activate Domain'}
                  </button>
                </div>
              </div>
            )}

            {config.customDomainStatus === 'active' && (
              <div className="mb-4">
                <div className="p-4 bg-green-900/30 border border-green-700 rounded-lg">
                  <h4 className="font-medium text-green-300 mb-2">Domain Active</h4>
                  <p className="text-sm text-gray-300">
                    Your custom domain is live! Visitors can now access your site at{' '}
                    <a
                      href={`https://${config.customDomain}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-cyan-400 hover:underline"
                    >
                      {config.customDomain}
                    </a>
                  </p>
                  {config.customDomainVerifiedAt && (
                    <p className="text-xs text-gray-400 mt-2">
                      Active since {new Date(config.customDomainVerifiedAt).toLocaleDateString()}
                    </p>
                  )}
                </div>
              </div>
            )}

            <button
              onClick={handleRemoveDomain}
              disabled={saving}
              className="px-4 py-2 bg-red-600 hover:bg-red-700 disabled:opacity-50 rounded-lg text-sm"
            >
              Remove Custom Domain
            </button>
          </div>
        ) : (
          /* No custom domain - show setup form */
          <div>
            {/* Setup Steps Overview */}
            <div className="mb-6 p-4 bg-slate-600/50 rounded-lg border border-slate-500">
              <h4 className="font-medium text-white mb-3">Custom Domain Setup (3 Steps)</h4>
              <div className="space-y-2 text-sm">
                <div className="flex items-start gap-3">
                  <div className="w-5 h-5 rounded-full bg-cyan-600 flex items-center justify-center text-xs font-bold shrink-0 mt-0.5">
                    1
                  </div>
                  <div>
                    <span className="text-gray-200 font-medium">Enter your domain</span>
                    <span className="text-gray-400"> - Tell us which domain you want to use</span>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <div className="w-5 h-5 rounded-full bg-slate-500 flex items-center justify-center text-xs font-bold shrink-0 mt-0.5">
                    2
                  </div>
                  <div>
                    <span className="text-gray-400">Add A records</span>
                    <span className="text-gray-500">
                      {' '}
                      - Add two DNS records at your registrar (for @ and www)
                    </span>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <div className="w-5 h-5 rounded-full bg-slate-500 flex items-center justify-center text-xs font-bold shrink-0 mt-0.5">
                    3
                  </div>
                  <div>
                    <span className="text-gray-400">Verify & activate</span>
                    <span className="text-gray-500">
                      {' '}
                      - We&apos;ll check your DNS and activate your domain
                    </span>
                  </div>
                </div>
              </div>
            </div>

            <form onSubmit={handleConfigureDomain}>
              <div className="mb-4">
                <label className="block text-sm font-medium mb-2">
                  Step 1: Enter Your Domain Name
                </label>
                <input
                  type="text"
                  value={newDomain}
                  onChange={(e) => setNewDomain(e.target.value.toLowerCase())}
                  placeholder="example.com"
                  className="w-full px-4 py-2 bg-slate-600 border border-slate-500 rounded-lg focus:outline-none focus:border-cyan-500"
                  required
                />
                <p className="text-xs text-gray-400 mt-1">
                  Enter your domain without http:// or https://
                </p>
              </div>

              {newDomain && displayServerIp && (
                <div className="mb-6 p-4 bg-slate-600 rounded-lg">
                  <h4 className="font-medium mb-2">What Happens Next?</h4>
                  <p className="text-sm text-gray-300 mb-3">
                    After clicking &quot;Start Setup&quot;, you&apos;ll need to add a DNS record at
                    your domain registrar (like GoDaddy, Namecheap, etc.):
                  </p>
                  <ul className="text-sm text-gray-300 mb-3 list-disc pl-5 space-y-1">
                    <li>
                      An A record for your root domain (@) pointing to{' '}
                      <code className="px-1 py-0.5 bg-slate-700 rounded">{displayServerIp}</code>
                    </li>
                    <li>
                      An A record for www pointing to{' '}
                      <code className="px-1 py-0.5 bg-slate-700 rounded">{displayServerIp}</code>
                    </li>
                  </ul>
                  <p className="text-sm text-amber-300">
                    Note: Your domain won&apos;t be active until you complete all 3 steps.
                  </p>
                  <p className="text-sm text-gray-400 mt-2">
                    Need help?{' '}
                    <a
                      href="https://forms.clickup.com/18006137/f/h5g3t-33933/YX9MJRKKCCJ778CL6K"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-cyan-400 hover:underline"
                    >
                      Contact support
                    </a>{' '}
                    and we&apos;ll walk you through it.
                  </p>
                </div>
              )}

              {nameserverWarning && (
                <div
                  className="mb-4 p-4 bg-red-900/50 border border-red-500 rounded-lg text-red-200"
                  role="alert"
                  aria-live="polite"
                >
                  {nameserverWarning}
                </div>
              )}

              <button
                type="submit"
                disabled={saving || !newDomain}
                className="px-4 py-2 bg-cyan-600 hover:bg-cyan-700 disabled:opacity-50 rounded-lg"
              >
                {saving ? 'Starting...' : 'Start Setup'}
              </button>
            </form>
          </div>
        )}

        {/* Setup Instructions - only show when no domain is configured yet */}
        {/* (once domain is configured, the pending status section shows instructions instead) */}
        {setupInstructions && !config?.customDomain && (
          <div className="mt-6 p-4 bg-amber-900/30 border border-amber-600 rounded-lg">
            <h4 className="font-semibold mb-1 text-amber-300">Step 2: Configure Your DNS</h4>
            <p className="text-sm text-amber-200 mb-3">
              Your domain is not active yet. Add the following DNS records to continue.
            </p>

            {setupInstructions.serverIp && (
              <div className="p-3 bg-slate-700 rounded space-y-4">
                {/* Header row */}
                <div className="grid grid-cols-3 gap-2 text-xs text-gray-400 border-b border-slate-600 pb-2">
                  <span>Type</span>
                  <span>Name/Host</span>
                  <span>Value/Target</span>
                </div>
                {/* A record for apex domain */}
                <div>
                  <p className="text-xs text-gray-400 mb-1">
                    1. A record for root domain (example.com):
                  </p>
                  <div className="grid grid-cols-3 gap-2 items-center">
                    <span className="text-cyan-300">A</span>
                    <span className="text-cyan-300">@ (or leave blank)</span>
                    <div className="flex items-center gap-2">
                      <code className="text-cyan-300 text-xs break-all">
                        {setupInstructions.serverIp}
                      </code>
                      <button
                        onClick={handleCopyIp}
                        className="px-2 py-1 text-xs bg-slate-500 hover:bg-slate-400 rounded transition-colors shrink-0"
                      >
                        {copiedIp ? 'Copied!' : 'Copy'}
                      </button>
                    </div>
                  </div>
                </div>
                {/* A record for www subdomain */}
                <div>
                  <p className="text-xs text-gray-400 mb-1">
                    2. A record for www (www.example.com):
                  </p>
                  <div className="grid grid-cols-3 gap-2 items-center">
                    <span className="text-cyan-300">A</span>
                    <span className="text-cyan-300">www</span>
                    <code className="text-cyan-300 text-xs break-all">
                      {setupInstructions.serverIp}
                    </code>
                  </div>
                </div>
                <p className="text-xs text-gray-400">
                  Both records must point to the same IP address. This ensures your site works
                  whether visitors type &quot;example.com&quot; or &quot;www.example.com&quot;.
                </p>
              </div>
            )}
            <p className="text-xs text-gray-400 mt-3">
              After adding both A records, DNS changes can take a few minutes to 48 hours to
              propagate. Return here and click &quot;Check My DNS&quot; to verify.
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
