"use client";

import Link from "next/link";
import { useConvexAuth } from "convex/react";
import { UserButton } from "@clerk/nextjs";

function OrdersIcon() {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z" />
      <line x1="3" y1="6" x2="21" y2="6" />
      <path d="M16 10a4 4 0 0 1-8 0" />
    </svg>
  );
}

export function HeaderUserAction() {
  const { isLoading, isAuthenticated } = useConvexAuth();

  if (isLoading || !isAuthenticated) {
    return (
      <Link
        href="/sign-in"
        className="group flex flex-col items-center gap-1"
      >
        <svg
          width="22"
          height="22"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
          className="text-[#3d5554] transition-colors group-hover:text-[#236f6b]"
        >
          <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
          <circle cx="12" cy="7" r="4" />
        </svg>
        <span className="text-[10px] font-medium tracking-wide text-[#3d5554] transition-colors group-hover:text-[#236f6b]">
          Sign In
        </span>
      </Link>
    );
  }

  return (
    <div className="flex flex-col items-center gap-1">
      <UserButton
        afterSignOutUrl="/"
        appearance={{
          elements: {
            avatarBox: "w-[22px] h-[22px]",
          },
        }}
      >
        <UserButton.MenuItems>
          <UserButton.Link
            label="My Orders"
            labelIcon={<OrdersIcon />}
            href="/account/orders"
          />
        </UserButton.MenuItems>
      </UserButton>
      <span className="text-[10px] font-medium tracking-wide text-[#3d5554]">
        Account
      </span>
    </div>
  );
}
