// SPDX-License-Identifier: GPL-3.0-or-later

import { useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { ExternalLink, ShieldAlert, Copy, CheckCircle } from 'lucide-react';
import Alert from './Alert';

// No-account, no-partner-token card → LTC on-ramp via Guardarian's PUBLIC buy page.
//
// We deliberately do NOT hold a partner/integration token. A partner token would
// stamp every purchase with our identity on the provider's records
// (partner → KYC'd customer → recipient address), effectively handing the provider a
// KYC-linked list of our customers. Token-less, the provider only ever sees "some
// customer bought LTC and sent it to some address" and never learns that address
// belongs to Private Archive — so nothing links our customers to us on their books.
//
// The price of staying token-less is that we cannot pin the recipient address in the
// URL (address-locking IS the partner feature). So the customer PASTES it: we surface
// the address prominently with a copy button and a hard "double-check it" warning. Our
// server only credits LTC that lands in the intent address, so a mistype is the
// customer's loss, never a risk to us.
//
// The card leg runs over CLEARNET (3-D Secure is usually blocked over Tor, and a card
// payment is non-anonymous anyway); Monero/Litecoin-direct stay the private default.

// Guardarian's public buy page. Token-less: the coin is fixed by the path, the
// customer enters the amount, and — because Guardarian is non-custodial — pastes the
// recipient address to receive LTC straight to it. Guardarian's public flow does not
// document URL amount-prefill, so we keep the link clean and show the amount in the UI.
const GUARDARIAN_BUY_LTC_URL = 'https://guardarian.com/buy-ltc-with-card';

interface CardOnrampProps {
  ltcAddress: string;
  ltcAmount: string; // LTC needed for N credits (reference)
  usdAmount: string; // fiat amount to enter on Guardarian
}

// Open a URL in the system browser. In the desktop bundle we call a small Rust
// command that launches the browser with a cleaned environment: an AppImage injects
// LD_LIBRARY_PATH and GTK/GDK module paths that make a browser launched via the shell
// plugin fail to start (this was the "button does nothing" bug). In a plain browser
// (dev / container build) fall back to window.open.
async function openExternal(u: string): Promise<void> {
  const isTauri =
    typeof window !== 'undefined' &&
    ('__TAURI_INTERNALS__' in window || '__TAURI__' in window);
  if (isTauri) {
    await invoke('open_external', { url: u });
  } else {
    window.open(u, '_blank', 'noreferrer');
  }
}

export default function CardOnramp({ ltcAddress, ltcAmount, usdAmount }: CardOnrampProps) {
  const [copied, setCopied] = useState(false);

  const copyAddress = async () => {
    try {
      await navigator.clipboard.writeText(ltcAddress);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error('Failed to copy:', err);
    }
  };

  return (
    <div className="space-y-3">
      <Alert type="warning">
        <div className="flex items-start space-x-2">
          <ShieldAlert className="w-4 h-4 mt-0.5 flex-shrink-0" />
          <p className="text-sm">
            Paying by card is an <strong>opt-in convenience that reduces your anonymity</strong>.
            Card payments are handled by <strong>Guardarian</strong>, an independent provider — not
            Private Archive, and with no partner account linking us to your purchase. Guardarian
            verifies your identity as the law requires (usually light for small amounts), and this
            step runs over the normal internet, not Tor. <strong>We never see any of it</strong> —
            only the resulting Litecoin arrives at your payment address. For maximum privacy, pay
            with Monero or Litecoin directly instead.
          </p>
        </div>
      </Alert>

      <div className="p-3 rounded-lg border border-amber-300 bg-amber-50 dark:border-amber-800 dark:bg-amber-900/20">
        <p className="text-sm font-medium text-slate-900 dark:text-white">
          On Guardarian, paste this as the <em>recipient Litecoin address</em>:
        </p>
        <div className="flex items-center space-x-2 mt-2">
          <input type="text" value={ltcAddress} readOnly className="input font-mono text-xs" />
          <button onClick={copyAddress} className="btn-secondary flex-shrink-0" title="Copy address">
            {copied ? <CheckCircle className="w-4 h-4 text-green-600" /> : <Copy className="w-4 h-4" />}
          </button>
        </div>
        <p className="text-xs text-slate-500 dark:text-slate-400 mt-2">
          Pasting the address yourself keeps it private: Guardarian never learns it belongs to
          Private Archive, so nothing on their records links your purchase to us. When you continue
          we copy it to your clipboard — paste it as the recipient on Guardarian and{' '}
          <strong>double-check it</strong>. Litecoin sent to any other address cannot be credited.
          Buy about ${usdAmount} of LTC (≈ {ltcAmount} LTC).
        </p>
      </div>

      <button
        type="button"
        onClick={() => {
          // Copy is best-effort and must not block the browser opening, so we fire
          // it without awaiting (a hung clipboard call was another way this button
          // could appear to do nothing).
          void copyAddress();
          openExternal(GUARDARIAN_BUY_LTC_URL).catch((err) =>
            console.error('Failed to open browser:', err),
          );
        }}
        className="btn-primary inline-flex items-center"
      >
        <ExternalLink className="w-4 h-4 mr-2" />
        Copy address &amp; buy LTC with card on Guardarian
      </button>
    </div>
  );
}
