'use client'

/**
 * DomainClaimCard — renders one EmailDomainClaim row + drives the two
 * verification paths (DNS TXT + email attestation).
 *
 * The card never knows the API directly — apps supply onVerifyDns /
 * onVerifyEmail / onRevoke callbacks that typically wrap
 * api.domainClaims.*. The verificationToken (creator-only, single-show) is
 * rendered when present, with copy-to-clipboard help text. startsim-o7s.
 */

import * as React from 'react'
import type { DomainClaimLite } from './types'
import {
  DOMAIN_CLAIM_DEFAULTS,
  type DomainClaimCardClassNames,
} from './domain-claim-card-default-class-names'

export interface DomainClaimCardProps {
  claim: DomainClaimLite
  onVerifyDns?: (claim: DomainClaimLite) => Promise<void> | void
  onInitiateEmail?: (claim: DomainClaimLite) => Promise<void> | void
  onVerifyEmail?: (claim: DomainClaimLite, code: string) => Promise<void> | void
  onRevoke?: (claim: DomainClaimLite) => Promise<void> | void
  classNames?: DomainClaimCardClassNames
  /** Override the DNS-record name hint shown to the user. */
  dnsRecordName?: string
}

export function DomainClaimCard({
  claim,
  onVerifyDns,
  onInitiateEmail,
  onVerifyEmail,
  onRevoke,
  classNames,
  dnsRecordName,
}: DomainClaimCardProps) {
  const cls = { ...DOMAIN_CLAIM_DEFAULTS, ...(classNames ?? {}) }
  const [busy, setBusy] = React.useState<'dns' | 'email-initiate' | 'email-code' | 'revoke' | null>(null)
  const [error, setError] = React.useState('')
  const [emailCode, setEmailCode] = React.useState('')
  const [emailInitiated, setEmailInitiated] = React.useState(false)

  function recordName() {
    return dnsRecordName ?? `_startsim-verify.${claim.domain}`
  }

  async function run<T>(label: typeof busy, fn: () => Promise<T> | T) {
    setError('')
    setBusy(label)
    try {
      await fn()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Verification failed')
    } finally {
      setBusy(null)
    }
  }

  return (
    <article className={cls.root}>
      <div className={cls.header}>
        <span className={cls.domain}>{claim.domain}</span>
        <span
          className={[
            cls.statusBadge,
            claim.verified ? cls.statusVerified : cls.statusUnverified,
          ].join(' ')}
        >
          {claim.verified ? 'Verified' : 'Pending verification'}
        </span>
      </div>

      {!claim.verified && (
        <div className={cls.body}>
          {claim.verificationToken && (
            <div>
              <p className={cls.sectionLabel}>DNS TXT verification</p>
              <p className={cls.helpText}>
                Add a TXT record at{' '}
                <code>{recordName()}</code> with this value, then click
                &quot;Verify DNS&quot;.
              </p>
              <div className={cls.tokenRow}>
                <code className={cls.tokenCode}>{claim.verificationToken}</code>
              </div>
            </div>
          )}

          <div>
            <p className={cls.sectionLabel}>Email attestation</p>
            <p className={cls.helpText}>
              We&apos;ll email <code>postmaster@{claim.domain}</code> a 6-digit
              code. Anyone at that mailbox can confirm the claim.
            </p>
            {emailInitiated && (
              <div className={cls.tokenRow}>
                <input
                  type="text"
                  inputMode="numeric"
                  maxLength={6}
                  value={emailCode}
                  onChange={(e) => setEmailCode(e.target.value.replace(/\D/g, ''))}
                  placeholder="123456"
                  aria-label="Attestation code"
                  className={cls.codeInput}
                />
                <button
                  type="button"
                  className={cls.primaryButton}
                  disabled={busy !== null || emailCode.length < 6}
                  onClick={() =>
                    run('email-code', async () => {
                      await onVerifyEmail?.(claim, emailCode)
                      setEmailCode('')
                    })
                  }
                >
                  {busy === 'email-code' ? 'Verifying…' : 'Submit code'}
                </button>
              </div>
            )}
          </div>

          {error && <p className={cls.errorText} role="alert">{error}</p>}
        </div>
      )}

      <div className={cls.actions}>
        {!claim.verified && (
          <>
            <button
              type="button"
              className={cls.primaryButton}
              disabled={busy !== null}
              onClick={() => run('dns', () => onVerifyDns?.(claim))}
            >
              {busy === 'dns' ? 'Checking…' : 'Verify DNS'}
            </button>
            <button
              type="button"
              className={cls.secondaryButton}
              disabled={busy !== null}
              onClick={() =>
                run('email-initiate', async () => {
                  await onInitiateEmail?.(claim)
                  setEmailInitiated(true)
                })
              }
            >
              {busy === 'email-initiate' ? 'Sending…' : 'Email attestation'}
            </button>
          </>
        )}
        {onRevoke && (
          <button
            type="button"
            className={cls.revokeButton}
            disabled={busy !== null}
            onClick={() => run('revoke', () => onRevoke(claim))}
          >
            {busy === 'revoke' ? 'Revoking…' : 'Revoke'}
          </button>
        )}
      </div>
    </article>
  )
}
