"use client";

import { useEffect, useState } from "react";
import { Download } from "lucide-react";
import { channelLabel, defaultStoreLink, type DistributionChannel } from "@/lib/platform/channels";
import { loadUpdateManifest, type ChannelRelease } from "@/lib/update/app-update-manifest";

interface DownloadLink {
  channel: DistributionChannel;
  url: string;
}

/** "Get the app" buttons for each store the app is published on (from app-update.json). */
export default function AppDownloadLinks() {
  const [links, setLinks] = useState<DownloadLink[]>([]);

  useEffect(() => {
    let current = true;

    loadUpdateManifest().then((manifest) => {
      if (!current || !manifest) return;

      const published = Object.entries(manifest.android)
        .filter(([, release]) => release && release.latestBuild > 0)
        .map(([channel, release]) => ({
          channel: channel as DistributionChannel,
          url: webUrl(channel as DistributionChannel, release!, manifest.appId),
        }))
        .filter((link): link is DownloadLink => !!link.url);

      setLinks(published);
    });

    return () => { current = false; };
  }, []);

  if (!links.length) return null;

  return (
    <div className="mt-3 flex flex-col w-full [&>*:not(:last-child)]:mb-2">
      {links.map((link) => (
        <a
          key={link.channel}
          href={link.url}
          target="_blank"
          rel="noopener noreferrer"
          className="flex items-center justify-center h-11 rounded-xl bg-primary text-primary-foreground text-sm font-medium"
        >
          <Download className="w-4 h-4 ml-2" />
          {link.channel === "direct" ? "دانلود مستقیم اپلیکیشن" : `دریافت از ${channelLabel(link.channel)}`}
        </a>
      ))}
    </div>
  );
}

// On the website: the store's web page, or the APK itself.
function webUrl(channel: DistributionChannel, release: ChannelRelease, appId: string): string | null {
  if (channel === "direct") return release.url ?? null;
  return release.fallbackUrl ?? defaultStoreLink(channel, appId)?.fallbackUrl ?? null;
}
