'use client'

/**
 * SignConfirmSheet — elegant pre-signing confirmation UI.
 *
 * Usage (imperative, no context needed):
 *
 *   import { confirmSign } from '@/components/wallet/SignConfirmSheet'
 *
 *   const ok = await confirmSign({
 *     label: 'Enable Auto-Trade',
 *     description: 'Bot will open live trades on Hyperliquid when signals fire.',
 *     danger: true,
 *   })
 *   if (!ok) return   // user cancelled
 *   const env = await signRequest(...)   // only NOW triggers MetaMask
 */

import { createRoot } from 'react-dom/client'

export interface SignConfirmOptions {
  /** Short action title, e.g. "Enable Auto-Trade" */
  label: string
  /** One-sentence explanation shown to the user */
  description: string
  /** If true, renders a red/warning accent — for irreversible / live-money actions */
  danger?: boolean
}

/** Renders a confirmation sheet and resolves true (confirm) or false (cancel). */
export function confirmSign(opts: SignConfirmOptions): Promise<boolean> {
  return new Promise((resolve) => {
    const container = document.createElement('div')
    document.body.appendChild(container)
    const root = createRoot(container)

    function cleanup(result: boolean) {
      root.unmount()
      container.remove()
      resolve(result)
    }

    root.render(<Sheet {...opts} onConfirm={() => cleanup(true)} onCancel={() => cleanup(false)} />)
  })
}

/* ─── Internal sheet component ─────────────────────────────────────────────── */

function Sheet({
  label, description, danger,
  onConfirm, onCancel,
}: SignConfirmOptions & { onConfirm: () => void; onCancel: () => void }) {
  const accent = danger ? '#ef4444' : '#f5a524'
  const accentSoft = danger ? 'rgba(239,68,68,0.1)' : 'rgba(245,165,36,0.1)'

  // Dismiss on backdrop click
  function handleBackdrop(e: React.MouseEvent<HTMLDivElement>) {
    if (e.target === e.currentTarget) onCancel()
  }

  // Dismiss on Escape
  function handleKey(e: React.KeyboardEvent) {
    if (e.key === 'Escape') onCancel()
  }

  return (
    <div
      onClick={handleBackdrop}
      onKeyDown={handleKey}
      role="dialog"
      aria-modal="true"
      aria-label={label}
      style={{
        position: 'fixed', inset: 0,
        background: 'rgba(0,0,0,0.70)',
        backdropFilter: 'blur(3px)',
        WebkitBackdropFilter: 'blur(3px)',
        zIndex: 99999,
        display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
        padding: '0 0 env(safe-area-inset-bottom, 0)',
      }}
    >
      <div
        style={{
          width: '100%', maxWidth: 480,
          background: '#111',
          borderRadius: '16px 16px 0 0',
          border: '1px solid #2a2a2a',
          borderBottom: 'none',
          padding: '28px 24px 32px',
          boxShadow: '0 -12px 48px rgba(0,0,0,0.5)',
          animation: 'signSheetIn 0.22s cubic-bezier(0.32,0.72,0,1)',
        }}
      >
        {/* 拖拽条 */}
        <div style={{
          width: 36, height: 4, borderRadius: 2,
          background: '#333', margin: '0 auto 24px',
        }} />

        {/* 图标 + 标题 */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
          <div style={{
            width: 40, height: 40, borderRadius: 10,
            background: accentSoft,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 20, flexShrink: 0,
          }}>
            🔏
          </div>
          <div>
            <div style={{ fontSize: 11, color: '#666', letterSpacing: '0.07em',
                          textTransform: 'uppercase', marginBottom: 2 }}>
              Wallet signature required
            </div>
            <div style={{ fontSize: 17, fontWeight: 700, color: '#fff', lineHeight: 1.2 }}>
              {label}
            </div>
          </div>
        </div>

        {/* 说明文字 */}
        <div style={{
          fontSize: 14, color: '#999', lineHeight: 1.6,
          margin: '16px 0 24px',
          paddingLeft: 52,   // 与标题对齐
        }}>
          {description}
        </div>

        {/* 说明条 */}
        <div style={{
          padding: '10px 12px', borderRadius: 8,
          background: 'rgba(255,255,255,0.04)',
          border: '1px solid #2a2a2a',
          fontSize: 12, color: '#666', lineHeight: 1.5,
          marginBottom: 20,
        }}>
          Signing is used only to verify your identity. It will NOT authorize
          any on-chain transfer and will NOT cost any gas. The MetaMask popup
          will appear after you click Confirm.
        </div>

        {/* 按钮组 */}
        <div style={{ display: 'flex', gap: 10 }}>
          <button
            onClick={onCancel}
            style={{
              flex: 1, padding: '12px 0',
              borderRadius: 10, border: '1px solid #2a2a2a',
              background: 'transparent', color: '#888',
              fontSize: 14, fontWeight: 600, cursor: 'pointer',
            }}
          >
            Cancel
          </button>
          <button
            onClick={onConfirm}
            autoFocus
            style={{
              flex: 2, padding: '12px 0',
              borderRadius: 10, border: 'none',
              background: accent, color: danger ? '#fff' : '#000',
              fontSize: 14, fontWeight: 700, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            }}
          >
            <span>Open MetaMask</span>
            <span style={{ opacity: 0.7, fontSize: 16 }}>→</span>
          </button>
        </div>
      </div>

      <style>{`
        @keyframes signSheetIn {
          from { transform: translateY(100%); opacity: 0; }
          to   { transform: translateY(0);    opacity: 1; }
        }
      `}</style>
    </div>
  )
}
