/* global React, firebase */
/* ============================================
   OrderFiles
   - Admin: drag/drop one or many EA files (.ex5, .set, .zip, ...)
            files attach to a SPECIFIC order doc → visible only to that customer.
   - Customer: sees their files with download links, file size, upload date.
   - Both share the same Firestore doc orders/{orderId}.expertFiles[].
   ============================================ */

function OrderFiles({ order, isAdmin: isAdminProp }) {
  const [uploading, setUploading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [dragOver, setDragOver] = React.useState(false);
  const fileRef = React.useRef(null);
  const isAdmin = isAdminProp ?? !!window.__effAdminMode;

  const files = Array.isArray(order?.expertFiles) ? order.expertFiles : [];

  async function handleFiles(fileList) {
    if (!isAdmin || !window.fb || !fileList?.length || !order?.id) return;
    setError(''); setUploading(true);
    try {
      const uploaded = [];
      for (const f of Array.from(fileList)) {
        const result = await window.Cloudinary.uploadRawToCloudinary(f, `orders/${order.id}`);
        uploaded.push({
          name: f.name,
          url: result.url,
          size: f.size || result.bytes || 0,
          uploadedAt: new Date().toISOString(),
          format: result.format || (f.name.split('.').pop() || '').toLowerCase(),
        });
      }
      const merged = [...files, ...uploaded];
      // Auto-complete: attaching at least one file marks the order COMPLETE (active),
      // unlocks it in the customer's dashboard, and emails them that the EA is ready.
      const becomingActive = order.status !== 'active' && merged.length > 0;
      const updates = { expertFiles: merged, updatedAt: firebase.firestore.FieldValue.serverTimestamp() };
      if (becomingActive) {
        updates.status = 'active';
        updates.deliveredAt = firebase.firestore.FieldValue.serverTimestamp();
      }
      await window.fb.db.collection('orders').doc(order.id).set(updates, { merge: true });
      if (becomingActive && window.Mailer && order.userEmail) {
        window.Mailer.sendOrderComplete({
          email: order.userEmail, name: order.userName,
          eaName: order.eaName, price: order.amount, method: order.method,
          orderId: order.id, licenseTerm: order.licenseTerm || null,
        }).catch(() => {});
      }
    } catch (e) {
      setError(e.message || 'Upload failed');
    } finally {
      setUploading(false);
    }
  }

  async function removeFile(idx) {
    if (!isAdmin || !window.fb || !order?.id) return;
    if (!confirm('Remove this file? The customer will lose access.')) return;
    const next = files.filter((_, i) => i !== idx);
    try {
      await window.fb.db.collection('orders').doc(order.id).set({
        expertFiles: next,
        updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
      }, { merge: true });
    } catch (e) { setError(e.message); }
  }

  function prettySize(bytes) {
    if (!bytes) return '—';
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
    return (bytes / 1024 / 1024).toFixed(2) + ' MB';
  }

  function fileTypeIcon(fmt) {
    const ext = (fmt || '').toLowerCase();
    const color = ext === 'ex5' || ext === 'ex4' ? 'var(--cyan)'
      : ext === 'set' ? 'var(--green)'
      : ext === 'zip' || ext === 'rar' || ext === '7z' ? 'var(--magenta)'
      : ext === 'pdf' ? 'var(--red)'
      : 'var(--text-2)';
    return (
      <div style={{ width: 38, height: 38, borderRadius: 6, background: 'rgba(0,0,0,0.55)', border: '1px solid var(--line-strong)', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-mono)', fontSize: 10, color, letterSpacing: '0.05em', flexShrink: 0 }}>
        {(ext || 'FILE').toUpperCase().slice(0, 4)}
      </div>
    );
  }

  return (
    <div>
      {/* File list */}
      {files.length > 0 ? (
        <div className="flex-col gap-2">
          {files.map((f, i) => (
            <div key={i} className="panel" style={{ padding: 12, background: 'rgba(0,0,0,0.4)' }}>
              <div className="flex gap-3" style={{ alignItems: 'center' }}>
                {fileTypeIcon(f.format || f.name?.split('.').pop())}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="font-mono" style={{ fontSize: 13, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{f.name}</div>
                  <div className="text-xs text-muted mt-1 font-mono">
                    {prettySize(f.size)} · {f.uploadedAt ? new Date(f.uploadedAt).toLocaleDateString() : '—'}
                  </div>
                </div>
                <a
                  href={f.url}
                  download={f.name}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="btn btn-primary btn-sm btn-sheen"
                  style={{ flexShrink: 0 }}
                >↓ Download</a>
                {isAdmin && (
                  <button
                    onClick={() => removeFile(i)}
                    title="Remove file"
                    style={{ background: 'rgba(255,59,92,0.1)', border: '1px solid rgba(255,59,92,0.35)', color: 'var(--red)', cursor: 'pointer', borderRadius: 6, width: 32, height: 32, fontSize: 14, flexShrink: 0 }}
                  >×</button>
                )}
              </div>
            </div>
          ))}
        </div>
      ) : (
        !isAdmin && (
          <div className="panel" style={{ padding: 16, background: 'rgba(255,184,0,0.06)', borderColor: 'rgba(255,184,0,0.3)' }}>
            <div className="flex gap-3" style={{ alignItems: 'center' }}>
              <span className="dot dot-pulse" style={{ color: 'var(--amber)' }} />
              <div>
                <div className="font-mono text-amber" style={{ fontSize: 12, letterSpacing: '0.1em' }}>PROCESSING YOUR ORDER</div>
                <div className="text-xs text-muted mt-1">Your EA files will appear here as soon as the admin uploads them. You'll receive an email notification.</div>
              </div>
            </div>
          </div>
        )
      )}

      {/* Admin uploader */}
      {isAdmin && (
        <div
          onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
          onDragLeave={() => setDragOver(false)}
          onDrop={(e) => { e.preventDefault(); setDragOver(false); handleFiles(e.dataTransfer.files); }}
          onClick={() => fileRef.current?.click()}
          style={{
            marginTop: files.length ? 10 : 0,
            padding: '18px 14px', textAlign: 'center', cursor: 'pointer',
            border: `1px dashed ${dragOver ? 'var(--cyan)' : 'rgba(255,45,170,0.4)'}`,
            borderRadius: 8,
            background: dragOver ? 'rgba(0,229,255,0.04)' : 'rgba(255,45,170,0.04)',
            transition: 'all 0.2s',
          }}
        >
          <input
            ref={fileRef}
            type="file"
            multiple
            accept=".ex5,.ex4,.set,.zip,.rar,.7z,.pdf,.txt,.png,.jpg,.mq5,.mq4"
            style={{ display: 'none' }}
            onChange={(e) => handleFiles(e.target.files)}
          />
          {uploading ? (
            <div className="flex-center gap-2">
              <span className="typing"><span /><span /><span /></span>
              <span className="font-mono text-xs text-cyan" style={{ letterSpacing: '0.15em' }}>UPLOADING...</span>
            </div>
          ) : (
            <>
              <div style={{ fontSize: 22, color: 'var(--magenta)', lineHeight: 1 }}>↗</div>
              <div className="font-mono text-xs mt-2" style={{ fontWeight: 600, letterSpacing: '0.1em', color: dragOver ? 'var(--cyan)' : 'var(--magenta)' }}>
                {dragOver ? 'RELEASE TO UPLOAD' : 'DROP EA FILES FOR THIS CUSTOMER'}
              </div>
              <div className="text-xs text-muted mt-1">.ex5 / .set / .zip / .pdf — any file, any size</div>
            </>
          )}
        </div>
      )}

      {error && (
        <div className="panel mt-2" style={{ padding: 10, background: 'rgba(255,59,92,0.08)', borderColor: 'rgba(255,59,92,0.3)' }}>
          <span className="text-red font-mono text-xs">⚠ {error}</span>
        </div>
      )}
    </div>
  );
}

window.OrderFiles = OrderFiles;
