All files / src/components/features/referral/ReferralCode index.tsx

15.13% Statements 28/185
100% Branches 0/0
0% Functions 0/1
15.13% Lines 28/185

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 1861x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                           1x 1x  
"use client";
 
import { useState, useEffect } from "react";
import { Button } from "@/components/ui";
import { Icon } from "@/components/ui/icons";
import { clientLogger } from '@/lib/logging/clientLogger';
import { cn } from "@/lib/core";
import { useFunnelSteps } from "@/hooks/useFunnelTracking";
 
interface ReferralCodeProps {
  className?: string;
}
 
interface ReferralData {
  code: string;
  referrerReward: {
    type: string;
    value: number;
  };
  refereeReward: {
    type: string;
    discountType: string;
    value: number;
  };
}
 
export function ReferralCode({ className }: ReferralCodeProps) {
  const [referralData, setReferralData] = useState<ReferralData | null>(null);
  const [loading, setLoading] = useState(true);
  const [copied, setCopied] = useState(false);
  const { trackStep } = useFunnelSteps();

  useEffect(() => {
    async function fetchReferralCode() {
      try {
        const response = await fetch("/api/referrals/code");
        const data = await response.json();

        if (data.success) {
          setReferralData(data.data);
        }
      } catch (error) {
        clientLogger.error('Failed to fetch referral code', error instanceof Error ? error : new Error(String(error)));
      } finally{
        setLoading(false);
      }
    }

    fetchReferralCode();
  }, []);

  const handleCopy = async () => {
    if (!referralData) return;

    try {
      await navigator.clipboard.writeText(referralData.code);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (error) {
      clientLogger.error('Failed to copy referral code', error instanceof Error ? error : new Error(String(error)));
    }
  };

  const handleShare = async (platform: "email" | "twitter" | "facebook") => {
    if (!referralData) return;

    const referralUrl = `${window.location.origin}?ref=${referralData.code}`;
    const message = `Get ${referralData.refereeReward.value}% off your first order at our store! Use my referral code: ${referralData.code}`;

    // Track share for engagement funnel
    trackStep('engagement', 'share', {
      platform,
      content_type: 'referral_code',
      referral_code: referralData.code});

    switch (platform) {
      case "email":
        window.location.href = `mailto:?subject=Check out this store!&body=${encodeURIComponent(message + "\n\n" + referralUrl)}`;
        break;
      case "twitter":
        window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(message)}&url=${encodeURIComponent(referralUrl)}`, "_blank");
        break;
      case "facebook":
        window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(referralUrl)}&quote=${encodeURIComponent(message)}`, "_blank");
        break;
    }
  };

  if (loading) {
    return (
      <div className={cn("animate-pulse", className)}>
        <div className="h-32 bg-gray-200 rounded-lg" />
      </div>
    );
  }

  if (!referralData) {
    return null;
  }

  return (
    <div className={cn("p-4 bg-gradient-to-br from-purple-50 to-pink-50 border border-purple-200 rounded-xl", className)}>
      <div className="flex items-center gap-2 mb-4">
        <div className="p-2 bg-purple-100 rounded-full">
          <Icon name="users" size={20} className="text-purple-600" />
        </div>
        <div>
          <h4 className="font-semibold text-gray-800">Refer a Friend</h4>
          <p className="text-xs text-gray-600">Share and earn rewards</p>
        </div>
      </div>

      {/* Rewards info */}
      <div className="grid grid-cols-2 gap-3 mb-4">
        <div className="p-2 bg-white rounded-lg border border-purple-100">
          <p className="text-xs text-gray-500 mb-1">Your friend gets</p>
          <p className="text-sm font-semibold text-purple-700">
            {referralData.refereeReward.value}% OFF
          </p>
        </div>
        <div className="p-2 bg-white rounded-lg border border-purple-100">
          <p className="text-xs text-gray-500 mb-1">You earn</p>
          <p className="text-sm font-semibold text-purple-700">
            {referralData.referrerReward.value} points
          </p>
        </div>
      </div>

      {/* Referral code */}
      <div className="mb-4">
        <label className="text-xs text-gray-600 block mb-1">Your referral code</label>
        <div className="flex items-center gap-2">
          <div className="flex-1 p-2 bg-white border border-purple-200 rounded font-mono text-center text-lg font-bold text-purple-700">
            {referralData.code}
          </div>
          <Button
            variant="secondary"
            size="sm"
            onClick={handleCopy}
            className="min-w-[80px]"
          >
            {copied ? (
              <>
                <Icon name="check" size={14} className="mr-1" />
                Copied
              </>
            ) : (
              <>
                <Icon name="edit" size={14} className="mr-1" />
                Copy
              </>
            )}
          </Button>
        </div>
      </div>

      {/* Share buttons */}
      <div className="flex gap-2">
        <button
          onClick={() => handleShare("email")}
          className="flex-1 p-2 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors flex items-center justify-center gap-1 text-gray-700"
        >
          <Icon name="email" size={16} />
          <span className="text-sm">Email</span>
        </button>
        <button
          onClick={() => handleShare("twitter")}
          className="flex-1 p-2 bg-sky-100 hover:bg-sky-200 rounded-lg transition-colors flex items-center justify-center gap-1 text-sky-700"
        >
          <Icon name="twitter" size={16} />
          <span className="text-sm">Twitter</span>
        </button>
        <button
          onClick={() => handleShare("facebook")}
          className="flex-1 p-2 bg-blue-100 hover:bg-blue-200 rounded-lg transition-colors flex items-center justify-center gap-1 text-blue-700"
        >
          <Icon name="facebook" size={16} />
          <span className="text-sm">Facebook</span>
        </button>
      </div>
    </div>
  );
}
 
export default ReferralCode;