// Saladin Thần số — Share modal (merged with Poster Generator)
// Exports: ShareModal, buildShareUrl

const SHARE_SG = '#14C560';
const SHARE_SN = '#1E3888';

// ─────────────────────────────────────────────────────────────
// Build share URL with utm tracking
// ─────────────────────────────────────────────────────────────
function buildShareUrl(source, user) {
  const N = (typeof window !== 'undefined' && window.SaladinNumerology) || {};
  if (N.buildShareUrl) {
    return N.buildShareUrl(source, { id: btoa(`${user.name}-${user.dob}`).slice(0, 8), lifePath: user.numbers && user.numbers.lifePath });
  }
  return `https://saladin.vn/than-so?utm_source=${source || 'direct'}&utm_medium=social&utm_campaign=share-result-2026`;
}

// ─────────────────────────────────────────────────────────────
// Main modal
// ─────────────────────────────────────────────────────────────
function ShareModal({ open, onClose, user, n = 7 }) {
  const [format, setFormat] = React.useState('square');
  const [photoDataUrl, setPhotoDataUrl] = React.useState(null);
  const [photoError, setPhotoError] = React.useState(null);
  const [showName, setShowName] = React.useState(true);
  const [copied, setCopied] = React.useState(false);
  const [rendering, setRendering] = React.useState(false);
  const previewRef = React.useRef(null);
  const fileInputRef = React.useRef(null);
  const renderToken = React.useRef(0);

  const N = (typeof window !== 'undefined' && window.SaladinNumerology) || {};
  const lifePath = (user && user.numbers && user.numbers.lifePath) || n || 7;

  const FORMATS = (typeof window !== 'undefined' && window.POSTER_FORMATS) || [
    { key: 'square',    label: 'FB Feed',  ratio: '1:1', w: 1080, h: 1080, icon: 'ri-square-line' },
    { key: 'story',     label: 'Story',    ratio: '9:16', w: 1080, h: 1920, icon: 'ri-rectangle-line' },
    { key: 'zalo',      label: 'Zalo',     ratio: '4:5', w: 1080, h: 1350, icon: 'ri-instagram-line' },
    { key: 'landscape', label: 'Landscape', ratio: '16:9', w: 1200, h: 675, icon: 'ri-image-line' },
  ];

  // Render preview when settings change
  React.useEffect(() => {
    if (!open) return;
    if (typeof window === 'undefined' || !window.renderPoster) return;
    let cancelled = false;
    const token = ++renderToken.current;
    setRendering(true);
    (async () => {
      try {
        const canvas = await window.renderPoster({
          format, style: 'modern',
          lifePath, userName: showName ? user.name : '',
          photoDataUrl, showName, showDob: false,
        });
        if (cancelled || token !== renderToken.current) return;
        const preview = previewRef.current;
        if (preview) {
          const ctx = preview.getContext('2d');
          preview.width = canvas.width;
          preview.height = canvas.height;
          ctx.drawImage(canvas, 0, 0);
        }
      } finally {
        if (!cancelled) setRendering(false);
      }
    })();
    return () => { cancelled = true; };
  }, [open, format, showName, photoDataUrl, lifePath, user && user.name]);

  // ESC to close
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  // Photo upload handler
  const handlePhotoSelect = async (file) => {
    setPhotoError(null);
    if (!file) return;
    if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) {
      setPhotoError('Chỉ hỗ trợ JPG, PNG, WEBP');
      return;
    }
    if (file.size > 5 * 1024 * 1024) {
      setPhotoError('Ảnh quá lớn — tối đa 5MB');
      return;
    }
    try {
      const reader = new FileReader();
      reader.onload = async () => {
        // Resize via offscreen canvas
        const img = new Image();
        img.onload = () => {
          const c = document.createElement('canvas');
          const max = 800;
          let w = img.width, h = img.height;
          if (Math.max(w, h) > max) {
            const r = max / Math.max(w, h);
            w = Math.round(w * r); h = Math.round(h * r);
          }
          c.width = w; c.height = h;
          const ctx = c.getContext('2d');
          ctx.imageSmoothingQuality = 'high';
          ctx.drawImage(img, 0, 0, w, h);
          setPhotoDataUrl(c.toDataURL('image/jpeg', 0.85));
          if (N.trackEvent) N.trackEvent('photo_uploaded', { size_kb: Math.round(file.size / 1024) });
        };
        img.src = reader.result;
      };
      reader.readAsDataURL(file);
    } catch (e) {
      setPhotoError('Không đọc được ảnh — thử ảnh khác');
    }
  };

  // Copy share URL
  const copyLink = () => {
    const url = buildShareUrl('direct', user);
    navigator.clipboard && navigator.clipboard.writeText(url);
    setCopied(true);
    if (N.trackEvent) N.trackEvent('share_action', { channel: 'copy', format, life_path: lifePath });
    setTimeout(() => setCopied(false), 2000);
  };

  // Download PNG poster
  const downloadPoster = async () => {
    if (typeof window === 'undefined' || !window.renderPoster) return;
    const canvas = await window.renderPoster({
      format, style: 'modern',
      lifePath, userName: showName ? user.name : '',
      photoDataUrl, showName,
    });
    canvas.toBlob((blob) => {
      if (!blob) return;
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `saladin-than-so-LifePath${lifePath}-${format}-${Date.now()}.png`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      if (N.trackEvent) N.trackEvent('poster_downloaded', {
        format, life_path: lifePath, has_photo: !!photoDataUrl,
      });
    }, 'image/png', 0.95);
  };

  // Native share with file (best for mobile)
  const nativeShare = async (channel) => {
    if (typeof window === 'undefined' || !window.renderPoster) return;
    try {
      const canvas = await window.renderPoster({
        format, style: 'modern',
        lifePath, userName: showName ? user.name : '',
        photoDataUrl, showName,
      });
      const url = buildShareUrl(channel, user);
      canvas.toBlob(async (blob) => {
        if (!blob) return;
        const file = new File([blob], 'saladin-than-so.png', { type: 'image/png' });
        if (navigator.canShare && navigator.canShare({ files: [file] })) {
          try {
            await navigator.share({
              title: 'Số của tôi — Saladin Thần số',
              text: `Khám phá con số của bạn: ${url}`,
              files: [file],
            });
            if (N.trackEvent) N.trackEvent('share_action', { channel, format, life_path: lifePath, method: 'native' });
          } catch (e) {/* user cancelled */}
        } else {
          // Fallback: open share URL in popup
          if (channel === 'facebook') {
            window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`, '_blank', 'width=600,height=480');
          } else {
            navigator.clipboard && navigator.clipboard.writeText(url);
            alert('Đã copy link! Paste vào ' + channel + ' để chia sẻ.');
          }
          if (N.trackEvent) N.trackEvent('share_action', { channel, format, life_path: lifePath, method: 'fallback' });
        }
      }, 'image/png', 0.95);
    } catch (e) {
      console.warn('share failed', e);
    }
  };

  const fmt = FORMATS.find(f => f.key === format);

  return (
    <div
      onClick={onClose}
      role="dialog"
      aria-modal="true"
      style={{
        position: 'fixed', inset: 0, zIndex: 100,
        background: 'rgba(0,0,0,0.55)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 16,
        animation: 'fadeIn 200ms ease-out',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: 'var(--bg)',
          borderRadius: 16,
          maxWidth: 880, width: '100%',
          maxHeight: '92vh', overflowY: 'auto',
          boxShadow: '0 20px 60px -10px rgba(0,0,0,0.4)',
          animation: 'modalIn 250ms cubic-bezier(0.4,0,0.2,1)',
          position: 'relative',
        }}
      >
        {/* Header */}
        <div style={{
          padding: '20px 24px',
          borderBottom: '1px solid var(--border-default)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div>
            <h2 style={{
              fontFamily: 'var(--font-display)', fontWeight: 700,
              fontSize: 20, margin: 0, color: 'var(--text-default)',
            }}>
              Chia sẻ kết quả
            </h2>
            <div style={{ fontSize: 13, color: 'var(--text-support)', marginTop: 2 }}>
              Tạo poster cá nhân hoá cho mọi mạng xã hội
            </div>
          </div>
          <button
            type="button" onClick={onClose} aria-label="Đóng"
            style={{
              background: 'transparent', border: 'none', cursor: 'pointer',
              padding: 8, color: 'var(--text-support)',
              borderRadius: 8,
            }}
          >
            <i className="ri-close-line" style={{ fontSize: 22 }}></i>
          </button>
        </div>

        {/* Body */}
        <div style={{ padding: 24 }}>
          {/* Format tabs */}
          <div style={{
            display: 'flex', gap: 6, flexWrap: 'wrap',
            marginBottom: 18,
          }}>
            {FORMATS.map(f => {
              const active = format === f.key;
              return (
                <button
                  key={f.key}
                  type="button"
                  onClick={() => { setFormat(f.key); if (N.trackEvent) N.trackEvent('poster_format_selected', { format: f.key }); }}
                  style={{
                    padding: '8px 14px', borderRadius: 50,
                    border: `1px solid ${active ? SHARE_SG : 'var(--border-default)'}`,
                    background: active ? 'var(--primary-95)' : 'var(--bg)',
                    color: active ? '#005323' : 'var(--text-default)',
                    fontSize: 12, fontWeight: 600,
                    cursor: 'pointer', fontFamily: 'inherit',
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                  }}
                >
                  <i className={f.icon} style={{ fontSize: 14 }}></i>
                  {f.label} · {f.ratio}
                </button>
              );
            })}
          </div>

          {/* Preview */}
          <div style={{
            background: '#000', borderRadius: 12, overflow: 'hidden',
            border: '1px solid var(--border-default)',
            marginBottom: 16,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            position: 'relative',
            maxHeight: 420,
          }}>
            <canvas
              ref={previewRef}
              style={{
                maxWidth: '100%', maxHeight: 400,
                display: 'block', objectFit: 'contain',
              }}
            />
            {rendering && (
              <div style={{
                position: 'absolute', top: 12, right: 12,
                padding: '6px 12px', background: 'var(--bg)',
                borderRadius: 50, fontSize: 12, color: 'var(--text-support)',
                display: 'inline-flex', alignItems: 'center', gap: 6,
                boxShadow: 'var(--shadow-sm)',
              }}>
                <i className="ri-loader-4-line" style={{ animation: 'spin 800ms linear infinite' }}></i>
                Đang vẽ…
              </div>
            )}
          </div>

          {/* Photo upload + toggles row */}
          <div style={{
            display: 'flex', flexWrap: 'wrap', gap: 12, marginBottom: 18,
            padding: 12, background: 'var(--bg-variant)', borderRadius: 10,
          }}>
            <button
              type="button"
              onClick={() => fileInputRef.current && fileInputRef.current.click()}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '8px 14px', background: 'var(--bg)',
                border: '1px solid var(--border-default)', borderRadius: 8,
                cursor: 'pointer', fontSize: 13, color: 'var(--text-default)',
                fontFamily: 'inherit', fontWeight: 500,
              }}
            >
              <i className="ri-image-add-line" style={{ fontSize: 16 }}></i>
              {photoDataUrl ? 'Đổi ảnh đại diện' : 'Thêm ảnh đại diện'}
            </button>
            {photoDataUrl && (
              <>
                <img src={photoDataUrl} alt="" style={{
                  width: 36, height: 36, borderRadius: '50%',
                  objectFit: 'cover', border: '2px solid #14C560',
                }}/>
                <button
                  type="button" onClick={() => setPhotoDataUrl(null)}
                  style={{
                    background: 'transparent', border: 'none',
                    fontSize: 12, color: '#BA1A1A', cursor: 'pointer',
                    fontFamily: 'inherit', fontWeight: 500,
                  }}
                >Xoá ảnh</button>
              </>
            )}
            <input
              ref={fileInputRef}
              type="file" accept="image/*" style={{ display: 'none' }}
              onChange={(e) => handlePhotoSelect(e.target.files[0])}
            />
            <label style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              fontSize: 13, color: 'var(--text-default)',
              cursor: 'pointer', marginLeft: 'auto',
            }}>
              <input
                type="checkbox" checked={showName}
                onChange={(e) => setShowName(e.target.checked)}
                style={{ accentColor: SHARE_SG, width: 16, height: 16 }}
              />
              Hiển thị tên
            </label>
            {photoError && (
              <div style={{
                width: '100%',
                fontSize: 12, color: '#BA1A1A',
                display: 'flex', alignItems: 'center', gap: 4,
              }}>
                <i className="ri-error-warning-fill" style={{ fontSize: 14 }}></i> {photoError}
              </div>
            )}
            <div style={{
              width: '100%', fontSize: 11,
              color: 'var(--text-support)',
              display: 'flex', alignItems: 'center', gap: 4,
            }}>
              <i className="ri-shield-check-line" style={{ fontSize: 12, color: SHARE_SG }}></i>
              Browser-only — Saladin không lưu ảnh của bạn
            </div>
          </div>

          {/* Share URL */}
          <div style={{
            display: 'flex', gap: 8, marginBottom: 14,
            padding: 6, background: 'var(--bg-variant)',
            borderRadius: 8, border: '1px solid var(--border-default)',
          }}>
            <input
              type="text" readOnly
              value={buildShareUrl('direct', user)}
              style={{
                flex: 1, minWidth: 0,
                padding: '6px 10px', border: 'none',
                background: 'transparent',
                fontSize: 12, fontFamily: 'var(--font-display)',
                color: 'var(--text-support)',
                outline: 'none',
              }}
            />
            <button
              type="button" onClick={copyLink}
              style={{
                background: copied ? SHARE_SG : 'var(--bg)',
                color: copied ? '#fff' : 'var(--text-default)',
                padding: '6px 12px', border: copied ? 'none' : '1px solid var(--border-default)',
                borderRadius: 6, fontSize: 12, fontWeight: 600,
                cursor: 'pointer', fontFamily: 'inherit',
                display: 'inline-flex', alignItems: 'center', gap: 4,
              }}
            >
              <i className={copied ? "ri-check-line" : "ri-link"} style={{ fontSize: 14 }}></i>
              {copied ? 'Đã copy' : 'Copy link'}
            </button>
          </div>

          {/* Action buttons */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))',
            gap: 8,
          }}>
            <ShareButton icon="ri-download-2-line" label="Tải poster" primary onClick={downloadPoster} />
            <ShareButton icon="ri-facebook-circle-fill" label="Facebook" onClick={() => nativeShare('facebook')} />
            <ShareButton icon="ri-tiktok-line" label="TikTok" onClick={() => nativeShare('tiktok')} />
            <ShareButton icon="ri-chat-3-line" label="Zalo" onClick={() => nativeShare('zalo')} />
          </div>

          {/* Tracking note */}
          <div style={{
            marginTop: 16, padding: 10,
            fontSize: 11, color: 'var(--text-support)',
            background: 'var(--bg-variant)', borderRadius: 6,
            display: 'flex', alignItems: 'flex-start', gap: 6, lineHeight: 1.5,
          }}>
            <i className="ri-information-line" style={{ fontSize: 13, color: SHARE_SN, marginTop: 1, flexShrink: 0 }}></i>
            Link share đính kèm utm_source để Saladin đo độ lan toả — không thu thập danh tính của bạn hoặc người nhận.
          </div>
        </div>
      </div>
    </div>
  );
}

function ShareButton({ icon, label, primary, onClick }) {
  return (
    <button
      type="button" onClick={onClick}
      style={{
        background: primary ? SHARE_SG : 'var(--bg)',
        color: primary ? '#fff' : 'var(--text-default)',
        border: primary ? 'none' : '1px solid var(--border-default)',
        borderRadius: 8,
        padding: '12px 14px',
        fontSize: 13, fontWeight: 600,
        cursor: 'pointer', fontFamily: 'inherit',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        boxShadow: primary ? '0 4px 12px -2px rgba(20,197,96,0.35)' : 'var(--shadow-xs)',
        transition: 'transform 100ms',
      }}
    >
      <i className={icon} style={{ fontSize: 16 }}></i>
      {label}
    </button>
  );
}

Object.assign(window, { ShareModal, buildShareUrl });
